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
AngelaFabregues/dipGame
dip/src/es/csic/iiia/fabregues/dip/orders/SUPMTOOrder.java
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Province.java // public class Province{ // // protected String name; // protected Vector<Region> regions; // private boolean isSC; // private Float provinceValue; //TODO treure-ho d'aqui // // public Province(String name) { // this.name = name; // this.regions = new Vector<Region>(); // isSC = false; // } // // public void addRegion(Region region) { // regions.add(region); // } // // public String getName() { // return name; // } // // public boolean isSC() { // return isSC; // } // // public Vector<Region> getRegions(){ // return regions; // } // // public void markAsSC() { // isSC = true; // } // // public Float getValue() { // return provinceValue; // } // // public void setValue(Float orderValue) { // this.provinceValue = orderValue; // } // // public String toString(){ // return name; // } // // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // }
import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Province; import es.csic.iiia.fabregues.dip.board.Region;
package es.csic.iiia.fabregues.dip.orders; /** * Support move order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class SUPMTOOrder extends Order { private MTOOrder mtoOrder;
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Province.java // public class Province{ // // protected String name; // protected Vector<Region> regions; // private boolean isSC; // private Float provinceValue; //TODO treure-ho d'aqui // // public Province(String name) { // this.name = name; // this.regions = new Vector<Region>(); // isSC = false; // } // // public void addRegion(Region region) { // regions.add(region); // } // // public String getName() { // return name; // } // // public boolean isSC() { // return isSC; // } // // public Vector<Region> getRegions(){ // return regions; // } // // public void markAsSC() { // isSC = true; // } // // public Float getValue() { // return provinceValue; // } // // public void setValue(Float orderValue) { // this.provinceValue = orderValue; // } // // public String toString(){ // return name; // } // // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // } // Path: dip/src/es/csic/iiia/fabregues/dip/orders/SUPMTOOrder.java import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Province; import es.csic.iiia.fabregues.dip.board.Region; package es.csic.iiia.fabregues.dip.orders; /** * Support move order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class SUPMTOOrder extends Order { private MTOOrder mtoOrder;
public SUPMTOOrder(Power power, Region region, MTOOrder mtoOrder) {
AngelaFabregues/dipGame
dip/src/es/csic/iiia/fabregues/dip/orders/SUPMTOOrder.java
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Province.java // public class Province{ // // protected String name; // protected Vector<Region> regions; // private boolean isSC; // private Float provinceValue; //TODO treure-ho d'aqui // // public Province(String name) { // this.name = name; // this.regions = new Vector<Region>(); // isSC = false; // } // // public void addRegion(Region region) { // regions.add(region); // } // // public String getName() { // return name; // } // // public boolean isSC() { // return isSC; // } // // public Vector<Region> getRegions(){ // return regions; // } // // public void markAsSC() { // isSC = true; // } // // public Float getValue() { // return provinceValue; // } // // public void setValue(Float orderValue) { // this.provinceValue = orderValue; // } // // public String toString(){ // return name; // } // // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // }
import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Province; import es.csic.iiia.fabregues.dip.board.Region;
package es.csic.iiia.fabregues.dip.orders; /** * Support move order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class SUPMTOOrder extends Order { private MTOOrder mtoOrder;
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Province.java // public class Province{ // // protected String name; // protected Vector<Region> regions; // private boolean isSC; // private Float provinceValue; //TODO treure-ho d'aqui // // public Province(String name) { // this.name = name; // this.regions = new Vector<Region>(); // isSC = false; // } // // public void addRegion(Region region) { // regions.add(region); // } // // public String getName() { // return name; // } // // public boolean isSC() { // return isSC; // } // // public Vector<Region> getRegions(){ // return regions; // } // // public void markAsSC() { // isSC = true; // } // // public Float getValue() { // return provinceValue; // } // // public void setValue(Float orderValue) { // this.provinceValue = orderValue; // } // // public String toString(){ // return name; // } // // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // } // Path: dip/src/es/csic/iiia/fabregues/dip/orders/SUPMTOOrder.java import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Province; import es.csic.iiia.fabregues.dip.board.Region; package es.csic.iiia.fabregues.dip.orders; /** * Support move order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class SUPMTOOrder extends Order { private MTOOrder mtoOrder;
public SUPMTOOrder(Power power, Region region, MTOOrder mtoOrder) {
AngelaFabregues/dipGame
dip/src/es/csic/iiia/fabregues/dip/orders/SUPMTOOrder.java
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Province.java // public class Province{ // // protected String name; // protected Vector<Region> regions; // private boolean isSC; // private Float provinceValue; //TODO treure-ho d'aqui // // public Province(String name) { // this.name = name; // this.regions = new Vector<Region>(); // isSC = false; // } // // public void addRegion(Region region) { // regions.add(region); // } // // public String getName() { // return name; // } // // public boolean isSC() { // return isSC; // } // // public Vector<Region> getRegions(){ // return regions; // } // // public void markAsSC() { // isSC = true; // } // // public Float getValue() { // return provinceValue; // } // // public void setValue(Float orderValue) { // this.provinceValue = orderValue; // } // // public String toString(){ // return name; // } // // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // }
import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Province; import es.csic.iiia.fabregues.dip.board.Region;
package es.csic.iiia.fabregues.dip.orders; /** * Support move order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class SUPMTOOrder extends Order { private MTOOrder mtoOrder; public SUPMTOOrder(Power power, Region region, MTOOrder mtoOrder) { super(power, region); this.mtoOrder = mtoOrder; } public Region getSupportedRegion() { return mtoOrder.getLocation(); }
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Province.java // public class Province{ // // protected String name; // protected Vector<Region> regions; // private boolean isSC; // private Float provinceValue; //TODO treure-ho d'aqui // // public Province(String name) { // this.name = name; // this.regions = new Vector<Region>(); // isSC = false; // } // // public void addRegion(Region region) { // regions.add(region); // } // // public String getName() { // return name; // } // // public boolean isSC() { // return isSC; // } // // public Vector<Region> getRegions(){ // return regions; // } // // public void markAsSC() { // isSC = true; // } // // public Float getValue() { // return provinceValue; // } // // public void setValue(Float orderValue) { // this.provinceValue = orderValue; // } // // public String toString(){ // return name; // } // // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // } // Path: dip/src/es/csic/iiia/fabregues/dip/orders/SUPMTOOrder.java import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Province; import es.csic.iiia.fabregues.dip.board.Region; package es.csic.iiia.fabregues.dip.orders; /** * Support move order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class SUPMTOOrder extends Order { private MTOOrder mtoOrder; public SUPMTOOrder(Power power, Region region, MTOOrder mtoOrder) { super(power, region); this.mtoOrder = mtoOrder; } public Region getSupportedRegion() { return mtoOrder.getLocation(); }
public Province getDestination() {
AngelaFabregues/dipGame
dip/src/es/csic/iiia/fabregues/dip/orders/MTOOrder.java
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // }
import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Region;
package es.csic.iiia.fabregues.dip.orders; /** * Move order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class MTOOrder extends Order { private Region destination;
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // } // Path: dip/src/es/csic/iiia/fabregues/dip/orders/MTOOrder.java import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Region; package es.csic.iiia.fabregues.dip.orders; /** * Move order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class MTOOrder extends Order { private Region destination;
public MTOOrder(Power power, Region region, Region dest) {
AngelaFabregues/dipGame
dip/src/es/csic/iiia/fabregues/dip/orders/RTOOrder.java
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // }
import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Region;
package es.csic.iiia.fabregues.dip.orders; /** * Retreate to order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class RTOOrder extends Order { private Region destination;
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java // public class Power { // // private String name; // // private List<Province> own; // private List<Province> homes; // private List<Region> control; // // public Power(String name) { // this.name = name; // // resetControl(); // // resetOwn(); // homes = new ArrayList<Province>(); // // } // // public String getName() { // return name; // } // // public void addControlledRegion(Region region){ // control.add(region); // } // // public List<Region> getControlledRegions() { // return control; // } // // public boolean isControlling(Region region){ // return control.contains(region); // } // // /** // * Returns true if the province is a SC owned by the power or false otherwise. // * @param Province // * @return // */ // public boolean isOwning(Province Province){ // if(Province instanceof Province){ // return own.contains((Province)Province); // } // return false; // } // // public List<Province> getOwnedSCs() { // return own; // } // // public void resetControl() { // control = new Vector<Region>(); // } // // public void addOwn(Province sc) { // own.add(sc); // } // // public void resetOwn() { // own = new Vector<Province>(); // } // // public void addHome(Province province) { // homes.add(province); // } // // public List<Province> getHomes() { // return homes; // } // // public String toString(){ // return name; // } // // public boolean isControlling(Province province) { // for(Region region: province.getRegions()){ // if(isControlling(region)){ // return true; // } // } // return false; // } // // public boolean equals(Object o){ // if(o instanceof Power){ // Power power = (Power) o; // return name.equals(power.getName()); // } // return super.equals(o); // } // } // // Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java // public class Region { // // private String name; // private Province province; // private Vector<Region> adjacentRegions; // // public Region(String name) { // adjacentRegions = new Vector<Region>(); // this.name = name; // } // // public Province getProvince() { // return province; // } // // public void setProvince(Province province) { // this.province = province; // } // // public String getName() { // return name; // } // // public void addAdjacentRegion(Region adjNode) { // adjacentRegions.add(adjNode); // } // // public Vector<Region> getAdjacentRegions() { // return adjacentRegions; // } // // public String toString() { // return name; // } // // public boolean equals(Object o){ // if(o instanceof Region){ // Region region = (Region) o; // return name.equals(region.getName()); // } // return super.equals(o); // } // } // Path: dip/src/es/csic/iiia/fabregues/dip/orders/RTOOrder.java import es.csic.iiia.fabregues.dip.board.Power; import es.csic.iiia.fabregues.dip.board.Region; package es.csic.iiia.fabregues.dip.orders; /** * Retreate to order * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class RTOOrder extends Order { private Region destination;
public RTOOrder(Region region, Power power, Region destination) {
AngelaFabregues/dipGame
gameManager/src/org/dipgame/gameManager/AlertsFrame.java
// Path: gameManager/src/org/dipgame/gameManager/utils/JTextPaneAppend.java // public class JTextPaneAppend extends JTextPane{ // // private static final long serialVersionUID = 1L; // // public void append(String s,Color color, Boolean bold) { // try { // StyledDocument doc = (StyledDocument) this.getDocument(); // Style style=doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // } catch(BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void append2(String s, Color color, Boolean bold){ // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 5); // StyleConstants.setRightIndent(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // try { // doc.insertString(doc.getLength(), s, style); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/TextBox.java // public class TextBox extends JTextPane { // // public TextBox(Color background) { // this.setBackground(background); // this.setAutoscrolls(true); // this.setEditable(false); // } // // public TextBox(String description, Color background) { // this(background); // append(description, Color.black, false); // } // // public String getText() { // return this.getText(); // } // // public void append(String s, Color color, Boolean bold) { // try { // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 10); // StyleConstants.setRightIndent(sa, 10); // StyleConstants.setSpaceAbove(sa, 5); // StyleConstants.setSpaceBelow(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } catch (BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void revalidateAll() { // this.revalidate(); // } // }
import java.awt.Color; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.dipgame.gameManager.utils.JTextPaneAppend; import org.dipgame.gameManager.utils.TextBox;
package org.dipgame.gameManager; /** * AlertsFrame * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class AlertsFrame extends JFrame { private List<String> alerts; public AlertsFrame(List<String> alerts, int applicationHeight){ this.alerts = alerts; this.setTitle("Game Manager alerts"); this.setBackground(Utils.CYAN); JPanel alertMainPanel = new JPanel(); alertMainPanel.setBackground(Utils.CYAN); BoxLayout boxLayout = new BoxLayout(alertMainPanel, BoxLayout.Y_AXIS); alertMainPanel.setLayout(boxLayout); alertMainPanel.add(MainPanel.createHeader()); JPanel footer = new JPanel(); footer.setBackground(Utils.CYAN); JPanel footerContent = new JPanel(); footerContent.setBackground(Utils.BLUE); footerContent.setPreferredSize(new Dimension(325, 20)); footerContent.add(Utils.getText("Game Manager outputs the following alerts:", new MouseAdapter() { })); footer.add(Utils.addBordersToLine(footerContent)); alertMainPanel.add(footer); JPanel descriptionPanel = new JPanel(); descriptionPanel.setBackground(Utils.CYAN); String description=""; for(String alert: this.alerts){ description+=alert+"\n\n"; }
// Path: gameManager/src/org/dipgame/gameManager/utils/JTextPaneAppend.java // public class JTextPaneAppend extends JTextPane{ // // private static final long serialVersionUID = 1L; // // public void append(String s,Color color, Boolean bold) { // try { // StyledDocument doc = (StyledDocument) this.getDocument(); // Style style=doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // } catch(BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void append2(String s, Color color, Boolean bold){ // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 5); // StyleConstants.setRightIndent(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // try { // doc.insertString(doc.getLength(), s, style); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/TextBox.java // public class TextBox extends JTextPane { // // public TextBox(Color background) { // this.setBackground(background); // this.setAutoscrolls(true); // this.setEditable(false); // } // // public TextBox(String description, Color background) { // this(background); // append(description, Color.black, false); // } // // public String getText() { // return this.getText(); // } // // public void append(String s, Color color, Boolean bold) { // try { // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 10); // StyleConstants.setRightIndent(sa, 10); // StyleConstants.setSpaceAbove(sa, 5); // StyleConstants.setSpaceBelow(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } catch (BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void revalidateAll() { // this.revalidate(); // } // } // Path: gameManager/src/org/dipgame/gameManager/AlertsFrame.java import java.awt.Color; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.dipgame.gameManager.utils.JTextPaneAppend; import org.dipgame.gameManager.utils.TextBox; package org.dipgame.gameManager; /** * AlertsFrame * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class AlertsFrame extends JFrame { private List<String> alerts; public AlertsFrame(List<String> alerts, int applicationHeight){ this.alerts = alerts; this.setTitle("Game Manager alerts"); this.setBackground(Utils.CYAN); JPanel alertMainPanel = new JPanel(); alertMainPanel.setBackground(Utils.CYAN); BoxLayout boxLayout = new BoxLayout(alertMainPanel, BoxLayout.Y_AXIS); alertMainPanel.setLayout(boxLayout); alertMainPanel.add(MainPanel.createHeader()); JPanel footer = new JPanel(); footer.setBackground(Utils.CYAN); JPanel footerContent = new JPanel(); footerContent.setBackground(Utils.BLUE); footerContent.setPreferredSize(new Dimension(325, 20)); footerContent.add(Utils.getText("Game Manager outputs the following alerts:", new MouseAdapter() { })); footer.add(Utils.addBordersToLine(footerContent)); alertMainPanel.add(footer); JPanel descriptionPanel = new JPanel(); descriptionPanel.setBackground(Utils.CYAN); String description=""; for(String alert: this.alerts){ description+=alert+"\n\n"; }
TextBox text = new TextBox(Color.white);
AngelaFabregues/dipGame
gameManager/src/org/dipgame/gameManager/Utils.java
// Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java // public class BareBonesBrowserLaunch { // // static final String[] browsers = { "google-chrome", "firefox", "opera", // "epiphany", "konqueror", "conkeror", "midori", "kazehakase", // "mozilla" }; // static final String errMsg = "Error attempting to launch web browser"; // // public static void openURL(String url) { // try { // attempt to use Desktop library from JDK 1.6+ // Class<?> d = Class.forName("java.awt.Desktop"); // d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }) // .invoke(d.getDeclaredMethod("getDesktop").invoke(null), // new Object[] { java.net.URI.create(url) }); // // above code mimicks: java.awt.Desktop.getDesktop().browse() // } catch (Exception ignore) { // library not available or failed // String osName = System.getProperty("os.name"); // try { // if (osName.startsWith("Mac OS")) { // Class.forName("com.apple.eio.FileManager") // .getDeclaredMethod("openURL", // new Class[] { String.class }) // .invoke(null, new Object[] { url }); // } else if (osName.startsWith("Windows")) // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + url); // else { // assume Unix or Linux // String browser = null; // for (String b : browsers) // if (browser == null // && Runtime.getRuntime() // .exec(new String[] { "which", b }) // .getInputStream().read() != -1) // Runtime.getRuntime().exec( // new String[] { browser = b, url }); // if (browser == null) // throw new Exception(Arrays.toString(browsers)); // } // } catch (Exception e) { // JOptionPane.showMessageDialog(null, // errMsg + "\n" + e.toString()); // } // } // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/JTextPaneAppend.java // public class JTextPaneAppend extends JTextPane{ // // private static final long serialVersionUID = 1L; // // public void append(String s,Color color, Boolean bold) { // try { // StyledDocument doc = (StyledDocument) this.getDocument(); // Style style=doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // } catch(BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void append2(String s, Color color, Boolean bold){ // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 5); // StyleConstants.setRightIndent(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // try { // doc.insertString(doc.getLength(), s, style); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } // // }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; import org.dipgame.gameManager.utils.JTextPaneAppend;
package org.dipgame.gameManager; /** * Utils * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class Utils { final static Color CYAN = new Color(99, 158, 255); final static String IP = "localhost"; final static int PORT = 16713; final static String LOG_FOLDER = "logs"; public final static Color BLUE = new Color(49, 97, 206); static final int FULL_SIZE = 768; static final int MIN_SIZE = 550; public static final int NEGO_PORT = 16714; public static final String LEAVE_EMPTY = "empty"; public static final String URL = "http://www.dipgame.org";
// Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java // public class BareBonesBrowserLaunch { // // static final String[] browsers = { "google-chrome", "firefox", "opera", // "epiphany", "konqueror", "conkeror", "midori", "kazehakase", // "mozilla" }; // static final String errMsg = "Error attempting to launch web browser"; // // public static void openURL(String url) { // try { // attempt to use Desktop library from JDK 1.6+ // Class<?> d = Class.forName("java.awt.Desktop"); // d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }) // .invoke(d.getDeclaredMethod("getDesktop").invoke(null), // new Object[] { java.net.URI.create(url) }); // // above code mimicks: java.awt.Desktop.getDesktop().browse() // } catch (Exception ignore) { // library not available or failed // String osName = System.getProperty("os.name"); // try { // if (osName.startsWith("Mac OS")) { // Class.forName("com.apple.eio.FileManager") // .getDeclaredMethod("openURL", // new Class[] { String.class }) // .invoke(null, new Object[] { url }); // } else if (osName.startsWith("Windows")) // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + url); // else { // assume Unix or Linux // String browser = null; // for (String b : browsers) // if (browser == null // && Runtime.getRuntime() // .exec(new String[] { "which", b }) // .getInputStream().read() != -1) // Runtime.getRuntime().exec( // new String[] { browser = b, url }); // if (browser == null) // throw new Exception(Arrays.toString(browsers)); // } // } catch (Exception e) { // JOptionPane.showMessageDialog(null, // errMsg + "\n" + e.toString()); // } // } // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/JTextPaneAppend.java // public class JTextPaneAppend extends JTextPane{ // // private static final long serialVersionUID = 1L; // // public void append(String s,Color color, Boolean bold) { // try { // StyledDocument doc = (StyledDocument) this.getDocument(); // Style style=doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // } catch(BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void append2(String s, Color color, Boolean bold){ // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 5); // StyleConstants.setRightIndent(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // try { // doc.insertString(doc.getLength(), s, style); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } // // } // Path: gameManager/src/org/dipgame/gameManager/Utils.java import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; import org.dipgame.gameManager.utils.JTextPaneAppend; package org.dipgame.gameManager; /** * Utils * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class Utils { final static Color CYAN = new Color(99, 158, 255); final static String IP = "localhost"; final static int PORT = 16713; final static String LOG_FOLDER = "logs"; public final static Color BLUE = new Color(49, 97, 206); static final int FULL_SIZE = 768; static final int MIN_SIZE = 550; public static final int NEGO_PORT = 16714; public static final String LEAVE_EMPTY = "empty"; public static final String URL = "http://www.dipgame.org";
static JTextPaneAppend getText(String text, final String url) {
AngelaFabregues/dipGame
gameManager/src/org/dipgame/gameManager/Utils.java
// Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java // public class BareBonesBrowserLaunch { // // static final String[] browsers = { "google-chrome", "firefox", "opera", // "epiphany", "konqueror", "conkeror", "midori", "kazehakase", // "mozilla" }; // static final String errMsg = "Error attempting to launch web browser"; // // public static void openURL(String url) { // try { // attempt to use Desktop library from JDK 1.6+ // Class<?> d = Class.forName("java.awt.Desktop"); // d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }) // .invoke(d.getDeclaredMethod("getDesktop").invoke(null), // new Object[] { java.net.URI.create(url) }); // // above code mimicks: java.awt.Desktop.getDesktop().browse() // } catch (Exception ignore) { // library not available or failed // String osName = System.getProperty("os.name"); // try { // if (osName.startsWith("Mac OS")) { // Class.forName("com.apple.eio.FileManager") // .getDeclaredMethod("openURL", // new Class[] { String.class }) // .invoke(null, new Object[] { url }); // } else if (osName.startsWith("Windows")) // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + url); // else { // assume Unix or Linux // String browser = null; // for (String b : browsers) // if (browser == null // && Runtime.getRuntime() // .exec(new String[] { "which", b }) // .getInputStream().read() != -1) // Runtime.getRuntime().exec( // new String[] { browser = b, url }); // if (browser == null) // throw new Exception(Arrays.toString(browsers)); // } // } catch (Exception e) { // JOptionPane.showMessageDialog(null, // errMsg + "\n" + e.toString()); // } // } // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/JTextPaneAppend.java // public class JTextPaneAppend extends JTextPane{ // // private static final long serialVersionUID = 1L; // // public void append(String s,Color color, Boolean bold) { // try { // StyledDocument doc = (StyledDocument) this.getDocument(); // Style style=doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // } catch(BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void append2(String s, Color color, Boolean bold){ // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 5); // StyleConstants.setRightIndent(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // try { // doc.insertString(doc.getLength(), s, style); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } // // }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; import org.dipgame.gameManager.utils.JTextPaneAppend;
package org.dipgame.gameManager; /** * Utils * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class Utils { final static Color CYAN = new Color(99, 158, 255); final static String IP = "localhost"; final static int PORT = 16713; final static String LOG_FOLDER = "logs"; public final static Color BLUE = new Color(49, 97, 206); static final int FULL_SIZE = 768; static final int MIN_SIZE = 550; public static final int NEGO_PORT = 16714; public static final String LEAVE_EMPTY = "empty"; public static final String URL = "http://www.dipgame.org"; static JTextPaneAppend getText(String text, final String url) { MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) {
// Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java // public class BareBonesBrowserLaunch { // // static final String[] browsers = { "google-chrome", "firefox", "opera", // "epiphany", "konqueror", "conkeror", "midori", "kazehakase", // "mozilla" }; // static final String errMsg = "Error attempting to launch web browser"; // // public static void openURL(String url) { // try { // attempt to use Desktop library from JDK 1.6+ // Class<?> d = Class.forName("java.awt.Desktop"); // d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }) // .invoke(d.getDeclaredMethod("getDesktop").invoke(null), // new Object[] { java.net.URI.create(url) }); // // above code mimicks: java.awt.Desktop.getDesktop().browse() // } catch (Exception ignore) { // library not available or failed // String osName = System.getProperty("os.name"); // try { // if (osName.startsWith("Mac OS")) { // Class.forName("com.apple.eio.FileManager") // .getDeclaredMethod("openURL", // new Class[] { String.class }) // .invoke(null, new Object[] { url }); // } else if (osName.startsWith("Windows")) // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + url); // else { // assume Unix or Linux // String browser = null; // for (String b : browsers) // if (browser == null // && Runtime.getRuntime() // .exec(new String[] { "which", b }) // .getInputStream().read() != -1) // Runtime.getRuntime().exec( // new String[] { browser = b, url }); // if (browser == null) // throw new Exception(Arrays.toString(browsers)); // } // } catch (Exception e) { // JOptionPane.showMessageDialog(null, // errMsg + "\n" + e.toString()); // } // } // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/JTextPaneAppend.java // public class JTextPaneAppend extends JTextPane{ // // private static final long serialVersionUID = 1L; // // public void append(String s,Color color, Boolean bold) { // try { // StyledDocument doc = (StyledDocument) this.getDocument(); // Style style=doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // } catch(BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void append2(String s, Color color, Boolean bold){ // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 5); // StyleConstants.setRightIndent(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // try { // doc.insertString(doc.getLength(), s, style); // } catch (BadLocationException e) { // e.printStackTrace(); // } // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } // // } // Path: gameManager/src/org/dipgame/gameManager/Utils.java import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; import org.dipgame.gameManager.utils.JTextPaneAppend; package org.dipgame.gameManager; /** * Utils * * @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es */ public class Utils { final static Color CYAN = new Color(99, 158, 255); final static String IP = "localhost"; final static int PORT = 16713; final static String LOG_FOLDER = "logs"; public final static Color BLUE = new Color(49, 97, 206); static final int FULL_SIZE = 768; static final int MIN_SIZE = 550; public static final int NEGO_PORT = 16714; public static final String LEAVE_EMPTY = "empty"; public static final String URL = "http://www.dipgame.org"; static JTextPaneAppend getText(String text, final String url) { MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) {
BareBonesBrowserLaunch.openURL(url);
AngelaFabregues/dipGame
gameManager/src/org/dipgame/gameManager/MainPanel.java
// Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java // public class BareBonesBrowserLaunch { // // static final String[] browsers = { "google-chrome", "firefox", "opera", // "epiphany", "konqueror", "conkeror", "midori", "kazehakase", // "mozilla" }; // static final String errMsg = "Error attempting to launch web browser"; // // public static void openURL(String url) { // try { // attempt to use Desktop library from JDK 1.6+ // Class<?> d = Class.forName("java.awt.Desktop"); // d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }) // .invoke(d.getDeclaredMethod("getDesktop").invoke(null), // new Object[] { java.net.URI.create(url) }); // // above code mimicks: java.awt.Desktop.getDesktop().browse() // } catch (Exception ignore) { // library not available or failed // String osName = System.getProperty("os.name"); // try { // if (osName.startsWith("Mac OS")) { // Class.forName("com.apple.eio.FileManager") // .getDeclaredMethod("openURL", // new Class[] { String.class }) // .invoke(null, new Object[] { url }); // } else if (osName.startsWith("Windows")) // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + url); // else { // assume Unix or Linux // String browser = null; // for (String b : browsers) // if (browser == null // && Runtime.getRuntime() // .exec(new String[] { "which", b }) // .getInputStream().read() != -1) // Runtime.getRuntime().exec( // new String[] { browser = b, url }); // if (browser == null) // throw new Exception(Arrays.toString(browsers)); // } // } catch (Exception e) { // JOptionPane.showMessageDialog(null, // errMsg + "\n" + e.toString()); // } // } // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/TextBox.java // public class TextBox extends JTextPane { // // public TextBox(Color background) { // this.setBackground(background); // this.setAutoscrolls(true); // this.setEditable(false); // } // // public TextBox(String description, Color background) { // this(background); // append(description, Color.black, false); // } // // public String getText() { // return this.getText(); // } // // public void append(String s, Color color, Boolean bold) { // try { // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 10); // StyleConstants.setRightIndent(sa, 10); // StyleConstants.setSpaceAbove(sa, 5); // StyleConstants.setSpaceBelow(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } catch (BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void revalidateAll() { // this.revalidate(); // } // }
import java.awt.BorderLayout; import java.awt.Choice; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.StringReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.List; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; import org.dipgame.gameManager.utils.TextBox;
FileReader fr = new FileReader(new File("files/availablePlayers.txt")); LineNumberReader ln = new LineNumberReader(fr); String line = ln.readLine(); try{ while (line != null) { line = line.trim(); if(line.length()!=0 && !line.startsWith("//")){ //ignoring empty lines and comments String key = line.substring(0, line.indexOf(';')); String value = line.substring(line.indexOf(';'+1)); loadedPlayers.put(key, value); availablePlayerNames.add(key); } line = ln.readLine(); } }catch (StringIndexOutOfBoundsException e) { alerts.add("Syntax error in file 'files/availablePlayers.txt' line: '"+line+"'."); canRun = false; } } static Component createHeader() { JPanel headerPanel = new JPanel(); headerPanel.setBackground(Utils.CYAN); ImageIcon icon = new ImageIcon("files/img/dipgame.png"); JLabel label = new JLabel(); label.setIcon(icon); label.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) {
// Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java // public class BareBonesBrowserLaunch { // // static final String[] browsers = { "google-chrome", "firefox", "opera", // "epiphany", "konqueror", "conkeror", "midori", "kazehakase", // "mozilla" }; // static final String errMsg = "Error attempting to launch web browser"; // // public static void openURL(String url) { // try { // attempt to use Desktop library from JDK 1.6+ // Class<?> d = Class.forName("java.awt.Desktop"); // d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }) // .invoke(d.getDeclaredMethod("getDesktop").invoke(null), // new Object[] { java.net.URI.create(url) }); // // above code mimicks: java.awt.Desktop.getDesktop().browse() // } catch (Exception ignore) { // library not available or failed // String osName = System.getProperty("os.name"); // try { // if (osName.startsWith("Mac OS")) { // Class.forName("com.apple.eio.FileManager") // .getDeclaredMethod("openURL", // new Class[] { String.class }) // .invoke(null, new Object[] { url }); // } else if (osName.startsWith("Windows")) // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + url); // else { // assume Unix or Linux // String browser = null; // for (String b : browsers) // if (browser == null // && Runtime.getRuntime() // .exec(new String[] { "which", b }) // .getInputStream().read() != -1) // Runtime.getRuntime().exec( // new String[] { browser = b, url }); // if (browser == null) // throw new Exception(Arrays.toString(browsers)); // } // } catch (Exception e) { // JOptionPane.showMessageDialog(null, // errMsg + "\n" + e.toString()); // } // } // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/TextBox.java // public class TextBox extends JTextPane { // // public TextBox(Color background) { // this.setBackground(background); // this.setAutoscrolls(true); // this.setEditable(false); // } // // public TextBox(String description, Color background) { // this(background); // append(description, Color.black, false); // } // // public String getText() { // return this.getText(); // } // // public void append(String s, Color color, Boolean bold) { // try { // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 10); // StyleConstants.setRightIndent(sa, 10); // StyleConstants.setSpaceAbove(sa, 5); // StyleConstants.setSpaceBelow(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } catch (BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void revalidateAll() { // this.revalidate(); // } // } // Path: gameManager/src/org/dipgame/gameManager/MainPanel.java import java.awt.BorderLayout; import java.awt.Choice; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.StringReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.List; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; import org.dipgame.gameManager.utils.TextBox; FileReader fr = new FileReader(new File("files/availablePlayers.txt")); LineNumberReader ln = new LineNumberReader(fr); String line = ln.readLine(); try{ while (line != null) { line = line.trim(); if(line.length()!=0 && !line.startsWith("//")){ //ignoring empty lines and comments String key = line.substring(0, line.indexOf(';')); String value = line.substring(line.indexOf(';'+1)); loadedPlayers.put(key, value); availablePlayerNames.add(key); } line = ln.readLine(); } }catch (StringIndexOutOfBoundsException e) { alerts.add("Syntax error in file 'files/availablePlayers.txt' line: '"+line+"'."); canRun = false; } } static Component createHeader() { JPanel headerPanel = new JPanel(); headerPanel.setBackground(Utils.CYAN); ImageIcon icon = new ImageIcon("files/img/dipgame.png"); JLabel label = new JLabel(); label.setIcon(icon); label.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) {
BareBonesBrowserLaunch.openURL("http://www.dipgame.org");
AngelaFabregues/dipGame
gameManager/src/org/dipgame/gameManager/MainPanel.java
// Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java // public class BareBonesBrowserLaunch { // // static final String[] browsers = { "google-chrome", "firefox", "opera", // "epiphany", "konqueror", "conkeror", "midori", "kazehakase", // "mozilla" }; // static final String errMsg = "Error attempting to launch web browser"; // // public static void openURL(String url) { // try { // attempt to use Desktop library from JDK 1.6+ // Class<?> d = Class.forName("java.awt.Desktop"); // d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }) // .invoke(d.getDeclaredMethod("getDesktop").invoke(null), // new Object[] { java.net.URI.create(url) }); // // above code mimicks: java.awt.Desktop.getDesktop().browse() // } catch (Exception ignore) { // library not available or failed // String osName = System.getProperty("os.name"); // try { // if (osName.startsWith("Mac OS")) { // Class.forName("com.apple.eio.FileManager") // .getDeclaredMethod("openURL", // new Class[] { String.class }) // .invoke(null, new Object[] { url }); // } else if (osName.startsWith("Windows")) // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + url); // else { // assume Unix or Linux // String browser = null; // for (String b : browsers) // if (browser == null // && Runtime.getRuntime() // .exec(new String[] { "which", b }) // .getInputStream().read() != -1) // Runtime.getRuntime().exec( // new String[] { browser = b, url }); // if (browser == null) // throw new Exception(Arrays.toString(browsers)); // } // } catch (Exception e) { // JOptionPane.showMessageDialog(null, // errMsg + "\n" + e.toString()); // } // } // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/TextBox.java // public class TextBox extends JTextPane { // // public TextBox(Color background) { // this.setBackground(background); // this.setAutoscrolls(true); // this.setEditable(false); // } // // public TextBox(String description, Color background) { // this(background); // append(description, Color.black, false); // } // // public String getText() { // return this.getText(); // } // // public void append(String s, Color color, Boolean bold) { // try { // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 10); // StyleConstants.setRightIndent(sa, 10); // StyleConstants.setSpaceAbove(sa, 5); // StyleConstants.setSpaceBelow(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } catch (BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void revalidateAll() { // this.revalidate(); // } // }
import java.awt.BorderLayout; import java.awt.Choice; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.StringReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.List; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; import org.dipgame.gameManager.utils.TextBox;
public void mouseReleased(MouseEvent e) { BareBonesBrowserLaunch.openURL("http://www.dipgame.org"); } }); headerPanel.add(label, BorderLayout.CENTER); return headerPanel; } static JPanel createFooter(int width) { JPanel footer = new JPanel(); footer.setBackground(Utils.CYAN); JPanel footerContent = new JPanel(); footerContent.setBackground(Utils.BLUE); footerContent.setPreferredSize(new Dimension(width, 20)); footerContent.add(Utils.getText("http://www.dipgame.org", "http://www.dipgame.org")); footer.add(Utils.addBordersToLine(footerContent)); return footer; } static Component createDescription() { JPanel descriptionPanel = new JPanel(); descriptionPanel.setBackground(Utils.CYAN); JPanel descriptionContent = new JPanel(); descriptionContent.setBackground(Utils.BLUE); int size = 200;
// Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java // public class BareBonesBrowserLaunch { // // static final String[] browsers = { "google-chrome", "firefox", "opera", // "epiphany", "konqueror", "conkeror", "midori", "kazehakase", // "mozilla" }; // static final String errMsg = "Error attempting to launch web browser"; // // public static void openURL(String url) { // try { // attempt to use Desktop library from JDK 1.6+ // Class<?> d = Class.forName("java.awt.Desktop"); // d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }) // .invoke(d.getDeclaredMethod("getDesktop").invoke(null), // new Object[] { java.net.URI.create(url) }); // // above code mimicks: java.awt.Desktop.getDesktop().browse() // } catch (Exception ignore) { // library not available or failed // String osName = System.getProperty("os.name"); // try { // if (osName.startsWith("Mac OS")) { // Class.forName("com.apple.eio.FileManager") // .getDeclaredMethod("openURL", // new Class[] { String.class }) // .invoke(null, new Object[] { url }); // } else if (osName.startsWith("Windows")) // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + url); // else { // assume Unix or Linux // String browser = null; // for (String b : browsers) // if (browser == null // && Runtime.getRuntime() // .exec(new String[] { "which", b }) // .getInputStream().read() != -1) // Runtime.getRuntime().exec( // new String[] { browser = b, url }); // if (browser == null) // throw new Exception(Arrays.toString(browsers)); // } // } catch (Exception e) { // JOptionPane.showMessageDialog(null, // errMsg + "\n" + e.toString()); // } // } // } // // } // // Path: gameManager/src/org/dipgame/gameManager/utils/TextBox.java // public class TextBox extends JTextPane { // // public TextBox(Color background) { // this.setBackground(background); // this.setAutoscrolls(true); // this.setEditable(false); // } // // public TextBox(String description, Color background) { // this(background); // append(description, Color.black, false); // } // // public String getText() { // return this.getText(); // } // // public void append(String s, Color color, Boolean bold) { // try { // StyledDocument doc = super.getStyledDocument(); // SimpleAttributeSet sa = new SimpleAttributeSet(); // StyleConstants.setAlignment(sa, StyleConstants.ALIGN_JUSTIFIED); // StyleConstants.setLeftIndent(sa, 10); // StyleConstants.setRightIndent(sa, 10); // StyleConstants.setSpaceAbove(sa, 5); // StyleConstants.setSpaceBelow(sa, 5); // Style style = doc.addStyle("name", null); // StyleConstants.setForeground(style, color); // StyleConstants.setBold(style, bold); // doc.insertString(doc.getLength(), s, style); // doc.setParagraphAttributes(0, doc.getLength(), sa, false); // } catch (BadLocationException exc) { // exc.printStackTrace(); // } // } // // public void revalidateAll() { // this.revalidate(); // } // } // Path: gameManager/src/org/dipgame/gameManager/MainPanel.java import java.awt.BorderLayout; import java.awt.Choice; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.StringReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.List; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; import org.dipgame.gameManager.utils.TextBox; public void mouseReleased(MouseEvent e) { BareBonesBrowserLaunch.openURL("http://www.dipgame.org"); } }); headerPanel.add(label, BorderLayout.CENTER); return headerPanel; } static JPanel createFooter(int width) { JPanel footer = new JPanel(); footer.setBackground(Utils.CYAN); JPanel footerContent = new JPanel(); footerContent.setBackground(Utils.BLUE); footerContent.setPreferredSize(new Dimension(width, 20)); footerContent.add(Utils.getText("http://www.dipgame.org", "http://www.dipgame.org")); footer.add(Utils.addBordersToLine(footerContent)); return footer; } static Component createDescription() { JPanel descriptionPanel = new JPanel(); descriptionPanel.setBackground(Utils.CYAN); JPanel descriptionContent = new JPanel(); descriptionContent.setBackground(Utils.BLUE); int size = 200;
TextBox text = new TextBox(Utils.BLUE);
Fedict/commons-eid
commons-eid-tests/src/test/java/be/bosa/commons/eid/client/tests/integration/TestBeIDCardListener.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/FileType.java // public enum FileType { // Identity(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x31}, 179), // IdentitySignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x32}, 128), // Address(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x33}, 121), // AddressSignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x34}, 128), // Photo(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x35}, 3064), // AuthentificationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x38}, 1061, 0x82), // NonRepudiationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x39}, 1082, 0x83), // CACertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3A}, 1044), // RootCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3B}, 914), // RRNCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3C}, 820); // // private final byte[] fileId; // private final byte keyId; // private final int estimatedMaxSize; // // FileType(byte[] fileId, int estimatedMaxSize) { // this.fileId = fileId; // this.keyId = -1; // this.estimatedMaxSize = estimatedMaxSize; // } // // FileType(byte[] fileId, int estimatedMaxSize, int keyId) { // this.fileId = fileId; // this.keyId = (byte) keyId; // this.estimatedMaxSize = estimatedMaxSize; // } // // public byte[] getFileId() { // return fileId; // } // // public byte getKeyId() { // return keyId; // } // // public boolean isCertificateUserCanSignWith() { // return keyId != -1; // } // // public boolean chainIncludesCitizenCA() { // return isCertificateUserCanSignWith(); // } // // public int getEstimatedMaxSize() { // return estimatedMaxSize; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardListener.java // public interface BeIDCardListener { // // void notifyReadProgress(FileType fileType, int offset, int estimatedMaxSize); // // void notifySigningBegin(FileType fileType); // // void notifySigningEnd(FileType fileType); // }
import be.bosa.commons.eid.client.FileType; import be.bosa.commons.eid.client.event.BeIDCardListener;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.tests.integration; public class TestBeIDCardListener implements BeIDCardListener { @Override
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/FileType.java // public enum FileType { // Identity(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x31}, 179), // IdentitySignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x32}, 128), // Address(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x33}, 121), // AddressSignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x34}, 128), // Photo(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x35}, 3064), // AuthentificationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x38}, 1061, 0x82), // NonRepudiationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x39}, 1082, 0x83), // CACertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3A}, 1044), // RootCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3B}, 914), // RRNCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3C}, 820); // // private final byte[] fileId; // private final byte keyId; // private final int estimatedMaxSize; // // FileType(byte[] fileId, int estimatedMaxSize) { // this.fileId = fileId; // this.keyId = -1; // this.estimatedMaxSize = estimatedMaxSize; // } // // FileType(byte[] fileId, int estimatedMaxSize, int keyId) { // this.fileId = fileId; // this.keyId = (byte) keyId; // this.estimatedMaxSize = estimatedMaxSize; // } // // public byte[] getFileId() { // return fileId; // } // // public byte getKeyId() { // return keyId; // } // // public boolean isCertificateUserCanSignWith() { // return keyId != -1; // } // // public boolean chainIncludesCitizenCA() { // return isCertificateUserCanSignWith(); // } // // public int getEstimatedMaxSize() { // return estimatedMaxSize; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardListener.java // public interface BeIDCardListener { // // void notifyReadProgress(FileType fileType, int offset, int estimatedMaxSize); // // void notifySigningBegin(FileType fileType); // // void notifySigningEnd(FileType fileType); // } // Path: commons-eid-tests/src/test/java/be/bosa/commons/eid/client/tests/integration/TestBeIDCardListener.java import be.bosa.commons.eid.client.FileType; import be.bosa.commons.eid.client.event.BeIDCardListener; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.tests.integration; public class TestBeIDCardListener implements BeIDCardListener { @Override
public void notifyReadProgress(FileType fileType, int offset, int estimatedMaxSize) {
Fedict/commons-eid
commons-eid-tests/src/test/java/be/bosa/commons/eid/client/tests/integration/simulation/SimulatedBeIDCard.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/FileType.java // public enum FileType { // Identity(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x31}, 179), // IdentitySignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x32}, 128), // Address(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x33}, 121), // AddressSignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x34}, 128), // Photo(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x35}, 3064), // AuthentificationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x38}, 1061, 0x82), // NonRepudiationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x39}, 1082, 0x83), // CACertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3A}, 1044), // RootCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3B}, 914), // RRNCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3C}, 820); // // private final byte[] fileId; // private final byte keyId; // private final int estimatedMaxSize; // // FileType(byte[] fileId, int estimatedMaxSize) { // this.fileId = fileId; // this.keyId = -1; // this.estimatedMaxSize = estimatedMaxSize; // } // // FileType(byte[] fileId, int estimatedMaxSize, int keyId) { // this.fileId = fileId; // this.keyId = (byte) keyId; // this.estimatedMaxSize = estimatedMaxSize; // } // // public byte[] getFileId() { // return fileId; // } // // public byte getKeyId() { // return keyId; // } // // public boolean isCertificateUserCanSignWith() { // return keyId != -1; // } // // public boolean chainIncludesCitizenCA() { // return isCertificateUserCanSignWith(); // } // // public int getEstimatedMaxSize() { // return estimatedMaxSize; // } // }
import be.bosa.commons.eid.client.FileType; import org.apache.commons.io.IOUtils; import javax.smartcardio.ATR; import java.io.IOException; import java.io.InputStream;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.tests.integration.simulation; public class SimulatedBeIDCard extends SimulatedCard { public SimulatedBeIDCard(String profile) { super(null); InputStream atrInputStream = SimulatedBeIDCard.class.getResourceAsStream("/" + profile + "_ATR.bin"); try { setATR(new ATR(IOUtils.toByteArray(atrInputStream))); } catch (IOException ioex) { // missing _ATR file, set ATR from testcard setATR(new ATR(new byte[]{0x3b, (byte) 0x98, 0x13, 0x40, 0x0a, (byte) 0xa5, 0x03, 0x01, 0x01, 0x01, (byte) 0xad, 0x13, 0x11})); } setFilesFromProfile(profile); } public SimulatedBeIDCard(ATR atr) { super(atr); } public void setFilesFromProfile(String profile) {
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/FileType.java // public enum FileType { // Identity(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x31}, 179), // IdentitySignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x32}, 128), // Address(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x33}, 121), // AddressSignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x34}, 128), // Photo(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x35}, 3064), // AuthentificationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x38}, 1061, 0x82), // NonRepudiationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x39}, 1082, 0x83), // CACertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3A}, 1044), // RootCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3B}, 914), // RRNCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3C}, 820); // // private final byte[] fileId; // private final byte keyId; // private final int estimatedMaxSize; // // FileType(byte[] fileId, int estimatedMaxSize) { // this.fileId = fileId; // this.keyId = -1; // this.estimatedMaxSize = estimatedMaxSize; // } // // FileType(byte[] fileId, int estimatedMaxSize, int keyId) { // this.fileId = fileId; // this.keyId = (byte) keyId; // this.estimatedMaxSize = estimatedMaxSize; // } // // public byte[] getFileId() { // return fileId; // } // // public byte getKeyId() { // return keyId; // } // // public boolean isCertificateUserCanSignWith() { // return keyId != -1; // } // // public boolean chainIncludesCitizenCA() { // return isCertificateUserCanSignWith(); // } // // public int getEstimatedMaxSize() { // return estimatedMaxSize; // } // } // Path: commons-eid-tests/src/test/java/be/bosa/commons/eid/client/tests/integration/simulation/SimulatedBeIDCard.java import be.bosa.commons.eid.client.FileType; import org.apache.commons.io.IOUtils; import javax.smartcardio.ATR; import java.io.IOException; import java.io.InputStream; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.tests.integration.simulation; public class SimulatedBeIDCard extends SimulatedCard { public SimulatedBeIDCard(String profile) { super(null); InputStream atrInputStream = SimulatedBeIDCard.class.getResourceAsStream("/" + profile + "_ATR.bin"); try { setATR(new ATR(IOUtils.toByteArray(atrInputStream))); } catch (IOException ioex) { // missing _ATR file, set ATR from testcard setATR(new ATR(new byte[]{0x3b, (byte) 0x98, 0x13, 0x40, 0x0a, (byte) 0xa5, 0x03, 0x01, 0x01, 0x01, (byte) 0xad, 0x13, 0x11})); } setFilesFromProfile(profile); } public SimulatedBeIDCard(ATR atr) { super(atr); } public void setFilesFromProfile(String profile) {
for (FileType type : FileType.values()) {
Fedict/commons-eid
commons-eid-consumer/src/main/java/be/bosa/commons/eid/consumer/BeIDIntegrity.java
// Path: commons-eid-consumer/src/main/java/be/bosa/commons/eid/consumer/tlv/TlvParser.java // public class TlvParser { // // private static final Log LOG = LogFactory.getLog(TlvParser.class); // // private TlvParser() { // } // // /** // * Parses the given file using the meta-data annotations within the tlvClass // * parameter. // */ // public static <T> T parse(byte[] file, Class<T> tlvClass) { // try { // return parseThrowing(file, tlvClass); // } catch (Exception ex) { // throw new RuntimeException("error parsing file: " + tlvClass.getName(), ex); // } // } // // private static byte[] copy(byte[] source, int idx, int count) { // byte[] result = new byte[count]; // System.arraycopy(source, idx, result, 0, count); // return result; // } // // private static <T> T parseThrowing(byte[] file, Class<T> tlvClass) // throws InstantiationException, IllegalAccessException, DataConvertorException, UnsupportedEncodingException { // Field[] fields = tlvClass.getDeclaredFields(); // Map<Integer, Field> tlvFields = new HashMap<>(); // T tlvObject = tlvClass.newInstance(); // // for (Field field : fields) { // TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class); // if (tlvFieldAnnotation != null) { // int tagId = tlvFieldAnnotation.value(); // if (tlvFields.containsKey(tagId)) { // throw new IllegalArgumentException("TLV field duplicate: " + tagId); // } // tlvFields.put(tagId, field); // } // OriginalData originalDataAnnotation = field.getAnnotation(OriginalData.class); // if (originalDataAnnotation != null) { // field.setAccessible(true); // field.set(tlvObject, file); // } // } // // int idx = 0; // while (idx < file.length - 1) { // int tag = file[idx]; // idx++; // byte lengthByte = file[idx]; // int length = lengthByte & 0x7f; // while ((lengthByte & 0x80) == 0x80) { // idx++; // lengthByte = file[idx]; // length = (length << 7) + (lengthByte & 0x7f); // } // idx++; // if (0 == tag) { // idx += length; // continue; // } // if (tlvFields.containsKey(tag)) { // Field tlvField = tlvFields.get(tag); // Class<?> tlvType = tlvField.getType(); // ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class); // byte[] tlvValue = copy(file, idx, length); // Object fieldValue; // if (null != convertDataAnnotation) { // Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value(); // DataConvertor<?> dataConvertor = dataConvertorClass.newInstance(); // fieldValue = dataConvertor.convert(tlvValue); // } else if (String.class == tlvType) { // fieldValue = new String(tlvValue, "UTF-8"); // } else if (Boolean.TYPE == tlvType) { // fieldValue = true; // } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) { // fieldValue = tlvValue; // } else { // throw new IllegalArgumentException("unsupported field type: " + tlvType.getName()); // } // if (tlvField.get(tlvObject) != null && !tlvField.getType().isPrimitive()) { // throw new RuntimeException("field was already set: " + tlvField.getName()); // } // tlvField.setAccessible(true); // tlvField.set(tlvObject, fieldValue); // } else { // LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length); // } // idx += length; // } // return tlvObject; // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import be.bosa.commons.eid.consumer.tlv.TlvParser; import java.io.ByteArrayInputStream; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays;
} /** * Gives back a parsed identity file after integrity verification. */ public Identity getVerifiedIdentity(byte[] identityFile, byte[] identitySignatureFile, X509Certificate rrnCertificate) throws NoSuchAlgorithmException { return getVerifiedIdentity(identityFile, identitySignatureFile, null, rrnCertificate); } /** * Gives back a parsed identity file after integrity verification including * the eID photo. */ public Identity getVerifiedIdentity(byte[] identityFile, byte[] identitySignatureFile, byte[] photo, X509Certificate rrnCertificate) throws NoSuchAlgorithmException { PublicKey publicKey = rrnCertificate.getPublicKey(); boolean result; try { result = verifySignature(rrnCertificate.getSigAlgName(), identitySignatureFile, publicKey, identityFile); if (!result) { throw new SecurityException("signature integrity error"); } } catch (Exception ex) { throw new SecurityException( "identity signature verification error: " + ex.getMessage(), ex); }
// Path: commons-eid-consumer/src/main/java/be/bosa/commons/eid/consumer/tlv/TlvParser.java // public class TlvParser { // // private static final Log LOG = LogFactory.getLog(TlvParser.class); // // private TlvParser() { // } // // /** // * Parses the given file using the meta-data annotations within the tlvClass // * parameter. // */ // public static <T> T parse(byte[] file, Class<T> tlvClass) { // try { // return parseThrowing(file, tlvClass); // } catch (Exception ex) { // throw new RuntimeException("error parsing file: " + tlvClass.getName(), ex); // } // } // // private static byte[] copy(byte[] source, int idx, int count) { // byte[] result = new byte[count]; // System.arraycopy(source, idx, result, 0, count); // return result; // } // // private static <T> T parseThrowing(byte[] file, Class<T> tlvClass) // throws InstantiationException, IllegalAccessException, DataConvertorException, UnsupportedEncodingException { // Field[] fields = tlvClass.getDeclaredFields(); // Map<Integer, Field> tlvFields = new HashMap<>(); // T tlvObject = tlvClass.newInstance(); // // for (Field field : fields) { // TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class); // if (tlvFieldAnnotation != null) { // int tagId = tlvFieldAnnotation.value(); // if (tlvFields.containsKey(tagId)) { // throw new IllegalArgumentException("TLV field duplicate: " + tagId); // } // tlvFields.put(tagId, field); // } // OriginalData originalDataAnnotation = field.getAnnotation(OriginalData.class); // if (originalDataAnnotation != null) { // field.setAccessible(true); // field.set(tlvObject, file); // } // } // // int idx = 0; // while (idx < file.length - 1) { // int tag = file[idx]; // idx++; // byte lengthByte = file[idx]; // int length = lengthByte & 0x7f; // while ((lengthByte & 0x80) == 0x80) { // idx++; // lengthByte = file[idx]; // length = (length << 7) + (lengthByte & 0x7f); // } // idx++; // if (0 == tag) { // idx += length; // continue; // } // if (tlvFields.containsKey(tag)) { // Field tlvField = tlvFields.get(tag); // Class<?> tlvType = tlvField.getType(); // ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class); // byte[] tlvValue = copy(file, idx, length); // Object fieldValue; // if (null != convertDataAnnotation) { // Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value(); // DataConvertor<?> dataConvertor = dataConvertorClass.newInstance(); // fieldValue = dataConvertor.convert(tlvValue); // } else if (String.class == tlvType) { // fieldValue = new String(tlvValue, "UTF-8"); // } else if (Boolean.TYPE == tlvType) { // fieldValue = true; // } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) { // fieldValue = tlvValue; // } else { // throw new IllegalArgumentException("unsupported field type: " + tlvType.getName()); // } // if (tlvField.get(tlvObject) != null && !tlvField.getType().isPrimitive()) { // throw new RuntimeException("field was already set: " + tlvField.getName()); // } // tlvField.setAccessible(true); // tlvField.set(tlvObject, fieldValue); // } else { // LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length); // } // idx += length; // } // return tlvObject; // } // } // Path: commons-eid-consumer/src/main/java/be/bosa/commons/eid/consumer/BeIDIntegrity.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import be.bosa.commons.eid.consumer.tlv.TlvParser; import java.io.ByteArrayInputStream; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; } /** * Gives back a parsed identity file after integrity verification. */ public Identity getVerifiedIdentity(byte[] identityFile, byte[] identitySignatureFile, X509Certificate rrnCertificate) throws NoSuchAlgorithmException { return getVerifiedIdentity(identityFile, identitySignatureFile, null, rrnCertificate); } /** * Gives back a parsed identity file after integrity verification including * the eID photo. */ public Identity getVerifiedIdentity(byte[] identityFile, byte[] identitySignatureFile, byte[] photo, X509Certificate rrnCertificate) throws NoSuchAlgorithmException { PublicKey publicKey = rrnCertificate.getPublicKey(); boolean result; try { result = verifySignature(rrnCertificate.getSigAlgName(), identitySignatureFile, publicKey, identityFile); if (!result) { throw new SecurityException("signature integrity error"); } } catch (Exception ex) { throw new SecurityException( "identity signature verification error: " + ex.getMessage(), ex); }
Identity identity = TlvParser.parse(identityFile, Identity.class);
Fedict/commons-eid
commons-eid-consumer/src/test/java/be/bosa/commons/eid/consumer/ByteArrayParserTest.java
// Path: commons-eid-consumer/src/main/java/be/bosa/commons/eid/consumer/tlv/ByteArrayParser.java // public class ByteArrayParser { // // private ByteArrayParser() { // } // // /** // * Parses the given file using the meta-data annotations within the baClass // * parameter. // */ // public static <T> T parse(byte[] file, Class<T> baClass) { // T t; // try { // t = parseThrowing(file, baClass); // } catch (Exception ex) { // throw new RuntimeException("error parsing file: " + baClass.getName(), ex); // } // return t; // } // // private static <T> T parseThrowing(byte[] data, Class<T> baClass) throws InstantiationException, IllegalAccessException { // Field[] fields = baClass.getDeclaredFields(); // // T baObject = baClass.newInstance(); // for (Field field : fields) { // ByteArrayField baFieldAnnotation = field.getAnnotation(ByteArrayField.class); // if (baFieldAnnotation != null) { // int offset = baFieldAnnotation.offset(); // int length = baFieldAnnotation.length(); // if (field.getType().isArray() && field.getType().getComponentType().equals(byte.class)) { // byte[] byteArray = new byte[length]; // System.arraycopy(data, offset, byteArray, 0, length); // field.set(baObject, byteArray); // } else if (field.getType().equals(int.class)) { // ByteBuffer buff = ByteBuffer.wrap(data); // switch (length) { // case 1 : // field.set(baObject, (int) buff.get(offset) & 0xff); // break; // // case 2 : // field.set(baObject, (int) buff.getShort(offset) & 0xffff); // break; // } // } // } // } // // return baObject; // } // }
import be.bosa.commons.eid.consumer.tlv.ByteArrayParser; import org.junit.Test; import java.math.BigInteger; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.consumer; public class ByteArrayParserTest { @Test public void testByteArrayParser() { byte[] cardDataBytes = new BigInteger("534c494e33660013930d2061c018063fd0004801011100020001010f", 16).toByteArray(); byte[] serialExpected = new byte[16]; byte[] chipSerialExpected = new byte[12]; System.arraycopy(cardDataBytes, 0, serialExpected, 0, 16); System.arraycopy(cardDataBytes, 4, chipSerialExpected, 0, 12);
// Path: commons-eid-consumer/src/main/java/be/bosa/commons/eid/consumer/tlv/ByteArrayParser.java // public class ByteArrayParser { // // private ByteArrayParser() { // } // // /** // * Parses the given file using the meta-data annotations within the baClass // * parameter. // */ // public static <T> T parse(byte[] file, Class<T> baClass) { // T t; // try { // t = parseThrowing(file, baClass); // } catch (Exception ex) { // throw new RuntimeException("error parsing file: " + baClass.getName(), ex); // } // return t; // } // // private static <T> T parseThrowing(byte[] data, Class<T> baClass) throws InstantiationException, IllegalAccessException { // Field[] fields = baClass.getDeclaredFields(); // // T baObject = baClass.newInstance(); // for (Field field : fields) { // ByteArrayField baFieldAnnotation = field.getAnnotation(ByteArrayField.class); // if (baFieldAnnotation != null) { // int offset = baFieldAnnotation.offset(); // int length = baFieldAnnotation.length(); // if (field.getType().isArray() && field.getType().getComponentType().equals(byte.class)) { // byte[] byteArray = new byte[length]; // System.arraycopy(data, offset, byteArray, 0, length); // field.set(baObject, byteArray); // } else if (field.getType().equals(int.class)) { // ByteBuffer buff = ByteBuffer.wrap(data); // switch (length) { // case 1 : // field.set(baObject, (int) buff.get(offset) & 0xff); // break; // // case 2 : // field.set(baObject, (int) buff.getShort(offset) & 0xffff); // break; // } // } // } // } // // return baObject; // } // } // Path: commons-eid-consumer/src/test/java/be/bosa/commons/eid/consumer/ByteArrayParserTest.java import be.bosa.commons.eid.consumer.tlv.ByteArrayParser; import org.junit.Test; import java.math.BigInteger; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.consumer; public class ByteArrayParserTest { @Test public void testByteArrayParser() { byte[] cardDataBytes = new BigInteger("534c494e33660013930d2061c018063fd0004801011100020001010f", 16).toByteArray(); byte[] serialExpected = new byte[16]; byte[] chipSerialExpected = new byte[12]; System.arraycopy(cardDataBytes, 0, serialExpected, 0, 16); System.arraycopy(cardDataBytes, 4, chipSerialExpected, 0, 12);
CardData cardData = ByteArrayParser.parse(cardDataBytes, CardData.class);
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LibJ2PCSCGNULinuxFix.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import java.io.File; import be.bosa.commons.eid.client.spi.Logger;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ /* * author Frank Marien */ package be.bosa.commons.eid.client.impl; /** * Encapsulate fixes regarding the dynamic loading of the pcsclite library on * GNU/Linux Systems. statically call LibJ2PCSCGNULinuxFix.fixNativeLibrary() * before using a TerminalFactory. * * @author Frank Cornelis * @author Frank Marien */ public class LibJ2PCSCGNULinuxFix { private static final int PCSC_LIBRARY_VERSION = 1; private static final String SMARTCARDIO_LIBRARY_PROPERTY = "sun.security.smartcardio.library"; private static final String LIBRARY_PATH_PROPERTY = "java.library.path"; private static final String GNULINUX_OS_PROPERTY_PREFIX = "Linux"; private static final String PCSC_LIBRARY_NAME = "pcsclite"; private static final String UBUNTU_MULTILIB_32_SUFFIX = "i386-linux-gnu"; private static final String UBUNTU_MULTILIB_64_SUFFIX = "x86_64-linux-gnu"; private static final String JRE_BITNESS_PROPERTY = "os.arch"; private static final String OS_NAME_PROPERTY = "os.name"; private static final String JRE_BITNESS_32_VALUE = "i386"; private static final String JRE_BITNESS_64_VALUE = "amd64"; enum UbuntuBitness { NA, PURE32, PURE64, MULTILIB } private LibJ2PCSCGNULinuxFix() { super(); } /** * Make sure libpcsclite is found. The libj2pcsc.so from the JRE attempts to * dlopen using the linker name "libpcsclite.so" instead of the appropriate * "libpcsclite.so.1". This causes libpcsclite not to be found on GNU/Linux * distributions that don't have the libpcsclite.so symbolic link. This * method finds the library and forces the JRE to use it instead of * attempting to locate it by itself. See also: * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=529339 * <br> * Does nothing if not on a GNU/Linux system */ public static void fixNativeLibrary() { fixNativeLibrary(new VoidLogger()); }
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LibJ2PCSCGNULinuxFix.java import java.io.File; import be.bosa.commons.eid.client.spi.Logger; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ /* * author Frank Marien */ package be.bosa.commons.eid.client.impl; /** * Encapsulate fixes regarding the dynamic loading of the pcsclite library on * GNU/Linux Systems. statically call LibJ2PCSCGNULinuxFix.fixNativeLibrary() * before using a TerminalFactory. * * @author Frank Cornelis * @author Frank Marien */ public class LibJ2PCSCGNULinuxFix { private static final int PCSC_LIBRARY_VERSION = 1; private static final String SMARTCARDIO_LIBRARY_PROPERTY = "sun.security.smartcardio.library"; private static final String LIBRARY_PATH_PROPERTY = "java.library.path"; private static final String GNULINUX_OS_PROPERTY_PREFIX = "Linux"; private static final String PCSC_LIBRARY_NAME = "pcsclite"; private static final String UBUNTU_MULTILIB_32_SUFFIX = "i386-linux-gnu"; private static final String UBUNTU_MULTILIB_64_SUFFIX = "x86_64-linux-gnu"; private static final String JRE_BITNESS_PROPERTY = "os.arch"; private static final String OS_NAME_PROPERTY = "os.name"; private static final String JRE_BITNESS_32_VALUE = "i386"; private static final String JRE_BITNESS_64_VALUE = "amd64"; enum UbuntuBitness { NA, PURE32, PURE64, MULTILIB } private LibJ2PCSCGNULinuxFix() { super(); } /** * Make sure libpcsclite is found. The libj2pcsc.so from the JRE attempts to * dlopen using the linker name "libpcsclite.so" instead of the appropriate * "libpcsclite.so.1". This causes libpcsclite not to be found on GNU/Linux * distributions that don't have the libpcsclite.so symbolic link. This * method finds the library and forces the JRE to use it instead of * attempting to locate it by itself. See also: * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=529339 * <br> * Does nothing if not on a GNU/Linux system */ public static void fixNativeLibrary() { fixNativeLibrary(new VoidLogger()); }
public static void fixNativeLibrary(Logger logger) {
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardAdapter.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/FileType.java // public enum FileType { // Identity(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x31}, 179), // IdentitySignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x32}, 128), // Address(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x33}, 121), // AddressSignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x34}, 128), // Photo(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x35}, 3064), // AuthentificationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x38}, 1061, 0x82), // NonRepudiationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x39}, 1082, 0x83), // CACertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3A}, 1044), // RootCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3B}, 914), // RRNCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3C}, 820); // // private final byte[] fileId; // private final byte keyId; // private final int estimatedMaxSize; // // FileType(byte[] fileId, int estimatedMaxSize) { // this.fileId = fileId; // this.keyId = -1; // this.estimatedMaxSize = estimatedMaxSize; // } // // FileType(byte[] fileId, int estimatedMaxSize, int keyId) { // this.fileId = fileId; // this.keyId = (byte) keyId; // this.estimatedMaxSize = estimatedMaxSize; // } // // public byte[] getFileId() { // return fileId; // } // // public byte getKeyId() { // return keyId; // } // // public boolean isCertificateUserCanSignWith() { // return keyId != -1; // } // // public boolean chainIncludesCitizenCA() { // return isCertificateUserCanSignWith(); // } // // public int getEstimatedMaxSize() { // return estimatedMaxSize; // } // }
import be.bosa.commons.eid.client.FileType;
/* * Commons eID Project. * Copyright (C) 2014 e-Contract.be BVBA. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.event; public class BeIDCardAdapter implements BeIDCardListener { @Override
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/FileType.java // public enum FileType { // Identity(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x31}, 179), // IdentitySignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x32}, 128), // Address(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x33}, 121), // AddressSignature(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x34}, 128), // Photo(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x01, 0x40, 0x35}, 3064), // AuthentificationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x38}, 1061, 0x82), // NonRepudiationCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x39}, 1082, 0x83), // CACertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3A}, 1044), // RootCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3B}, 914), // RRNCertificate(new byte[]{0x3F, 0x00, (byte) 0xDF, 0x00, 0x50, 0x3C}, 820); // // private final byte[] fileId; // private final byte keyId; // private final int estimatedMaxSize; // // FileType(byte[] fileId, int estimatedMaxSize) { // this.fileId = fileId; // this.keyId = -1; // this.estimatedMaxSize = estimatedMaxSize; // } // // FileType(byte[] fileId, int estimatedMaxSize, int keyId) { // this.fileId = fileId; // this.keyId = (byte) keyId; // this.estimatedMaxSize = estimatedMaxSize; // } // // public byte[] getFileId() { // return fileId; // } // // public byte getKeyId() { // return keyId; // } // // public boolean isCertificateUserCanSignWith() { // return keyId != -1; // } // // public boolean chainIncludesCitizenCA() { // return isCertificateUserCanSignWith(); // } // // public int getEstimatedMaxSize() { // return estimatedMaxSize; // } // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardAdapter.java import be.bosa.commons.eid.client.FileType; /* * Commons eID Project. * Copyright (C) 2014 e-Contract.be BVBA. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.event; public class BeIDCardAdapter implements BeIDCardListener { @Override
public void notifyReadProgress(FileType fileType, int offset,
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/BeIDCardUI.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CancelledException.java // public class CancelledException extends BeIDCardsException { // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/PINPurpose.java // public enum PINPurpose { // PINTest("test"), // AuthenticationSignature("authentication"), // NonRepudiationSignature("nonrepudiation"); // // private final String type; // // PINPurpose(final String type) { // this.type = type; // } // // public String getType() { // return this.type; // } // // /** // * Determine the likely reason for a PIN request by checking the certificate // * chain involved. // * // * @param fileType the File on the BeID that is involved in the operation // * @return the PIN Purpose associated with this type of file // */ // public static PINPurpose fromFileType(final FileType fileType) { // switch (fileType) { // case AuthentificationCertificate: // return AuthenticationSignature; // case NonRepudiationCertificate: // return NonRepudiationSignature; // default: // return PINTest; // } // } // }
import be.bosa.commons.eid.client.CancelledException; import be.bosa.commons.eid.client.PINPurpose; import java.util.Locale;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.spi; /** * Implement a BeIDCardUI to interact with the user from a BeIDCard instance. * * @author Frank Marien */ public interface BeIDCardUI { /** * set Locale for subsequent operations. Implementations MUST ensure that * after this call, any of the other methods for the same instance respect * the locale set here. Implementations MAY choose to update any interface * elements already facing the user at time of call, but this is not * required. */ void setLocale(Locale newLocale); /** * get the Locale currently set. * * @return the current Locale for this UI */ Locale getLocale(); /** * get PIN from the user * * @param triesLeft the number of attempts left before the PIN is blocked. * @param type the reason why the PIN code is requested * @return the PIN code. * @throws CancelledException thrown in case the user cancels the PIN entry. */
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CancelledException.java // public class CancelledException extends BeIDCardsException { // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/PINPurpose.java // public enum PINPurpose { // PINTest("test"), // AuthenticationSignature("authentication"), // NonRepudiationSignature("nonrepudiation"); // // private final String type; // // PINPurpose(final String type) { // this.type = type; // } // // public String getType() { // return this.type; // } // // /** // * Determine the likely reason for a PIN request by checking the certificate // * chain involved. // * // * @param fileType the File on the BeID that is involved in the operation // * @return the PIN Purpose associated with this type of file // */ // public static PINPurpose fromFileType(final FileType fileType) { // switch (fileType) { // case AuthentificationCertificate: // return AuthenticationSignature; // case NonRepudiationCertificate: // return NonRepudiationSignature; // default: // return PINTest; // } // } // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/BeIDCardUI.java import be.bosa.commons.eid.client.CancelledException; import be.bosa.commons.eid.client.PINPurpose; import java.util.Locale; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.spi; /** * Implement a BeIDCardUI to interact with the user from a BeIDCard instance. * * @author Frank Marien */ public interface BeIDCardUI { /** * set Locale for subsequent operations. Implementations MUST ensure that * after this call, any of the other methods for the same instance respect * the locale set here. Implementations MAY choose to update any interface * elements already facing the user at time of call, but this is not * required. */ void setLocale(Locale newLocale); /** * get the Locale currently set. * * @return the current Locale for this UI */ Locale getLocale(); /** * get PIN from the user * * @param triesLeft the number of attempts left before the PIN is blocked. * @param type the reason why the PIN code is requested * @return the PIN code. * @throws CancelledException thrown in case the user cancels the PIN entry. */
char[] obtainPIN(int triesLeft, PINPurpose type) throws CancelledException;
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/BeIDCardUI.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CancelledException.java // public class CancelledException extends BeIDCardsException { // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/PINPurpose.java // public enum PINPurpose { // PINTest("test"), // AuthenticationSignature("authentication"), // NonRepudiationSignature("nonrepudiation"); // // private final String type; // // PINPurpose(final String type) { // this.type = type; // } // // public String getType() { // return this.type; // } // // /** // * Determine the likely reason for a PIN request by checking the certificate // * chain involved. // * // * @param fileType the File on the BeID that is involved in the operation // * @return the PIN Purpose associated with this type of file // */ // public static PINPurpose fromFileType(final FileType fileType) { // switch (fileType) { // case AuthentificationCertificate: // return AuthenticationSignature; // case NonRepudiationCertificate: // return NonRepudiationSignature; // default: // return PINTest; // } // } // }
import be.bosa.commons.eid.client.CancelledException; import be.bosa.commons.eid.client.PINPurpose; import java.util.Locale;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.spi; /** * Implement a BeIDCardUI to interact with the user from a BeIDCard instance. * * @author Frank Marien */ public interface BeIDCardUI { /** * set Locale for subsequent operations. Implementations MUST ensure that * after this call, any of the other methods for the same instance respect * the locale set here. Implementations MAY choose to update any interface * elements already facing the user at time of call, but this is not * required. */ void setLocale(Locale newLocale); /** * get the Locale currently set. * * @return the current Locale for this UI */ Locale getLocale(); /** * get PIN from the user * * @param triesLeft the number of attempts left before the PIN is blocked. * @param type the reason why the PIN code is requested * @return the PIN code. * @throws CancelledException thrown in case the user cancels the PIN entry. */
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CancelledException.java // public class CancelledException extends BeIDCardsException { // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/PINPurpose.java // public enum PINPurpose { // PINTest("test"), // AuthenticationSignature("authentication"), // NonRepudiationSignature("nonrepudiation"); // // private final String type; // // PINPurpose(final String type) { // this.type = type; // } // // public String getType() { // return this.type; // } // // /** // * Determine the likely reason for a PIN request by checking the certificate // * chain involved. // * // * @param fileType the File on the BeID that is involved in the operation // * @return the PIN Purpose associated with this type of file // */ // public static PINPurpose fromFileType(final FileType fileType) { // switch (fileType) { // case AuthentificationCertificate: // return AuthenticationSignature; // case NonRepudiationCertificate: // return NonRepudiationSignature; // default: // return PINTest; // } // } // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/BeIDCardUI.java import be.bosa.commons.eid.client.CancelledException; import be.bosa.commons.eid.client.PINPurpose; import java.util.Locale; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.spi; /** * Implement a BeIDCardUI to interact with the user from a BeIDCard instance. * * @author Frank Marien */ public interface BeIDCardUI { /** * set Locale for subsequent operations. Implementations MUST ensure that * after this call, any of the other methods for the same instance respect * the locale set here. Implementations MAY choose to update any interface * elements already facing the user at time of call, but this is not * required. */ void setLocale(Locale newLocale); /** * get the Locale currently set. * * @return the current Locale for this UI */ Locale getLocale(); /** * get PIN from the user * * @param triesLeft the number of attempts left before the PIN is blocked. * @param type the reason why the PIN code is requested * @return the PIN code. * @throws CancelledException thrown in case the user cancels the PIN entry. */
char[] obtainPIN(int triesLeft, PINPurpose type) throws CancelledException;
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/CardTerminalsProxy.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import org.apache.commons.lang3.exception.ExceptionUtils; import be.bosa.commons.eid.client.spi.Logger; import static java.util.Objects.requireNonNull; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Optional; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import javax.smartcardio.CardTerminals; import javax.smartcardio.TerminalFactory;
/* * Commons eID Project. * Copyright (C) 2014 - 2019 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.impl; public class CardTerminalsProxy extends CardTerminals { private final CardTerminals delegate;
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/CardTerminalsProxy.java import org.apache.commons.lang3.exception.ExceptionUtils; import be.bosa.commons.eid.client.spi.Logger; import static java.util.Objects.requireNonNull; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Optional; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import javax.smartcardio.CardTerminals; import javax.smartcardio.TerminalFactory; /* * Commons eID Project. * Copyright (C) 2014 - 2019 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.impl; public class CardTerminalsProxy extends CardTerminals { private final CardTerminals delegate;
private final Logger logger;
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/BeIDCardUIAdapter.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/PINPurpose.java // public enum PINPurpose { // PINTest("test"), // AuthenticationSignature("authentication"), // NonRepudiationSignature("nonrepudiation"); // // private final String type; // // PINPurpose(final String type) { // this.type = type; // } // // public String getType() { // return this.type; // } // // /** // * Determine the likely reason for a PIN request by checking the certificate // * chain involved. // * // * @param fileType the File on the BeID that is involved in the operation // * @return the PIN Purpose associated with this type of file // */ // public static PINPurpose fromFileType(final FileType fileType) { // switch (fileType) { // case AuthentificationCertificate: // return AuthenticationSignature; // case NonRepudiationCertificate: // return NonRepudiationSignature; // default: // return PINTest; // } // } // }
import java.util.Locale; import be.bosa.commons.eid.client.PINPurpose;
/* * Commons eID Project. * Copyright (C) 2012-2013 FedICT. * Copyright (C) 2014 e-Contract.be BVBA. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.spi; /** * An adapter implementing BeIDCardUI with empty default actions. Intended to be * extended by a useful class overriding only those methods it requires. For * example, in an embedded application having only a secure PINPAD reader, none * of the obtain() methods would ever be called. * * @author Frank Marien */ public class BeIDCardUIAdapter implements BeIDCardUI { private static final String OPERATION_CANCELLED = "operation cancelled."; protected Locale locale; @Override
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/PINPurpose.java // public enum PINPurpose { // PINTest("test"), // AuthenticationSignature("authentication"), // NonRepudiationSignature("nonrepudiation"); // // private final String type; // // PINPurpose(final String type) { // this.type = type; // } // // public String getType() { // return this.type; // } // // /** // * Determine the likely reason for a PIN request by checking the certificate // * chain involved. // * // * @param fileType the File on the BeID that is involved in the operation // * @return the PIN Purpose associated with this type of file // */ // public static PINPurpose fromFileType(final FileType fileType) { // switch (fileType) { // case AuthentificationCertificate: // return AuthenticationSignature; // case NonRepudiationCertificate: // return NonRepudiationSignature; // default: // return PINTest; // } // } // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/BeIDCardUIAdapter.java import java.util.Locale; import be.bosa.commons.eid.client.PINPurpose; /* * Commons eID Project. * Copyright (C) 2012-2013 FedICT. * Copyright (C) 2014 e-Contract.be BVBA. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.spi; /** * An adapter implementing BeIDCardUI with empty default actions. Intended to be * extended by a useful class overriding only those methods it requires. For * example, in an embedded application having only a secure PINPAD reader, none * of the obtain() methods would ever be called. * * @author Frank Marien */ public class BeIDCardUIAdapter implements BeIDCardUI { private static final String OPERATION_CANCELLED = "operation cancelled."; protected Locale locale; @Override
public char[] obtainPIN(final int triesLeft, final PINPurpose type) {
Fedict/commons-eid
commons-eid-tests/src/test/java/be/bosa/commons/eid/client/tests/integration/CMSTest.java
// Path: commons-eid-jca/src/main/java/be/bosa/commons/eid/jca/BeIDProvider.java // public class BeIDProvider extends Provider { // // public static final String NAME = "BeIDProvider"; // private static final Log LOG = LogFactory.getLog(BeIDProvider.class); // // public BeIDProvider() { // super(NAME, 1.0, "BeID Provider"); // // putService(new BeIDService(this, "KeyStore", "BeID", BeIDKeyStore.class.getName())); // // Map<String, String> signatureServiceAttributes = new HashMap<>(); // signatureServiceAttributes.put("SupportedKeyClasses", BeIDPrivateKey.class.getName()); // putService(new BeIDService(this, "Signature", "SHA1withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA224withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA256withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA384withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA512withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "NONEwithRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "RIPEMD128withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "RIPEMD160withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "RIPEMD256withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA1withRSAandMGF1", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA256withRSAandMGF1", BeIDSignature.class.getName(), signatureServiceAttributes)); // // putService(new BeIDService(this, "KeyManagerFactory", "BeID", BeIDKeyManagerFactory.class.getName())); // // putService(new BeIDService(this, "SecureRandom", "BeID", BeIDSecureRandom.class.getName())); // } // // /** // * Inner class used by {@link BeIDProvider}. // * // * @author Frank Cornelis // * // */ // private static final class BeIDService extends Service { // // public BeIDService(Provider provider, String type, String algorithm, String className) { // super(provider, type, algorithm, className, null, null); // } // // public BeIDService(Provider provider, String type, String algorithm, String className, Map<String, String> attributes) { // super(provider, type, algorithm, className, null, attributes); // } // // @Override // public Object newInstance(Object constructorParameter) throws NoSuchAlgorithmException { // LOG.debug("newInstance: " + super.getType()); // if (super.getType().equals("Signature")) { // return new BeIDSignature(getAlgorithm()); // } // return super.newInstance(constructorParameter); // } // // @Override // public boolean supportsParameter(Object parameter) { // LOG.debug("supportedParameter: " + parameter); // return super.supportsParameter(parameter); // } // } // }
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.junit.Test; import be.bosa.commons.eid.jca.BeIDProvider; import java.security.KeyStore; import java.security.PrivateKey; import java.security.Security; import java.security.cert.X509Certificate; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.cms.CMSTypedData; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner;
/* * Commons eID Project. * Copyright (C) 2013 Frank Cornelis. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.tests.integration; public class CMSTest { @Test public void testCMSSignature() throws Exception {
// Path: commons-eid-jca/src/main/java/be/bosa/commons/eid/jca/BeIDProvider.java // public class BeIDProvider extends Provider { // // public static final String NAME = "BeIDProvider"; // private static final Log LOG = LogFactory.getLog(BeIDProvider.class); // // public BeIDProvider() { // super(NAME, 1.0, "BeID Provider"); // // putService(new BeIDService(this, "KeyStore", "BeID", BeIDKeyStore.class.getName())); // // Map<String, String> signatureServiceAttributes = new HashMap<>(); // signatureServiceAttributes.put("SupportedKeyClasses", BeIDPrivateKey.class.getName()); // putService(new BeIDService(this, "Signature", "SHA1withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA224withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA256withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA384withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA512withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "NONEwithRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "RIPEMD128withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "RIPEMD160withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "RIPEMD256withRSA", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA1withRSAandMGF1", BeIDSignature.class.getName(), signatureServiceAttributes)); // putService(new BeIDService(this, "Signature", "SHA256withRSAandMGF1", BeIDSignature.class.getName(), signatureServiceAttributes)); // // putService(new BeIDService(this, "KeyManagerFactory", "BeID", BeIDKeyManagerFactory.class.getName())); // // putService(new BeIDService(this, "SecureRandom", "BeID", BeIDSecureRandom.class.getName())); // } // // /** // * Inner class used by {@link BeIDProvider}. // * // * @author Frank Cornelis // * // */ // private static final class BeIDService extends Service { // // public BeIDService(Provider provider, String type, String algorithm, String className) { // super(provider, type, algorithm, className, null, null); // } // // public BeIDService(Provider provider, String type, String algorithm, String className, Map<String, String> attributes) { // super(provider, type, algorithm, className, null, attributes); // } // // @Override // public Object newInstance(Object constructorParameter) throws NoSuchAlgorithmException { // LOG.debug("newInstance: " + super.getType()); // if (super.getType().equals("Signature")) { // return new BeIDSignature(getAlgorithm()); // } // return super.newInstance(constructorParameter); // } // // @Override // public boolean supportsParameter(Object parameter) { // LOG.debug("supportedParameter: " + parameter); // return super.supportsParameter(parameter); // } // } // } // Path: commons-eid-tests/src/test/java/be/bosa/commons/eid/client/tests/integration/CMSTest.java import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.junit.Test; import be.bosa.commons.eid.jca.BeIDProvider; import java.security.KeyStore; import java.security.PrivateKey; import java.security.Security; import java.security.cert.X509Certificate; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.cms.CMSTypedData; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.ContentSigner; /* * Commons eID Project. * Copyright (C) 2013 Frank Cornelis. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.tests.integration; public class CMSTest { @Test public void testCMSSignature() throws Exception {
Security.addProvider(new BeIDProvider());
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/CCID.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/exception/BeIDException.java // public class BeIDException extends Exception { // // public BeIDException() { // } // // public BeIDException(String message) { // super(message); // } // // public BeIDException(Throwable cause) { // super(cause); // } // // public BeIDException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import javax.smartcardio.ResponseAPDU; import be.bosa.commons.eid.client.exception.BeIDException; import be.bosa.commons.eid.client.spi.Logger; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.EnumMap; import java.util.Locale; import javax.smartcardio.Card; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import javax.smartcardio.CommandAPDU;
/* * Commons eID Project. * Copyright (C) 2008-2013 FedICT. * Copyright (C) 2014 e-Contract.be BVBA. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.impl; /** * CCID I/O according to the USB Smart card CCID 1.1 specifications. * FrankM added PPDU support. * * @author Frank Cornelis * @author Frank Marien */ public class CCID { private static final int GET_FEATURES = 0x42000D48; private static final int GET_FEATURES_ON_WINDOWS = 0x31 << 16 | 3400 << 2; private static final int MIN_PIN_SIZE = 4; private static final int MAX_PIN_SIZE = 12; private static final String DUTCH_LANGUAGE = "nl"; private static final String FRENCH_LANGUAGE = Locale.FRENCH.getLanguage(); private static final String GERMAN_LANGUAGE = Locale.GERMAN.getLanguage(); private static final int DUTCH_LANGUAGE_CODE = 0x13; private static final int FRENCH_LANGUAGE_CODE = 0x0c; private static final int GERMAN_LANGUAGE_CODE = 0x07; private static final int ENGLISH_LANGUAGE_CODE = 0x09;
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/exception/BeIDException.java // public class BeIDException extends Exception { // // public BeIDException() { // } // // public BeIDException(String message) { // super(message); // } // // public BeIDException(Throwable cause) { // super(cause); // } // // public BeIDException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/CCID.java import javax.smartcardio.ResponseAPDU; import be.bosa.commons.eid.client.exception.BeIDException; import be.bosa.commons.eid.client.spi.Logger; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.EnumMap; import java.util.Locale; import javax.smartcardio.Card; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import javax.smartcardio.CommandAPDU; /* * Commons eID Project. * Copyright (C) 2008-2013 FedICT. * Copyright (C) 2014 e-Contract.be BVBA. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.impl; /** * CCID I/O according to the USB Smart card CCID 1.1 specifications. * FrankM added PPDU support. * * @author Frank Cornelis * @author Frank Marien */ public class CCID { private static final int GET_FEATURES = 0x42000D48; private static final int GET_FEATURES_ON_WINDOWS = 0x31 << 16 | 3400 << 2; private static final int MIN_PIN_SIZE = 4; private static final int MAX_PIN_SIZE = 12; private static final String DUTCH_LANGUAGE = "nl"; private static final String FRENCH_LANGUAGE = Locale.FRENCH.getLanguage(); private static final String GERMAN_LANGUAGE = Locale.GERMAN.getLanguage(); private static final int DUTCH_LANGUAGE_CODE = 0x13; private static final int FRENCH_LANGUAGE_CODE = 0x0c; private static final int GERMAN_LANGUAGE_CODE = 0x07; private static final int ENGLISH_LANGUAGE_CODE = 0x09;
private final Logger logger;
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/CCID.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/exception/BeIDException.java // public class BeIDException extends Exception { // // public BeIDException() { // } // // public BeIDException(String message) { // super(message); // } // // public BeIDException(Throwable cause) { // super(cause); // } // // public BeIDException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import javax.smartcardio.ResponseAPDU; import be.bosa.commons.eid.client.exception.BeIDException; import be.bosa.commons.eid.client.spi.Logger; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.EnumMap; import java.util.Locale; import javax.smartcardio.Card; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import javax.smartcardio.CommandAPDU;
if (featureCode != null) { logger.debug("FEATURE " + feature.name() + " = " + Integer.toHexString(featureCode)); } } usesPPDU = true; } else { logger.error("CCID Features via PPDU Not Supported"); } } private Integer findFeaturePPDU(byte featureTag, byte[] features) { for (byte tag : features) { if (featureTag == tag) return (int) tag; } return null; } public boolean usesPPDU() { return usesPPDU; } public boolean hasFeature(FEATURE feature) { return getFeature(feature) != null; } public Integer getFeature(FEATURE feature) { return features.get(feature); }
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/exception/BeIDException.java // public class BeIDException extends Exception { // // public BeIDException() { // } // // public BeIDException(String message) { // super(message); // } // // public BeIDException(Throwable cause) { // super(cause); // } // // public BeIDException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/CCID.java import javax.smartcardio.ResponseAPDU; import be.bosa.commons.eid.client.exception.BeIDException; import be.bosa.commons.eid.client.spi.Logger; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.EnumMap; import java.util.Locale; import javax.smartcardio.Card; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import javax.smartcardio.CommandAPDU; if (featureCode != null) { logger.debug("FEATURE " + feature.name() + " = " + Integer.toHexString(featureCode)); } } usesPPDU = true; } else { logger.error("CCID Features via PPDU Not Supported"); } } private Integer findFeaturePPDU(byte featureTag, byte[] features) { for (byte tag : features) { if (featureTag == tag) return (int) tag; } return null; } public boolean usesPPDU() { return usesPPDU; } public boolean hasFeature(FEATURE feature) { return getFeature(feature) != null; } public Integer getFeature(FEATURE feature) { return features.get(feature); }
protected byte[] transmitPPDUCommand(int controlCode, byte[] command) throws CardException, BeIDException {
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client; /** * A BeIDCardManager uses a {@link CardAndTerminalManager} to detect Card * Insertion and Removal Events, distinguishes between Belgian eID and other * cards, calls any registered BeIDCardEventsListeners for eID cards inserted * and removed, and any registered CardEventsListener for other cards being * inserted and removed. Note that by default, a BeIDCardManager will only * connect to cards using card protocol "T=0" to ensure optimal compatibility * with Belgian eID cards in all card readers, meaning that if you wish to use * its "other card" facility you may have to supply your own * CardAndTerminalManager with a protocol setting of "ALL". * * @author Frank Marien * @author Frank Cornelis */ public class BeIDCardManager { private static final byte[] ATR_PATTERN = new byte[]{0x3b, (byte) 0x98, 0x00, 0x40, 0x00, (byte) 0x00, 0x00, 0x00, 0x01, 0x01, (byte) 0xad, 0x13, 0x10,}; private static final byte[] ATR_MASK = new byte[]{(byte) 0xff, (byte) 0xff, 0x00, (byte) 0xff, 0x00, 0x00, 0x00, 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf0,}; private final CardAndTerminalManager cardAndTerminalManager; private final Map<CardTerminal, BeIDCard> terminalsAndCards;
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client; /** * A BeIDCardManager uses a {@link CardAndTerminalManager} to detect Card * Insertion and Removal Events, distinguishes between Belgian eID and other * cards, calls any registered BeIDCardEventsListeners for eID cards inserted * and removed, and any registered CardEventsListener for other cards being * inserted and removed. Note that by default, a BeIDCardManager will only * connect to cards using card protocol "T=0" to ensure optimal compatibility * with Belgian eID cards in all card readers, meaning that if you wish to use * its "other card" facility you may have to supply your own * CardAndTerminalManager with a protocol setting of "ALL". * * @author Frank Marien * @author Frank Cornelis */ public class BeIDCardManager { private static final byte[] ATR_PATTERN = new byte[]{0x3b, (byte) 0x98, 0x00, 0x40, 0x00, (byte) 0x00, 0x00, 0x00, 0x01, 0x01, (byte) 0xad, 0x13, 0x10,}; private static final byte[] ATR_MASK = new byte[]{(byte) 0xff, (byte) 0xff, 0x00, (byte) 0xff, 0x00, 0x00, 0x00, 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf0,}; private final CardAndTerminalManager cardAndTerminalManager; private final Map<CardTerminal, BeIDCard> terminalsAndCards;
private final Set<BeIDCardEventsListener> beIdListeners;
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client; /** * A BeIDCardManager uses a {@link CardAndTerminalManager} to detect Card * Insertion and Removal Events, distinguishes between Belgian eID and other * cards, calls any registered BeIDCardEventsListeners for eID cards inserted * and removed, and any registered CardEventsListener for other cards being * inserted and removed. Note that by default, a BeIDCardManager will only * connect to cards using card protocol "T=0" to ensure optimal compatibility * with Belgian eID cards in all card readers, meaning that if you wish to use * its "other card" facility you may have to supply your own * CardAndTerminalManager with a protocol setting of "ALL". * * @author Frank Marien * @author Frank Cornelis */ public class BeIDCardManager { private static final byte[] ATR_PATTERN = new byte[]{0x3b, (byte) 0x98, 0x00, 0x40, 0x00, (byte) 0x00, 0x00, 0x00, 0x01, 0x01, (byte) 0xad, 0x13, 0x10,}; private static final byte[] ATR_MASK = new byte[]{(byte) 0xff, (byte) 0xff, 0x00, (byte) 0xff, 0x00, 0x00, 0x00, 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf0,}; private final CardAndTerminalManager cardAndTerminalManager; private final Map<CardTerminal, BeIDCard> terminalsAndCards; private final Set<BeIDCardEventsListener> beIdListeners;
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client; /** * A BeIDCardManager uses a {@link CardAndTerminalManager} to detect Card * Insertion and Removal Events, distinguishes between Belgian eID and other * cards, calls any registered BeIDCardEventsListeners for eID cards inserted * and removed, and any registered CardEventsListener for other cards being * inserted and removed. Note that by default, a BeIDCardManager will only * connect to cards using card protocol "T=0" to ensure optimal compatibility * with Belgian eID cards in all card readers, meaning that if you wish to use * its "other card" facility you may have to supply your own * CardAndTerminalManager with a protocol setting of "ALL". * * @author Frank Marien * @author Frank Cornelis */ public class BeIDCardManager { private static final byte[] ATR_PATTERN = new byte[]{0x3b, (byte) 0x98, 0x00, 0x40, 0x00, (byte) 0x00, 0x00, 0x00, 0x01, 0x01, (byte) 0xad, 0x13, 0x10,}; private static final byte[] ATR_MASK = new byte[]{(byte) 0xff, (byte) 0xff, 0x00, (byte) 0xff, 0x00, 0x00, 0x00, 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf0,}; private final CardAndTerminalManager cardAndTerminalManager; private final Map<CardTerminal, BeIDCard> terminalsAndCards; private final Set<BeIDCardEventsListener> beIdListeners;
private final Set<CardEventsListener> otherCardListeners;
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client; /** * A BeIDCardManager uses a {@link CardAndTerminalManager} to detect Card * Insertion and Removal Events, distinguishes between Belgian eID and other * cards, calls any registered BeIDCardEventsListeners for eID cards inserted * and removed, and any registered CardEventsListener for other cards being * inserted and removed. Note that by default, a BeIDCardManager will only * connect to cards using card protocol "T=0" to ensure optimal compatibility * with Belgian eID cards in all card readers, meaning that if you wish to use * its "other card" facility you may have to supply your own * CardAndTerminalManager with a protocol setting of "ALL". * * @author Frank Marien * @author Frank Cornelis */ public class BeIDCardManager { private static final byte[] ATR_PATTERN = new byte[]{0x3b, (byte) 0x98, 0x00, 0x40, 0x00, (byte) 0x00, 0x00, 0x00, 0x01, 0x01, (byte) 0xad, 0x13, 0x10,}; private static final byte[] ATR_MASK = new byte[]{(byte) 0xff, (byte) 0xff, 0x00, (byte) 0xff, 0x00, 0x00, 0x00, 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf0,}; private final CardAndTerminalManager cardAndTerminalManager; private final Map<CardTerminal, BeIDCard> terminalsAndCards; private final Set<BeIDCardEventsListener> beIdListeners; private final Set<CardEventsListener> otherCardListeners;
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client; /** * A BeIDCardManager uses a {@link CardAndTerminalManager} to detect Card * Insertion and Removal Events, distinguishes between Belgian eID and other * cards, calls any registered BeIDCardEventsListeners for eID cards inserted * and removed, and any registered CardEventsListener for other cards being * inserted and removed. Note that by default, a BeIDCardManager will only * connect to cards using card protocol "T=0" to ensure optimal compatibility * with Belgian eID cards in all card readers, meaning that if you wish to use * its "other card" facility you may have to supply your own * CardAndTerminalManager with a protocol setting of "ALL". * * @author Frank Marien * @author Frank Cornelis */ public class BeIDCardManager { private static final byte[] ATR_PATTERN = new byte[]{0x3b, (byte) 0x98, 0x00, 0x40, 0x00, (byte) 0x00, 0x00, 0x00, 0x01, 0x01, (byte) 0xad, 0x13, 0x10,}; private static final byte[] ATR_MASK = new byte[]{(byte) 0xff, (byte) 0xff, 0x00, (byte) 0xff, 0x00, 0x00, 0x00, 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf0,}; private final CardAndTerminalManager cardAndTerminalManager; private final Map<CardTerminal, BeIDCard> terminalsAndCards; private final Set<BeIDCardEventsListener> beIdListeners; private final Set<CardEventsListener> otherCardListeners;
private final Logger logger;
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client; /** * A BeIDCardManager uses a {@link CardAndTerminalManager} to detect Card * Insertion and Removal Events, distinguishes between Belgian eID and other * cards, calls any registered BeIDCardEventsListeners for eID cards inserted * and removed, and any registered CardEventsListener for other cards being * inserted and removed. Note that by default, a BeIDCardManager will only * connect to cards using card protocol "T=0" to ensure optimal compatibility * with Belgian eID cards in all card readers, meaning that if you wish to use * its "other card" facility you may have to supply your own * CardAndTerminalManager with a protocol setting of "ALL". * * @author Frank Marien * @author Frank Cornelis */ public class BeIDCardManager { private static final byte[] ATR_PATTERN = new byte[]{0x3b, (byte) 0x98, 0x00, 0x40, 0x00, (byte) 0x00, 0x00, 0x00, 0x01, 0x01, (byte) 0xad, 0x13, 0x10,}; private static final byte[] ATR_MASK = new byte[]{(byte) 0xff, (byte) 0xff, 0x00, (byte) 0xff, 0x00, 0x00, 0x00, 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf0,}; private final CardAndTerminalManager cardAndTerminalManager; private final Map<CardTerminal, BeIDCard> terminalsAndCards; private final Set<BeIDCardEventsListener> beIdListeners; private final Set<CardEventsListener> otherCardListeners; private final Logger logger; private boolean terminalManagerIsPrivate; /** * Instantiate a BeIDCardManager with a default (void) logger and a private * CardAndTerminalManager that is automatically started and stopped with the * BeIDCardManager, and that only connects to Cards with Protocol T=0 */ public BeIDCardManager() {
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; /* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client; /** * A BeIDCardManager uses a {@link CardAndTerminalManager} to detect Card * Insertion and Removal Events, distinguishes between Belgian eID and other * cards, calls any registered BeIDCardEventsListeners for eID cards inserted * and removed, and any registered CardEventsListener for other cards being * inserted and removed. Note that by default, a BeIDCardManager will only * connect to cards using card protocol "T=0" to ensure optimal compatibility * with Belgian eID cards in all card readers, meaning that if you wish to use * its "other card" facility you may have to supply your own * CardAndTerminalManager with a protocol setting of "ALL". * * @author Frank Marien * @author Frank Cornelis */ public class BeIDCardManager { private static final byte[] ATR_PATTERN = new byte[]{0x3b, (byte) 0x98, 0x00, 0x40, 0x00, (byte) 0x00, 0x00, 0x00, 0x01, 0x01, (byte) 0xad, 0x13, 0x10,}; private static final byte[] ATR_MASK = new byte[]{(byte) 0xff, (byte) 0xff, 0x00, (byte) 0xff, 0x00, 0x00, 0x00, 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xf0,}; private final CardAndTerminalManager cardAndTerminalManager; private final Map<CardTerminal, BeIDCard> terminalsAndCards; private final Set<BeIDCardEventsListener> beIdListeners; private final Set<CardEventsListener> otherCardListeners; private final Logger logger; private boolean terminalManagerIsPrivate; /** * Instantiate a BeIDCardManager with a default (void) logger and a private * CardAndTerminalManager that is automatically started and stopped with the * BeIDCardManager, and that only connects to Cards with Protocol T=0 */ public BeIDCardManager() {
this(new VoidLogger());
Fedict/commons-eid
commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // }
import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap;
/** * Stops this BeIDCardManager. If no CardAndTerminalManager was given at * construction, this will stop our private CardAndTerminalManager. After * this, no registered listeners will receive any more events. If a * CardAndTerminalManager was given at construction, this has no effect. * * @return this BeIDCardManager to allow for method chaining */ public BeIDCardManager stop() throws InterruptedException { if (terminalManagerIsPrivate) { cardAndTerminalManager.stop(); } return this; } /* * Private Support methods. Shamelessly copied from eid-applet-core */ private boolean matchesEidAtr(ATR atr) { byte[] atrBytes = atr.getBytes(); if (atrBytes.length != ATR_PATTERN.length) { return false; } for (int idx = 0; idx < atrBytes.length; idx++) { atrBytes[idx] &= ATR_MASK[idx]; } return Arrays.equals(atrBytes, ATR_PATTERN); } public BeIDCardManager setLocale(Locale newLocale) {
// Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/CardAndTerminalManager.java // public enum Protocol { // T0("T=0"), T1("T=1"), TCL("T=CL"), ANY("*"); // // private final String protocol; // // Protocol(String protocol) { // this.protocol = protocol; // } // // String getProtocol() { // return protocol; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/BeIDCardEventsListener.java // public interface BeIDCardEventsListener { // void eIDCardEventsInitialized(); // // void eIDCardInserted(CardTerminal cardTerminal, BeIDCard card); // // void eIDCardRemoved(CardTerminal cardTerminal, BeIDCard card); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/event/CardEventsListener.java // public interface CardEventsListener { // void cardEventsInitialized(); // // void cardInserted(CardTerminal cardTerminal, Card card); // // void cardRemoved(CardTerminal cardTerminal); // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/LocaleManager.java // public final class LocaleManager { // // private static Locale locale; // // private LocaleManager() { // super(); // } // // public static void setLocale(Locale newLocale) { // LocaleManager.locale = newLocale; // } // // public static Locale getLocale() { // if (LocaleManager.locale == null) { // LocaleManager.locale = Locale.getDefault(); // } // // return LocaleManager.locale; // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/impl/VoidLogger.java // public final class VoidLogger implements Logger { // // public VoidLogger() { // super(); // } // // @Override // public void error(final String message) { // // empty // } // // @Override // public void debug(final String message) { // // empty // } // } // // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/spi/Logger.java // public interface Logger { // // /** // * Error messages receiver. // * // * @param message the error message. // */ // void error(String message); // // /** // * Debug messages receiver. // * // * @param message the debug message. // */ // void debug(String message); // } // Path: commons-eid-client/src/main/java/be/bosa/commons/eid/client/BeIDCardManager.java import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import be.bosa.commons.eid.client.CardAndTerminalManager.Protocol; import be.bosa.commons.eid.client.event.BeIDCardEventsListener; import be.bosa.commons.eid.client.event.CardEventsListener; import be.bosa.commons.eid.client.impl.LocaleManager; import be.bosa.commons.eid.client.impl.VoidLogger; import be.bosa.commons.eid.client.spi.Logger; import javax.smartcardio.ATR; import javax.smartcardio.Card; import javax.smartcardio.CardTerminal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; /** * Stops this BeIDCardManager. If no CardAndTerminalManager was given at * construction, this will stop our private CardAndTerminalManager. After * this, no registered listeners will receive any more events. If a * CardAndTerminalManager was given at construction, this has no effect. * * @return this BeIDCardManager to allow for method chaining */ public BeIDCardManager stop() throws InterruptedException { if (terminalManagerIsPrivate) { cardAndTerminalManager.stop(); } return this; } /* * Private Support methods. Shamelessly copied from eid-applet-core */ private boolean matchesEidAtr(ATR atr) { byte[] atrBytes = atr.getBytes(); if (atrBytes.length != ATR_PATTERN.length) { return false; } for (int idx = 0; idx < atrBytes.length; idx++) { atrBytes[idx] &= ATR_MASK[idx]; } return Arrays.equals(atrBytes, ATR_PATTERN); } public BeIDCardManager setLocale(Locale newLocale) {
LocaleManager.setLocale(newLocale);
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/fragment/AllUserFragment.java
// Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java // public interface Api { // // String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; // // @GET("api/users") // Observable<User> login(@Query("name") String name, @Query("phone") String phone); // // @POST("api/users") // Observable<BaseData> register(@Body RegisterBody registerUser); // // @PUT("api/users") // Observable<User> updateUser(@Body User updateUser); // // @POST("api/sign") // Observable<BaseData> sign(@Body SignBody user); // // @DELETE("api/sign") // Observable<BaseData> unSign(@Query("name") String name); // // @GET("api/message_all") // Observable<UsersData> getAllUser(); // // @GET("api/message") // Observable<UsersData> getSignedUser(); // // @GET("api/addplease/{code}") // Observable<BaseData> addCode(@Path("code") String code); // // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // }
import com.wecan.xhin.studio.api.Api; import com.wecan.xhin.studio.bean.down.UsersData; import rx.Observable;
package com.wecan.xhin.studio.fragment; /** * Created by xhinliang on 15-11-20. * xhinliang@gmail.com */ public class AllUserFragment extends UsersFragment { public static AllUserFragment newInstance() { return new AllUserFragment(); } @Override
// Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java // public interface Api { // // String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; // // @GET("api/users") // Observable<User> login(@Query("name") String name, @Query("phone") String phone); // // @POST("api/users") // Observable<BaseData> register(@Body RegisterBody registerUser); // // @PUT("api/users") // Observable<User> updateUser(@Body User updateUser); // // @POST("api/sign") // Observable<BaseData> sign(@Body SignBody user); // // @DELETE("api/sign") // Observable<BaseData> unSign(@Query("name") String name); // // @GET("api/message_all") // Observable<UsersData> getAllUser(); // // @GET("api/message") // Observable<UsersData> getSignedUser(); // // @GET("api/addplease/{code}") // Observable<BaseData> addCode(@Path("code") String code); // // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // Path: app/src/main/java/com/wecan/xhin/studio/fragment/AllUserFragment.java import com.wecan.xhin.studio.api.Api; import com.wecan.xhin.studio.bean.down.UsersData; import rx.Observable; package com.wecan.xhin.studio.fragment; /** * Created by xhinliang on 15-11-20. * xhinliang@gmail.com */ public class AllUserFragment extends UsersFragment { public static AllUserFragment newInstance() { return new AllUserFragment(); } @Override
protected Observable<UsersData> getUserApi(Api api) {
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/fragment/AllUserFragment.java
// Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java // public interface Api { // // String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; // // @GET("api/users") // Observable<User> login(@Query("name") String name, @Query("phone") String phone); // // @POST("api/users") // Observable<BaseData> register(@Body RegisterBody registerUser); // // @PUT("api/users") // Observable<User> updateUser(@Body User updateUser); // // @POST("api/sign") // Observable<BaseData> sign(@Body SignBody user); // // @DELETE("api/sign") // Observable<BaseData> unSign(@Query("name") String name); // // @GET("api/message_all") // Observable<UsersData> getAllUser(); // // @GET("api/message") // Observable<UsersData> getSignedUser(); // // @GET("api/addplease/{code}") // Observable<BaseData> addCode(@Path("code") String code); // // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // }
import com.wecan.xhin.studio.api.Api; import com.wecan.xhin.studio.bean.down.UsersData; import rx.Observable;
package com.wecan.xhin.studio.fragment; /** * Created by xhinliang on 15-11-20. * xhinliang@gmail.com */ public class AllUserFragment extends UsersFragment { public static AllUserFragment newInstance() { return new AllUserFragment(); } @Override
// Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java // public interface Api { // // String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; // // @GET("api/users") // Observable<User> login(@Query("name") String name, @Query("phone") String phone); // // @POST("api/users") // Observable<BaseData> register(@Body RegisterBody registerUser); // // @PUT("api/users") // Observable<User> updateUser(@Body User updateUser); // // @POST("api/sign") // Observable<BaseData> sign(@Body SignBody user); // // @DELETE("api/sign") // Observable<BaseData> unSign(@Query("name") String name); // // @GET("api/message_all") // Observable<UsersData> getAllUser(); // // @GET("api/message") // Observable<UsersData> getSignedUser(); // // @GET("api/addplease/{code}") // Observable<BaseData> addCode(@Path("code") String code); // // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // Path: app/src/main/java/com/wecan/xhin/studio/fragment/AllUserFragment.java import com.wecan.xhin.studio.api.Api; import com.wecan.xhin.studio.bean.down.UsersData; import rx.Observable; package com.wecan.xhin.studio.fragment; /** * Created by xhinliang on 15-11-20. * xhinliang@gmail.com */ public class AllUserFragment extends UsersFragment { public static AllUserFragment newInstance() { return new AllUserFragment(); } @Override
protected Observable<UsersData> getUserApi(Api api) {
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/api/Api.java
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // }
import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable;
package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users")
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // } // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable; package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users")
Observable<User> login(@Query("name") String name, @Query("phone") String phone);
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/api/Api.java
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // }
import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable;
package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users") Observable<User> login(@Query("name") String name, @Query("phone") String phone); @POST("api/users")
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // } // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable; package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users") Observable<User> login(@Query("name") String name, @Query("phone") String phone); @POST("api/users")
Observable<BaseData> register(@Body RegisterBody registerUser);
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/api/Api.java
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // }
import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable;
package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users") Observable<User> login(@Query("name") String name, @Query("phone") String phone); @POST("api/users")
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // } // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable; package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users") Observable<User> login(@Query("name") String name, @Query("phone") String phone); @POST("api/users")
Observable<BaseData> register(@Body RegisterBody registerUser);
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/api/Api.java
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // }
import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable;
package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users") Observable<User> login(@Query("name") String name, @Query("phone") String phone); @POST("api/users") Observable<BaseData> register(@Body RegisterBody registerUser); @PUT("api/users") Observable<User> updateUser(@Body User updateUser); @POST("api/sign")
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // } // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable; package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users") Observable<User> login(@Query("name") String name, @Query("phone") String phone); @POST("api/users") Observable<BaseData> register(@Body RegisterBody registerUser); @PUT("api/users") Observable<User> updateUser(@Body User updateUser); @POST("api/sign")
Observable<BaseData> sign(@Body SignBody user);
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/api/Api.java
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // }
import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable;
package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users") Observable<User> login(@Query("name") String name, @Query("phone") String phone); @POST("api/users") Observable<BaseData> register(@Body RegisterBody registerUser); @PUT("api/users") Observable<User> updateUser(@Body User updateUser); @POST("api/sign") Observable<BaseData> sign(@Body SignBody user); @DELETE("api/sign") Observable<BaseData> unSign(@Query("name") String name); @GET("api/message_all")
// Path: app/src/main/java/com/wecan/xhin/studio/bean/common/User.java // public class User extends BaseObservable implements Parcelable { // public int position; // public int group_name; // public int id; // public int sex; // public int status; // // public String phone; // public String sign_date; // // // public String name; // public String imgurl; // public String description; // // public static final String[] groups = { // "组别", "前端", "后台", "移动", "产品", "设计", "YOU KNOW NOTHING" // }; // // public static final String[] positions = { // "职位", "组员", "组长", "室长", "John Snow" // }; // // public static final String[] sexs = { // "性别", "男", "女" // }; // public static final int VALUE_STATUS_SIGN = 1; // public static final int VALUE_STATUS_UNSIGN = 0; // // public String getName() { // return name; // } // // public static String getGroupName(int group) { // return groups[group]; // } // // public static String getPositionName(int position) { // return positions[position]; // } // // public static String getSexName(int sex) { // return sexs[sex]; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.position); // dest.writeInt(this.group_name); // dest.writeInt(this.id); // dest.writeInt(this.sex); // dest.writeInt(this.status); // dest.writeString(this.phone); // dest.writeString(this.sign_date); // dest.writeString(this.name); // dest.writeString(this.imgurl); // dest.writeString(this.description); // } // // public User() { // } // // protected User(Parcel in) { // this.position = in.readInt(); // this.group_name = in.readInt(); // this.id = in.readInt(); // this.sex = in.readInt(); // this.status = in.readInt(); // this.phone = in.readString(); // this.sign_date = in.readString(); // this.name = in.readString(); // this.imgurl = in.readString(); // this.description = in.readString(); // } // // public static final Creator<User> CREATOR = new Creator<User>() { // public User createFromParcel(Parcel source) { // return new User(source); // } // // public User[] newArray(int size) { // return new User[size]; // } // }; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/BaseData.java // public class BaseData { // public int status; // public String message; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/down/UsersData.java // public class UsersData extends BaseData { // public List<User> data; // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/RegisterBody.java // public class RegisterBody { // // private int position; // private int group_name; // private int sex; // private String phone; // private String name; // private String imgurl; // private String code; // private String description; // // public RegisterBody(int position, int group_name, String phone, int sex, String name, String code) { // this.position = position; // this.group_name = group_name; // this.phone = phone; // this.sex = sex; // this.name = name; // this.code = code; // this.imgurl = ""; // this.description = ""; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/bean/up/SignBody.java // public class SignBody { // public String name; // // public SignBody(String name) { // this.name = name; // } // } // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java import com.wecan.xhin.studio.bean.common.User; import com.wecan.xhin.studio.bean.down.BaseData; import com.wecan.xhin.studio.bean.down.UsersData; import com.wecan.xhin.studio.bean.up.RegisterBody; import com.wecan.xhin.studio.bean.up.SignBody; import retrofit.http.Body; import retrofit.http.DELETE; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.PUT; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable; package com.wecan.xhin.studio.api; public interface Api { String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; @GET("api/users") Observable<User> login(@Query("name") String name, @Query("phone") String phone); @POST("api/users") Observable<BaseData> register(@Body RegisterBody registerUser); @PUT("api/users") Observable<User> updateUser(@Body User updateUser); @POST("api/sign") Observable<BaseData> sign(@Body SignBody user); @DELETE("api/sign") Observable<BaseData> unSign(@Query("name") String name); @GET("api/message_all")
Observable<UsersData> getAllUser();
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/adapter/LibrariesAdapter.java
// Path: app/src/main/java/com/wecan/xhin/studio/bean/GitRepository.java // public class GitRepository { // public String author; // public String name; // public String url; // // public GitRepository(String author, String name, String url) { // this.author = author; // this.name = name; // this.url = url; // } // // // @Override // public String toString() { // return String.format("%s / %s", author, name); // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/reactivex/BindingRecyclerView.java // public class BindingRecyclerView { // // public static abstract class ListAdapter<T, VH extends ViewHolder> extends RecyclerView.Adapter<VH> { // // protected final LayoutInflater inflater; // protected final ObservableList<T> data; // // private final AtomicInteger refs = new AtomicInteger(); // // private final ObservableList.OnListChangedCallback<ObservableList<T>> callback = // new ObservableList.OnListChangedCallback<ObservableList<T>>() { // @Override // public void onChanged(ObservableList<T> sender) { // notifyDataSetChanged(); // } // // @Override // public void onItemRangeChanged(ObservableList<T> sender, // int positionStart, int itemCount) { // notifyItemRangeChanged(positionStart, itemCount); // } // // @Override // public void onItemRangeInserted(ObservableList<T> sender, // int positionStart, int itemCount) { // notifyItemRangeInserted(positionStart, itemCount); // } // // @Override // public void onItemRangeMoved(ObservableList<T> sender, // int fromPosition, int toPosition, int itemCount) { // for (int i = 0; i < itemCount; i++) { // notifyItemMoved(fromPosition + i, toPosition + i); // } // } // // @Override // public void onItemRangeRemoved(ObservableList<T> sender, // int positionStart, int itemCount) { // notifyItemRangeRemoved(positionStart, itemCount); // } // }; // // public ListAdapter(Context context, ObservableList<T> data) { // this.inflater = LayoutInflater.from(context); // this.data = data; // } // // @Override // public int getItemCount() { // return data.size(); // } // // @Override // public void onAttachedToRecyclerView(RecyclerView recyclerView) { // if (refs.getAndIncrement() == 0) { // data.addOnListChangedCallback(callback); // } // } // // @Override // public void onDetachedFromRecyclerView(RecyclerView recyclerView) { // if (refs.decrementAndGet() == 0) { // data.removeOnListChangedCallback(callback); // } // } // // } // // public static class ViewHolder<V extends ViewDataBinding> extends RecyclerView.ViewHolder { // // public final V binding; // // public ViewHolder(LayoutInflater inflater, @LayoutRes int layoutId, ViewGroup parent) { // this(DataBindingUtil.<V>inflate(inflater, layoutId, parent, false)); // } // // public ViewHolder(V binding) { // super(binding.getRoot()); // this.binding = binding; // } // // } // // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.view.ViewClickEvent; import com.wecan.xhin.studio.bean.GitRepository; import com.wecan.xhin.studio.databinding.RecyclerItemHeaderBinding; import com.wecan.xhin.studio.databinding.RecyclerItemLibraryBinding; import com.wecan.xhin.studio.reactivex.BindingRecyclerView; import java.util.List; import rx.functions.Action1;
package com.wecan.xhin.studio.adapter; /** * Created by xhinliang on 15-11-23. * xhinliang@gmail.com */ public class LibrariesAdapter extends RecyclerView.Adapter<BindingRecyclerView.ViewHolder> { private static final int VALUE_TYPE_HEADER = 0; private static final int VALUE_TYPE_LIBRARY = 1;
// Path: app/src/main/java/com/wecan/xhin/studio/bean/GitRepository.java // public class GitRepository { // public String author; // public String name; // public String url; // // public GitRepository(String author, String name, String url) { // this.author = author; // this.name = name; // this.url = url; // } // // // @Override // public String toString() { // return String.format("%s / %s", author, name); // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/reactivex/BindingRecyclerView.java // public class BindingRecyclerView { // // public static abstract class ListAdapter<T, VH extends ViewHolder> extends RecyclerView.Adapter<VH> { // // protected final LayoutInflater inflater; // protected final ObservableList<T> data; // // private final AtomicInteger refs = new AtomicInteger(); // // private final ObservableList.OnListChangedCallback<ObservableList<T>> callback = // new ObservableList.OnListChangedCallback<ObservableList<T>>() { // @Override // public void onChanged(ObservableList<T> sender) { // notifyDataSetChanged(); // } // // @Override // public void onItemRangeChanged(ObservableList<T> sender, // int positionStart, int itemCount) { // notifyItemRangeChanged(positionStart, itemCount); // } // // @Override // public void onItemRangeInserted(ObservableList<T> sender, // int positionStart, int itemCount) { // notifyItemRangeInserted(positionStart, itemCount); // } // // @Override // public void onItemRangeMoved(ObservableList<T> sender, // int fromPosition, int toPosition, int itemCount) { // for (int i = 0; i < itemCount; i++) { // notifyItemMoved(fromPosition + i, toPosition + i); // } // } // // @Override // public void onItemRangeRemoved(ObservableList<T> sender, // int positionStart, int itemCount) { // notifyItemRangeRemoved(positionStart, itemCount); // } // }; // // public ListAdapter(Context context, ObservableList<T> data) { // this.inflater = LayoutInflater.from(context); // this.data = data; // } // // @Override // public int getItemCount() { // return data.size(); // } // // @Override // public void onAttachedToRecyclerView(RecyclerView recyclerView) { // if (refs.getAndIncrement() == 0) { // data.addOnListChangedCallback(callback); // } // } // // @Override // public void onDetachedFromRecyclerView(RecyclerView recyclerView) { // if (refs.decrementAndGet() == 0) { // data.removeOnListChangedCallback(callback); // } // } // // } // // public static class ViewHolder<V extends ViewDataBinding> extends RecyclerView.ViewHolder { // // public final V binding; // // public ViewHolder(LayoutInflater inflater, @LayoutRes int layoutId, ViewGroup parent) { // this(DataBindingUtil.<V>inflate(inflater, layoutId, parent, false)); // } // // public ViewHolder(V binding) { // super(binding.getRoot()); // this.binding = binding; // } // // } // // } // Path: app/src/main/java/com/wecan/xhin/studio/adapter/LibrariesAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.view.ViewClickEvent; import com.wecan.xhin.studio.bean.GitRepository; import com.wecan.xhin.studio.databinding.RecyclerItemHeaderBinding; import com.wecan.xhin.studio.databinding.RecyclerItemLibraryBinding; import com.wecan.xhin.studio.reactivex.BindingRecyclerView; import java.util.List; import rx.functions.Action1; package com.wecan.xhin.studio.adapter; /** * Created by xhinliang on 15-11-23. * xhinliang@gmail.com */ public class LibrariesAdapter extends RecyclerView.Adapter<BindingRecyclerView.ViewHolder> { private static final int VALUE_TYPE_HEADER = 0; private static final int VALUE_TYPE_LIBRARY = 1;
private List<GitRepository> libraries;
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/net/OkHttpGlideModule.java
// Path: app/src/main/java/com/wecan/xhin/studio/App.java // public class App extends Application { // // // public static final String VALUE_AVOS_APPID = "AkVsXJ4RoWq1juPauOHe1OW5"; // public static final String VALUE_AVOS_APPKEY = "gFICBkjJSxlI5fHnvNyB7Lfj"; // // public static final String KEY_PREFERENCE_USER = "user"; // public static final String KEY_PREFERENCE_PHONE = "phone"; // public static final String KEY_BUILD_VERSION = "build_version"; // public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // // private final HashMap<Class, Object> apis = new HashMap<>(); // // private Retrofit retrofit; // // //返回当前单例的静态方法,判断是否是当前的App调用 // public static App from(Context context) { // Context application = context.getApplicationContext(); // if (application instanceof App) // return (App) application; // throw new IllegalArgumentException("Context must be from Studio"); // } // // // @Override // public void onCreate() { // super.onCreate(); // // AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY); // OkHttpClient okHttpClient = new OkHttpClient(); // //OKHttp的使用 // okHttpClient.networkInterceptors().add(new Interceptor() { // @Override // public Response intercept(Chain chain) throws IOException { // return chain.proceed(chain.request().newBuilder() // .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME) // .build()); // } // }); // // if (BuildConfig.DEBUG) { // okHttpClient.networkInterceptors().add(new LoggingInterceptor()); // } // // //初始化Gson // Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) // .setDateFormat(DATE_FORMAT_PATTERN) // .create(); // // // //初始化Retrofit // retrofit = new Retrofit.Builder() // .client(okHttpClient) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .baseUrl(Api.BASE_URL) // .build(); // } // // //返回Retrofit的API // public <T> T createApi(Class<T> service) { // if (!apis.containsKey(service)) { // T instance = retrofit.create(service); // apis.put(service, instance); // } // //noinspection unchecked // return (T) apis.get(service); // } // // public OkHttpClient getHttpClient() { // return retrofit.client(); // } // }
import android.content.Context; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.integration.okhttp.OkHttpUrlLoader; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.module.GlideModule; import com.wecan.xhin.studio.App; import java.io.InputStream;
package com.wecan.xhin.studio.net; public class OkHttpGlideModule implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { } @Override public void registerComponents(Context context, Glide glide) { glide.register(GlideUrl.class, InputStream.class,
// Path: app/src/main/java/com/wecan/xhin/studio/App.java // public class App extends Application { // // // public static final String VALUE_AVOS_APPID = "AkVsXJ4RoWq1juPauOHe1OW5"; // public static final String VALUE_AVOS_APPKEY = "gFICBkjJSxlI5fHnvNyB7Lfj"; // // public static final String KEY_PREFERENCE_USER = "user"; // public static final String KEY_PREFERENCE_PHONE = "phone"; // public static final String KEY_BUILD_VERSION = "build_version"; // public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // // private final HashMap<Class, Object> apis = new HashMap<>(); // // private Retrofit retrofit; // // //返回当前单例的静态方法,判断是否是当前的App调用 // public static App from(Context context) { // Context application = context.getApplicationContext(); // if (application instanceof App) // return (App) application; // throw new IllegalArgumentException("Context must be from Studio"); // } // // // @Override // public void onCreate() { // super.onCreate(); // // AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY); // OkHttpClient okHttpClient = new OkHttpClient(); // //OKHttp的使用 // okHttpClient.networkInterceptors().add(new Interceptor() { // @Override // public Response intercept(Chain chain) throws IOException { // return chain.proceed(chain.request().newBuilder() // .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME) // .build()); // } // }); // // if (BuildConfig.DEBUG) { // okHttpClient.networkInterceptors().add(new LoggingInterceptor()); // } // // //初始化Gson // Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) // .setDateFormat(DATE_FORMAT_PATTERN) // .create(); // // // //初始化Retrofit // retrofit = new Retrofit.Builder() // .client(okHttpClient) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .baseUrl(Api.BASE_URL) // .build(); // } // // //返回Retrofit的API // public <T> T createApi(Class<T> service) { // if (!apis.containsKey(service)) { // T instance = retrofit.create(service); // apis.put(service, instance); // } // //noinspection unchecked // return (T) apis.get(service); // } // // public OkHttpClient getHttpClient() { // return retrofit.client(); // } // } // Path: app/src/main/java/com/wecan/xhin/studio/net/OkHttpGlideModule.java import android.content.Context; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.integration.okhttp.OkHttpUrlLoader; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.module.GlideModule; import com.wecan.xhin.studio.App; import java.io.InputStream; package com.wecan.xhin.studio.net; public class OkHttpGlideModule implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { } @Override public void registerComponents(Context context, Glide glide) { glide.register(GlideUrl.class, InputStream.class,
new OkHttpUrlLoader.Factory(App.from(context).getHttpClient()));
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/App.java
// Path: baselib/src/main/java/com/wecan/xhin/baselib/net/LoggingInterceptor.java // public class LoggingInterceptor implements Interceptor { // // private static final String TAG = "OkHttp"; // // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // // Log.d(TAG, String.format("%s\n%s", request, request.headers())); // // Response response = chain.proceed(request); // // Log.d(TAG, String.format("%s\n%s", response, response.headers())); // // return response; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java // public interface Api { // // String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; // // @GET("api/users") // Observable<User> login(@Query("name") String name, @Query("phone") String phone); // // @POST("api/users") // Observable<BaseData> register(@Body RegisterBody registerUser); // // @PUT("api/users") // Observable<User> updateUser(@Body User updateUser); // // @POST("api/sign") // Observable<BaseData> sign(@Body SignBody user); // // @DELETE("api/sign") // Observable<BaseData> unSign(@Query("name") String name); // // @GET("api/message_all") // Observable<UsersData> getAllUser(); // // @GET("api/message") // Observable<UsersData> getSignedUser(); // // @GET("api/addplease/{code}") // Observable<BaseData> addCode(@Path("code") String code); // // }
import android.app.Application; import android.content.Context; import com.avos.avoscloud.AVOSCloud; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Response; import com.wecan.xhin.baselib.net.LoggingInterceptor; import com.wecan.xhin.studio.api.Api; import java.io.IOException; import java.util.HashMap; import retrofit.GsonConverterFactory; import retrofit.Retrofit; import retrofit.RxJavaCallAdapterFactory;
package com.wecan.xhin.studio; public class App extends Application { public static final String VALUE_AVOS_APPID = "AkVsXJ4RoWq1juPauOHe1OW5"; public static final String VALUE_AVOS_APPKEY = "gFICBkjJSxlI5fHnvNyB7Lfj"; public static final String KEY_PREFERENCE_USER = "user"; public static final String KEY_PREFERENCE_PHONE = "phone"; public static final String KEY_BUILD_VERSION = "build_version"; public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; private final HashMap<Class, Object> apis = new HashMap<>(); private Retrofit retrofit; //返回当前单例的静态方法,判断是否是当前的App调用 public static App from(Context context) { Context application = context.getApplicationContext(); if (application instanceof App) return (App) application; throw new IllegalArgumentException("Context must be from Studio"); } @Override public void onCreate() { super.onCreate(); AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY); OkHttpClient okHttpClient = new OkHttpClient(); //OKHttp的使用 okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME) .build()); } }); if (BuildConfig.DEBUG) {
// Path: baselib/src/main/java/com/wecan/xhin/baselib/net/LoggingInterceptor.java // public class LoggingInterceptor implements Interceptor { // // private static final String TAG = "OkHttp"; // // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // // Log.d(TAG, String.format("%s\n%s", request, request.headers())); // // Response response = chain.proceed(request); // // Log.d(TAG, String.format("%s\n%s", response, response.headers())); // // return response; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java // public interface Api { // // String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; // // @GET("api/users") // Observable<User> login(@Query("name") String name, @Query("phone") String phone); // // @POST("api/users") // Observable<BaseData> register(@Body RegisterBody registerUser); // // @PUT("api/users") // Observable<User> updateUser(@Body User updateUser); // // @POST("api/sign") // Observable<BaseData> sign(@Body SignBody user); // // @DELETE("api/sign") // Observable<BaseData> unSign(@Query("name") String name); // // @GET("api/message_all") // Observable<UsersData> getAllUser(); // // @GET("api/message") // Observable<UsersData> getSignedUser(); // // @GET("api/addplease/{code}") // Observable<BaseData> addCode(@Path("code") String code); // // } // Path: app/src/main/java/com/wecan/xhin/studio/App.java import android.app.Application; import android.content.Context; import com.avos.avoscloud.AVOSCloud; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Response; import com.wecan.xhin.baselib.net.LoggingInterceptor; import com.wecan.xhin.studio.api.Api; import java.io.IOException; import java.util.HashMap; import retrofit.GsonConverterFactory; import retrofit.Retrofit; import retrofit.RxJavaCallAdapterFactory; package com.wecan.xhin.studio; public class App extends Application { public static final String VALUE_AVOS_APPID = "AkVsXJ4RoWq1juPauOHe1OW5"; public static final String VALUE_AVOS_APPKEY = "gFICBkjJSxlI5fHnvNyB7Lfj"; public static final String KEY_PREFERENCE_USER = "user"; public static final String KEY_PREFERENCE_PHONE = "phone"; public static final String KEY_BUILD_VERSION = "build_version"; public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; private final HashMap<Class, Object> apis = new HashMap<>(); private Retrofit retrofit; //返回当前单例的静态方法,判断是否是当前的App调用 public static App from(Context context) { Context application = context.getApplicationContext(); if (application instanceof App) return (App) application; throw new IllegalArgumentException("Context must be from Studio"); } @Override public void onCreate() { super.onCreate(); AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY); OkHttpClient okHttpClient = new OkHttpClient(); //OKHttp的使用 okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME) .build()); } }); if (BuildConfig.DEBUG) {
okHttpClient.networkInterceptors().add(new LoggingInterceptor());
XhinLiang/Studio
app/src/main/java/com/wecan/xhin/studio/App.java
// Path: baselib/src/main/java/com/wecan/xhin/baselib/net/LoggingInterceptor.java // public class LoggingInterceptor implements Interceptor { // // private static final String TAG = "OkHttp"; // // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // // Log.d(TAG, String.format("%s\n%s", request, request.headers())); // // Response response = chain.proceed(request); // // Log.d(TAG, String.format("%s\n%s", response, response.headers())); // // return response; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java // public interface Api { // // String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; // // @GET("api/users") // Observable<User> login(@Query("name") String name, @Query("phone") String phone); // // @POST("api/users") // Observable<BaseData> register(@Body RegisterBody registerUser); // // @PUT("api/users") // Observable<User> updateUser(@Body User updateUser); // // @POST("api/sign") // Observable<BaseData> sign(@Body SignBody user); // // @DELETE("api/sign") // Observable<BaseData> unSign(@Query("name") String name); // // @GET("api/message_all") // Observable<UsersData> getAllUser(); // // @GET("api/message") // Observable<UsersData> getSignedUser(); // // @GET("api/addplease/{code}") // Observable<BaseData> addCode(@Path("code") String code); // // }
import android.app.Application; import android.content.Context; import com.avos.avoscloud.AVOSCloud; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Response; import com.wecan.xhin.baselib.net.LoggingInterceptor; import com.wecan.xhin.studio.api.Api; import java.io.IOException; import java.util.HashMap; import retrofit.GsonConverterFactory; import retrofit.Retrofit; import retrofit.RxJavaCallAdapterFactory;
super.onCreate(); AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY); OkHttpClient okHttpClient = new OkHttpClient(); //OKHttp的使用 okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME) .build()); } }); if (BuildConfig.DEBUG) { okHttpClient.networkInterceptors().add(new LoggingInterceptor()); } //初始化Gson Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setDateFormat(DATE_FORMAT_PATTERN) .create(); //初始化Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// Path: baselib/src/main/java/com/wecan/xhin/baselib/net/LoggingInterceptor.java // public class LoggingInterceptor implements Interceptor { // // private static final String TAG = "OkHttp"; // // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // // Log.d(TAG, String.format("%s\n%s", request, request.headers())); // // Response response = chain.proceed(request); // // Log.d(TAG, String.format("%s\n%s", response, response.headers())); // // return response; // } // } // // Path: app/src/main/java/com/wecan/xhin/studio/api/Api.java // public interface Api { // // String BASE_URL = "http://121.42.209.19/RestfulApi/index.php/"; // // @GET("api/users") // Observable<User> login(@Query("name") String name, @Query("phone") String phone); // // @POST("api/users") // Observable<BaseData> register(@Body RegisterBody registerUser); // // @PUT("api/users") // Observable<User> updateUser(@Body User updateUser); // // @POST("api/sign") // Observable<BaseData> sign(@Body SignBody user); // // @DELETE("api/sign") // Observable<BaseData> unSign(@Query("name") String name); // // @GET("api/message_all") // Observable<UsersData> getAllUser(); // // @GET("api/message") // Observable<UsersData> getSignedUser(); // // @GET("api/addplease/{code}") // Observable<BaseData> addCode(@Path("code") String code); // // } // Path: app/src/main/java/com/wecan/xhin/studio/App.java import android.app.Application; import android.content.Context; import com.avos.avoscloud.AVOSCloud; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Response; import com.wecan.xhin.baselib.net.LoggingInterceptor; import com.wecan.xhin.studio.api.Api; import java.io.IOException; import java.util.HashMap; import retrofit.GsonConverterFactory; import retrofit.Retrofit; import retrofit.RxJavaCallAdapterFactory; super.onCreate(); AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY); OkHttpClient okHttpClient = new OkHttpClient(); //OKHttp的使用 okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME) .build()); } }); if (BuildConfig.DEBUG) { okHttpClient.networkInterceptors().add(new LoggingInterceptor()); } //初始化Gson Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setDateFormat(DATE_FORMAT_PATTERN) .create(); //初始化Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(Api.BASE_URL)
square/protoparser
src/test/java/com/squareup/protoparser/UtilsTest.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // }
import org.junit.Test; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static org.assertj.core.api.Assertions.assertThat;
package com.squareup.protoparser; public class UtilsTest { @Test public void indentationTest() { String input = "Foo\nBar\nBaz"; String expected = " Foo\n Bar\n Baz\n"; StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // Path: src/test/java/com/squareup/protoparser/UtilsTest.java import org.junit.Test; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static org.assertj.core.api.Assertions.assertThat; package com.squareup.protoparser; public class UtilsTest { @Test public void indentationTest() { String input = "Foo\nBar\nBaz"; String expected = " Foo\n Bar\n Baz\n"; StringBuilder builder = new StringBuilder();
appendIndented(builder, input);
square/protoparser
src/test/java/com/squareup/protoparser/UtilsTest.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // }
import org.junit.Test; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static org.assertj.core.api.Assertions.assertThat;
package com.squareup.protoparser; public class UtilsTest { @Test public void indentationTest() { String input = "Foo\nBar\nBaz"; String expected = " Foo\n Bar\n Baz\n"; StringBuilder builder = new StringBuilder(); appendIndented(builder, input); assertThat(builder.toString()).isEqualTo(expected); } @Test public void documentationTest() { String input = "Foo\nBar\nBaz"; String expected = "" + "// Foo\n" + "// Bar\n" + "// Baz\n"; StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // Path: src/test/java/com/squareup/protoparser/UtilsTest.java import org.junit.Test; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static org.assertj.core.api.Assertions.assertThat; package com.squareup.protoparser; public class UtilsTest { @Test public void indentationTest() { String input = "Foo\nBar\nBaz"; String expected = " Foo\n Bar\n Baz\n"; StringBuilder builder = new StringBuilder(); appendIndented(builder, input); assertThat(builder.toString()).isEqualTo(expected); } @Test public void documentationTest() { String input = "Foo\nBar\nBaz"; String expected = "" + "// Foo\n" + "// Bar\n" + "// Baz\n"; StringBuilder builder = new StringBuilder();
appendDocumentation(builder, input);
square/protoparser
src/test/java/com/squareup/protoparser/OptionElementTest.java
// Path: src/test/java/com/squareup/protoparser/TestUtils.java // @SafeVarargs // static <T> List<T> list(T... values) { // return Arrays.asList(values); // } // // Path: src/test/java/com/squareup/protoparser/TestUtils.java // static Map<String, Object> map(Object... keysAndValues) { // Map<String, Object> result = new LinkedHashMap<>(); // for (int i = 0; i < keysAndValues.length; i += 2) { // result.put((String) keysAndValues[i], keysAndValues[i + 1]); // } // return result; // }
import java.util.List; import java.util.Map; import org.junit.Test; import static com.squareup.protoparser.OptionElement.Kind.BOOLEAN; import static com.squareup.protoparser.OptionElement.Kind.LIST; import static com.squareup.protoparser.OptionElement.Kind.MAP; import static com.squareup.protoparser.OptionElement.Kind.OPTION; import static com.squareup.protoparser.OptionElement.Kind.STRING; import static com.squareup.protoparser.TestUtils.list; import static com.squareup.protoparser.TestUtils.map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import static org.junit.Assert.fail;
fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("name == null"); } } @Test public void nullValueThrows() { try { OptionElement.create("test", STRING, null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("value == null"); } } @Test public void simpleToSchema() { OptionElement option = OptionElement.create("foo", STRING, "bar"); String expected = "foo = \"bar\""; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void nestedToSchema() { OptionElement option = OptionElement.create("foo.boo", OPTION, OptionElement.create("bar", STRING, "baz"), true); String expected = "(foo.boo).bar = \"baz\""; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void listToSchema() { OptionElement option = OptionElement.create("foo", LIST,
// Path: src/test/java/com/squareup/protoparser/TestUtils.java // @SafeVarargs // static <T> List<T> list(T... values) { // return Arrays.asList(values); // } // // Path: src/test/java/com/squareup/protoparser/TestUtils.java // static Map<String, Object> map(Object... keysAndValues) { // Map<String, Object> result = new LinkedHashMap<>(); // for (int i = 0; i < keysAndValues.length; i += 2) { // result.put((String) keysAndValues[i], keysAndValues[i + 1]); // } // return result; // } // Path: src/test/java/com/squareup/protoparser/OptionElementTest.java import java.util.List; import java.util.Map; import org.junit.Test; import static com.squareup.protoparser.OptionElement.Kind.BOOLEAN; import static com.squareup.protoparser.OptionElement.Kind.LIST; import static com.squareup.protoparser.OptionElement.Kind.MAP; import static com.squareup.protoparser.OptionElement.Kind.OPTION; import static com.squareup.protoparser.OptionElement.Kind.STRING; import static com.squareup.protoparser.TestUtils.list; import static com.squareup.protoparser.TestUtils.map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import static org.junit.Assert.fail; fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("name == null"); } } @Test public void nullValueThrows() { try { OptionElement.create("test", STRING, null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("value == null"); } } @Test public void simpleToSchema() { OptionElement option = OptionElement.create("foo", STRING, "bar"); String expected = "foo = \"bar\""; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void nestedToSchema() { OptionElement option = OptionElement.create("foo.boo", OPTION, OptionElement.create("bar", STRING, "baz"), true); String expected = "(foo.boo).bar = \"baz\""; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void listToSchema() { OptionElement option = OptionElement.create("foo", LIST,
list(OptionElement.create("ping", STRING, "pong", true),
square/protoparser
src/test/java/com/squareup/protoparser/OptionElementTest.java
// Path: src/test/java/com/squareup/protoparser/TestUtils.java // @SafeVarargs // static <T> List<T> list(T... values) { // return Arrays.asList(values); // } // // Path: src/test/java/com/squareup/protoparser/TestUtils.java // static Map<String, Object> map(Object... keysAndValues) { // Map<String, Object> result = new LinkedHashMap<>(); // for (int i = 0; i < keysAndValues.length; i += 2) { // result.put((String) keysAndValues[i], keysAndValues[i + 1]); // } // return result; // }
import java.util.List; import java.util.Map; import org.junit.Test; import static com.squareup.protoparser.OptionElement.Kind.BOOLEAN; import static com.squareup.protoparser.OptionElement.Kind.LIST; import static com.squareup.protoparser.OptionElement.Kind.MAP; import static com.squareup.protoparser.OptionElement.Kind.OPTION; import static com.squareup.protoparser.OptionElement.Kind.STRING; import static com.squareup.protoparser.TestUtils.list; import static com.squareup.protoparser.TestUtils.map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import static org.junit.Assert.fail;
} } @Test public void simpleToSchema() { OptionElement option = OptionElement.create("foo", STRING, "bar"); String expected = "foo = \"bar\""; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void nestedToSchema() { OptionElement option = OptionElement.create("foo.boo", OPTION, OptionElement.create("bar", STRING, "baz"), true); String expected = "(foo.boo).bar = \"baz\""; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void listToSchema() { OptionElement option = OptionElement.create("foo", LIST, list(OptionElement.create("ping", STRING, "pong", true), OptionElement.create("kit", STRING, "kat")), true); String expected = "" + "(foo) = [\n" + " (ping) = \"pong\",\n" + " kit = \"kat\"\n" + "]"; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void mapToSchema() { OptionElement option =
// Path: src/test/java/com/squareup/protoparser/TestUtils.java // @SafeVarargs // static <T> List<T> list(T... values) { // return Arrays.asList(values); // } // // Path: src/test/java/com/squareup/protoparser/TestUtils.java // static Map<String, Object> map(Object... keysAndValues) { // Map<String, Object> result = new LinkedHashMap<>(); // for (int i = 0; i < keysAndValues.length; i += 2) { // result.put((String) keysAndValues[i], keysAndValues[i + 1]); // } // return result; // } // Path: src/test/java/com/squareup/protoparser/OptionElementTest.java import java.util.List; import java.util.Map; import org.junit.Test; import static com.squareup.protoparser.OptionElement.Kind.BOOLEAN; import static com.squareup.protoparser.OptionElement.Kind.LIST; import static com.squareup.protoparser.OptionElement.Kind.MAP; import static com.squareup.protoparser.OptionElement.Kind.OPTION; import static com.squareup.protoparser.OptionElement.Kind.STRING; import static com.squareup.protoparser.TestUtils.list; import static com.squareup.protoparser.TestUtils.map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import static org.junit.Assert.fail; } } @Test public void simpleToSchema() { OptionElement option = OptionElement.create("foo", STRING, "bar"); String expected = "foo = \"bar\""; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void nestedToSchema() { OptionElement option = OptionElement.create("foo.boo", OPTION, OptionElement.create("bar", STRING, "baz"), true); String expected = "(foo.boo).bar = \"baz\""; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void listToSchema() { OptionElement option = OptionElement.create("foo", LIST, list(OptionElement.create("ping", STRING, "pong", true), OptionElement.create("kit", STRING, "kat")), true); String expected = "" + "(foo) = [\n" + " (ping) = \"pong\",\n" + " kit = \"kat\"\n" + "]"; assertThat(option.toSchema()).isEqualTo(expected); } @Test public void mapToSchema() { OptionElement option =
OptionElement.create("foo", MAP, map("ping", "pong", "kit", list("kat", "kot")));
square/protoparser
src/test/java/com/squareup/protoparser/DataTypeTest.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // }
import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.ANY; import static com.squareup.protoparser.DataType.ScalarType.BOOL; import static com.squareup.protoparser.DataType.ScalarType.BYTES; import static com.squareup.protoparser.DataType.ScalarType.DOUBLE; import static com.squareup.protoparser.DataType.ScalarType.FIXED32; import static com.squareup.protoparser.DataType.ScalarType.FIXED64; import static com.squareup.protoparser.DataType.ScalarType.FLOAT; import static com.squareup.protoparser.DataType.ScalarType.INT32; import static com.squareup.protoparser.DataType.ScalarType.INT64; import static com.squareup.protoparser.DataType.ScalarType.SFIXED32; import static com.squareup.protoparser.DataType.ScalarType.SFIXED64; import static com.squareup.protoparser.DataType.ScalarType.SINT32; import static com.squareup.protoparser.DataType.ScalarType.SINT64; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.DataType.ScalarType.UINT32; import static com.squareup.protoparser.DataType.ScalarType.UINT64; import static org.assertj.core.api.Assertions.assertThat;
package com.squareup.protoparser; public final class DataTypeTest { @Test public void scalarToString() { assertThat(ANY.toString()).isEqualTo("any"); assertThat(BOOL.toString()).isEqualTo("bool"); assertThat(BYTES.toString()).isEqualTo("bytes"); assertThat(DOUBLE.toString()).isEqualTo("double"); assertThat(FLOAT.toString()).isEqualTo("float"); assertThat(FIXED32.toString()).isEqualTo("fixed32"); assertThat(FIXED64.toString()).isEqualTo("fixed64"); assertThat(INT32.toString()).isEqualTo("int32"); assertThat(INT64.toString()).isEqualTo("int64"); assertThat(SFIXED32.toString()).isEqualTo("sfixed32"); assertThat(SFIXED64.toString()).isEqualTo("sfixed64"); assertThat(SINT32.toString()).isEqualTo("sint32"); assertThat(SINT64.toString()).isEqualTo("sint64"); assertThat(STRING.toString()).isEqualTo("string"); assertThat(UINT32.toString()).isEqualTo("uint32"); assertThat(UINT64.toString()).isEqualTo("uint64"); } @Test public void mapToString() {
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // Path: src/test/java/com/squareup/protoparser/DataTypeTest.java import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.ANY; import static com.squareup.protoparser.DataType.ScalarType.BOOL; import static com.squareup.protoparser.DataType.ScalarType.BYTES; import static com.squareup.protoparser.DataType.ScalarType.DOUBLE; import static com.squareup.protoparser.DataType.ScalarType.FIXED32; import static com.squareup.protoparser.DataType.ScalarType.FIXED64; import static com.squareup.protoparser.DataType.ScalarType.FLOAT; import static com.squareup.protoparser.DataType.ScalarType.INT32; import static com.squareup.protoparser.DataType.ScalarType.INT64; import static com.squareup.protoparser.DataType.ScalarType.SFIXED32; import static com.squareup.protoparser.DataType.ScalarType.SFIXED64; import static com.squareup.protoparser.DataType.ScalarType.SINT32; import static com.squareup.protoparser.DataType.ScalarType.SINT64; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.DataType.ScalarType.UINT32; import static com.squareup.protoparser.DataType.ScalarType.UINT64; import static org.assertj.core.api.Assertions.assertThat; package com.squareup.protoparser; public final class DataTypeTest { @Test public void scalarToString() { assertThat(ANY.toString()).isEqualTo("any"); assertThat(BOOL.toString()).isEqualTo("bool"); assertThat(BYTES.toString()).isEqualTo("bytes"); assertThat(DOUBLE.toString()).isEqualTo("double"); assertThat(FLOAT.toString()).isEqualTo("float"); assertThat(FIXED32.toString()).isEqualTo("fixed32"); assertThat(FIXED64.toString()).isEqualTo("fixed64"); assertThat(INT32.toString()).isEqualTo("int32"); assertThat(INT64.toString()).isEqualTo("int64"); assertThat(SFIXED32.toString()).isEqualTo("sfixed32"); assertThat(SFIXED64.toString()).isEqualTo("sfixed64"); assertThat(SINT32.toString()).isEqualTo("sint32"); assertThat(SINT64.toString()).isEqualTo("sint64"); assertThat(STRING.toString()).isEqualTo("string"); assertThat(UINT32.toString()).isEqualTo("uint32"); assertThat(UINT64.toString()).isEqualTo("uint64"); } @Test public void mapToString() {
assertThat(MapType.create(STRING, STRING).toString()).isEqualTo("map<string, string>");
square/protoparser
src/test/java/com/squareup/protoparser/DataTypeTest.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // }
import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.ANY; import static com.squareup.protoparser.DataType.ScalarType.BOOL; import static com.squareup.protoparser.DataType.ScalarType.BYTES; import static com.squareup.protoparser.DataType.ScalarType.DOUBLE; import static com.squareup.protoparser.DataType.ScalarType.FIXED32; import static com.squareup.protoparser.DataType.ScalarType.FIXED64; import static com.squareup.protoparser.DataType.ScalarType.FLOAT; import static com.squareup.protoparser.DataType.ScalarType.INT32; import static com.squareup.protoparser.DataType.ScalarType.INT64; import static com.squareup.protoparser.DataType.ScalarType.SFIXED32; import static com.squareup.protoparser.DataType.ScalarType.SFIXED64; import static com.squareup.protoparser.DataType.ScalarType.SINT32; import static com.squareup.protoparser.DataType.ScalarType.SINT64; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.DataType.ScalarType.UINT32; import static com.squareup.protoparser.DataType.ScalarType.UINT64; import static org.assertj.core.api.Assertions.assertThat;
package com.squareup.protoparser; public final class DataTypeTest { @Test public void scalarToString() { assertThat(ANY.toString()).isEqualTo("any"); assertThat(BOOL.toString()).isEqualTo("bool"); assertThat(BYTES.toString()).isEqualTo("bytes"); assertThat(DOUBLE.toString()).isEqualTo("double"); assertThat(FLOAT.toString()).isEqualTo("float"); assertThat(FIXED32.toString()).isEqualTo("fixed32"); assertThat(FIXED64.toString()).isEqualTo("fixed64"); assertThat(INT32.toString()).isEqualTo("int32"); assertThat(INT64.toString()).isEqualTo("int64"); assertThat(SFIXED32.toString()).isEqualTo("sfixed32"); assertThat(SFIXED64.toString()).isEqualTo("sfixed64"); assertThat(SINT32.toString()).isEqualTo("sint32"); assertThat(SINT64.toString()).isEqualTo("sint64"); assertThat(STRING.toString()).isEqualTo("string"); assertThat(UINT32.toString()).isEqualTo("uint32"); assertThat(UINT64.toString()).isEqualTo("uint64"); } @Test public void mapToString() { assertThat(MapType.create(STRING, STRING).toString()).isEqualTo("map<string, string>"); } @Test public void namedToString() {
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // Path: src/test/java/com/squareup/protoparser/DataTypeTest.java import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.ANY; import static com.squareup.protoparser.DataType.ScalarType.BOOL; import static com.squareup.protoparser.DataType.ScalarType.BYTES; import static com.squareup.protoparser.DataType.ScalarType.DOUBLE; import static com.squareup.protoparser.DataType.ScalarType.FIXED32; import static com.squareup.protoparser.DataType.ScalarType.FIXED64; import static com.squareup.protoparser.DataType.ScalarType.FLOAT; import static com.squareup.protoparser.DataType.ScalarType.INT32; import static com.squareup.protoparser.DataType.ScalarType.INT64; import static com.squareup.protoparser.DataType.ScalarType.SFIXED32; import static com.squareup.protoparser.DataType.ScalarType.SFIXED64; import static com.squareup.protoparser.DataType.ScalarType.SINT32; import static com.squareup.protoparser.DataType.ScalarType.SINT64; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.DataType.ScalarType.UINT32; import static com.squareup.protoparser.DataType.ScalarType.UINT64; import static org.assertj.core.api.Assertions.assertThat; package com.squareup.protoparser; public final class DataTypeTest { @Test public void scalarToString() { assertThat(ANY.toString()).isEqualTo("any"); assertThat(BOOL.toString()).isEqualTo("bool"); assertThat(BYTES.toString()).isEqualTo("bytes"); assertThat(DOUBLE.toString()).isEqualTo("double"); assertThat(FLOAT.toString()).isEqualTo("float"); assertThat(FIXED32.toString()).isEqualTo("fixed32"); assertThat(FIXED64.toString()).isEqualTo("fixed64"); assertThat(INT32.toString()).isEqualTo("int32"); assertThat(INT64.toString()).isEqualTo("int64"); assertThat(SFIXED32.toString()).isEqualTo("sfixed32"); assertThat(SFIXED64.toString()).isEqualTo("sfixed64"); assertThat(SINT32.toString()).isEqualTo("sint32"); assertThat(SINT64.toString()).isEqualTo("sint64"); assertThat(STRING.toString()).isEqualTo("string"); assertThat(UINT32.toString()).isEqualTo("uint32"); assertThat(UINT64.toString()).isEqualTo("uint64"); } @Test public void mapToString() { assertThat(MapType.create(STRING, STRING).toString()).isEqualTo("map<string, string>"); } @Test public void namedToString() {
assertThat(NamedType.create("test").toString()).isEqualTo("test");
square/protoparser
src/test/java/com/squareup/protoparser/ProtoFileTest.java
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MAX_TAG_VALUE = (1 << 29) - 1; // 536,870,911 // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MIN_TAG_VALUE = 1; // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // }
import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.ProtoFile.MAX_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.MIN_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.isValidTag; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
assertThat(e).hasMessage("extendDeclarations == null"); } try { ProtoFile.builder("test.proto").addExtendDeclarations( Collections.<ExtendElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("extend == null"); } try { ProtoFile.builder("test.proto").addOption(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } try { ProtoFile.builder("test.proto").addOptions(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("options == null"); } try { ProtoFile.builder("test.proto").addOptions(Collections.<OptionElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } } @Test public void tagValueValidation() {
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MAX_TAG_VALUE = (1 << 29) - 1; // 536,870,911 // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MIN_TAG_VALUE = 1; // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // Path: src/test/java/com/squareup/protoparser/ProtoFileTest.java import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.ProtoFile.MAX_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.MIN_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.isValidTag; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; assertThat(e).hasMessage("extendDeclarations == null"); } try { ProtoFile.builder("test.proto").addExtendDeclarations( Collections.<ExtendElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("extend == null"); } try { ProtoFile.builder("test.proto").addOption(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } try { ProtoFile.builder("test.proto").addOptions(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("options == null"); } try { ProtoFile.builder("test.proto").addOptions(Collections.<OptionElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } } @Test public void tagValueValidation() {
assertThat(isValidTag(MIN_TAG_VALUE - 1)).isFalse(); // Less than minimum.
square/protoparser
src/test/java/com/squareup/protoparser/ProtoFileTest.java
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MAX_TAG_VALUE = (1 << 29) - 1; // 536,870,911 // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MIN_TAG_VALUE = 1; // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // }
import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.ProtoFile.MAX_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.MIN_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.isValidTag; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
assertThat(e).hasMessage("extendDeclarations == null"); } try { ProtoFile.builder("test.proto").addExtendDeclarations( Collections.<ExtendElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("extend == null"); } try { ProtoFile.builder("test.proto").addOption(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } try { ProtoFile.builder("test.proto").addOptions(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("options == null"); } try { ProtoFile.builder("test.proto").addOptions(Collections.<OptionElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } } @Test public void tagValueValidation() {
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MAX_TAG_VALUE = (1 << 29) - 1; // 536,870,911 // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MIN_TAG_VALUE = 1; // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // Path: src/test/java/com/squareup/protoparser/ProtoFileTest.java import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.ProtoFile.MAX_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.MIN_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.isValidTag; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; assertThat(e).hasMessage("extendDeclarations == null"); } try { ProtoFile.builder("test.proto").addExtendDeclarations( Collections.<ExtendElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("extend == null"); } try { ProtoFile.builder("test.proto").addOption(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } try { ProtoFile.builder("test.proto").addOptions(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("options == null"); } try { ProtoFile.builder("test.proto").addOptions(Collections.<OptionElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } } @Test public void tagValueValidation() {
assertThat(isValidTag(MIN_TAG_VALUE - 1)).isFalse(); // Less than minimum.
square/protoparser
src/test/java/com/squareup/protoparser/ProtoFileTest.java
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MAX_TAG_VALUE = (1 << 29) - 1; // 536,870,911 // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MIN_TAG_VALUE = 1; // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // }
import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.ProtoFile.MAX_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.MIN_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.isValidTag; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("extend == null"); } try { ProtoFile.builder("test.proto").addOption(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } try { ProtoFile.builder("test.proto").addOptions(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("options == null"); } try { ProtoFile.builder("test.proto").addOptions(Collections.<OptionElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } } @Test public void tagValueValidation() { assertThat(isValidTag(MIN_TAG_VALUE - 1)).isFalse(); // Less than minimum. assertThat(isValidTag(MIN_TAG_VALUE)).isTrue(); assertThat(isValidTag(1234)).isTrue(); assertThat(isValidTag(19222)).isFalse(); // Reserved range. assertThat(isValidTag(2319573)).isTrue();
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MAX_TAG_VALUE = (1 << 29) - 1; // 536,870,911 // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MIN_TAG_VALUE = 1; // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // Path: src/test/java/com/squareup/protoparser/ProtoFileTest.java import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.ProtoFile.MAX_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.MIN_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.isValidTag; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("extend == null"); } try { ProtoFile.builder("test.proto").addOption(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } try { ProtoFile.builder("test.proto").addOptions(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("options == null"); } try { ProtoFile.builder("test.proto").addOptions(Collections.<OptionElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } } @Test public void tagValueValidation() { assertThat(isValidTag(MIN_TAG_VALUE - 1)).isFalse(); // Less than minimum. assertThat(isValidTag(MIN_TAG_VALUE)).isTrue(); assertThat(isValidTag(1234)).isTrue(); assertThat(isValidTag(19222)).isFalse(); // Reserved range. assertThat(isValidTag(2319573)).isTrue();
assertThat(isValidTag(MAX_TAG_VALUE)).isTrue();
square/protoparser
src/test/java/com/squareup/protoparser/ProtoFileTest.java
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MAX_TAG_VALUE = (1 << 29) - 1; // 536,870,911 // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MIN_TAG_VALUE = 1; // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // }
import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.ProtoFile.MAX_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.MIN_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.isValidTag; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
+ "import public \"example.other\";\n" + "\n" + "message Message {}\n"; assertThat(file.toSchema()).isEqualTo(expected); } @Test public void simpleWithServicesToSchema() { TypeElement element = MessageElement.builder().name("Message").build(); ServiceElement service = ServiceElement.builder().name("Service").build(); ProtoFile file = ProtoFile.builder("file.proto").addType(element).addService(service).build(); String expected = "" + "// file.proto\n" + "\n" + "message Message {}\n" + "\n" + "service Service {}\n"; assertThat(file.toSchema()).isEqualTo(expected); } @Test public void addMultipleServices() { ServiceElement service1 = ServiceElement.builder().name("Service1").build(); ServiceElement service2 = ServiceElement.builder().name("Service2").build(); ProtoFile file = ProtoFile.builder("file.proto") .addServices(Arrays.asList(service1, service2)) .build(); assertThat(file.services()).hasSize(2); } @Test public void simpleWithOptionsToSchema() { TypeElement element = MessageElement.builder().name("Message").build();
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MAX_TAG_VALUE = (1 << 29) - 1; // 536,870,911 // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static final int MIN_TAG_VALUE = 1; // // Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // Path: src/test/java/com/squareup/protoparser/ProtoFileTest.java import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.ProtoFile.MAX_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.MIN_TAG_VALUE; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.isValidTag; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; + "import public \"example.other\";\n" + "\n" + "message Message {}\n"; assertThat(file.toSchema()).isEqualTo(expected); } @Test public void simpleWithServicesToSchema() { TypeElement element = MessageElement.builder().name("Message").build(); ServiceElement service = ServiceElement.builder().name("Service").build(); ProtoFile file = ProtoFile.builder("file.proto").addType(element).addService(service).build(); String expected = "" + "// file.proto\n" + "\n" + "message Message {}\n" + "\n" + "service Service {}\n"; assertThat(file.toSchema()).isEqualTo(expected); } @Test public void addMultipleServices() { ServiceElement service1 = ServiceElement.builder().name("Service1").build(); ServiceElement service2 = ServiceElement.builder().name("Service2").build(); ProtoFile file = ProtoFile.builder("file.proto") .addServices(Arrays.asList(service1, service2)) .build(); assertThat(file.services()).hasSize(2); } @Test public void simpleWithOptionsToSchema() { TypeElement element = MessageElement.builder().name("Message").build();
OptionElement option = OptionElement.create("kit", Kind.STRING, "kat");
square/protoparser
src/test/java/com/squareup/protoparser/ServiceElementTest.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // }
import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
ServiceElement.builder().addOption(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } try { ServiceElement.builder().addOptions(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("options == null"); } try { ServiceElement.builder().addOptions(Collections.<OptionElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } } @Test public void emptyToSchema() { ServiceElement service = ServiceElement.builder().name("Service").build(); String expected = "service Service {}\n"; assertThat(service.toSchema()).isEqualTo(expected); } @Test public void singleToSchema() { ServiceElement service = ServiceElement.builder() .name("Service") .addRpc(RpcElement.builder() .name("Name")
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // Path: src/test/java/com/squareup/protoparser/ServiceElementTest.java import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; ServiceElement.builder().addOption(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } try { ServiceElement.builder().addOptions(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("options == null"); } try { ServiceElement.builder().addOptions(Collections.<OptionElement>singleton(null)); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("option == null"); } } @Test public void emptyToSchema() { ServiceElement service = ServiceElement.builder().name("Service").build(); String expected = "service Service {}\n"; assertThat(service.toSchema()).isEqualTo(expected); } @Test public void singleToSchema() { ServiceElement service = ServiceElement.builder() .name("Service") .addRpc(RpcElement.builder() .name("Name")
.requestType(NamedType.create("RequestType"))
square/protoparser
src/test/java/com/squareup/protoparser/ServiceElementTest.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // }
import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
.build()) .build(); String expected = "" + "service Service {\n" + " rpc Name (RequestType) returns (ResponseType);\n" + "}\n"; assertThat(service.toSchema()).isEqualTo(expected); } @Test public void addMultipleRpcs() { RpcElement firstName = RpcElement.builder() .name("FirstName") .requestType(NamedType.create("RequestType")) .responseType(NamedType.create("ResponseType")) .build(); RpcElement lastName = RpcElement.builder() .name("LastName") .requestType(NamedType.create("RequestType")) .responseType(NamedType.create("ResponseType")) .build(); ServiceElement service = ServiceElement.builder() .name("Service") .addRpcs(Arrays.asList(firstName, lastName)) .build(); assertThat(service.rpcs()).hasSize(2); } @Test public void singleWithOptionsToSchema() { ServiceElement service = ServiceElement.builder() .name("Service")
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // Path: src/test/java/com/squareup/protoparser/ServiceElementTest.java import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; .build()) .build(); String expected = "" + "service Service {\n" + " rpc Name (RequestType) returns (ResponseType);\n" + "}\n"; assertThat(service.toSchema()).isEqualTo(expected); } @Test public void addMultipleRpcs() { RpcElement firstName = RpcElement.builder() .name("FirstName") .requestType(NamedType.create("RequestType")) .responseType(NamedType.create("ResponseType")) .build(); RpcElement lastName = RpcElement.builder() .name("LastName") .requestType(NamedType.create("RequestType")) .responseType(NamedType.create("ResponseType")) .build(); ServiceElement service = ServiceElement.builder() .name("Service") .addRpcs(Arrays.asList(firstName, lastName)) .build(); assertThat(service.rpcs()).hasSize(2); } @Test public void singleWithOptionsToSchema() { ServiceElement service = ServiceElement.builder() .name("Service")
.addOption(OptionElement.create("foo", Kind.STRING, "bar"))
square/protoparser
src/main/java/com/squareup/protoparser/FieldElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/FieldElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder();
appendDocumentation(builder, documentation());
square/protoparser
src/main/java/com/squareup/protoparser/FieldElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) {
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/FieldElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) {
appendIndented(builder, option.toSchema());
square/protoparser
src/main/java/com/squareup/protoparser/FieldElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchema()); } builder.append(']'); } return builder.append(";\n").toString(); } public enum Label { OPTIONAL, REQUIRED, REPEATED, /** Indicates the field is a member of a {@code oneof} block. */ ONE_OF } public static final class Builder { private Label label; private DataType type; private String name; private Integer tag; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder label(Label label) {
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/FieldElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchema()); } builder.append(']'); } return builder.append(";\n").toString(); } public enum Label { OPTIONAL, REQUIRED, REPEATED, /** Indicates the field is a member of a {@code oneof} block. */ ONE_OF } public static final class Builder { private Label label; private DataType type; private String name; private Integer tag; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder label(Label label) {
this.label = checkNotNull(label, "label");
square/protoparser
src/main/java/com/squareup/protoparser/FieldElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchema()); } builder.append(']'); } return builder.append(";\n").toString(); } public enum Label { OPTIONAL, REQUIRED, REPEATED, /** Indicates the field is a member of a {@code oneof} block. */ ONE_OF } public static final class Builder { private Label label; private DataType type; private String name; private Integer tag; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder label(Label label) { this.label = checkNotNull(label, "label"); return this; } public Builder type(DataType type) { this.type = checkNotNull(type, "type"); return this; } public Builder name(String name) { this.name = checkNotNull(name, "name"); return this; } public Builder tag(int tag) { this.tag = tag; return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public FieldElement build() { checkNotNull(label, "label"); checkNotNull(type, "type"); checkNotNull(name, "name"); checkNotNull(tag, "tag");
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/FieldElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchema()); } builder.append(']'); } return builder.append(";\n").toString(); } public enum Label { OPTIONAL, REQUIRED, REPEATED, /** Indicates the field is a member of a {@code oneof} block. */ ONE_OF } public static final class Builder { private Label label; private DataType type; private String name; private Integer tag; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder label(Label label) { this.label = checkNotNull(label, "label"); return this; } public Builder type(DataType type) { this.type = checkNotNull(type, "type"); return this; } public Builder name(String name) { this.name = checkNotNull(name, "name"); return this; } public Builder tag(int tag) { this.tag = tag; return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public FieldElement build() { checkNotNull(label, "label"); checkNotNull(type, "type"); checkNotNull(name, "name"); checkNotNull(tag, "tag");
checkArgument(isValidTag(tag), "Illegal tag value: %s", tag);
square/protoparser
src/main/java/com/squareup/protoparser/FieldElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchema()); } builder.append(']'); } return builder.append(";\n").toString(); } public enum Label { OPTIONAL, REQUIRED, REPEATED, /** Indicates the field is a member of a {@code oneof} block. */ ONE_OF } public static final class Builder { private Label label; private DataType type; private String name; private Integer tag; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder label(Label label) { this.label = checkNotNull(label, "label"); return this; } public Builder type(DataType type) { this.type = checkNotNull(type, "type"); return this; } public Builder name(String name) { this.name = checkNotNull(name, "name"); return this; } public Builder tag(int tag) { this.tag = tag; return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public FieldElement build() { checkNotNull(label, "label"); checkNotNull(type, "type"); checkNotNull(name, "name"); checkNotNull(tag, "tag");
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/FieldElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchema()); } builder.append(']'); } return builder.append(";\n").toString(); } public enum Label { OPTIONAL, REQUIRED, REPEATED, /** Indicates the field is a member of a {@code oneof} block. */ ONE_OF } public static final class Builder { private Label label; private DataType type; private String name; private Integer tag; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder label(Label label) { this.label = checkNotNull(label, "label"); return this; } public Builder type(DataType type) { this.type = checkNotNull(type, "type"); return this; } public Builder name(String name) { this.name = checkNotNull(name, "name"); return this; } public Builder tag(int tag) { this.tag = tag; return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public FieldElement build() { checkNotNull(label, "label"); checkNotNull(type, "type"); checkNotNull(name, "name"); checkNotNull(tag, "tag");
checkArgument(isValidTag(tag), "Illegal tag value: %s", tag);
square/protoparser
src/main/java/com/squareup/protoparser/FieldElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchema()); } builder.append(']'); } return builder.append(";\n").toString(); } public enum Label { OPTIONAL, REQUIRED, REPEATED, /** Indicates the field is a member of a {@code oneof} block. */ ONE_OF } public static final class Builder { private Label label; private DataType type; private String name; private Integer tag; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder label(Label label) { this.label = checkNotNull(label, "label"); return this; } public Builder type(DataType type) { this.type = checkNotNull(type, "type"); return this; } public Builder name(String name) { this.name = checkNotNull(name, "name"); return this; } public Builder tag(int tag) { this.tag = tag; return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public FieldElement build() { checkNotNull(label, "label"); checkNotNull(type, "type"); checkNotNull(name, "name"); checkNotNull(tag, "tag"); checkArgument(isValidTag(tag), "Illegal tag value: %s", tag); return new AutoValue_FieldElement(label, type, name, tag, documentation,
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/FieldElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkArgument; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class FieldElement { public static Builder builder() { return new Builder(); } FieldElement() { } public abstract Label label(); /** * Returns the type of this field. May be a message type name, an enum type * name, or a <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar"> * scalar value type</a> like {@code int64} or {@code bytes}. */ public abstract DataType type(); public abstract String name(); public abstract int tag(); public abstract String documentation(); public abstract List<OptionElement> options(); /** Returns true when the {@code deprecated} option is present and set to true. */ public final boolean isDeprecated() { OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated"); return deprecatedOption != null && "true".equals(deprecatedOption.value()); } /** Returns true when the {@code packed} option is present and set to true. */ public final boolean isPacked() { OptionElement packedOption = OptionElement.findByName(options(), "packed"); return packedOption != null && "true".equals(packedOption.value()); } /** Returns the {@code default} option value or {@code null}. */ public final OptionElement getDefault() { OptionElement defaultOption = OptionElement.findByName(options(), "default"); return defaultOption != null ? defaultOption : null; } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); if (label() != Label.ONE_OF) { builder.append(label().name().toLowerCase(Locale.US)).append(' '); } builder.append(type()) .append(' ') .append(name()) .append(" = ") .append(tag()); if (!options().isEmpty()) { builder.append(" [\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchema()); } builder.append(']'); } return builder.append(";\n").toString(); } public enum Label { OPTIONAL, REQUIRED, REPEATED, /** Indicates the field is a member of a {@code oneof} block. */ ONE_OF } public static final class Builder { private Label label; private DataType type; private String name; private Integer tag; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder label(Label label) { this.label = checkNotNull(label, "label"); return this; } public Builder type(DataType type) { this.type = checkNotNull(type, "type"); return this; } public Builder name(String name) { this.name = checkNotNull(name, "name"); return this; } public Builder tag(int tag) { this.tag = tag; return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public FieldElement build() { checkNotNull(label, "label"); checkNotNull(type, "type"); checkNotNull(name, "name"); checkNotNull(tag, "tag"); checkArgument(isValidTag(tag), "Illegal tag value: %s", tag); return new AutoValue_FieldElement(label, type, name, tag, documentation,
immutableCopyOf(options));
square/protoparser
src/main/java/com/squareup/protoparser/OneOfElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class OneOfElement { public static Builder builder() { return new Builder(); } OneOfElement() { } public abstract String name(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/OneOfElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class OneOfElement { public static Builder builder() { return new Builder(); } OneOfElement() { } public abstract String name(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder();
appendDocumentation(builder, documentation());
square/protoparser
src/main/java/com/squareup/protoparser/OneOfElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class OneOfElement { public static Builder builder() { return new Builder(); } OneOfElement() { } public abstract String name(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("oneof ").append(name()).append(" {"); if (!fields().isEmpty()) { builder.append('\n'); for (FieldElement field : fields()) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/OneOfElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class OneOfElement { public static Builder builder() { return new Builder(); } OneOfElement() { } public abstract String name(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("oneof ").append(name()).append(" {"); if (!fields().isEmpty()) { builder.append('\n'); for (FieldElement field : fields()) {
appendIndented(builder, field.toSchema());
square/protoparser
src/main/java/com/squareup/protoparser/OneOfElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class OneOfElement { public static Builder builder() { return new Builder(); } OneOfElement() { } public abstract String name(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("oneof ").append(name()).append(" {"); if (!fields().isEmpty()) { builder.append('\n'); for (FieldElement field : fields()) { appendIndented(builder, field.toSchema()); } } return builder.append("}\n").toString(); } public static final class Builder { private String name; private String documentation = ""; private final List<FieldElement> fields = new ArrayList<>(); private Builder() { } public Builder name(String name) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/OneOfElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class OneOfElement { public static Builder builder() { return new Builder(); } OneOfElement() { } public abstract String name(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("oneof ").append(name()).append(" {"); if (!fields().isEmpty()) { builder.append('\n'); for (FieldElement field : fields()) { appendIndented(builder, field.toSchema()); } } return builder.append("}\n").toString(); } public static final class Builder { private String name; private String documentation = ""; private final List<FieldElement> fields = new ArrayList<>(); private Builder() { } public Builder name(String name) {
this.name = checkNotNull(name, "name");
square/protoparser
src/main/java/com/squareup/protoparser/OneOfElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
private Builder() { } public Builder name(String name) { this.name = checkNotNull(name, "name"); return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addField(FieldElement field) { fields.add(checkNotNull(field, "field")); return this; } public Builder addFields(Collection<FieldElement> fields) { for (FieldElement field : checkNotNull(fields, "fields")) { addField(field); } return this; } public OneOfElement build() { checkNotNull(name, "name"); // TODO check non-empty?
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/OneOfElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; private Builder() { } public Builder name(String name) { this.name = checkNotNull(name, "name"); return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addField(FieldElement field) { fields.add(checkNotNull(field, "field")); return this; } public Builder addFields(Collection<FieldElement> fields) { for (FieldElement field : checkNotNull(fields, "fields")) { addField(field); } return this; } public OneOfElement build() { checkNotNull(name, "name"); // TODO check non-empty?
return new AutoValue_OneOfElement(name, documentation, immutableCopyOf(fields));
square/protoparser
src/main/java/com/squareup/protoparser/DataType.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // }
import java.util.Locale; import static com.squareup.protoparser.Utils.checkNotNull;
// Copyright 2015 Square, Inc. package com.squareup.protoparser; /** * Representation of a scalar, map, or named type. While this class is an interface, only the * included implementations are supported. */ public interface DataType { enum Kind { /** Type is a {@link ScalarType}. */ SCALAR, /** Type is a {@link MapType}. */ MAP, /** Type is a {@link NamedType}. */ NAMED } /** The kind of this type (and therefore implementing class). */ Kind kind(); enum ScalarType implements DataType { ANY, BOOL, BYTES, DOUBLE, FLOAT, FIXED32, FIXED64, INT32, INT64, SFIXED32, SFIXED64, SINT32, SINT64, STRING, UINT32, UINT64; @Override public Kind kind() { return Kind.SCALAR; } @Override public String toString() { return name().toLowerCase(Locale.US); } } final class MapType implements DataType { public static MapType create(DataType keyType, DataType valueType) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // Path: src/main/java/com/squareup/protoparser/DataType.java import java.util.Locale; import static com.squareup.protoparser.Utils.checkNotNull; // Copyright 2015 Square, Inc. package com.squareup.protoparser; /** * Representation of a scalar, map, or named type. While this class is an interface, only the * included implementations are supported. */ public interface DataType { enum Kind { /** Type is a {@link ScalarType}. */ SCALAR, /** Type is a {@link MapType}. */ MAP, /** Type is a {@link NamedType}. */ NAMED } /** The kind of this type (and therefore implementing class). */ Kind kind(); enum ScalarType implements DataType { ANY, BOOL, BYTES, DOUBLE, FLOAT, FIXED32, FIXED64, INT32, INT64, SFIXED32, SFIXED64, SINT32, SINT64, STRING, UINT32, UINT64; @Override public Kind kind() { return Kind.SCALAR; } @Override public String toString() { return name().toLowerCase(Locale.US); } } final class MapType implements DataType { public static MapType create(DataType keyType, DataType valueType) {
return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType"));
square/protoparser
src/main/java/com/squareup/protoparser/RpcElement.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class RpcElement { public static Builder builder() { return new Builder(); } RpcElement() { } public abstract String name(); public abstract String documentation();
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/RpcElement.java import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class RpcElement { public static Builder builder() { return new Builder(); } RpcElement() { } public abstract String name(); public abstract String documentation();
public abstract NamedType requestType();
square/protoparser
src/main/java/com/squareup/protoparser/RpcElement.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class RpcElement { public static Builder builder() { return new Builder(); } RpcElement() { } public abstract String name(); public abstract String documentation(); public abstract NamedType requestType(); public abstract NamedType responseType(); public abstract List<OptionElement> options(); public final String toSchema() { StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/RpcElement.java import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class RpcElement { public static Builder builder() { return new Builder(); } RpcElement() { } public abstract String name(); public abstract String documentation(); public abstract NamedType requestType(); public abstract NamedType responseType(); public abstract List<OptionElement> options(); public final String toSchema() { StringBuilder builder = new StringBuilder();
appendDocumentation(builder, documentation());
square/protoparser
src/main/java/com/squareup/protoparser/RpcElement.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class RpcElement { public static Builder builder() { return new Builder(); } RpcElement() { } public abstract String name(); public abstract String documentation(); public abstract NamedType requestType(); public abstract NamedType responseType(); public abstract List<OptionElement> options(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("rpc ") .append(name()) .append(" (") .append(requestType()) .append(") returns (") .append(responseType()) .append(')'); if (!options().isEmpty()) { builder.append(" {\n"); for (OptionElement option : options()) {
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/RpcElement.java import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2014 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class RpcElement { public static Builder builder() { return new Builder(); } RpcElement() { } public abstract String name(); public abstract String documentation(); public abstract NamedType requestType(); public abstract NamedType responseType(); public abstract List<OptionElement> options(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("rpc ") .append(name()) .append(" (") .append(requestType()) .append(") returns (") .append(responseType()) .append(')'); if (!options().isEmpty()) { builder.append(" {\n"); for (OptionElement option : options()) {
appendIndented(builder, option.toSchemaDeclaration());
square/protoparser
src/main/java/com/squareup/protoparser/RpcElement.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("rpc ") .append(name()) .append(" (") .append(requestType()) .append(") returns (") .append(responseType()) .append(')'); if (!options().isEmpty()) { builder.append(" {\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchemaDeclaration()); } builder.append("}"); } return builder.append(";\n").toString(); } public static final class Builder { private String name; private String documentation = ""; private NamedType requestType; private NamedType responseType; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder name(String name) {
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/RpcElement.java import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("rpc ") .append(name()) .append(" (") .append(requestType()) .append(") returns (") .append(responseType()) .append(')'); if (!options().isEmpty()) { builder.append(" {\n"); for (OptionElement option : options()) { appendIndented(builder, option.toSchemaDeclaration()); } builder.append("}"); } return builder.append(";\n").toString(); } public static final class Builder { private String name; private String documentation = ""; private NamedType requestType; private NamedType responseType; private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder name(String name) {
this.name = checkNotNull(name, "name");
square/protoparser
src/main/java/com/squareup/protoparser/RpcElement.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
} public Builder requestType(NamedType requestType) { this.requestType = checkNotNull(requestType, "requestType"); return this; } public Builder responseType(NamedType responseType) { this.responseType = checkNotNull(responseType, "responseType"); return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public RpcElement build() { checkNotNull(name, "name"); checkNotNull(requestType, "requestType"); checkNotNull(responseType, "responseType"); return new AutoValue_RpcElement(name, documentation, requestType, responseType,
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/RpcElement.java import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.NamedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; } public Builder requestType(NamedType requestType) { this.requestType = checkNotNull(requestType, "requestType"); return this; } public Builder responseType(NamedType responseType) { this.responseType = checkNotNull(responseType, "responseType"); return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public RpcElement build() { checkNotNull(name, "name"); checkNotNull(requestType, "requestType"); checkNotNull(responseType, "responseType"); return new AutoValue_RpcElement(name, documentation, requestType, responseType,
immutableCopyOf(options));
square/protoparser
src/main/java/com/squareup/protoparser/ExtensionsElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // }
import com.google.auto.value.AutoValue; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.checkArgument;
// Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtensionsElement { public static ExtensionsElement create(int start, int end) { return create(start, end, ""); } public static ExtensionsElement create(int start, int end, String documentation) {
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // Path: src/main/java/com/squareup/protoparser/ExtensionsElement.java import com.google.auto.value.AutoValue; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.checkArgument; // Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtensionsElement { public static ExtensionsElement create(int start, int end) { return create(start, end, ""); } public static ExtensionsElement create(int start, int end, String documentation) {
checkArgument(isValidTag(start), "Invalid start value: %s", start);
square/protoparser
src/main/java/com/squareup/protoparser/ExtensionsElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // }
import com.google.auto.value.AutoValue; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.checkArgument;
// Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtensionsElement { public static ExtensionsElement create(int start, int end) { return create(start, end, ""); } public static ExtensionsElement create(int start, int end, String documentation) {
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // Path: src/main/java/com/squareup/protoparser/ExtensionsElement.java import com.google.auto.value.AutoValue; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.checkArgument; // Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtensionsElement { public static ExtensionsElement create(int start, int end) { return create(start, end, ""); } public static ExtensionsElement create(int start, int end, String documentation) {
checkArgument(isValidTag(start), "Invalid start value: %s", start);
square/protoparser
src/main/java/com/squareup/protoparser/ExtensionsElement.java
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // }
import com.google.auto.value.AutoValue; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.checkArgument;
// Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtensionsElement { public static ExtensionsElement create(int start, int end) { return create(start, end, ""); } public static ExtensionsElement create(int start, int end, String documentation) { checkArgument(isValidTag(start), "Invalid start value: %s", start); checkArgument(isValidTag(end), "Invalid end value: %s", end); return new AutoValue_ExtensionsElement(documentation, start, end); } ExtensionsElement() { } public abstract String documentation(); public abstract int start(); public abstract int end(); public final String toSchema() { StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/ProtoFile.java // static boolean isValidTag(int value) { // return (value >= MIN_TAG_VALUE && value < RESERVED_TAG_VALUE_START) // || (value > RESERVED_TAG_VALUE_END && value <= MAX_TAG_VALUE); // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void checkArgument(boolean condition, String message, Object... messageArgs) { // if (!condition) { // if (messageArgs.length > 0) { // message = String.format(message, messageArgs); // } // throw new IllegalArgumentException(message); // } // } // Path: src/main/java/com/squareup/protoparser/ExtensionsElement.java import com.google.auto.value.AutoValue; import static com.squareup.protoparser.ProtoFile.isValidTag; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.checkArgument; // Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtensionsElement { public static ExtensionsElement create(int start, int end) { return create(start, end, ""); } public static ExtensionsElement create(int start, int end, String documentation) { checkArgument(isValidTag(start), "Invalid start value: %s", start); checkArgument(isValidTag(end), "Invalid end value: %s", end); return new AutoValue_ExtensionsElement(documentation, start, end); } ExtensionsElement() { } public abstract String documentation(); public abstract int start(); public abstract int end(); public final String toSchema() { StringBuilder builder = new StringBuilder();
appendDocumentation(builder, documentation());
square/protoparser
src/test/java/com/squareup/protoparser/RpcElementTest.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // }
import com.squareup.protoparser.DataType.NamedType; import java.util.Collections; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
package com.squareup.protoparser; public final class RpcElementTest { @Test public void nameRequired() { try { RpcElement.builder()
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // Path: src/test/java/com/squareup/protoparser/RpcElementTest.java import com.squareup.protoparser.DataType.NamedType; import java.util.Collections; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; package com.squareup.protoparser; public final class RpcElementTest { @Test public void nameRequired() { try { RpcElement.builder()
.requestType(NamedType.create("Foo"))
square/protoparser
src/test/java/com/squareup/protoparser/MessageElementTest.java
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // }
import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.BOOL; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.FieldElement.Label.ONE_OF; import static com.squareup.protoparser.FieldElement.Label.REQUIRED; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
.name("Message") .addFields(Arrays.asList(firstName, lastName)) .build(); assertThat(element.fields()).hasSize(2); } @Test public void simpleWithDocumentationToSchema() { TypeElement element = MessageElement.builder() .name("Message") .documentation("Hello") .addField(FieldElement.builder().label(REQUIRED).type(STRING).name("name").tag(1).build()) .build(); String expected = "" + "// Hello\n" + "message Message {\n" + " required string name = 1;\n" + "}\n"; assertThat(element.toSchema()).isEqualTo(expected); } @Test public void simpleWithOptionsToSchema() { FieldElement field = FieldElement.builder() .label(REQUIRED) .type(STRING) .name("name") .tag(1) .build(); TypeElement element = MessageElement.builder() .name("Message") .addField(field)
// Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // Path: src/test/java/com/squareup/protoparser/MessageElementTest.java import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.BOOL; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.FieldElement.Label.ONE_OF; import static com.squareup.protoparser.FieldElement.Label.REQUIRED; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; .name("Message") .addFields(Arrays.asList(firstName, lastName)) .build(); assertThat(element.fields()).hasSize(2); } @Test public void simpleWithDocumentationToSchema() { TypeElement element = MessageElement.builder() .name("Message") .documentation("Hello") .addField(FieldElement.builder().label(REQUIRED).type(STRING).name("name").tag(1).build()) .build(); String expected = "" + "// Hello\n" + "message Message {\n" + " required string name = 1;\n" + "}\n"; assertThat(element.toSchema()).isEqualTo(expected); } @Test public void simpleWithOptionsToSchema() { FieldElement field = FieldElement.builder() .label(REQUIRED) .type(STRING) .name("name") .tag(1) .build(); TypeElement element = MessageElement.builder() .name("Message") .addField(field)
.addOption(OptionElement.create("kit", Kind.STRING, "kat"))
square/protoparser
src/main/java/com/squareup/protoparser/OptionElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static java.util.Collections.unmodifiableMap;
map.put(name, value); } else if (value instanceof OptionElement) { Map<String, Object> newMap = optionsAsMap(Collections.singletonList((OptionElement) value)); Object oldValue = map.get(name); if (oldValue instanceof Map) { Map<String, Object> oldMap = (Map<String, Object>) oldValue; // Existing nested maps are immutable. Make a mutable copy, update, and replace. oldMap = new LinkedHashMap<>(oldMap); oldMap.putAll(newMap); map.put(name, oldMap); } else { map.put(name, newMap); } } else if (value instanceof Map) { Object oldValue = map.get(name); if (oldValue instanceof Map) { ((Map<String, Object>) oldValue).putAll((Map<String, Object>) value); } else { map.put(name, value); } } else { throw new AssertionError("Option value must be String, Option, List, or Map<String, ?>"); } } return unmodifiableMap(map); } /** Return the option with the specified name from the supplied list or null. */ public static OptionElement findByName(List<OptionElement> options, String name) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // Path: src/main/java/com/squareup/protoparser/OptionElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static java.util.Collections.unmodifiableMap; map.put(name, value); } else if (value instanceof OptionElement) { Map<String, Object> newMap = optionsAsMap(Collections.singletonList((OptionElement) value)); Object oldValue = map.get(name); if (oldValue instanceof Map) { Map<String, Object> oldMap = (Map<String, Object>) oldValue; // Existing nested maps are immutable. Make a mutable copy, update, and replace. oldMap = new LinkedHashMap<>(oldMap); oldMap.putAll(newMap); map.put(name, oldMap); } else { map.put(name, newMap); } } else if (value instanceof Map) { Object oldValue = map.get(name); if (oldValue instanceof Map) { ((Map<String, Object>) oldValue).putAll((Map<String, Object>) value); } else { map.put(name, value); } } else { throw new AssertionError("Option value must be String, Option, List, or Map<String, ?>"); } } return unmodifiableMap(map); } /** Return the option with the specified name from the supplied list or null. */ public static OptionElement findByName(List<OptionElement> options, String name) {
checkNotNull(options, "options");
square/protoparser
src/main/java/com/squareup/protoparser/OptionElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static java.util.Collections.unmodifiableMap;
case MAP: { StringBuilder builder = new StringBuilder(); builder.append(formatName()).append(" = {\n"); //noinspection unchecked Map<String, ?> valueMap = (Map<String, ?>) value; formatOptionMap(builder, valueMap); builder.append('}'); return builder.toString(); } case LIST: { StringBuilder builder = new StringBuilder(); builder.append(formatName()).append(" = [\n"); //noinspection unchecked List<OptionElement> optionList = (List<OptionElement>) value; formatOptionList(builder, optionList); builder.append(']'); return builder.toString(); } default: throw new AssertionError(); } } public final String toSchemaDeclaration() { return "option " + toSchema() + ";\n"; } static void formatOptionList(StringBuilder builder, List<OptionElement> optionList) { for (int i = 0, count = optionList.size(); i < count; i++) { String endl = (i < count - 1) ? "," : "";
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // Path: src/main/java/com/squareup/protoparser/OptionElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static java.util.Collections.unmodifiableMap; case MAP: { StringBuilder builder = new StringBuilder(); builder.append(formatName()).append(" = {\n"); //noinspection unchecked Map<String, ?> valueMap = (Map<String, ?>) value; formatOptionMap(builder, valueMap); builder.append('}'); return builder.toString(); } case LIST: { StringBuilder builder = new StringBuilder(); builder.append(formatName()).append(" = [\n"); //noinspection unchecked List<OptionElement> optionList = (List<OptionElement>) value; formatOptionList(builder, optionList); builder.append(']'); return builder.toString(); } default: throw new AssertionError(); } } public final String toSchemaDeclaration() { return "option " + toSchema() + ";\n"; } static void formatOptionList(StringBuilder builder, List<OptionElement> optionList) { for (int i = 0, count = optionList.size(); i < count; i++) { String endl = (i < count - 1) ? "," : "";
appendIndented(builder, optionList.get(i).toSchema() + endl);
square/protoparser
src/main/java/com/squareup/protoparser/ProtoParser.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // enum ScalarType implements DataType { // ANY, // BOOL, // BYTES, // DOUBLE, // FLOAT, // FIXED32, // FIXED64, // INT32, // INT64, // SFIXED32, // SFIXED64, // SINT32, // SINT64, // STRING, // UINT32, // UINT64; // // @Override public Kind kind() { // return Kind.SCALAR; // } // // @Override public String toString() { // return name().toLowerCase(Locale.US); // } // }
import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.DataType.ScalarType; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_3; import static java.nio.charset.StandardCharsets.UTF_8;
*/ private List<Object> readList() { if (readChar() != '[') throw new AssertionError(); List<Object> result = new ArrayList<>(); while (true) { if (peekChar() == ']') { // If we see the close brace, finish immediately. This handles [] and ,] cases. pos++; return result; } result.add(readKindAndValue().value()); char c = peekChar(); if (c == ',') { pos++; } else if (c != ']') { throw unexpected("expected ',' or ']'"); } } } /** Reads an rpc and returns it. */ private RpcElement readRpc(String documentation) { RpcElement.Builder builder = RpcElement.builder() .name(readName()) .documentation(documentation); if (readChar() != '(') throw unexpected("expected '('"); DataType requestType = readDataType();
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // enum ScalarType implements DataType { // ANY, // BOOL, // BYTES, // DOUBLE, // FLOAT, // FIXED32, // FIXED64, // INT32, // INT64, // SFIXED32, // SFIXED64, // SINT32, // SINT64, // STRING, // UINT32, // UINT64; // // @Override public Kind kind() { // return Kind.SCALAR; // } // // @Override public String toString() { // return name().toLowerCase(Locale.US); // } // } // Path: src/main/java/com/squareup/protoparser/ProtoParser.java import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.DataType.ScalarType; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_3; import static java.nio.charset.StandardCharsets.UTF_8; */ private List<Object> readList() { if (readChar() != '[') throw new AssertionError(); List<Object> result = new ArrayList<>(); while (true) { if (peekChar() == ']') { // If we see the close brace, finish immediately. This handles [] and ,] cases. pos++; return result; } result.add(readKindAndValue().value()); char c = peekChar(); if (c == ',') { pos++; } else if (c != ']') { throw unexpected("expected ',' or ']'"); } } } /** Reads an rpc and returns it. */ private RpcElement readRpc(String documentation) { RpcElement.Builder builder = RpcElement.builder() .name(readName()) .documentation(documentation); if (readChar() != '(') throw unexpected("expected '('"); DataType requestType = readDataType();
if (!(requestType instanceof NamedType)) {
square/protoparser
src/main/java/com/squareup/protoparser/ProtoParser.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // enum ScalarType implements DataType { // ANY, // BOOL, // BYTES, // DOUBLE, // FLOAT, // FIXED32, // FIXED64, // INT32, // INT64, // SFIXED32, // SFIXED64, // SINT32, // SINT64, // STRING, // UINT32, // UINT64; // // @Override public Kind kind() { // return Kind.SCALAR; // } // // @Override public String toString() { // return name().toLowerCase(Locale.US); // } // }
import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.DataType.ScalarType; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_3; import static java.nio.charset.StandardCharsets.UTF_8;
} /** Reads a (paren-wrapped), [square-wrapped] or naked symbol name. */ private String readName() { String optionName; char c = peekChar(); if (c == '(') { pos++; optionName = readWord(); if (readChar() != ')') throw unexpected("expected ')'"); } else if (c == '[') { pos++; optionName = readWord(); if (readChar() != ']') throw unexpected("expected ']'"); } else { optionName = readWord(); } return optionName; } /** Reads a scalar, map, or type name. */ private DataType readDataType() { String name = readWord(); switch (name) { case "map": if (readChar() != '<') throw unexpected("expected '<'"); DataType keyType = readDataType(); if (readChar() != ',') throw unexpected("expected ','"); DataType valueType = readDataType(); if (readChar() != '>') throw unexpected("expected '>'");
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // enum ScalarType implements DataType { // ANY, // BOOL, // BYTES, // DOUBLE, // FLOAT, // FIXED32, // FIXED64, // INT32, // INT64, // SFIXED32, // SFIXED64, // SINT32, // SINT64, // STRING, // UINT32, // UINT64; // // @Override public Kind kind() { // return Kind.SCALAR; // } // // @Override public String toString() { // return name().toLowerCase(Locale.US); // } // } // Path: src/main/java/com/squareup/protoparser/ProtoParser.java import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.DataType.ScalarType; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_3; import static java.nio.charset.StandardCharsets.UTF_8; } /** Reads a (paren-wrapped), [square-wrapped] or naked symbol name. */ private String readName() { String optionName; char c = peekChar(); if (c == '(') { pos++; optionName = readWord(); if (readChar() != ')') throw unexpected("expected ')'"); } else if (c == '[') { pos++; optionName = readWord(); if (readChar() != ']') throw unexpected("expected ']'"); } else { optionName = readWord(); } return optionName; } /** Reads a scalar, map, or type name. */ private DataType readDataType() { String name = readWord(); switch (name) { case "map": if (readChar() != '<') throw unexpected("expected '<'"); DataType keyType = readDataType(); if (readChar() != ',') throw unexpected("expected ','"); DataType valueType = readDataType(); if (readChar() != '>') throw unexpected("expected '>'");
return MapType.create(keyType, valueType);
square/protoparser
src/main/java/com/squareup/protoparser/ProtoParser.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // enum ScalarType implements DataType { // ANY, // BOOL, // BYTES, // DOUBLE, // FLOAT, // FIXED32, // FIXED64, // INT32, // INT64, // SFIXED32, // SFIXED64, // SINT32, // SINT64, // STRING, // UINT32, // UINT64; // // @Override public Kind kind() { // return Kind.SCALAR; // } // // @Override public String toString() { // return name().toLowerCase(Locale.US); // } // }
import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.DataType.ScalarType; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_3; import static java.nio.charset.StandardCharsets.UTF_8;
/** Reads a (paren-wrapped), [square-wrapped] or naked symbol name. */ private String readName() { String optionName; char c = peekChar(); if (c == '(') { pos++; optionName = readWord(); if (readChar() != ')') throw unexpected("expected ')'"); } else if (c == '[') { pos++; optionName = readWord(); if (readChar() != ']') throw unexpected("expected ']'"); } else { optionName = readWord(); } return optionName; } /** Reads a scalar, map, or type name. */ private DataType readDataType() { String name = readWord(); switch (name) { case "map": if (readChar() != '<') throw unexpected("expected '<'"); DataType keyType = readDataType(); if (readChar() != ',') throw unexpected("expected ','"); DataType valueType = readDataType(); if (readChar() != '>') throw unexpected("expected '>'"); return MapType.create(keyType, valueType); case "any":
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class MapType implements DataType { // public static MapType create(DataType keyType, DataType valueType) { // return new MapType(checkNotNull(keyType, "keyType"), checkNotNull(valueType, "valueType")); // } // // private final DataType keyType; // private final DataType valueType; // // private MapType(DataType keyType, DataType valueType) { // this.keyType = keyType; // this.valueType = valueType; // } // // @Override public Kind kind() { // return Kind.MAP; // } // // public DataType keyType() { // return keyType; // } // // public DataType valueType() { // return valueType; // } // // @Override public String toString() { // return "map<" + keyType + ", " + valueType + ">"; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof MapType)) return false; // MapType other = (MapType) obj; // return keyType.equals(other.keyType) && valueType.equals(other.valueType); // } // // @Override public int hashCode() { // return keyType.hashCode() * 37 + valueType.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/DataType.java // enum ScalarType implements DataType { // ANY, // BOOL, // BYTES, // DOUBLE, // FLOAT, // FIXED32, // FIXED64, // INT32, // INT64, // SFIXED32, // SFIXED64, // SINT32, // SINT64, // STRING, // UINT32, // UINT64; // // @Override public Kind kind() { // return Kind.SCALAR; // } // // @Override public String toString() { // return name().toLowerCase(Locale.US); // } // } // Path: src/main/java/com/squareup/protoparser/ProtoParser.java import com.google.auto.value.AutoValue; import com.squareup.protoparser.DataType.MapType; import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.DataType.ScalarType; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_2; import static com.squareup.protoparser.ProtoFile.Syntax.PROTO_3; import static java.nio.charset.StandardCharsets.UTF_8; /** Reads a (paren-wrapped), [square-wrapped] or naked symbol name. */ private String readName() { String optionName; char c = peekChar(); if (c == '(') { pos++; optionName = readWord(); if (readChar() != ')') throw unexpected("expected ')'"); } else if (c == '[') { pos++; optionName = readWord(); if (readChar() != ']') throw unexpected("expected ']'"); } else { optionName = readWord(); } return optionName; } /** Reads a scalar, map, or type name. */ private DataType readDataType() { String name = readWord(); switch (name) { case "map": if (readChar() != '<') throw unexpected("expected '<'"); DataType keyType = readDataType(); if (readChar() != ',') throw unexpected("expected ','"); DataType valueType = readDataType(); if (readChar() != '>') throw unexpected("expected '>'"); return MapType.create(keyType, valueType); case "any":
return ScalarType.ANY;
square/protoparser
src/main/java/com/squareup/protoparser/ExtendElement.java
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtendElement { public static Builder builder() { return new Builder(); } ExtendElement() { } public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ExtendElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtendElement { public static Builder builder() { return new Builder(); } ExtendElement() { } public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder();
appendDocumentation(builder, documentation());
square/protoparser
src/main/java/com/squareup/protoparser/ExtendElement.java
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtendElement { public static Builder builder() { return new Builder(); } ExtendElement() { } public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("extend ") .append(name()) .append(" {"); if (!fields().isEmpty()) { builder.append('\n'); for (FieldElement field : fields()) {
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ExtendElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ExtendElement { public static Builder builder() { return new Builder(); } ExtendElement() { } public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("extend ") .append(name()) .append(" {"); if (!fields().isEmpty()) { builder.append('\n'); for (FieldElement field : fields()) {
appendIndented(builder, field.toSchema());
square/protoparser
src/main/java/com/squareup/protoparser/ExtendElement.java
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("extend ") .append(name()) .append(" {"); if (!fields().isEmpty()) { builder.append('\n'); for (FieldElement field : fields()) { appendIndented(builder, field.toSchema()); } } return builder.append("}\n").toString(); } public static final class Builder { private String name; private String qualifiedName; private String documentation = ""; private final List<FieldElement> fields = new ArrayList<>(); private Builder() { } public Builder name(String name) {
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ExtendElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<FieldElement> fields(); public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("extend ") .append(name()) .append(" {"); if (!fields().isEmpty()) { builder.append('\n'); for (FieldElement field : fields()) { appendIndented(builder, field.toSchema()); } } return builder.append("}\n").toString(); } public static final class Builder { private String name; private String qualifiedName; private String documentation = ""; private final List<FieldElement> fields = new ArrayList<>(); private Builder() { } public Builder name(String name) {
this.name = checkNotNull(name, "name");
square/protoparser
src/main/java/com/squareup/protoparser/ExtendElement.java
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
} return this; } public Builder qualifiedName(String qualifiedName) { this.qualifiedName = checkNotNull(qualifiedName, "qualifiedName"); return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addField(FieldElement field) { fields.add(checkNotNull(field, "field")); return this; } public Builder addFields(Collection<FieldElement> fields) { for (FieldElement field : checkNotNull(fields, "fields")) { addField(field); } return this; } public ExtendElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName");
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ExtendElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; } return this; } public Builder qualifiedName(String qualifiedName) { this.qualifiedName = checkNotNull(qualifiedName, "qualifiedName"); return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addField(FieldElement field) { fields.add(checkNotNull(field, "field")); return this; } public Builder addFields(Collection<FieldElement> fields) { for (FieldElement field : checkNotNull(fields, "fields")) { addField(field); } return this; } public ExtendElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName");
validateFieldTagUniqueness(qualifiedName, fields, Collections.<OneOfElement>emptyList());
square/protoparser
src/main/java/com/squareup/protoparser/ExtendElement.java
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
} public Builder qualifiedName(String qualifiedName) { this.qualifiedName = checkNotNull(qualifiedName, "qualifiedName"); return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addField(FieldElement field) { fields.add(checkNotNull(field, "field")); return this; } public Builder addFields(Collection<FieldElement> fields) { for (FieldElement field : checkNotNull(fields, "fields")) { addField(field); } return this; } public ExtendElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName"); validateFieldTagUniqueness(qualifiedName, fields, Collections.<OneOfElement>emptyList()); return new AutoValue_ExtendElement(name, qualifiedName, documentation,
// Path: src/main/java/com/squareup/protoparser/MessageElement.java // static void validateFieldTagUniqueness(String qualifiedName, List<FieldElement> fields, // List<OneOfElement> oneOfs) { // List<FieldElement> allFields = new ArrayList<>(fields); // for (OneOfElement oneOf : oneOfs) { // allFields.addAll(oneOf.fields()); // } // // Set<Integer> tags = new LinkedHashSet<>(); // for (FieldElement field : allFields) { // int tag = field.tag(); // if (!tags.add(tag)) { // throw new IllegalStateException("Duplicate tag " + tag + " in " + qualifiedName); // } // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ExtendElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.squareup.protoparser.MessageElement.validateFieldTagUniqueness; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; } public Builder qualifiedName(String qualifiedName) { this.qualifiedName = checkNotNull(qualifiedName, "qualifiedName"); return this; } public Builder documentation(String documentation) { this.documentation = checkNotNull(documentation, "documentation"); return this; } public Builder addField(FieldElement field) { fields.add(checkNotNull(field, "field")); return this; } public Builder addFields(Collection<FieldElement> fields) { for (FieldElement field : checkNotNull(fields, "fields")) { addField(field); } return this; } public ExtendElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName"); validateFieldTagUniqueness(qualifiedName, fields, Collections.<OneOfElement>emptyList()); return new AutoValue_ExtendElement(name, qualifiedName, documentation,
immutableCopyOf(fields));
square/protoparser
src/main/java/com/squareup/protoparser/EnumElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
for (EnumConstantElement constant : enumElement.constants()) { String name = constant.name(); if (!names.add(name)) { throw new IllegalStateException( "Duplicate enum constant " + name + " in scope " + qualifiedName); } } } } } public static Builder builder() { return new Builder(); } EnumElement() { } @Override public abstract String name(); @Override public abstract String qualifiedName(); @Override public abstract String documentation(); public abstract List<EnumConstantElement> constants(); @Override public abstract List<OptionElement> options(); @Override public final List<TypeElement> nestedElements() { return Collections.emptyList(); // Enums do not allow nested type declarations. } @Override public final String toSchema() { StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/EnumElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; for (EnumConstantElement constant : enumElement.constants()) { String name = constant.name(); if (!names.add(name)) { throw new IllegalStateException( "Duplicate enum constant " + name + " in scope " + qualifiedName); } } } } } public static Builder builder() { return new Builder(); } EnumElement() { } @Override public abstract String name(); @Override public abstract String qualifiedName(); @Override public abstract String documentation(); public abstract List<EnumConstantElement> constants(); @Override public abstract List<OptionElement> options(); @Override public final List<TypeElement> nestedElements() { return Collections.emptyList(); // Enums do not allow nested type declarations. } @Override public final String toSchema() { StringBuilder builder = new StringBuilder();
appendDocumentation(builder, documentation());
square/protoparser
src/main/java/com/squareup/protoparser/EnumElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
} } } public static Builder builder() { return new Builder(); } EnumElement() { } @Override public abstract String name(); @Override public abstract String qualifiedName(); @Override public abstract String documentation(); public abstract List<EnumConstantElement> constants(); @Override public abstract List<OptionElement> options(); @Override public final List<TypeElement> nestedElements() { return Collections.emptyList(); // Enums do not allow nested type declarations. } @Override public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("enum ") .append(name()) .append(" {"); if (!options().isEmpty()) { builder.append('\n'); for (OptionElement option : options()) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/EnumElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; } } } public static Builder builder() { return new Builder(); } EnumElement() { } @Override public abstract String name(); @Override public abstract String qualifiedName(); @Override public abstract String documentation(); public abstract List<EnumConstantElement> constants(); @Override public abstract List<OptionElement> options(); @Override public final List<TypeElement> nestedElements() { return Collections.emptyList(); // Enums do not allow nested type declarations. } @Override public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("enum ") .append(name()) .append(" {"); if (!options().isEmpty()) { builder.append('\n'); for (OptionElement option : options()) {
appendIndented(builder, option.toSchemaDeclaration());
square/protoparser
src/main/java/com/squareup/protoparser/EnumElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
return this; } public Builder addConstants(Collection<EnumConstantElement> constants) { for (EnumConstantElement constant : checkNotNull(constants, "constants")) { addConstant(constant); } return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public EnumElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName"); if (!parseAllowAlias(options)) { validateTagUniqueness(qualifiedName, constants); } return new AutoValue_EnumElement(name, qualifiedName, documentation,
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/EnumElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; return this; } public Builder addConstants(Collection<EnumConstantElement> constants) { for (EnumConstantElement constant : checkNotNull(constants, "constants")) { addConstant(constant); } return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public EnumElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName"); if (!parseAllowAlias(options)) { validateTagUniqueness(qualifiedName, constants); } return new AutoValue_EnumElement(name, qualifiedName, documentation,
immutableCopyOf(constants), immutableCopyOf(options));
square/protoparser
src/main/java/com/squareup/protoparser/MessageElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
static void validateFieldLabel(String qualifiedName, List<FieldElement> fields) { for (FieldElement field : fields) { if (field.label() == FieldElement.Label.ONE_OF) { throw new IllegalStateException("Field '" + field.name() + "' in " + qualifiedName + " improperly declares itself a member of a 'oneof' group but is not."); } } } public static Builder builder() { return new Builder(); } MessageElement() { } @Override public abstract String name(); @Override public abstract String qualifiedName(); @Override public abstract String documentation(); public abstract List<FieldElement> fields(); public abstract List<OneOfElement> oneOfs(); @Override public abstract List<TypeElement> nestedElements(); public abstract List<ExtensionsElement> extensions(); @Override public abstract List<OptionElement> options(); @Override public final String toSchema() { StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/MessageElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; static void validateFieldLabel(String qualifiedName, List<FieldElement> fields) { for (FieldElement field : fields) { if (field.label() == FieldElement.Label.ONE_OF) { throw new IllegalStateException("Field '" + field.name() + "' in " + qualifiedName + " improperly declares itself a member of a 'oneof' group but is not."); } } } public static Builder builder() { return new Builder(); } MessageElement() { } @Override public abstract String name(); @Override public abstract String qualifiedName(); @Override public abstract String documentation(); public abstract List<FieldElement> fields(); public abstract List<OneOfElement> oneOfs(); @Override public abstract List<TypeElement> nestedElements(); public abstract List<ExtensionsElement> extensions(); @Override public abstract List<OptionElement> options(); @Override public final String toSchema() { StringBuilder builder = new StringBuilder();
appendDocumentation(builder, documentation());
square/protoparser
src/main/java/com/squareup/protoparser/MessageElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
+ " improperly declares itself a member of a 'oneof' group but is not."); } } } public static Builder builder() { return new Builder(); } MessageElement() { } @Override public abstract String name(); @Override public abstract String qualifiedName(); @Override public abstract String documentation(); public abstract List<FieldElement> fields(); public abstract List<OneOfElement> oneOfs(); @Override public abstract List<TypeElement> nestedElements(); public abstract List<ExtensionsElement> extensions(); @Override public abstract List<OptionElement> options(); @Override public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("message ") .append(name()) .append(" {"); if (!options().isEmpty()) { builder.append('\n'); for (OptionElement option : options()) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/MessageElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; + " improperly declares itself a member of a 'oneof' group but is not."); } } } public static Builder builder() { return new Builder(); } MessageElement() { } @Override public abstract String name(); @Override public abstract String qualifiedName(); @Override public abstract String documentation(); public abstract List<FieldElement> fields(); public abstract List<OneOfElement> oneOfs(); @Override public abstract List<TypeElement> nestedElements(); public abstract List<ExtensionsElement> extensions(); @Override public abstract List<OptionElement> options(); @Override public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("message ") .append(name()) .append(" {"); if (!options().isEmpty()) { builder.append('\n'); for (OptionElement option : options()) {
appendIndented(builder, option.toSchemaDeclaration());
square/protoparser
src/main/java/com/squareup/protoparser/MessageElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
} if (!extensions().isEmpty()) { builder.append('\n'); for (ExtensionsElement extension : extensions()) { appendIndented(builder, extension.toSchema()); } } if (!nestedElements().isEmpty()) { builder.append('\n'); for (TypeElement type : nestedElements()) { appendIndented(builder, type.toSchema()); } } return builder.append("}\n").toString(); } public static final class Builder { private String name; private String qualifiedName; private String documentation = ""; private final List<FieldElement> fields = new ArrayList<>(); private final List<OneOfElement> oneOfs = new ArrayList<>(); private final List<TypeElement> nestedElements = new ArrayList<>(); private final List<ExtensionsElement> extensions = new ArrayList<>(); private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder name(String name) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/MessageElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; } if (!extensions().isEmpty()) { builder.append('\n'); for (ExtensionsElement extension : extensions()) { appendIndented(builder, extension.toSchema()); } } if (!nestedElements().isEmpty()) { builder.append('\n'); for (TypeElement type : nestedElements()) { appendIndented(builder, type.toSchema()); } } return builder.append("}\n").toString(); } public static final class Builder { private String name; private String qualifiedName; private String documentation = ""; private final List<FieldElement> fields = new ArrayList<>(); private final List<OneOfElement> oneOfs = new ArrayList<>(); private final List<TypeElement> nestedElements = new ArrayList<>(); private final List<ExtensionsElement> extensions = new ArrayList<>(); private final List<OptionElement> options = new ArrayList<>(); private Builder() { } public Builder name(String name) {
this.name = checkNotNull(name, "name");
square/protoparser
src/main/java/com/squareup/protoparser/MessageElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
} public Builder addExtensions(Collection<ExtensionsElement> extensions) { for (ExtensionsElement extension : checkNotNull(extensions, "extensions")) { addExtensions(extension); } return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public MessageElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName"); validateFieldTagUniqueness(qualifiedName, fields, oneOfs); validateFieldLabel(qualifiedName, fields); EnumElement.validateValueUniquenessInScope(qualifiedName, nestedElements); return new AutoValue_MessageElement(name, qualifiedName, documentation,
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/MessageElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; } public Builder addExtensions(Collection<ExtensionsElement> extensions) { for (ExtensionsElement extension : checkNotNull(extensions, "extensions")) { addExtensions(extension); } return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public MessageElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName"); validateFieldTagUniqueness(qualifiedName, fields, oneOfs); validateFieldLabel(qualifiedName, fields); EnumElement.validateValueUniquenessInScope(qualifiedName, nestedElements); return new AutoValue_MessageElement(name, qualifiedName, documentation,
immutableCopyOf(fields), immutableCopyOf(oneOfs), immutableCopyOf(nestedElements),
square/protoparser
src/test/java/com/squareup/protoparser/FieldElementTest.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // }
import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.FieldElement.Label.OPTIONAL; import static com.squareup.protoparser.FieldElement.Label.REQUIRED; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
package com.squareup.protoparser; public final class FieldElementTest { @Test public void field() { FieldElement field = FieldElement.builder() .label(OPTIONAL)
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // Path: src/test/java/com/squareup/protoparser/FieldElementTest.java import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.FieldElement.Label.OPTIONAL; import static com.squareup.protoparser.FieldElement.Label.REQUIRED; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; package com.squareup.protoparser; public final class FieldElementTest { @Test public void field() { FieldElement field = FieldElement.builder() .label(OPTIONAL)
.type(NamedType.create("CType"))
square/protoparser
src/test/java/com/squareup/protoparser/FieldElementTest.java
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // }
import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.FieldElement.Label.OPTIONAL; import static com.squareup.protoparser.FieldElement.Label.REQUIRED; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail;
package com.squareup.protoparser; public final class FieldElementTest { @Test public void field() { FieldElement field = FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("CType")) .name("ctype") .tag(1)
// Path: src/main/java/com/squareup/protoparser/DataType.java // final class NamedType implements DataType { // public static NamedType create(String name) { // return new NamedType(checkNotNull(name, "name")); // } // // private final String name; // // private NamedType(String name) { // this.name = name; // } // // public String name() { // return name; // } // // @Override public Kind kind() { // return Kind.NAMED; // } // // @Override public String toString() { // return name; // } // // @Override public boolean equals(Object obj) { // if (obj == this) return true; // if (!(obj instanceof NamedType)) return false; // NamedType other = (NamedType) obj; // return name.equals(other.name); // } // // @Override public int hashCode() { // return name.hashCode(); // } // } // // Path: src/main/java/com/squareup/protoparser/OptionElement.java // public enum Kind { // STRING, // BOOLEAN, // NUMBER, // ENUM, // MAP, // LIST, // OPTION // } // Path: src/test/java/com/squareup/protoparser/FieldElementTest.java import com.squareup.protoparser.DataType.NamedType; import com.squareup.protoparser.OptionElement.Kind; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import static com.squareup.protoparser.DataType.ScalarType.STRING; import static com.squareup.protoparser.FieldElement.Label.OPTIONAL; import static com.squareup.protoparser.FieldElement.Label.REQUIRED; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; package com.squareup.protoparser; public final class FieldElementTest { @Test public void field() { FieldElement field = FieldElement.builder() .label(OPTIONAL) .type(NamedType.create("CType")) .name("ctype") .tag(1)
.addOption(OptionElement.create("default", Kind.ENUM, "TEST"))
square/protoparser
src/main/java/com/squareup/protoparser/ServiceElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ServiceElement { public static Builder builder() { return new Builder(); } public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<RpcElement> rpcs(); public abstract List<OptionElement> options(); ServiceElement() { } public final String toSchema() { StringBuilder builder = new StringBuilder();
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ServiceElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ServiceElement { public static Builder builder() { return new Builder(); } public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<RpcElement> rpcs(); public abstract List<OptionElement> options(); ServiceElement() { } public final String toSchema() { StringBuilder builder = new StringBuilder();
appendDocumentation(builder, documentation());
square/protoparser
src/main/java/com/squareup/protoparser/ServiceElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
// Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ServiceElement { public static Builder builder() { return new Builder(); } public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<RpcElement> rpcs(); public abstract List<OptionElement> options(); ServiceElement() { } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("service ") .append(name()) .append(" {"); if (!options().isEmpty()) { builder.append('\n'); for (OptionElement option : options()) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ServiceElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; // Copyright 2013 Square, Inc. package com.squareup.protoparser; @AutoValue public abstract class ServiceElement { public static Builder builder() { return new Builder(); } public abstract String name(); public abstract String qualifiedName(); public abstract String documentation(); public abstract List<RpcElement> rpcs(); public abstract List<OptionElement> options(); ServiceElement() { } public final String toSchema() { StringBuilder builder = new StringBuilder(); appendDocumentation(builder, documentation()); builder.append("service ") .append(name()) .append(" {"); if (!options().isEmpty()) { builder.append('\n'); for (OptionElement option : options()) {
appendIndented(builder, option.toSchemaDeclaration());
square/protoparser
src/main/java/com/squareup/protoparser/ServiceElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
appendDocumentation(builder, documentation()); builder.append("service ") .append(name()) .append(" {"); if (!options().isEmpty()) { builder.append('\n'); for (OptionElement option : options()) { appendIndented(builder, option.toSchemaDeclaration()); } } if (!rpcs().isEmpty()) { builder.append('\n'); for (RpcElement rpc : rpcs()) { appendIndented(builder, rpc.toSchema()); } } return builder.append("}\n").toString(); } public static final class Builder { private String name; private String qualifiedName; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private final List<RpcElement> rpcs = new ArrayList<>(); private Builder() { } public Builder name(String name) {
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ServiceElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; appendDocumentation(builder, documentation()); builder.append("service ") .append(name()) .append(" {"); if (!options().isEmpty()) { builder.append('\n'); for (OptionElement option : options()) { appendIndented(builder, option.toSchemaDeclaration()); } } if (!rpcs().isEmpty()) { builder.append('\n'); for (RpcElement rpc : rpcs()) { appendIndented(builder, rpc.toSchema()); } } return builder.append("}\n").toString(); } public static final class Builder { private String name; private String qualifiedName; private String documentation = ""; private final List<OptionElement> options = new ArrayList<>(); private final List<RpcElement> rpcs = new ArrayList<>(); private Builder() { } public Builder name(String name) {
this.name = checkNotNull(name, "name");
square/protoparser
src/main/java/com/squareup/protoparser/ServiceElement.java
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // }
import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf;
} public Builder addRpc(RpcElement rpc) { rpcs.add(checkNotNull(rpc, "rpc")); return this; } public Builder addRpcs(Collection<RpcElement> rpcs) { for (RpcElement rpc : checkNotNull(rpcs, "rpcs")) { addRpc(rpc); } return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public ServiceElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName");
// Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendDocumentation(StringBuilder builder, String documentation) { // if (documentation.isEmpty()) { // return; // } // for (String line : documentation.split("\n")) { // builder.append("// ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static void appendIndented(StringBuilder builder, String value) { // for (String line : value.split("\n")) { // builder.append(" ").append(line).append('\n'); // } // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> T checkNotNull(T value, String name) { // if (value == null) { // throw new NullPointerException(name + " == null"); // } // return value; // } // // Path: src/main/java/com/squareup/protoparser/Utils.java // static <T> List<T> immutableCopyOf(List<T> list) { // return unmodifiableList(new ArrayList<>(list)); // } // Path: src/main/java/com/squareup/protoparser/ServiceElement.java import com.google.auto.value.AutoValue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.squareup.protoparser.Utils.appendDocumentation; import static com.squareup.protoparser.Utils.appendIndented; import static com.squareup.protoparser.Utils.checkNotNull; import static com.squareup.protoparser.Utils.immutableCopyOf; } public Builder addRpc(RpcElement rpc) { rpcs.add(checkNotNull(rpc, "rpc")); return this; } public Builder addRpcs(Collection<RpcElement> rpcs) { for (RpcElement rpc : checkNotNull(rpcs, "rpcs")) { addRpc(rpc); } return this; } public Builder addOption(OptionElement option) { options.add(checkNotNull(option, "option")); return this; } public Builder addOptions(Collection<OptionElement> options) { for (OptionElement option : checkNotNull(options, "options")) { addOption(option); } return this; } public ServiceElement build() { checkNotNull(name, "name"); checkNotNull(qualifiedName, "qualifiedName");
return new AutoValue_ServiceElement(name, qualifiedName, documentation, immutableCopyOf(rpcs),
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/RequestUtil.java
// Path: src/main/java/com/adeptj/runtime/exception/ServerException.java // public class ServerException extends RuntimeException { // // private static final long serialVersionUID = 2206058386357128479L; // // public ServerException(Throwable cause) { // super(cause); // } // }
import com.adeptj.runtime.exception.ServerException; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import static javax.servlet.RequestDispatcher.ERROR_EXCEPTION;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utils for {@link HttpServletRequest} * * @author Rakesh.Kumar, AdeptJ */ public final class RequestUtil { private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class); private RequestUtil() { } public static Object getAttribute(HttpServletRequest req, String name) { return req.getAttribute(name); } public static boolean hasException(HttpServletRequest req) { return getAttribute(req, ERROR_EXCEPTION) != null; } public static String getException(HttpServletRequest req) { return ExceptionUtils.getStackTrace((Throwable) RequestUtil.getAttribute(req, ERROR_EXCEPTION)); } public static void logout(HttpServletRequest req) { try { req.logout(); } catch (ServletException ex) { LOGGER.error(ex.getMessage(), ex);
// Path: src/main/java/com/adeptj/runtime/exception/ServerException.java // public class ServerException extends RuntimeException { // // private static final long serialVersionUID = 2206058386357128479L; // // public ServerException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/adeptj/runtime/common/RequestUtil.java import com.adeptj.runtime.exception.ServerException; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import static javax.servlet.RequestDispatcher.ERROR_EXCEPTION; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utils for {@link HttpServletRequest} * * @author Rakesh.Kumar, AdeptJ */ public final class RequestUtil { private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class); private RequestUtil() { } public static Object getAttribute(HttpServletRequest req, String name) { return req.getAttribute(name); } public static boolean hasException(HttpServletRequest req) { return getAttribute(req, ERROR_EXCEPTION) != null; } public static String getException(HttpServletRequest req) { return ExceptionUtils.getStackTrace((Throwable) RequestUtil.getAttribute(req, ERROR_EXCEPTION)); } public static void logout(HttpServletRequest req) { try { req.logout(); } catch (ServletException ex) { LOGGER.error(ex.getMessage(), ex);
throw new ServerException(ex);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/HttpSessionEvents.java
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // }
import com.adeptj.runtime.common.Times; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionIdListener; import javax.servlet.http.HttpSessionListener; import java.time.Instant; import java.util.Date; import java.util.Optional;
sessionListener().ifPresent(listener -> listener.sessionCreated(event)); break; case SESSION_DESTROYED: logSessionDestroyed(event); sessionListener().ifPresent(listener -> listener.sessionDestroyed(event)); break; default: // NO-OP break; } } // <<---------- HttpSessionIdListener ---------->> public static void handleSessionIdChangedEvent(HttpSessionEvent event, String oldSessionId) { sessionIdListener().ifPresent(listener -> listener.sessionIdChanged(event, oldSessionId)); } private static void logSessionCreated(HttpSessionEvent event) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Created HttpSession with id: [{}], @Time: [{}]", event.getSession().getId(), Date.from(Instant.ofEpochMilli(event.getSession().getCreationTime()))); } } private static void logSessionDestroyed(HttpSessionEvent event) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Destroyed HttpSession with id: [{}], active for: [{}] seconds.", event.getSession().getId(),
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // Path: src/main/java/com/adeptj/runtime/osgi/HttpSessionEvents.java import com.adeptj.runtime.common.Times; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionIdListener; import javax.servlet.http.HttpSessionListener; import java.time.Instant; import java.util.Date; import java.util.Optional; sessionListener().ifPresent(listener -> listener.sessionCreated(event)); break; case SESSION_DESTROYED: logSessionDestroyed(event); sessionListener().ifPresent(listener -> listener.sessionDestroyed(event)); break; default: // NO-OP break; } } // <<---------- HttpSessionIdListener ---------->> public static void handleSessionIdChangedEvent(HttpSessionEvent event, String oldSessionId) { sessionIdListener().ifPresent(listener -> listener.sessionIdChanged(event, oldSessionId)); } private static void logSessionCreated(HttpSessionEvent event) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Created HttpSession with id: [{}], @Time: [{}]", event.getSession().getId(), Date.from(Instant.ofEpochMilli(event.getSession().getCreationTime()))); } } private static void logSessionDestroyed(HttpSessionEvent event) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Destroyed HttpSession with id: [{}], active for: [{}] seconds.", event.getSession().getId(),
Times.elapsedSeconds(event.getSession().getCreationTime()));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/core/RuntimeInitializer.java
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/exception/RuntimeInitializationException.java // public class RuntimeInitializationException extends RuntimeException { // // private static final long serialVersionUID = 6443421220206654015L; // // public RuntimeInitializationException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java // @WebListener("Stops the OSGi Framework when ServletContext is destroyed") // public class FrameworkShutdownHandler implements ServletContextListener { // // @Override // public void contextDestroyed(ServletContextEvent event) { // long startTime = System.nanoTime(); // Logger logger = LoggerFactory.getLogger(this.getClass()); // logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); // ServiceTrackers.getInstance().closeEventDispatcherTracker(); // // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // // is changed which results in a NPE. // ServiceTrackers.getInstance().closeDispatcherServletTracker(); // FrameworkManager.getInstance().stopFramework(); // ServletContextHolder.getInstance().setServletContext(null); // logger.info("OSGi Framework stopped in [{}] ms!!", Times.elapsedMillis(startTime)); // } // // }
import java.util.Set; import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.exception.RuntimeInitializationException; import com.adeptj.runtime.osgi.FrameworkShutdownHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.annotation.HandlesTypes; import java.util.ServiceLoader;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.core; /** * An SCI(ServletContainerInitializer) that is called by the Container while startup is in progress. * This will further call onStartup method of all of the {@link HandlesTypes} classes registered with this SCI. * * @author Rakesh.Kumar, AdeptJ */ @HandlesTypes(StartupAware.class) public class RuntimeInitializer implements ServletContainerInitializer { private static final String SYS_PROP_SCAN_STARTUP_AWARE_CLASSES = "scan.startup.aware.classes"; /** * {@inheritDoc} */ @Override public void onStartup(Set<Class<?>> startupAwareClasses, ServletContext context) {
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/exception/RuntimeInitializationException.java // public class RuntimeInitializationException extends RuntimeException { // // private static final long serialVersionUID = 6443421220206654015L; // // public RuntimeInitializationException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java // @WebListener("Stops the OSGi Framework when ServletContext is destroyed") // public class FrameworkShutdownHandler implements ServletContextListener { // // @Override // public void contextDestroyed(ServletContextEvent event) { // long startTime = System.nanoTime(); // Logger logger = LoggerFactory.getLogger(this.getClass()); // logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); // ServiceTrackers.getInstance().closeEventDispatcherTracker(); // // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // // is changed which results in a NPE. // ServiceTrackers.getInstance().closeDispatcherServletTracker(); // FrameworkManager.getInstance().stopFramework(); // ServletContextHolder.getInstance().setServletContext(null); // logger.info("OSGi Framework stopped in [{}] ms!!", Times.elapsedMillis(startTime)); // } // // } // Path: src/main/java/com/adeptj/runtime/core/RuntimeInitializer.java import java.util.Set; import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.exception.RuntimeInitializationException; import com.adeptj.runtime.osgi.FrameworkShutdownHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.annotation.HandlesTypes; import java.util.ServiceLoader; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.core; /** * An SCI(ServletContainerInitializer) that is called by the Container while startup is in progress. * This will further call onStartup method of all of the {@link HandlesTypes} classes registered with this SCI. * * @author Rakesh.Kumar, AdeptJ */ @HandlesTypes(StartupAware.class) public class RuntimeInitializer implements ServletContainerInitializer { private static final String SYS_PROP_SCAN_STARTUP_AWARE_CLASSES = "scan.startup.aware.classes"; /** * {@inheritDoc} */ @Override public void onStartup(Set<Class<?>> startupAwareClasses, ServletContext context) {
ServletContextHolder.getInstance().setServletContext(context);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/core/RuntimeInitializer.java
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/exception/RuntimeInitializationException.java // public class RuntimeInitializationException extends RuntimeException { // // private static final long serialVersionUID = 6443421220206654015L; // // public RuntimeInitializationException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java // @WebListener("Stops the OSGi Framework when ServletContext is destroyed") // public class FrameworkShutdownHandler implements ServletContextListener { // // @Override // public void contextDestroyed(ServletContextEvent event) { // long startTime = System.nanoTime(); // Logger logger = LoggerFactory.getLogger(this.getClass()); // logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); // ServiceTrackers.getInstance().closeEventDispatcherTracker(); // // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // // is changed which results in a NPE. // ServiceTrackers.getInstance().closeDispatcherServletTracker(); // FrameworkManager.getInstance().stopFramework(); // ServletContextHolder.getInstance().setServletContext(null); // logger.info("OSGi Framework stopped in [{}] ms!!", Times.elapsedMillis(startTime)); // } // // }
import java.util.Set; import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.exception.RuntimeInitializationException; import com.adeptj.runtime.osgi.FrameworkShutdownHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.annotation.HandlesTypes; import java.util.ServiceLoader;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.core; /** * An SCI(ServletContainerInitializer) that is called by the Container while startup is in progress. * This will further call onStartup method of all of the {@link HandlesTypes} classes registered with this SCI. * * @author Rakesh.Kumar, AdeptJ */ @HandlesTypes(StartupAware.class) public class RuntimeInitializer implements ServletContainerInitializer { private static final String SYS_PROP_SCAN_STARTUP_AWARE_CLASSES = "scan.startup.aware.classes"; /** * {@inheritDoc} */ @Override public void onStartup(Set<Class<?>> startupAwareClasses, ServletContext context) { ServletContextHolder.getInstance().setServletContext(context); Logger logger = LoggerFactory.getLogger(this.getClass()); for (Class<?> startupAwareClass : startupAwareClasses) { logger.info("@HandlesTypes: [{}]", startupAwareClass); try { ((StartupAware) startupAwareClass.getConstructor().newInstance()).onStartup(context); } catch (Exception ex) { // NOSONAR logger.error("Exception while executing StartupAware#onStartup!!", ex);
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/exception/RuntimeInitializationException.java // public class RuntimeInitializationException extends RuntimeException { // // private static final long serialVersionUID = 6443421220206654015L; // // public RuntimeInitializationException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java // @WebListener("Stops the OSGi Framework when ServletContext is destroyed") // public class FrameworkShutdownHandler implements ServletContextListener { // // @Override // public void contextDestroyed(ServletContextEvent event) { // long startTime = System.nanoTime(); // Logger logger = LoggerFactory.getLogger(this.getClass()); // logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); // ServiceTrackers.getInstance().closeEventDispatcherTracker(); // // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // // is changed which results in a NPE. // ServiceTrackers.getInstance().closeDispatcherServletTracker(); // FrameworkManager.getInstance().stopFramework(); // ServletContextHolder.getInstance().setServletContext(null); // logger.info("OSGi Framework stopped in [{}] ms!!", Times.elapsedMillis(startTime)); // } // // } // Path: src/main/java/com/adeptj/runtime/core/RuntimeInitializer.java import java.util.Set; import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.exception.RuntimeInitializationException; import com.adeptj.runtime.osgi.FrameworkShutdownHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.annotation.HandlesTypes; import java.util.ServiceLoader; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.core; /** * An SCI(ServletContainerInitializer) that is called by the Container while startup is in progress. * This will further call onStartup method of all of the {@link HandlesTypes} classes registered with this SCI. * * @author Rakesh.Kumar, AdeptJ */ @HandlesTypes(StartupAware.class) public class RuntimeInitializer implements ServletContainerInitializer { private static final String SYS_PROP_SCAN_STARTUP_AWARE_CLASSES = "scan.startup.aware.classes"; /** * {@inheritDoc} */ @Override public void onStartup(Set<Class<?>> startupAwareClasses, ServletContext context) { ServletContextHolder.getInstance().setServletContext(context); Logger logger = LoggerFactory.getLogger(this.getClass()); for (Class<?> startupAwareClass : startupAwareClasses) { logger.info("@HandlesTypes: [{}]", startupAwareClass); try { ((StartupAware) startupAwareClass.getConstructor().newInstance()).onStartup(context); } catch (Exception ex) { // NOSONAR logger.error("Exception while executing StartupAware#onStartup!!", ex);
throw new RuntimeInitializationException(ex);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/core/RuntimeInitializer.java
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/exception/RuntimeInitializationException.java // public class RuntimeInitializationException extends RuntimeException { // // private static final long serialVersionUID = 6443421220206654015L; // // public RuntimeInitializationException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java // @WebListener("Stops the OSGi Framework when ServletContext is destroyed") // public class FrameworkShutdownHandler implements ServletContextListener { // // @Override // public void contextDestroyed(ServletContextEvent event) { // long startTime = System.nanoTime(); // Logger logger = LoggerFactory.getLogger(this.getClass()); // logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); // ServiceTrackers.getInstance().closeEventDispatcherTracker(); // // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // // is changed which results in a NPE. // ServiceTrackers.getInstance().closeDispatcherServletTracker(); // FrameworkManager.getInstance().stopFramework(); // ServletContextHolder.getInstance().setServletContext(null); // logger.info("OSGi Framework stopped in [{}] ms!!", Times.elapsedMillis(startTime)); // } // // }
import java.util.Set; import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.exception.RuntimeInitializationException; import com.adeptj.runtime.osgi.FrameworkShutdownHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.annotation.HandlesTypes; import java.util.ServiceLoader;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.core; /** * An SCI(ServletContainerInitializer) that is called by the Container while startup is in progress. * This will further call onStartup method of all of the {@link HandlesTypes} classes registered with this SCI. * * @author Rakesh.Kumar, AdeptJ */ @HandlesTypes(StartupAware.class) public class RuntimeInitializer implements ServletContainerInitializer { private static final String SYS_PROP_SCAN_STARTUP_AWARE_CLASSES = "scan.startup.aware.classes"; /** * {@inheritDoc} */ @Override public void onStartup(Set<Class<?>> startupAwareClasses, ServletContext context) { ServletContextHolder.getInstance().setServletContext(context); Logger logger = LoggerFactory.getLogger(this.getClass()); for (Class<?> startupAwareClass : startupAwareClasses) { logger.info("@HandlesTypes: [{}]", startupAwareClass); try { ((StartupAware) startupAwareClass.getConstructor().newInstance()).onStartup(context); } catch (Exception ex) { // NOSONAR logger.error("Exception while executing StartupAware#onStartup!!", ex); throw new RuntimeInitializationException(ex); } }
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/exception/RuntimeInitializationException.java // public class RuntimeInitializationException extends RuntimeException { // // private static final long serialVersionUID = 6443421220206654015L; // // public RuntimeInitializationException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java // @WebListener("Stops the OSGi Framework when ServletContext is destroyed") // public class FrameworkShutdownHandler implements ServletContextListener { // // @Override // public void contextDestroyed(ServletContextEvent event) { // long startTime = System.nanoTime(); // Logger logger = LoggerFactory.getLogger(this.getClass()); // logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); // ServiceTrackers.getInstance().closeEventDispatcherTracker(); // // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // // is changed which results in a NPE. // ServiceTrackers.getInstance().closeDispatcherServletTracker(); // FrameworkManager.getInstance().stopFramework(); // ServletContextHolder.getInstance().setServletContext(null); // logger.info("OSGi Framework stopped in [{}] ms!!", Times.elapsedMillis(startTime)); // } // // } // Path: src/main/java/com/adeptj/runtime/core/RuntimeInitializer.java import java.util.Set; import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.exception.RuntimeInitializationException; import com.adeptj.runtime.osgi.FrameworkShutdownHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.annotation.HandlesTypes; import java.util.ServiceLoader; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.core; /** * An SCI(ServletContainerInitializer) that is called by the Container while startup is in progress. * This will further call onStartup method of all of the {@link HandlesTypes} classes registered with this SCI. * * @author Rakesh.Kumar, AdeptJ */ @HandlesTypes(StartupAware.class) public class RuntimeInitializer implements ServletContainerInitializer { private static final String SYS_PROP_SCAN_STARTUP_AWARE_CLASSES = "scan.startup.aware.classes"; /** * {@inheritDoc} */ @Override public void onStartup(Set<Class<?>> startupAwareClasses, ServletContext context) { ServletContextHolder.getInstance().setServletContext(context); Logger logger = LoggerFactory.getLogger(this.getClass()); for (Class<?> startupAwareClass : startupAwareClasses) { logger.info("@HandlesTypes: [{}]", startupAwareClass); try { ((StartupAware) startupAwareClass.getConstructor().newInstance()).onStartup(context); } catch (Exception ex) { // NOSONAR logger.error("Exception while executing StartupAware#onStartup!!", ex); throw new RuntimeInitializationException(ex); } }
context.addListener(FrameworkShutdownHandler.class);