answer
stringlengths
17
10.2M
package com.ffxivcensus.gatherer; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.regex.Pattern; /** * Object class to represent a Character/Player. This class specifies the attributes and behaviour of a player object. * It also serves the functionality of fetching player data from the Lodestone. * * @author Peter Reid * @see Gatherer */ public class Player { private int id; private String realm; private String playerName; private String race; private String gender; private String grandCompany; private String freeCompany; private int lvlGladiator; private int lvlPugilist; private int lvlMarauder; private int lvlLancer; private int lvlArcher; private int lvlRogue; private int lvlConjurer; private int lvlThaumaturge; private int lvlArcanist; private int lvlDarkKnight; private int lvlMachinist; private int lvlAstrologian; private int lvlCarpenter; private int lvlBlacksmith; private int lvlArmorer; private int lvlGoldsmith; private int lvlLeatherworker; private int lvlWeaver; private int lvlAlchemist; private int lvlCulinarian; private int lvlMiner; private int lvlBotanist; private int lvlFisher; private boolean has30DaysSub; private boolean has60DaysSub; private boolean has90DaysSub; private boolean has180DaysSub; private boolean has270DaysSub; private boolean has360DaysSub; private boolean has450DaysSub; private boolean has630DaysSub; private boolean has960DaysSub; private boolean hasPreOrderArr; private boolean hasPreOrderHW; private boolean hasArtbook; private boolean hasBeforeMeteor; private boolean hasBeforeTheFall; private boolean hasSoundtrack; private boolean hasAttendedEternalBond; private boolean hasCompletedHWSightseeing; private boolean hasCompleted2pt5; private boolean hasFiftyComms; private boolean hasMooglePlush; private boolean hasCompletedHildibrand; private boolean hasPS4Collectors; private boolean hasEternalBond; private boolean hasARRCollectors; private boolean hasKobold; private boolean hasSahagin; private boolean hasAmaljaa; private boolean hasSylph; private boolean hasCompletedHW; private boolean hasCompleted3pt1; private boolean isLegacyPlayer; private ArrayList minions; private ArrayList mounts; /** * Constructor for player object. * * @param id id of character to fetch. */ public Player(int id) { this.setId(id); setRealm(null); setPlayerName(null); setRace(null); setGender(null); setGrandCompany(null); setFreeCompany(null); setLvlGladiator(0); setLvlPugilist(0); setLvlMarauder(0); setLvlLancer(0); setLvlArcher(0); setLvlRogue(0); setLvlConjurer(0); setLvlThaumaturge(0); setLvlArcanist(0); setLvlDarkKnight(0); setLvlMachinist(0); setLvlAstrologian(0); setLvlCarpenter(0); setLvlBlacksmith(0); setLvlArmorer(0); setLvlGoldsmith(0); setLvlLeatherworker(0); setLvlWeaver(0); setLvlAlchemist(0); setLvlCulinarian(0); setLvlMiner(0); setLvlBotanist(0); setLvlFisher(0); setHas30DaysSub(false); setHas60DaysSub(false); setHas90DaysSub(false); setHas180DaysSub(false); setHas270DaysSub(false); setHas360DaysSub(false); setHas450DaysSub(false); setHas630DaysSub(false); setHas960DaysSub(false); setHasPreOrderArr(false); setHasPreOrderHW(false); setHasArtbook(false); setHasBeforeMeteor(false); setHasBeforeTheFall(false); setHasSoundtrack(false); setHasAttendedEternalBond(false); setHasCompletedHWSightseeing(false); setHasCompleted2pt5(false); setHasFiftyComms(false); setHasMooglePlush(false); setHasCompletedHildibrand(false); setHasPS4Collectors(false); setHasEternalBond(false); setHasARRCollectors(false); setHasKobold(false); setHasSahagin(false); setHasAmaljaa(false); setHasSylph(false); setHasCompletedHW(false); setHasCompleted3pt1(false); } /** * Get the player's ID. * * @return the ID of the player object */ public int getId() { return id; } /** * Set the player's ID. * * @param id the ID of the player object */ public void setId(int id) { this.id = id; } /** * Get the player's realm. * * @return the player's realm */ public String getRealm() { return realm; } /** * Set the player's realm. * * @param realm the player's realm */ public void setRealm(String realm) { this.realm = realm; } /** * Get the player's name. * * @return the player's name. */ public String getPlayerName() { return playerName; } /** * Set the player's name. * * @param playerName the player's name. */ public void setPlayerName(String playerName) { this.playerName = playerName; } /** * Get the player's race. * * @return the player's race */ public String getRace() { return race; } /** * Set the player's race. * * @param race the player's race. */ public void setRace(String race) { this.race = race; } /** * Get the player's gender. * * @return the player's gender. */ public String getGender() { return gender; } /** * Set the player's gender. * * @param gender the player's gender. */ public void setGender(String gender) { this.gender = gender; } /** * Get the player's grand company. * * @return the player's grand company. */ public String getGrandCompany() { return grandCompany; } /** * Set the player's grand company. * * @param grandCompany the player's grand company. */ public void setGrandCompany(String grandCompany) { this.grandCompany = grandCompany; } /** * Get the player's free company. * @return player's free company. */ public String getFreeCompany() { return freeCompany; } /** * Set the player's free company. * @param freeCompany the player's free company. */ public void setFreeCompany(String freeCompany) { this.freeCompany = freeCompany; } /** * Get the player's gladiator level. * * @return the player's gladiator level. */ public int getLvlGladiator() { return lvlGladiator; } /** * Set's the player's gladiator level. * * @param lvlGladiator the player's gladiator level. */ public void setLvlGladiator(int lvlGladiator) { this.lvlGladiator = lvlGladiator; } /** * Get the player's pugilist level. * * @return the player's pugilist level. */ public int getLvlPugilist() { return lvlPugilist; } /** * Set the player's pugilist level. * * @param lvlPugilist the player's pugilist level. */ public void setLvlPugilist(int lvlPugilist) { this.lvlPugilist = lvlPugilist; } /** * Get the player's marauder level. * * @return the player's marauder level. */ public int getLvlMarauder() { return lvlMarauder; } /** * Set the player's marauder level * * @param lvlMarauder the player's marauder level. */ public void setLvlMarauder(int lvlMarauder) { this.lvlMarauder = lvlMarauder; } /** * Get the player's lancer level. * * @return the player's lancer level. */ public int getLvlLancer() { return lvlLancer; } /** * Set the player's lancer level. * * @param lvlLancer the player's lancer level. */ public void setLvlLancer(int lvlLancer) { this.lvlLancer = lvlLancer; } /** * Get the player's archer level. * * @return the player's archer level. */ public int getLvlArcher() { return lvlArcher; } /** * Set the player's archer level. * * @param lvlArcher the player's archer level. */ public void setLvlArcher(int lvlArcher) { this.lvlArcher = lvlArcher; } /** * Get the player's rogue level. * * @return the player's rogue level. */ public int getLvlRogue() { return lvlRogue; } /** * Set the player's rogue level. * * @param lvlRogue the player's rogue level. */ public void setLvlRogue(int lvlRogue) { this.lvlRogue = lvlRogue; } /** * Get the player's conjurer level. * * @return the player's conjurer level. */ public int getLvlConjurer() { return lvlConjurer; } /** * Set the player's conjurer level. * * @param lvlConjurer the player's conjurer level. */ public void setLvlConjurer(int lvlConjurer) { this.lvlConjurer = lvlConjurer; } /** * Get the player's thaumaturge level. * * @return the player's thaumaturge level. */ public int getLvlThaumaturge() { return lvlThaumaturge; } /** * Set the player's thaumaturge level. * * @param lvlThaumaturge the player's thaumaturge level. */ public void setLvlThaumaturge(int lvlThaumaturge) { this.lvlThaumaturge = lvlThaumaturge; } /** * Set the player's arcanist level. * * @return the player's arcanist level. */ public int getLvlArcanist() { return lvlArcanist; } /** * Set the player's arcanist level. * * @param lvlArcanist the player's arcanist level */ public void setLvlArcanist(int lvlArcanist) { this.lvlArcanist = lvlArcanist; } /** * Get the players dark knight level. * * @return the player's dark knight level. */ public int getLvlDarkKnight() { return lvlDarkKnight; } /** * Set the player's dark knight level. * * @param lvlDarkKnight the player's dark knight level. */ public void setLvlDarkKnight(int lvlDarkKnight) { this.lvlDarkKnight = lvlDarkKnight; } /** * Get the player's machinist level. * * @return the player's machinist level. */ public int getLvlMachinist() { return lvlMachinist; } /** * Set the player's machinist level. * * @param lvlMachinist the player's machinist level. */ public void setLvlMachinist(int lvlMachinist) { this.lvlMachinist = lvlMachinist; } /** * Get the player's astrologian level. * * @return the player's astrologian level. */ public int getLvlAstrologian() { return lvlAstrologian; } /** * Set the player's astrologian level. * * @param lvlAstrologian the player's astrologian level. */ public void setLvlAstrologian(int lvlAstrologian) { this.lvlAstrologian = lvlAstrologian; } /** * Get the player's carpenter level. * * @return the player's carpenter level. */ public int getLvlCarpenter() { return lvlCarpenter; } /** * Set the player's carpenter's level. * * @param lvlCarpenter the player's carpenter level. */ public void setLvlCarpenter(int lvlCarpenter) { this.lvlCarpenter = lvlCarpenter; } /** * Get the player's blacksmith level. * * @return the player's blacksmith level. */ public int getLvlBlacksmith() { return lvlBlacksmith; } /** * Set the player's blacksmith level. * * @param lvlBlacksmith the blacksmith level. */ public void setLvlBlacksmith(int lvlBlacksmith) { this.lvlBlacksmith = lvlBlacksmith; } /** * Get the player's armorer level. * * @return the player's armorer level. */ public int getLvlArmorer() { return lvlArmorer; } /** * Set the player's armorer level. * * @param lvlArmorer the player's armorer level. */ public void setLvlArmorer(int lvlArmorer) { this.lvlArmorer = lvlArmorer; } /** * Get the player's goldsmith level. * * @return the player's goldsmith level. */ public int getLvlGoldsmith() { return lvlGoldsmith; } /** * Set the player's goldsmith level. * * @param lvlGoldsmith the player's goldsmith level. */ public void setLvlGoldsmith(int lvlGoldsmith) { this.lvlGoldsmith = lvlGoldsmith; } /** * Get the player's leatherworker level. * * @return the player's leatherworker level. */ public int getLvlLeatherworker() { return lvlLeatherworker; } /** * Set the player's leatherworker level. * * @param lvlLeatherworker the player's leatherworker level. */ public void setLvlLeatherworker(int lvlLeatherworker) { this.lvlLeatherworker = lvlLeatherworker; } /** * Get the player's weaver level. * * @return the player's weaver level. */ public int getLvlWeaver() { return lvlWeaver; } /** * Set the player's weaver level. * * @param lvlWeaver the player's waever level. */ public void setLvlWeaver(int lvlWeaver) { this.lvlWeaver = lvlWeaver; } /** * Get the player's alchemist level. * * @return the player's alchemist level */ public int getLvlAlchemist() { return lvlAlchemist; } /** * Set the player's alchemist level. * * @param lvlAlchemist the player's alchemist level. */ public void setLvlAlchemist(int lvlAlchemist) { this.lvlAlchemist = lvlAlchemist; } /** * Get the player's culinarian level. * * @return the player's culinarian level. */ public int getLvlCulinarian() { return lvlCulinarian; } /** * Set the player's culinarian level. * * @param lvlCulinarian the player's culinarian level. */ public void setLvlCulinarian(int lvlCulinarian) { this.lvlCulinarian = lvlCulinarian; } /** * Get the player's miner level. * * @return the player's miner level. */ public int getLvlMiner() { return lvlMiner; } /** * Set the player's miner level. * * @param lvlMiner the player's miner level. */ public void setLvlMiner(int lvlMiner) { this.lvlMiner = lvlMiner; } /** * Get the player's botanist level. * * @return the player's botanist level. */ public int getLvlBotanist() { return lvlBotanist; } /** * Set the player's botanist level. * * @param lvlBotanist the player's botanist level. */ public void setLvlBotanist(int lvlBotanist) { this.lvlBotanist = lvlBotanist; } /** * Get the player's fisher level. * * @return the player's fisher level. */ public int getLvlFisher() { return lvlFisher; } /** * Set the player's fisher level. * * @param lvlFisher the player's fisher level. */ public void setLvlFisher(int lvlFisher) { this.lvlFisher = lvlFisher; } /** * Get whether the player has had 30 days of subscription time. * * @return whether the player has had 30 days of subscription time. */ public boolean isHas30DaysSub() { return has30DaysSub; } /** * Get bit value of whether player has had 30 days of subscription. * * @return whether the player has had 30 days of subscription time as a bit value. */ public int getBitHas30DaysSub() { if (isHas30DaysSub()) { return 1; } else { return 0; } } /** * Set whether the player has had 30 days of subscription time. * * @param has30DaysSub whether the player has had 30 days of subscription time. */ public void setHas30DaysSub(boolean has30DaysSub) { this.has30DaysSub = has30DaysSub; } /** * Get whether the player has had 60 days of subscription time. * * @return whether the player has had 60 days of subscription time. */ public boolean isHas60DaysSub() { return has60DaysSub; } /** * Get bit value of whether the player has had 60 days of subscription time. * * @return whether the player has had 60 days of subscription time as a bit value. */ public int getBitHas60DaysSub() { if (isHas60DaysSub()) { return 1; } else { return 0; } } /** * Set whether the player has had 60 days of subscription time. * * @param has60DaysSub whether the player has had 60 days of subscription time. */ public void setHas60DaysSub(boolean has60DaysSub) { this.has60DaysSub = has60DaysSub; } /** * Get whether the player has had 90 days of subscription time. * * @return whether the player has had 90 days of subscription time. */ public boolean isHas90DaysSub() { return has90DaysSub; } /** * Get bit value of whether the player has had 90 days of subscription time. * * @return whether the player has had 90 days of subscription time as a bit value. */ public int getBitHas90DaysSub() { if (isHas90DaysSub()) { return 1; } else { return 0; } } /** * Set whether the player has had 90 days of subscription time. * * @param has90DaysSub whether the player has had 90 days of subscription time. */ public void setHas90DaysSub(boolean has90DaysSub) { this.has90DaysSub = has90DaysSub; } /** * Get whether the player has had 180 days of subscription time. * * @return whether the player has had 180 days of subscription time. */ public boolean isHas180DaysSub() { return has180DaysSub; } /** * Get bit value of whether the player has had 180 days of subscription time. * * @return whether the player has had 180 days of subscription time as a bit value. */ public int getBitHas180DaysSub() { if (isHas90DaysSub()) { return 1; } else { return 0; } } /** * Set whether the player has had 180 days of subscription time. * * @param has180DaysSub whether the player has had 180 days of subscription time. */ public void setHas180DaysSub(boolean has180DaysSub) { this.has180DaysSub = has180DaysSub; } /** * Get whether the player has had 270 days of subscription time. * * @return whether the player has had 270 days of subscription time. */ public boolean isHas270DaysSub() { return has270DaysSub; } /** * Get bit value of whether the player has had 270 days of subscription time. * * @return whether the player has had 270 days of subscription time as a bit value. */ public int getBitHas270DaysSub() { if (isHas270DaysSub()) { return 1; } else { return 0; } } /** * Set whether the player has had 270 days of subscription time. * * @param has270DaysSub whether the player has had 270 days of subscription time. */ public void setHas270DaysSub(boolean has270DaysSub) { this.has270DaysSub = has270DaysSub; } /** * Get whether the player has had 360 days of subscription time. * * @return whether the player has had 360 days of subscription time. */ public boolean isHas360DaysSub() { return has360DaysSub; } /** * Get bit value of whether the player has had 360 days of subscription time. * * @return whether the player has had 360 days of subscription time as a bit value. */ public int getBitHas360DaysSub() { if (isHas360DaysSub()) { return 1; } else { return 0; } } /** * Set whether the player has had 360 days of subscription time. * * @param has360DaysSub whether the player has had 360 days of subscription time. */ public void setHas360DaysSub(boolean has360DaysSub) { this.has360DaysSub = has360DaysSub; } /** * Get whether the player has had 450 days of subscription time. * * @return whether the player has had 450 days of subscription time. */ public boolean isHas450DaysSub() { return has450DaysSub; } /** * Get bit value of whether the player has had 450 days of subscription time. * * @return whether the player has had 450 days of subscription time as a bit value. */ public int getBitHas450DaysSub() { if (isHas450DaysSub()) { return 1; } else { return 0; } } /** * Set whether the player has had 450 days of subscription time. * * @param has450DaysSub whether the player has had 450 days of subscription time. */ public void setHas450DaysSub(boolean has450DaysSub) { this.has450DaysSub = has450DaysSub; } /** * Set whether the player has had 630 days of subscription time. * * @param has630DaysSub whether the player has had 630 days of subscription time. */ public void setHas630DaysSub(boolean has630DaysSub) { this.has630DaysSub = has630DaysSub; } /** * Get whether the player has had 630 days of subscription time. * * @return whether the player has had 630 days of subscription time. */ public boolean isHas630DaysSub() { return has630DaysSub; } /** * Get bit value of whether the player has had 630 days of subscription time. * * @return whether the player has had 630 days of subscription time as a bit value. */ public int getBitHas630DaysSub() { if (isHas630DaysSub()) { return 1; } else { return 0; } } /** * Set whether the player has had 960 days of subscription time. * * @param has960DaysSub whether the player has had 630 days of subscription time. */ public void setHas960DaysSub(boolean has960DaysSub) { this.has960DaysSub = has960DaysSub; } /** * Get whether the player has had 960 days of subscription time. * * @return whether the player has had 960 days of subscription time. */ public boolean isHas960DaysSub() { return has960DaysSub; } /** * Get bit value of whether the player has had 960 days of subscription time. * * @return whether the player has had 960 days of subscription time as a bit value. */ public int getBitHas960DaysSub() { if (isHas960DaysSub()) { return 1; } else { return 0; } } /** * Get whether the player had preordered "A Realm Reborn". * * @return whether the player had preordered "A Realm Reborn". */ public boolean isHasPreOrderArr() { return hasPreOrderArr; } /** * Get the bit value representing whether player had preordered "A Realm Reborn". * * @return bit value representing whether player had preordered "A Realm Reborn". */ public int getBitHasPreOrderArr() { if (isHasPreOrderArr()) { return 1; } else { return 0; } } /** * Set whether the player had preordered "A Realm Reborn" * * @param hasPreOrderArr whether the player had preordered "A Realm Reborn" */ public void setHasPreOrderArr(boolean hasPreOrderArr) { this.hasPreOrderArr = hasPreOrderArr; } /** * Get whether the user had preordered "Heavensward". * * @return whether the user had preordered "Heavensward". */ public boolean isHasPreOrderHW() { return hasPreOrderHW; } /** * Get bit value stating whether the user had preordered "Heavensward". * * @return bit value representing whether the user had preordered "Heavensward". */ public int getBitHasPreOrderHW() { if (isHasPreOrderHW()) { return 1; } else { return 0; } } /** * Set whether the user had preordered "Heavensward". * * @param hasPreOrderHW whether the user had preordered "Heavensward". */ public void setHasPreOrderHW(boolean hasPreOrderHW) { this.hasPreOrderHW = hasPreOrderHW; } /** * Gets whether the user has purchased the artbook. * * @return whether the user has purchased the artbook. */ public boolean isHasArtbook() { return hasArtbook; } /** * Get bit value as to whether the player has purchased the artbook. * * @return bit value as to whether the player has purchased the artbook. */ public int getBitHasArtBook() { if (isHasArtbook()) { return 1; } else { return 0; } } /** * Set whether the player has purchased the artbook. * * @param hasArtbook whether the player has purchased the artbook. */ public void setHasArtbook(boolean hasArtbook) { this.hasArtbook = hasArtbook; } /** * Get whether the player has purchased the before the meteor sound track. * * @return whether the player has purchased the before the meteor sound track. */ public boolean isHasBeforeMeteor() { return hasBeforeMeteor; } /** * Get bit value for whether the player has purchased the before the meteor sound track. * * @return bit value whether the player has purchased the before the meteor sound track. */ public int getBitHasBeforeMeteor() { if (isHasBeforeMeteor()) { return 1; } else { return 0; } } /** * Set whether the player has purchased the before the meteor sound track. * * @param hasBeforeMeteor whether the player has purchased the before the meteor sound track. */ public void setHasBeforeMeteor(boolean hasBeforeMeteor) { this.hasBeforeMeteor = hasBeforeMeteor; } /** * Get whether the player has purchased the before the fall sound track. * * @return whether the player has purchased the before the fall sound track. */ public boolean isHasBeforeTheFall() { return hasBeforeTheFall; } /** * Get bit value for whether the player has purchased the before the fall sound track. * * @return bit value whether the player has purchased the before the fall sound track. */ public int getBitHasBeforeTheFall() { if (isHasBeforeTheFall()) { return 1; } else { return 0; } } /** * Set whether the player has purchased the before the fall sound track. * * @param hasBeforeTheFall whether the player has purchased the before the fall sound track. */ public void setHasBeforeTheFall(boolean hasBeforeTheFall) { this.hasBeforeTheFall = hasBeforeTheFall; } /** * Get whether the player has purchased the sound track. * * @return whether the player has purchased the sound track. */ public boolean isHasSoundtrack() { return hasSoundtrack; } /** * Get bit value for whether the player has purchased the sound track. * * @return bit value whether the player has purchased the sound track. */ public int getBitHasSoundTrack() { if (isHasSoundtrack()) { return 1; } else { return 0; } } /** * Set whether the player has purchased the sound track. * * @param hasSoundtrack whether the player has purchased the sound track. */ public void setHasSoundtrack(boolean hasSoundtrack) { this.hasSoundtrack = hasSoundtrack; } /** * Gets whether the player has attended an "Eternal Bond" ceremony. * * @return whether the player has attended an "Eternal Bond" ceremony. */ public boolean isHasAttendedEternalBond() { return hasAttendedEternalBond; } /** * Get bit value for whether the player has attended an "Eternal Bond" ceremony. * * @return bit value whether the player has attended an "Eternal Bond" ceremony. */ public int getBitHasAttendedEternalBond() { if (isHasAttendedEternalBond()) { return 1; } else { return 0; } } /** * Set whether the player has attended an "Eternal Bond" ceremony. * * @param hasAttendedEternalBond whether the player has attended an "Eternal Bond" ceremony. */ public void setHasAttendedEternalBond(boolean hasAttendedEternalBond) { this.hasAttendedEternalBond = hasAttendedEternalBond; } /** * Get whether the player has completed the Heavensward sightseeing log. * * @return whether the player has completed the Heavensward sightseeing log. */ public boolean isHasCompletedHWSightseeing() { return hasCompletedHWSightseeing; } /** * Get bit value indicating whether player has completed Heavensward sightseeing log. * * @return bit value indicating whether player has completed Heavensward sightseeing log. */ public int getBitHasCompletedHWSightseeing() { if (isHasCompletedHWSightseeing()) { return 1; } else { return 0; } } /** * Set whether the player has completed the Heavensward sightseeing log. * * @param hasCompletedHWSightseeing whether the player has completed the Heavensward sightseeing log. */ public void setHasCompletedHWSightseeing(boolean hasCompletedHWSightseeing) { this.hasCompletedHWSightseeing = hasCompletedHWSightseeing; } /** * Get whether the player has completed the 2.5 story. * * @return whether the player has completed the 2.5 story. */ public boolean isHasCompleted2pt5() { return hasCompleted2pt5; } /** * Get bit value as to whether the player has completed the 2.5 story. * * @return bit value as to whether the player has completed the 2.5 story. */ public int getBitHasCompleted2pt5() { if (isHasCompleted2pt5()) { return 1; } else { return 0; } } /** * Set whether the player has completed the 2.5 story. * * @param hasCompleted2pt5 whether the player has completed the 2.5 story. */ public void setHasCompleted2pt5(boolean hasCompleted2pt5) { this.hasCompleted2pt5 = hasCompleted2pt5; } /** * Set whether the player has received 50 player commendations. * * @return whether the player has received 50 player commendations. */ public boolean isHasFiftyComms() { return hasFiftyComms; } /** * Get bit value as to whether the player has received 50 player commendations. * * @return bit value for whether the player has received 50 player commendations. */ public int getBitHasFiftyComms() { if (isHasFiftyComms()) { return 1; } else { return 0; } } /** * Set whether the player has received 50 player commendations. * * @param hasFiftyComms whether the player has received 50 player commendations. */ public void setHasFiftyComms(boolean hasFiftyComms) { this.hasFiftyComms = hasFiftyComms; } /** * Get whether the player has purchased the "Moogle Plush". * * @return whether the player has purchased the "Moogle Plush". */ public boolean isHasMooglePlush() { return hasMooglePlush; } /** * Get bit value whether the player has received 50 player commendations. * * @return whether the player has received 50 player commendations. */ public int getBitHasMooglePlush() { if (isHasMooglePlush()) { return 1; } else { return 0; } } /** * Set whether the player has purchased the "Moogle Plush". * * @param hasMooglePlush whether the player has purchased the "Moogle Plush". */ public void setHasMooglePlush(boolean hasMooglePlush) { this.hasMooglePlush = hasMooglePlush; } /** * Get whether the player has completed the Hildibrand quest series. * * @return whether the player has completed the Hildibrand quest series. */ public boolean isHasCompletedHildibrand() { return hasCompletedHildibrand; } /** * Get bit value whether the player has completed the Hildibrand quest series. * * @return bit value whether the player has completed the Hildibrand quest series. */ public int getBitHasCompletedHildibrand() { if (isHasCompletedHildibrand()) { return 1; } else { return 0; } } /** * Set whether the player has completed the Hildibrand quest series. * * @param hasCompletedHildibrand whether the player has completed the Hildibrand quest series. */ public void setHasCompletedHildibrand(boolean hasCompletedHildibrand) { this.hasCompletedHildibrand = hasCompletedHildibrand; } /** * Get whether the player has purchased the PS4 collectors edition. * * @return whether the player has purchased the PS4 collectors edition. */ public boolean isHasPS4Collectors() { return hasPS4Collectors; } /** * Get bit value whether the player has purchased the PS4 collectors edition. * * @return bit value whether the player has purchased the PS4 collectors edition. */ public int getBitHasPS4Collectors() { if (isHasPS4Collectors()) { return 1; } else { return 0; } } /** * Set whether the player has purchased the PS4 collectors edition. * * @param hasPS4Collectors whether the player has purchased the PS4 collectors edition. */ public void setHasPS4Collectors(boolean hasPS4Collectors) { this.hasPS4Collectors = hasPS4Collectors; } /** * Get whether player has an "Eternal Bond" with another player. * * @return whether player has an "Eternal Bond" with another player. */ public boolean isHasEternalBond() { return hasEternalBond; } /** * Get bit value as to whether player has an "Eternal Bond" with another player. * * @return whether player has an "Eternal Bond" with another player. */ public int getBitHasEternalBond() { if (isHasEternalBond()) { return 1; } else { return 0; } } /** * Set whether player has an "Eternal Bond" with another player. * * @param hasEternalBond whether player has an "Eternal Bond" with another player. */ public void setHasEternalBond(boolean hasEternalBond) { this.hasEternalBond = hasEternalBond; } /** * Get whether the player has purchased the "A Realm Reborn" collectors edition. * * @return whether the player has purchased the "A Realm Reborn" collectors edition. */ public boolean isHasARRCollectors() { return hasARRCollectors; } /** * Get bit value whether the player has purchased the "A Realm Reborn" collectors edition. * * @return bit value whether the player has purchased the "A Realm Reborn" collectors edition. */ public int getBitHasARRCollectors() { if (isHasARRCollectors()) { return 1; } else { return 0; } } /** * Set whether the player has purchased the "A Realm Reborn" collectors edition. * * @param hasARRCollectors whether the player has purchased the "A Realm Reborn" collectors edition. */ public void setHasARRCollectors(boolean hasARRCollectors) { this.hasARRCollectors = hasARRCollectors; } /** * Get whether the player has completed the "Kobold" dailies reputation. * * @return whether the player has completed the "Kobold" dailies reputation. */ public boolean isHasKobold() { return hasKobold; } /** * Get bit value whether the player has completed the "Kobold" dailies reputation. * * @return bit value whether the player has completed the "Kobold" dailies reputation. */ public int getBitHasKobold() { if (isHasKobold()) { return 1; } else { return 0; } } /** * Set whether the player has completed the "Kobold" dailies reputation. * * @param hasKobold whether the player has completed the "Kobold" dailies reputation. */ public void setHasKobold(boolean hasKobold) { this.hasKobold = hasKobold; } /** * Get whether the player has completed the "Sahagin" dailies reputation. * * @return whether the player has completed the "Sahagin" dailies reputation. */ public boolean isHasSahagin() { return hasSahagin; } /** * Get bit value for whether the player has completed the "Sahagin" dailies reputation. * * @return bit value for whether the player has completed the "Sahagin" dailies reputation. */ public int getBitHasSahagin() { if (isHasSahagin()) { return 1; } else { return 0; } } /** * Set whether the player has completed the "Sahagin" dailies reputation. * * @param hasSahagin whether the player has completed the "Sahagin" dailies reputation. */ public void setHasSahagin(boolean hasSahagin) { this.hasSahagin = hasSahagin; } /** * Get whether the player has completed the "Amaljaa" dailies reputation. * * @return whether the player has completed the "Amaljaa" dailies reputation. */ public boolean isHasAmaljaa() { return hasAmaljaa; } /** * Get bit value whether the player has completed the "Amaljaa" dailies reputation. * * @return bit value whether the player has completed the "Amaljaa" dailies reputation. */ public int getBitHasAmaljaa() { if (isHasAmaljaa()) { return 1; } else { return 0; } } /** * Set whether the player has completed the "Amaljaa" dailies reputation. * * @param hasAmaljaa whether the player has completed the "Amaljaa" dailies reputation. */ public void setHasAmaljaa(boolean hasAmaljaa) { this.hasAmaljaa = hasAmaljaa; } /** * Get whether the player has completed the "Sylph" dailies reputation. * * @return whether the player has completed the "Sylph" dailies reputation. */ public boolean isHasSylph() { return hasSylph; } /** * Get bit value whether the player has completed the "Sylph" dailies reputation. * * @return bit value whether the player has completed the "Sylph" dailies reputation. */ public int getBitHasSylph() { if (isHasSylph()) { return 1; } else { return 0; } } /** * Set whether the player has completed the "Sylph" dailies reputation. * * @param hasSylph whether the player has completed the "Sylph" dailies reputation. */ public void setHasSylph(boolean hasSylph) { this.hasSylph = hasSylph; } /** * Get whether the player has completed the Heavensward 3.0 story. * * @return whether the player has completed the Heavensward 3.0 story. */ public boolean isHasCompletedHW() { return hasCompletedHW; } /** * Get bit value whether the player has completed the Heavensward 3.0 story. * * @return bit value whether the player has completed the Heavensward 3.0 story. */ public int getBitHasCompletedHW() { if (isHasCompletedHW()) { return 1; } else { return 0; } } /** * Set whether the player has completed the Heavensward 3.0 story. * * @param hasCompletedHW whether the player has completed the Heavensward 3.0 story. */ public void setHasCompletedHW(boolean hasCompletedHW) { this.hasCompletedHW = hasCompletedHW; } /** * Get whether the user has completed the 3.1 story. * * @return whether the user has completed the 3.1 story. */ public boolean isHasCompleted3pt1() { return hasCompleted3pt1; } /** * Get bit value whether the user has completed the 3.1 story. * * @return bit value */ public int getBitHasCompleted3pt1() { if (hasCompleted3pt1) { return 1; } else { return 0; } } /** * Set whether the user has completed the 3.1 story. * * @param hasCompleted3pt1 whether the user has completed the 3.1 story. */ public void setHasCompleted3pt1(boolean hasCompleted3pt1) { this.hasCompleted3pt1 = hasCompleted3pt1; } /** * Get whether the user played 1.0. * * @return whether the user has played 1.0 */ public boolean getIsLegacyPlayer() { return isLegacyPlayer; } /** * Get bit value whether the user has played 1.0 * * @return bit value indicating whether player has played 1.0. */ public int getBitIsLegacyPlayer() { if (isLegacyPlayer) { return 1; } else { return 0; } } /** * Set whether the user has played 1.0. * * @param isLegacyPlayer whether the player has played 1.0. */ public void setIsLegacyPlayer(boolean isLegacyPlayer) { this.isLegacyPlayer = isLegacyPlayer; } /** * Get the character's minion set as a comma delimited string. * @return comma delimited string of player's minions. */ public String getMinionsString(){ StringBuilder sbMinions = new StringBuilder(); for(int index =0; index < this.minions.size(); index++){//For each minion string if(index != 0){ sbMinions.append(","); } sbMinions.append(this.minions.get(index).toString()); } return sbMinions.toString(); } /** * Get the character's mount set as a comma delimited string. * @return comma delimited string of player's mounts. */ public String getMountsString(){ StringBuilder sbMounts = new StringBuilder(); for(int index =0; index < this.mounts.size(); index++){//For each mount string if(index != 0){ sbMounts.append(","); } sbMounts.append(this.mounts.get(index).toString()); } return sbMounts.toString(); } /** * Set player class levels. * * @param arrLevels integer array of classes in order displayed on lodestone. */ public void setLevels(int[] arrLevels) { this.setLvlGladiator(arrLevels[0]); this.setLvlPugilist(arrLevels[1]); this.setLvlMarauder(arrLevels[2]); this.setLvlLancer(arrLevels[3]); this.setLvlArcher(arrLevels[4]); this.setLvlRogue(arrLevels[5]); this.setLvlConjurer(arrLevels[6]); this.setLvlThaumaturge(arrLevels[7]); this.setLvlArcanist(arrLevels[8]); this.setLvlDarkKnight(arrLevels[9]); this.setLvlMachinist(arrLevels[10]); this.setLvlAstrologian(arrLevels[11]); this.setLvlCarpenter(arrLevels[12]); this.setLvlBlacksmith(arrLevels[13]); this.setLvlArmorer(arrLevels[14]); this.setLvlGoldsmith(arrLevels[15]); this.setLvlLeatherworker(arrLevels[16]); this.setLvlWeaver(arrLevels[17]); this.setLvlAlchemist(arrLevels[18]); this.setLvlCulinarian(arrLevels[19]); this.setLvlMiner(arrLevels[20]); this.setLvlBotanist(arrLevels[21]); this.setLvlFisher(arrLevels[22]); } /** * Get player's mount set. * * @return the player's mounts as an arraylist. */ public ArrayList getMounts() { return mounts; } /** * Set player's mount set. * * @param mounts the player's mounts as an arraylist. */ public void setMounts(ArrayList mounts) { this.mounts = mounts; } /** * Get player's minion set. * * @return the player's minions as an arraylist. */ public ArrayList getMinions() { return minions; } /** * Set player's minion set. * * @param minions the player's minions as an arraylist. */ public void setMinions(ArrayList minions) { this.minions = minions; } /** * Determine if a player has a specified mount * * @param mountName the name of the mount to check for. * @return whether the player has the specified mount. */ public boolean doesPlayerHaveMount(String mountName) { return this.mounts.contains(mountName); } /** * Determine if a player has a specified minion. * * @param minionName the name of the minion to check for * @return whether the player has the specified minion. */ public boolean doesPlayerHaveMinion(String minionName) { return this.minions.contains(minionName); } /** * Fetch a player from the lodestone specified by ID. * * @param playerID the ID of the player to fetch * @return the player object matching the specified ID. * @throws Exception exception thrown if more class levels returned than anticipated. */ public static Player getPlayer(int playerID) throws Exception { //Initialize player object to return Player player = new Player(playerID); //Declare HTML document Document doc; //URL to connect to String url = "http://eu.finalfantasyxiv.com/lodestone/character/" + playerID + "/"; try { //Fetch the specified URL doc = Jsoup.connect(url).get(); player.setPlayerName(getNameFromPage(doc)); player.setRealm(getRealmFromPage(doc)); player.setRace(getRaceFromPage(doc)); player.setGender(getGenderFromPage(doc)); player.setGrandCompany(getGrandCompanyFromPage(doc)); player.setFreeCompany(getFreeCompanyFromPage(doc)); player.setLevels(getLevelsFromPage(doc)); player.setMounts(getMountsFromPage(doc)); player.setMinions(getMinionsFromPage(doc)); player.setHas30DaysSub(player.doesPlayerHaveMinion("Wind-up Cursor")); player.setHas60DaysSub(player.doesPlayerHaveMinion("Black Chocobo Chick")); player.setHas90DaysSub(player.doesPlayerHaveMinion("Beady Eye")); player.setHas180DaysSub(player.doesPlayerHaveMinion("Minion Of Light")); player.setHas270DaysSub(player.doesPlayerHaveMinion("Wind-up Leader")); player.setHas360DaysSub(player.doesPlayerHaveMinion("Wind-up Odin")); player.setHas450DaysSub(player.doesPlayerHaveMinion("Wind-up Goblin")); player.setHas630DaysSub(player.doesPlayerHaveMinion("Wind-up Nanamo")); player.setHas960DaysSub(player.doesPlayerHaveMinion("Wind-up Firion")); player.setHasPreOrderArr(player.doesPlayerHaveMinion("Cait Sith Doll")); player.setHasPreOrderHW(player.doesPlayerHaveMinion("Chocobo Chick Courier")); player.setHasArtbook(player.doesPlayerHaveMinion("Model Enterprise")); player.setHasBeforeMeteor(player.doesPlayerHaveMinion("Wind-up Dalamud")); player.setHasBeforeTheFall(player.doesPlayerHaveMinion("Set Of Primogs")); player.setHasSoundtrack(player.doesPlayerHaveMinion("Wind-up Bahamut")); player.setHasAttendedEternalBond(player.doesPlayerHaveMinion("Demon Box")); player.setHasCompletedHWSightseeing(player.doesPlayerHaveMinion("Fledgling Apkallu")); player.setHasCompleted2pt5(player.doesPlayerHaveMinion("Midgardsormr")); player.setHasFiftyComms(player.doesPlayerHaveMinion("Princely Hatchling")); player.setHasMooglePlush(player.doesPlayerHaveMinion("Wind-up Delivery Moogle")); player.setHasCompletedHildibrand(player.doesPlayerHaveMinion("Wind-up Gentleman")); player.setHasPS4Collectors(player.doesPlayerHaveMinion("Wind-up Moogle")); player.setHasCompleted3pt1(player.doesPlayerHaveMinion("Wind-up Haurchefant")); player.setHasEternalBond(player.doesPlayerHaveMount("Ceremony Chocobo")); player.setHasARRCollectors(player.doesPlayerHaveMount("Coeurl")); player.setHasKobold(player.doesPlayerHaveMount("Bomb Palanquin")); player.setHasSahagin(player.doesPlayerHaveMount("Cavalry Elbst")); player.setHasAmaljaa(player.doesPlayerHaveMount("Cavalry Drake")); player.setHasSylph(player.doesPlayerHaveMount("Laurel Goobbue")); player.setHasCompletedHW(player.doesPlayerHaveMount("Midgardsormr")); player.setIsLegacyPlayer(player.doesPlayerHaveMount("Legacy Chocobo")); } catch (IOException ioEx) { throw new Exception("Character " + playerID + " does not exist."); } return player; } /** * Given a lodestone profile page, return the name of the character. * * @param doc the lodestone profile page. * @return the name of the character. */ private static String getNameFromPage(Document doc) { String[] parts = doc.title().split(Pattern.quote("|")); String name = parts[0].trim(); return name; } /** * Given a lodestone profile page, return the realm of the character. * * @param doc the lodestone profile page. * @return the realm of the character. */ private static String getRealmFromPage(Document doc) { //Get elements in the player name area Elements elements = doc.getElementsByClass("player_name_txt"); String realmName = elements.get(0).getElementsByTag("span").text().replace("(", "").replace(")", ""); //Return the realm name (contained in span) return realmName; } /** * Given a lodestone profile page, return the race of the character. * * @param doc the lodestone profile page. * @return the race of the character. */ private static String getRaceFromPage(Document doc) { return doc.getElementsByClass("chara_profile_title").get(0).text().split(Pattern.quote("/"))[0].trim(); } /** * Given a lodestone profile page, return the gender of the character. * * @param doc the lodestone profile page. * @return the gender of the character. */ private static String getGenderFromPage(Document doc) { String[] parts = doc.getElementsByClass("chara_profile_title").get(0).text().split(Pattern.quote("/")); String gender = parts[2].trim(); if (gender.equals("")) { return "male"; } else if (gender.equals("")) { return "female"; } else { return null; } } /** * Given a lodestone profile page, return the grand company of the character. * * @param doc the lodestone profile page. * @return the grand company of the character. */ private static String getGrandCompanyFromPage(Document doc) { String gc = null; String fc = null; //Get all elements with class chara_profile_box_info Elements elements = doc.getElementsByClass("txt_name"); //Checks to see if optional FC has been added if (elements.size() == 5) { fc = elements.get(4).getElementsByTag("a").text(); } if (elements.size() == 5) { //If GC and FC present gc = elements.get(3).text().split(Pattern.quote("/"))[0]; } else if (elements.size() == 4) { //If only GC present gc = elements.get(3).text().split(Pattern.quote("/"))[0]; if (!gc.equals("Immortal Flames") && !gc.equals("Order of the Twin Adder") && !gc.equals("Maelstrom")) { //If not a valid GC gc = "none"; } } else if (elements.size() == 3) { gc = "none"; } return gc; } /** * Given a lodestone profile page, return the free company of the character. * * @param doc the lodestone profile page. * @return the free company of the character. */ private static String getFreeCompanyFromPage(Document doc) { String gc = null; String fc = null; //Get all elements with class chara_profile_box_info Elements elements = doc.getElementsByClass("txt_name"); //Checks to see if optional FC has been added if (elements.size() == 5) { fc = elements.get(4).getElementsByTag("a").text(); } else if (elements.size() == 4) { //If only 4 elements present //Assume that gc is what is in slot 3 gc = elements.get(3).text().split(Pattern.quote("/"))[0]; if (!gc.equals("Immortal Flames") && !gc.equals("Order of the Twin Adder") && !gc.equals("Maelstrom")) { //If not a valid GC gc = "none"; fc = elements.get(3).text().split(Pattern.quote("/"))[0]; } else { fc= "none"; } } else if (elements.size() == 3) { fc = "none"; } return fc; } /** * Given a lodestone profile page, return the levelset of the character. * * @param doc the lodestone profile page * @return the set of levels of the player in the order displayed on the lodestone. * @throws Exception Exception thrown if more classes found than anticipated. */ private static int[] getLevelsFromPage(Document doc) throws Exception { //Initialize array list in which to store levels (in order displayed on lodestone) ArrayList levels = new ArrayList(); //Get the html of the table for levels Elements table = doc.getElementsByClass("class_list").select("tr"); for (Element e : table) { //For each row of table //Select the first level String lvlOne = e.select("td:eq(1)").text(); //Initialize var to store second String lvlTwo = null; if (e.select("td").size() > 3) { //Second level lvlTwo = e.select("td:eq(4)").text(); } if (lvlOne.equals("-")) {//If a dash levels.add(0); } else { levels.add(Integer.parseInt(lvlOne)); } if (lvlTwo.equals("-")) { levels.add(0); } else if (!lvlTwo.equals("")) { levels.add(Integer.parseInt(lvlTwo)); } } //Initialize int array int[] arrLevels = new int[levels.size()]; //Convert array list to array of ints for (int index = 0; index < levels.size(); index++) { arrLevels[index] = Integer.parseInt(levels.get(index).toString()); } //Check if levels array is larger than this system is programmed for if (arrLevels.length > 23) { throw new Exception("Error: More class levels found than anticipated (23). The class definitions need to be updated."); } return arrLevels; } /** * Get the set of minions from a page. * * @param doc the lodestone profile page to parse. * @return the set of strings representing the player's minions. */ private static ArrayList getMinionsFromPage(Document doc) { //Get minion box element Element minionBox = doc.getElementsByClass("minion_box").get(1); //Get minions Elements minionSet = minionBox.getElementsByTag("a"); //Initialize array in which to store minions ArrayList minions = new ArrayList(); for (int index = 0; index < minionSet.size(); index++) { //For each minion link store into array minions.add(minionSet.get(index).attr("title")); } return minions; } /** * Get the set of mounts from a page. * * @param doc the lodestone profile page to parse. * @return the set of strings representing the player's mounts. */ private static ArrayList getMountsFromPage(Document doc) { //Get minion box element Element minionBox = doc.getElementsByClass("minion_box").get(0); //Get mounts Elements mountSet = minionBox.getElementsByTag("a"); //Initialize array in which to store minions ArrayList mounts = new ArrayList(); for (int index = 0; index < mountSet.size(); index++) { //For each mount link store into array mounts.add(mountSet.get(index).attr("title")); } return mounts; } }
package com.fishercoder.solutions; import java.util.Arrays; import java.util.PriorityQueue; public class _1005 { public static class Solution1 { public int largestSumAfterKNegations(int[] A, int K) { PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for (int num : A) { minHeap.offer(num); } while (K minHeap.offer(-minHeap.poll()); } int sum = 0; while (!minHeap.isEmpty()) { sum += minHeap.poll(); } return sum; } } public static class Solution2 { public int largestSumAfterKNegations(int[] A, int K) { Arrays.sort(A); for (int i = 0; i < A.length && K > 0 && A[i] < 0; i++, K A[i] = -A[i]; } int sum = 0; int min = Integer.MAX_VALUE; for (int i = 0; i < A.length; i++) { min = Math.min(min, A[i]); sum += A[i]; } return K % 2 == 0 ? sum : sum - min * 2; } } }
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 1182. Shortest Distance to Target Color * * You are given an array colors, in which there are three colors: 1, 2 and 3. * You are also given some queries. Each query consists of two integers i and c, * return the shortest distance between the given index i and the target color c. If there is no solution return -1. * * Example 1: * Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]] * Output: [3,0,3] * Explanation: * The nearest 3 from index 1 is at index 4 (3 steps away). * The nearest 2 from index 2 is at index 2 itself (0 steps away). * The nearest 1 from index 6 is at index 3 (3 steps away). * * Example 2: * Input: colors = [1,2], queries = [[0,3]] * Output: [-1] * Explanation: There is no 3 in the array. * * Constraints: * 1 <= colors.length <= 5*10^4 * 1 <= colors[i] <= 3 * 1 <= queries.length <= 5*10^4 * queries[i].length == 2 * 0 <= queries[i][0] < colors.length * 1 <= queries[i][1] <= 3 * */ public class _1182 { public static class Solution1 { public List<Integer> shortestDistanceColor(int[] colors, int[][] queries) { Map<Integer, List<Integer>> map = buildMap(colors); List<Integer> result = new ArrayList<>(); for (int[] query : queries) { result.add(binarySearch(query[0], map.get(query[1]))); } return result; } private Integer binarySearch(int index, List<Integer> indices) { if (indices == null) { return -1; } int left = 0; int right = indices.size() - 1; int minDistance = Integer.MAX_VALUE; while (left <= right) { int mid = left + (right - left) / 2; if (indices.get(mid) == index) { return 0; } else if (indices.get(mid) > index) { minDistance = Math.min(minDistance, indices.get(mid) - index); right = mid - 1; } else { minDistance = Math.min(minDistance, index - indices.get(mid)); left = mid + 1; } } return minDistance; } private Map<Integer, List<Integer>> buildMap(int[] colors) { Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < colors.length; i++) { if (!map.containsKey(colors[i])) { map.put(colors[i], new ArrayList<>()); } map.get(colors[i]).add(i); } return map; } } }
package com.fishercoder.solutions; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class _1271 { public static class Solution1 { public String toHexspeak(String num) { long numInt = Long.parseLong(num); String hexString = Long.toHexString(numInt); StringBuilder sb = new StringBuilder(); Set<Character> set = new HashSet<>(Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', '1', '0', 'a', 'b', 'c', 'd', 'e', 'f')); for (char c : hexString.toCharArray()) { if (!set.contains(c)) { return "ERROR"; } else if (c == '1') { sb.append("I"); } else if (c == '0') { sb.append("O"); } else { sb.append(Character.toUpperCase(c)); } } return sb.toString(); } } }
package com.github.davidmoten.rx2; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import com.github.davidmoten.rx2.util.ZippedEntry; import io.reactivex.Emitter; import io.reactivex.Flowable; import io.reactivex.Single; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; public final class Bytes { private static final int DEFAULT_BUFFER_SIZE = 8192; private Bytes() { // prevent instantiation } /** * Returns a Flowable stream of byte arrays from the given * {@link InputStream} between 1 and {@code bufferSize} bytes. * * @param is * input stream of bytes * @param bufferSize * max emitted byte array size * @return a stream of byte arrays */ public static Flowable<byte[]> from(final InputStream is, final int bufferSize) { return Flowable.generate(new Consumer<Emitter<byte[]>>() { @Override public void accept(Emitter<byte[]> emitter) throws Exception { byte[] buffer = new byte[bufferSize]; int count = is.read(buffer); if (count == -1) { emitter.onComplete(); } else if (count < bufferSize) { emitter.onNext(Arrays.copyOf(buffer, count)); } else { emitter.onNext(buffer); } } }); } public static Flowable<byte[]> from(File file) { return from(file, 8192); } public static Flowable<byte[]> from(final File file, final int size) { Callable<InputStream> resourceFactory = new Callable<InputStream>() { @Override public InputStream call() throws FileNotFoundException { return new BufferedInputStream(new FileInputStream(file), size); } }; Function<InputStream, Flowable<byte[]>> observableFactory = new Function<InputStream, Flowable<byte[]>>() { @Override public Flowable<byte[]> apply(InputStream is) { return from(is, size); } }; return Flowable.using(resourceFactory, observableFactory, InputStreamCloseHolder.INSTANCE, true); } private static final class InputStreamCloseHolder { static final Consumer<InputStream> INSTANCE = new Consumer<InputStream>() { @Override public void accept(InputStream is) throws IOException { is.close(); } }; } /** * Returns an Flowable stream of byte arrays from the given * {@link InputStream} of {@code 8192} bytes. The final byte array may be * less than {@code 8192} bytes. * * @param is * input stream of bytes * @return a stream of byte arrays */ public static Flowable<byte[]> from(InputStream is) { return from(is, DEFAULT_BUFFER_SIZE); } public static Flowable<ZippedEntry> unzip(final File file) { Callable<ZipInputStream> resourceFactory = new Callable<ZipInputStream>() { @Override public ZipInputStream call() throws FileNotFoundException { return new ZipInputStream(new FileInputStream(file)); } }; Function<ZipInputStream, Flowable<ZippedEntry>> observableFactory = ZipHolder.OBSERVABLE_FACTORY; Consumer<ZipInputStream> disposeAction = ZipHolder.DISPOSER; return Flowable.using(resourceFactory, observableFactory, disposeAction); } public static Flowable<ZippedEntry> unzip(final InputStream is) { return unzip(new ZipInputStream(is)); } public static Flowable<ZippedEntry> unzip(final ZipInputStream zis) { return Flowable.generate(new Consumer<Emitter<ZippedEntry>>() { @Override public void accept(Emitter<ZippedEntry> emitter) throws IOException { ZipEntry zipEntry = zis.getNextEntry(); if (zipEntry != null) { emitter.onNext(new ZippedEntry(zipEntry, zis)); } else { // end of stream so eagerly close the stream (might not be a // good idea since this method did not create the zis zis.close(); emitter.onComplete(); } } }); } public static Single<byte[]> collect(Flowable<byte[]> source) { return source.collect(BosCreatorHolder.INSTANCE, BosCollectorHolder.INSTANCE).map(BosToArrayHolder.INSTANCE); } public static Function<Flowable<byte[]>, Single<byte[]>> collect() { return new Function<Flowable<byte[]>, Single<byte[]>>() { @Override public Single<byte[]> apply(Flowable<byte[]> source) throws Exception { return collect(source); } }; } private static final class BosCreatorHolder { static final Callable<ByteArrayOutputStream> INSTANCE = new Callable<ByteArrayOutputStream>() { @Override public ByteArrayOutputStream call() { return new ByteArrayOutputStream(); } }; } private static final class BosCollectorHolder { static final BiConsumer<ByteArrayOutputStream, byte[]> INSTANCE = new BiConsumer<ByteArrayOutputStream, byte[]>() { @Override public void accept(ByteArrayOutputStream bos, byte[] bytes) throws IOException { bos.write(bytes); } }; } private static final class BosToArrayHolder { static final Function<ByteArrayOutputStream, byte[]> INSTANCE = new Function<ByteArrayOutputStream, byte[]>() { @Override public byte[] apply(ByteArrayOutputStream bos) { return bos.toByteArray(); } }; } private static final class ZipHolder { static final Consumer<ZipInputStream> DISPOSER = new Consumer<ZipInputStream>() { @Override public void accept(ZipInputStream zis) throws IOException { zis.close(); } }; final static Function<ZipInputStream, Flowable<ZippedEntry>> OBSERVABLE_FACTORY = new Function<ZipInputStream, Flowable<ZippedEntry>>() { @Override public Flowable<ZippedEntry> apply(ZipInputStream zis) { return unzip(zis); } }; } }
package com.github.rconner.anansi; import com.google.common.collect.UnmodifiableIterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * A special case immutable singly-linked list used for building Paths. This is singly-linked for a couple reasons. One * is that in graph traversals, the reverse direction would not be a list, but a tree. Another is that being * singly-linked allows unused paths to be garbage collected. This is roughly how LISP implements lists, and works very * nicely for building predecessor graphs. */ final class Chain<E> implements Iterable<E> { // FIXME: add (enum singleton) terminator instead of null? // That would allow representation of an empty chain. private final E head; private final Chain<E> tail; private final int size; private Chain(E head, Chain<E> tail) { this.head = head; this.tail = tail; size = (tail == null) ? 1 : tail.size + 1; } /** * Creates a Chain with a single element. * * @param element * @return */ public static <T> Chain<T> of(T element) { return new Chain<T>(element, null); } /** * Creates a Chain with the given elements, in order. * * @param elements * @return */ public static <T> Chain<T> copyOf(T... elements) { Chain<T> chain = null; for (int i = elements.length - 1; i >= 0; i chain = new Chain<T>(elements[i], chain); } return chain; } public E head() { return head; } public Chain<E> tail() { return tail; } public int size() { return size; } /** * Creates a returns new Chain from this Chain with an element prepended. This is essentially a &quot;push&quot; * operation, except that it creates a new Chain. */ public Chain<E> with(E element) { return new Chain<E>(element, this); } @Override public Iterator<E> iterator() { return new UnmodifiableIterator<E>() { Chain<E> rest = Chain.this; @Override public boolean hasNext() { return rest != null; } @Override public E next() { if (rest == null) { throw new NoSuchElementException(); } E element = rest.head(); rest = rest.tail(); return element; } }; } // This is a trade-off that probably needs some benchmarking. // This implementation computes the backing array once, and then keeps it around forever. // One alternative is to create a new backing array every time iterator() is called. // Another is to keep a weak reference to the backing array and only recompute if it has been gc'd. public Iterable<E> reverse() { // There's no way to do this without saving all the elements, at least no way that isn't O(n^2). // An ImmutableList would work, except they don't allow null elements. return new Iterable<E>() { // Lazily initialized private Object[] array; private synchronized Object[] getArray() { if (array == null) { array = new Object[size]; Chain<E> rest = Chain.this; for (int i = size() - 1; i >= 0; i array[i] = rest.head(); rest = rest.tail(); } } return array; } @Override public Iterator<E> iterator() { // Arrays.asList( ... ).iterator() returns a ListIterator, which allows elements to be mutated. final Object[] ref = getArray(); return new UnmodifiableIterator<E>() { private int i = 0; @Override public boolean hasNext() { return i < ref.length; } @Override public E next() { if (i >= ref.length) { throw new NoSuchElementException(); } return (E) ref[i++]; } }; } }; } }
package com.kodcu.service.ui; import com.kodcu.component.EditorPane; import com.kodcu.component.ImageTab; import com.kodcu.component.MenuItemBuilt; import com.kodcu.component.MyTab; import com.kodcu.config.StoredConfigBean; import com.kodcu.controller.ApplicationController; import com.kodcu.other.Current; import com.kodcu.other.ExtensionFilters; import com.kodcu.other.IOHelper; import com.kodcu.other.Item; import com.kodcu.service.DirectoryService; import com.kodcu.service.ParserService; import com.kodcu.service.PathResolverService; import com.kodcu.service.ThreadService; import com.kodcu.service.convert.markdown.MarkdownService; import com.kodcu.service.extension.AsciiTreeGenerator; import com.kodcu.service.shortcut.ShortcutProvider; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseButton; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.FileChooser; import netscape.javascript.JSObject; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; @Component public class TabService { private final Logger logger = LoggerFactory.getLogger(TabService.class); private final ApplicationController controller; private final EditorService editorService; private final PathResolverService pathResolver; private final ThreadService threadService; private final Current current; private final DirectoryService directoryService; private final StoredConfigBean storedConfigBean; private final ParserService parserService; private final ApplicationContext applicationContext; private final ShortcutProvider shortcutProvider; private final AsciiTreeGenerator asciiTreeGenerator; private ObservableList<Optional<Path>> closedPaths = FXCollections.observableArrayList(); @Autowired public TabService(final ApplicationController controller, final EditorService editorService, final PathResolverService pathResolver, final ThreadService threadService, final Current current, final DirectoryService directoryService, StoredConfigBean storedConfigBean, ParserService parserService, ApplicationContext applicationContext, ShortcutProvider shortcutProvider, AsciiTreeGenerator asciiTreeGenerator) { this.controller = controller; this.editorService = editorService; this.pathResolver = pathResolver; this.threadService = threadService; this.current = current; this.directoryService = directoryService; this.storedConfigBean = storedConfigBean; this.parserService = parserService; this.applicationContext = applicationContext; this.shortcutProvider = shortcutProvider; this.asciiTreeGenerator = asciiTreeGenerator; } public void addTab(Path path, Runnable... runnables) { ObservableList<String> recentFiles = storedConfigBean.getRecentFiles(); if (Files.notExists(path)) { recentFiles.remove(path.toString()); logger.debug("Path {} not found in the filesystem", path); return; } ObservableList<Tab> tabs = controller.getTabPane().getTabs(); for (Tab tab : tabs) { MyTab myTab = (MyTab) tab; Path currentPath = myTab.getPath(); if (Objects.nonNull(currentPath)) if (currentPath.equals(path)) { myTab.select(); // Select already added tab return; } } AnchorPane anchorPane = new AnchorPane(); MyTab tab = createTab(); tab.setTabText(path.getFileName().toString()); EditorPane editorPane = tab.getEditorPane(); threadService.runActionLater(() -> { TabPane tabPane = controller.getTabPane(); tabPane.getTabs().add(tab); tab.select(); }); Node editorVBox = editorService.createEditorVBox(editorPane, tab); controller.fitToParent(editorVBox); anchorPane.getChildren().add(editorVBox); tab.setContent(anchorPane); tab.setPath(path); Tooltip tip = new Tooltip(path.toString()); Tooltip.install(tab.getGraphic(), tip); recentFiles.remove(path.toString()); recentFiles.add(0, path.toString()); editorPane.getHandleReadyTasks().clear(); editorPane.getHandleReadyTasks().addAll(runnables); editorPane.load(String.format("http://localhost:%d/editor.html", controller.getPort())); } public void newDoc() { newDoc(""); } public void newDoc(final String content) { MyTab tab = this.createTab(); EditorPane editorPane = tab.getEditorPane(); editorPane.setInitialEditorValue(content); AnchorPane anchorPane = new AnchorPane(); Node editorVBox = editorService.createEditorVBox(editorPane, tab); controller.fitToParent(editorVBox); anchorPane.getChildren().add(editorVBox); tab.setContent(anchorPane); tab.setTabText("new *"); TabPane tabPane = controller.getTabPane(); tabPane.getTabs().add(tab); tab.select(); editorPane.load(String.format("http://localhost:%d/editor.html", controller.getPort())); } public void openDoc() { FileChooser fileChooser = directoryService.newFileChooser("Open File"); fileChooser.getExtensionFilters().add(ExtensionFilters.ASCIIDOC); fileChooser.getExtensionFilters().add(ExtensionFilters.MARKDOWN); fileChooser.getExtensionFilters().add(ExtensionFilters.ALL); List<File> chosenFiles = fileChooser.showOpenMultipleDialog(controller.getStage()); if (chosenFiles != null) { chosenFiles.stream().map(File::toPath).forEach(this::previewDocument); chosenFiles.stream() .map(File::toString).filter(file -> !storedConfigBean.getRecentFiles().contains(file)) .forEach(storedConfigBean.getRecentFiles()::addAll); directoryService.setInitialDirectory(Optional.ofNullable(chosenFiles.get(0))); } } public Path getSelectedTabPath() { TreeItem<Item> selectedItem = controller.getTreeView().getSelectionModel().getSelectedItem(); Item value = selectedItem.getValue(); Path path = value.getPath(); return path; } public MyTab createTab() { final MyTab tab = applicationContext.getBean(MyTab.class); tab.setOnCloseRequest(event -> { event.consume(); tab.close(); }); MenuItem menuItem0 = new MenuItem("Close"); menuItem0.setOnAction(actionEvent -> { tab.close(); }); MenuItem menuItem1 = new MenuItem("Close All"); menuItem1.setOnAction(actionEvent -> { ObservableList<Tab> tabs = tab.getTabPane().getTabs(); ObservableList<Tab> clonedTabs = FXCollections.observableArrayList(tabs); if (clonedTabs.size() > 0) { clonedTabs.forEach((closedTab) -> { MyTab myTab = (MyTab) closedTab; myTab.close(); }); } }); MenuItem menuItem2 = new MenuItem("Close Others"); menuItem2.setOnAction(actionEvent -> { ObservableList<Tab> blackList = FXCollections.observableArrayList(); blackList.addAll(tab.getTabPane().getTabs()); blackList.remove(tab); blackList.forEach(t -> { MyTab closeTab = (MyTab) t; closeTab.close(); }); }); // MenuItem menuItem3 = new MenuItem("Close Unmodified"); // menuItem3.setOnAction(actionEvent -> { // ObservableList<Tab> clonedTabs = FXCollections.observableArrayList(); // clonedTabs.addAll(controller.getTabPane().getTabs()); // for (Tab clonedTab : clonedTabs) { // MyTab myTab = (MyTab) clonedTab; // if (!myTab.getTabText().contains(" *")) // threadService.runActionLater(()->{ // myTab.close(); MenuItem menuItem4 = new MenuItem("Select Next Tab"); menuItem4.setOnAction(actionEvent -> { TabPane tabPane = tab.getTabPane(); if (tabPane.getSelectionModel().isSelected(tabPane.getTabs().size() - 1)) tabPane.getSelectionModel().selectFirst(); else tabPane.getSelectionModel().selectNext(); }); MenuItem menuItem5 = new MenuItem("Select Previous Tab"); menuItem5.setOnAction(actionEvent -> { SingleSelectionModel<Tab> selectionModel = tab.getTabPane().getSelectionModel(); if (selectionModel.isSelected(0)) selectionModel.selectLast(); else selectionModel.selectPrevious(); }); MenuItem menuItem6 = new MenuItem("Reopen Closed Tab"); menuItem6.setOnAction(actionEvent -> { if (closedPaths.size() > 0) { int index = closedPaths.size() - 1; closedPaths.get(index).filter(pathResolver::isAsciidoc).ifPresent(this::addTab); closedPaths.get(index).filter(pathResolver::isMarkdown).ifPresent(this::addTab); closedPaths.get(index).filter(pathResolver::isImage).ifPresent(this::addImageTab); closedPaths.remove(index); } }); MenuItem menuItem7 = new MenuItem("Open File Location"); menuItem7.setOnAction(event -> { current.currentPath().ifPresent(path -> { controller.getHostServices().showDocument(path.getParent().toUri().toASCIIString()); }); }); MenuItem menuItem8 = new MenuItem("New File"); menuItem8.setOnAction(controller::newDoc); MenuItem reloadMenuItem = new MenuItem("Reload"); reloadMenuItem.setOnAction(event -> { tab.reloadDocument("Do you want reload this unsaved document?"); }); MenuItem gotoWorkdir = new MenuItem("Go to Workdir"); gotoWorkdir.setOnAction(event -> { current.currentPath().map(Path::getParent).ifPresent(directoryService::changeWorkigDir); }); ContextMenu contextMenu = new ContextMenu(); contextMenu.getItems().addAll(menuItem0, menuItem1, menuItem2, new SeparatorMenuItem(), menuItem4, menuItem5, menuItem6, new SeparatorMenuItem(), reloadMenuItem, new SeparatorMenuItem(), gotoWorkdir, new SeparatorMenuItem(), menuItem7, menuItem8); tab.contextMenuProperty().setValue(contextMenu); Label label = tab.getLabel(); label.setOnMouseClicked(mouseEvent -> { if (mouseEvent.getButton().equals(MouseButton.SECONDARY)) { tab.select(); } else if (mouseEvent.getClickCount() > 1) { controller.adjustSplitPane(); } }); return tab; } public void previewDocument(Path path) { if (Objects.isNull(path)) { logger.error("Null path cannot be viewed"); return; } if (Files.isDirectory(path)) { if (path.equals(directoryService.workingDirectory())) { directoryService.changeWorkigDir(path.getParent()); } else { directoryService.changeWorkigDir(path); } } else if (pathResolver.isImage(path)) { addImageTab(path); } else if (pathResolver.isHTML(path) || pathResolver.isAsciidoc(path) || pathResolver.isMarkdown(path)) { addTab(path); } else if (pathResolver.isEpub(path)) { controller.getHostServices() .showDocument(String.format("http://localhost:%d/epub/viewer?path=%s", controller.getPort(), path.toString())); } else { List<String> supportedModes = controller.getSupportedModes(); String extension = FilenameUtils.getExtension(path.toString()); if ("".equals(extension) || supportedModes.contains(extension)) { addTab(path); controller.hidePreviewPanel(); } else { controller.getHostServices() .showDocument(path.toUri().toString()); } } } public void addImageTab(Path imagePath) { TabPane previewTabPane = controller.getPreviewTabPane(); ImageTab tab = new ImageTab(imagePath); if (previewTabPane.getTabs().contains(tab)) { previewTabPane.getSelectionModel().select(tab); return; } Image image = new Image(IOHelper.pathToUrl(imagePath)); ImageView imageView = new ImageView(image); imageView.setPreserveRatio(true); imageView.setFitWidth(previewTabPane.getWidth()); previewTabPane.widthProperty().addListener((observable, oldValue, newValue) -> { imageView.setFitWidth(previewTabPane.getWidth()); }); Tooltip tip = new Tooltip(imagePath.toString()); Tooltip.install(tab.getGraphic(), tip); ScrollPane scrollPane = new ScrollPane(); scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); scrollPane.setContent(imageView); scrollPane.addEventFilter(ScrollEvent.SCROLL, e -> { if (e.isControlDown() && e.getDeltaY() > 0) { // zoom in imageView.setFitWidth(imageView.getFitWidth() + 16.0); } else if (e.isControlDown() && e.getDeltaY() < 0) { // zoom out imageView.setFitWidth(imageView.getFitWidth() - 16.0); } }); tab.setContent(scrollPane); previewTabPane.getTabs().add(tab); previewTabPane.getSelectionModel().select(tab); } public void initializeTabChangeListener(TabPane tabPane) { ReadOnlyObjectProperty<Tab> itemProperty = tabPane.getSelectionModel().selectedItemProperty(); itemProperty.addListener((observable, oldValue, selectedTab) -> { if (Objects.isNull(selectedTab)) return; threadService.runActionLater(() -> { EditorPane editorPane = ((MyTab) selectedTab).getEditorPane(); if (Objects.nonNull(editorPane)) { try { editorPane.rerender(); editorPane.focus(); } catch (Exception e) { logger.error("Problem occured after changing tab {}", selectedTab, e); } } }); }); } public ObservableList<Optional<Path>> getClosedPaths() { return closedPaths; } }
package com.mdsol.skyfire; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.acceleo.common.IAcceleoConstants; import org.eclipse.acceleo.common.internal.utils.AcceleoPackageRegistry; import org.eclipse.acceleo.common.internal.utils.workspace.AcceleoWorkspaceUtil; import org.eclipse.acceleo.common.internal.utils.workspace.BundleURLConverter; import org.eclipse.acceleo.common.utils.ModelUtils; import org.eclipse.acceleo.model.mtl.MtlPackage; import org.eclipse.acceleo.model.mtl.resource.AcceleoResourceSetImpl; import org.eclipse.acceleo.model.mtl.resource.EMtlBinaryResourceFactoryImpl; import org.eclipse.acceleo.model.mtl.resource.EMtlResourceFactoryImpl; import org.eclipse.emf.common.EMFPlugin; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.URIConverter; import org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl; import org.eclipse.ocl.ecore.EcoreEnvironment; import org.eclipse.ocl.ecore.EcoreEnvironmentFactory; import org.eclipse.ocl.expressions.ExpressionsPackage; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.Model; import org.eclipse.uml2.uml.StateMachine; /** * A class that provides functions to access UML models. Classes in Acceleo are used to be helpers * to access the models. * * @author Nan Li * @version 1.0 Nov 14, 2012 */ public class ModelAccessor { private static Logger logger = LogManager.getLogger("ModelAccessor"); /** * Gets the {@link org.eclipse.emf.ecore.EObject} object of a UML model specified by path * * @param path * a String representation of the path of a UML model * @return an {@link org.eclipse.emf.ecore.EObject} object * @throws IOException * when the path to the model is not found */ public static EObject getModelObject(final String path) throws IOException { final URI modelURI = URI.createFileURI(path); final URIConverter uriConverter = createURIConverter(); @SuppressWarnings("deprecation") final Map<URI, URI> uriMap = EcorePlugin.computePlatformURIMap(); final ResourceSet modelResourceSet = new AcceleoResourceSetImpl(); modelResourceSet.setPackageRegistry(AcceleoPackageRegistry.INSTANCE); if (uriConverter != null) { modelResourceSet.setURIConverter(uriConverter); } // make sure that metamodel projects in the workspace override those in // plugins modelResourceSet.getURIConverter().getURIMap().putAll(uriMap); registerResourceFactories(modelResourceSet); registerPackages(modelResourceSet); final URI newModelURI = URI.createURI(modelURI.toString(), true); final EObject model = ModelUtils.load(newModelURI, modelResourceSet); return model; } /** * Gets all objects of {@link org.eclipse.uml2.uml.StateMachine} in the model * * @param model * a UML model to parse * @return a list of {@link org.eclipse.uml2.uml.StateMachine} in the model */ public static List<StateMachine> getStateMachines(final EObject model) { final List<StateMachine> result = new ArrayList<>(); final EList<Element> elements = ((Model) model).getOwnedElements(); for (final Element elementObject : elements) { if (elementObject instanceof StateMachine) { result.add((StateMachine) elementObject); } } return result; } /** * The methods below are copied from Acceleo. */ /** * Creates the URI Converter we'll use to load our modules. Take note that this should never be * used out of Eclipse. * * @return The created URI Converter. * @since 3.0 */ protected static URIConverter createURIConverter() { if (!EMFPlugin.IS_ECLIPSE_RUNNING) { return null; } return new ExtensibleURIConverterImpl() { /** * {@inheritDoc} * */ @Override public URI normalize(final URI uri) { URI normalized = getURIMap().get(uri); if (normalized == null) { final BundleURLConverter conv = new BundleURLConverter(uri.toString()); if (conv.resolveBundle() != null) { normalized = URI.createURI(conv.resolveAsPlatformPlugin()); getURIMap().put(uri, normalized); } } if (normalized != null) { return normalized; } return super.normalize(uri); } }; } /** * This will update the resource set's package registry with all usual EPackages. * * @param resourceSet * The resource set which registry has to be updated. */ public static void registerPackages(final ResourceSet resourceSet) { resourceSet.getPackageRegistry().put(EcorePackage.eINSTANCE.getNsURI(), EcorePackage.eINSTANCE); resourceSet.getPackageRegistry().put( org.eclipse.ocl.ecore.EcorePackage.eINSTANCE.getNsURI(), org.eclipse.ocl.ecore.EcorePackage.eINSTANCE); resourceSet.getPackageRegistry().put(ExpressionsPackage.eINSTANCE.getNsURI(), ExpressionsPackage.eINSTANCE); resourceSet.getPackageRegistry().put(MtlPackage.eINSTANCE.getNsURI(), MtlPackage.eINSTANCE); resourceSet.getPackageRegistry().put("http: getOCLStdLibPackage()); if (!isInWorkspace(org.eclipse.uml2.uml.UMLPackage.class)) { resourceSet.getPackageRegistry().put( org.eclipse.uml2.uml.UMLPackage.eINSTANCE.getNsURI(), org.eclipse.uml2.uml.UMLPackage.eINSTANCE); } } /** * This will update the resource set's resource factory registry with all usual factories. * * @param resourceSet * The resource set which registry has to be updated. */ public static void registerResourceFactories(final ResourceSet resourceSet) { resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getContentTypeToFactoryMap() .put(IAcceleoConstants.BINARY_CONTENT_TYPE, new EMtlBinaryResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getContentTypeToFactoryMap() .put(IAcceleoConstants.XMI_CONTENT_TYPE, new EMtlResourceFactoryImpl()); } /** * Returns the package containing the OCL standard library. * * @return The package containing the OCL standard library. */ protected static EPackage getOCLStdLibPackage() { final EcoreEnvironmentFactory factory = new EcoreEnvironmentFactory(); final EcoreEnvironment environment = (EcoreEnvironment) factory.createEnvironment(); final EPackage oclStdLibPackage = (EPackage) EcoreUtil .getRootContainer(environment.getOCLStandardLibrary().getBag()); environment.dispose(); return oclStdLibPackage; } /** * Clients can override this if the default behavior doesn't properly find the emtl module URL. * * @param moduleName * Name of the module we're searching for. * @return The template's URL. This will use Eclipse-specific behavior if possible, and use the * class loader otherwise. */ protected final URL findModuleURL(final String moduleName) { URL moduleURL = null; if (EMFPlugin.IS_ECLIPSE_RUNNING) { try { moduleURL = AcceleoWorkspaceUtil.getResourceURL(getClass(), moduleName); } catch (final IOException e) { // Swallow this, we'll try and locate the module through the // class loader logger.error(e); } } if (moduleURL == null) { moduleURL = getClass().getResource(moduleName); } return moduleURL; } /** * Creates the URI that will be used to resolve the template that is to be launched. * * @param entry * The path towards the template file. Could be a jar or file scheme URI, or we'll * assume it represents a relative path. * @return The actual URI from which the template file can be resolved. */ protected final URI createTemplateURI(final String entry) { if (entry.startsWith("file:") || entry.startsWith("jar:")) { //$NON-NLS-1$ //$NON-NLS-2$ return URI.createURI(URI.decode(entry)); } return URI.createFileURI(URI.decode(entry)); } /** * Checks whether the given EPackage class is located in the workspace. * * @param ePackageClass * The EPackage class we need to take into account. * @return <code>true</code> if the given class has been loaded from a dynamically installed * bundle, <code>false</code> otherwise. * @since 3.1 */ public static boolean isInWorkspace(final Class<? extends EPackage> ePackageClass) { return EMFPlugin.IS_ECLIPSE_RUNNING && AcceleoWorkspaceUtil.INSTANCE.isInDynamicBundle(ePackageClass); } }
package com.packt.sfjd.ch10; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.ml.Pipeline; import org.apache.spark.ml.PipelineModel; import org.apache.spark.ml.PipelineStage; import org.apache.spark.ml.classification.DecisionTreeClassifier; import org.apache.spark.ml.classification.LogisticRegression; import org.apache.spark.ml.feature.Binarizer; import org.apache.spark.ml.feature.Bucketizer; import org.apache.spark.ml.feature.PCA; import org.apache.spark.ml.feature.StandardScaler; import org.apache.spark.ml.feature.StringIndexer; import org.apache.spark.ml.feature.VectorAssembler; import org.apache.spark.ml.feature.VectorIndexer; import org.apache.spark.ml.feature.VectorSlicer; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.types.StructType; public class FlightDelay { public static void main(String[] args) { System.setProperty("hadoop.home.dir", "E:\\sumitK\\Hadoop"); SparkSession sparkSession = SparkSession .builder() .master("local") .config("spark.sql.warehouse.dir", "file:///E:/sumitK/Hadoop/warehouse") .appName("FlightDelay").getOrCreate(); Logger rootLogger = LogManager.getRootLogger(); rootLogger.setLevel(Level.WARN); Dataset<String> flight2007 = sparkSession.read() .textFile("E:\\sumitK\\Hadoop\\flights_2007.csv.bz2") .limit(999999); Dataset<String> flight2008 = sparkSession.read() .textFile("E:\\sumitK\\Hadoop\\flights_2008.csv.bz2") .limit(999999); String header = flight2007.head(); System.out.println("The header in the file is :: " + header); // val trainingData = flight2007 // .filter(x => x != header) // .map(x => x.split(",")) // .filter(x => x(21) == "0") // .filter(x => x(17) == "ORD") // .filter(x => x(14) != "NA") // .map(p => Flight(p(1), p(2), p(3), getMinuteOfDay(p(4)), // getMinuteOfDay(p(5)), getMinuteOfDay(p(6)), getMinuteOfDay(p(7)), // p(8), p(11).toInt, p(12).toInt, p(13).toInt, p(14).toDouble, // p(15).toInt, p(16), p(18).toInt)) // .toDF // / header.s // p-> new Flight(p[1], p[2], p[3], getMinuteOfDay(p[4]), // getMinuteOfDay(p[5]), getMinuteOfDay(p[6]), getMinuteOfDay(p[7]), // p[8], (p[11].equalsIgnoreCase("NA"))?0:Integer.parseInt(p[11]), // (p[12].equalsIgnoreCase("NA"))?0:Integer.parseInt(p[12]), // (p[13].equalsIgnoreCase("NA"))?0:Integer.parseInt(p[13]), // Double.parseDouble(p[14]), // (p[15].equalsIgnoreCase("NA"))?0:Integer.parseInt(p[15]), p[16], // (p[18].equalsIgnoreCase("NA"))?0:Integer.parseInt(p[18]) JavaRDD<Flight> trainingRDD = flight2007 .filter(x -> !x.equalsIgnoreCase(header)) .javaRDD() .map(x -> x.split(",")) .filter(x -> x[21].equalsIgnoreCase("0")) .filter(x -> x[17].equalsIgnoreCase("ORD")) .filter(x -> x[14].equalsIgnoreCase("NA")) .map(p -> new Flight(p[1], p[2], p[3], getMinuteOfDay(p[4]), getMinuteOfDay(p[5]), getMinuteOfDay(p[6]), getMinuteOfDay(p[7]), p[8], (p[11] .equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[11]), (p[12].equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[12]), (p[13].equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[13]), (p[14].equalsIgnoreCase("NA")) ? 0 : Double .parseDouble(p[14]), (p[15] .equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[15]), p[16], (p[18] .equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[18]))); Dataset<Row> trainingData = sparkSession.createDataFrame(trainingRDD,Flight.class).cache(); // String header1 = flight2008.head(); JavaRDD<Flight> testingRDD = flight2008 .filter(x -> !x.equalsIgnoreCase(header)) .javaRDD() .map(x -> x.split(",")) .filter(x -> x[21].equalsIgnoreCase("0")) .filter(x -> x[17].equalsIgnoreCase("ORD")) .filter(x -> x[14].equalsIgnoreCase("NA")) .map(p -> new Flight(p[1], p[2], p[3], getMinuteOfDay(p[4]), getMinuteOfDay(p[5]), getMinuteOfDay(p[6]), getMinuteOfDay(p[7]), p[8], (p[11] .equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[11]), (p[12].equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[12]), (p[13].equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[13]), (p[14].equalsIgnoreCase("NA")) ? 0 : Double .parseDouble(p[14]), (p[15] .equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[15]), p[16], (p[18] .equalsIgnoreCase("NA")) ? 0 : Integer .parseInt(p[18]))); Dataset<Row> testingData = sparkSession.createDataFrame(testingRDD, Flight.class).cache(); System.out.println("The training data count is "+trainingData.count()); System.out.println("The testing data count is "+testingData.count()); //tranformor to convert string to category values StringIndexer monthIndexer = new StringIndexer().setInputCol("month").setOutputCol("MonthCat").setHandleInvalid("skip"); StringIndexer dayofMonthIndexer = new StringIndexer().setInputCol("dayofMonth").setOutputCol("DayofMonthCat").setHandleInvalid("skip"); StringIndexer dayOfWeekIndexer = new StringIndexer().setInputCol("dayOfWeek").setOutputCol("DayOfWeekCat").setHandleInvalid("skip"); StringIndexer uniqueCarrierIndexer = new StringIndexer().setInputCol("uniqueCarrier").setOutputCol("UniqueCarrierCat").setHandleInvalid("skip"); StringIndexer originIndexer = new StringIndexer().setInputCol("origin").setOutputCol("OriginCat").setHandleInvalid("skip"); //assemble raw feature VectorAssembler assembler = new VectorAssembler() .setInputCols(new String[] {"MonthCat", "DayofMonthCat", "DayOfWeekCat", "UniqueCarrierCat", "OriginCat", "depTime", "CRSDepTime", "arrTime", "CRSArrTime", "actualElapsedTime", "CRSElapsedTime", "airTime","depDelay", "distance"}) .setOutputCol("rawFeatures"); //vestor slicer VectorSlicer slicer = new VectorSlicer().setInputCol("rawFeatures").setOutputCol("slicedfeatures").setNames(new String[] {"MonthCat", "DayofMonthCat", "DayOfWeekCat", "UniqueCarrierCat", "depTime", "arrTime", "actualElapsedTime", "airTime", "depDelay", "distance"}); //scale the features //Made a change by setting withMean as false which converts the output to dense vector StandardScaler scaler = new StandardScaler().setInputCol("slicedfeatures").setOutputCol("features").setWithStd(true).setWithMean(false); //labels for binary classifier Binarizer binarizerClassifier = new Binarizer().setInputCol("arrDelay").setOutputCol("binaryLabel").setThreshold(15.0); //logistic regression LogisticRegression lr = new LogisticRegression().setMaxIter(10).setRegParam(0.3).setElasticNetParam(0.8).setLabelCol("binaryLabel").setFeaturesCol("features"); // Chain indexers and tree in a Pipeline Pipeline lrPipeline = new Pipeline().setStages(new PipelineStage[] {monthIndexer, dayofMonthIndexer, dayOfWeekIndexer, uniqueCarrierIndexer, originIndexer, assembler, slicer, scaler, binarizerClassifier, lr}); // Train model. StructType str=trainingData.schema(); //str.catalogString(); //str.fieldNames(); str.printTreeString(); PipelineModel lrModel = lrPipeline.fit(trainingData); // Make predictions. Dataset<Row> lrPredictions = lrModel.transform(testingData); // Select example rows to display. lrPredictions.select("prediction", "binaryLabel", "features").show(20); //index category index in raw feature VectorIndexer indexer = new VectorIndexer().setInputCol("rawFeatures").setOutputCol("rawFeaturesIndexed").setMaxCategories(10); //PCA PCA pca = new PCA().setInputCol("rawFeaturesIndexed").setOutputCol("features").setK(10); //label for multi class classifier Bucketizer bucketizer = new Bucketizer().setInputCol("arrDelay").setOutputCol("multiClassLabel").setSplits(new double[]{Double.NEGATIVE_INFINITY, 0.0, 15.0, Double.POSITIVE_INFINITY}); // Train a DecisionTree model. DecisionTreeClassifier dt = new DecisionTreeClassifier().setLabelCol("multiClassLabel").setFeaturesCol("features"); // Chain all into a Pipeline Pipeline dtPipeline = new Pipeline().setStages(new PipelineStage[] {monthIndexer, dayofMonthIndexer, dayOfWeekIndexer, uniqueCarrierIndexer, originIndexer, assembler, indexer, pca, bucketizer, dt}); // Train model. PipelineModel dtModel = dtPipeline.fit(trainingData); // Make predictions. Dataset<Row> dtPredictions = dtModel.transform(testingData); // Select example rows to display. dtPredictions.select("prediction", "multiClassLabel", "features").show(20); sparkSession.stop(); } // calculate minuted from midnight, input is military time format private static Integer getMinuteOfDay(String depTime) { //System.out.println("the deptTime is:" + depTime); return (depTime.equalsIgnoreCase("NA")) ? 0 : ((Integer.parseInt(depTime) / 100) * 60 + (Integer.parseInt(depTime) % 100)); } }
package com.skraylabs.poker; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class Application { static final String MSG_TOO_FEW_ARGS = "Too few arguments"; static final String MSG_TOO_MANY_ARGS = "Too many arguments"; static final String MSG_USAGE = "Usage: PokerCalculator filepath"; static final String MSG_INVALID_INPUT = "Input is formatted incorrectly"; static final String MSG_FILE_NOT_OPENED = "File [%s] could not be opened"; static final int ERROR_CODE_BAD_ARGS = 1; static final int ERROR_INVALID_INPUT = 2; static final int ERROR_FILE_NOT_OPENED = 3; private static Application app; private String errorMessage; private String filepath; /** * Access the filepath where Application will attempt to read input from. * * @return relative filepath to input file */ public String getFilepath() { return filepath; } public static void main(String... args) { app = new Application(); app.execute(args); } /** * Execute application * * @param args should be exactly 1 string specifying the input filepath to read from. */ public void execute(String... args) { if (!validate(args)) { System.out.println(errorMessage); System.out.println(MSG_USAGE); exit(ERROR_CODE_BAD_ARGS); } else { // Create input stream from filepath this.filepath = args[0]; InputStream input = null; try { input = createInputStream(); } catch (FileNotFoundException e) { errorMessage = String.format(MSG_FILE_NOT_OPENED, filepath); System.out.println(errorMessage); exit(ERROR_FILE_NOT_OPENED); } // TODO: process input from file // Close input stream if (input != null) { try { input.close(); } catch (IOException e) { // Could not close input stream. } } } } /** * Terminate execution with a given error code. * @param errorCode nonzero for abnormal termination. */ public void exit(int errorCode) { System.exit(errorCode); } /** * Validate the command line arguments. Will set errorMessage to an appropriate value if * validation fails. * * @param args command line arguments * @return true if valid, false otherwise */ private boolean validate(String[] args) { boolean result = true; if (args.length < 1) { errorMessage = MSG_TOO_FEW_ARGS; result = false; } else if (args.length > 1) { errorMessage = MSG_TOO_MANY_ARGS; result = false; } return result; } /** * Helper method to create an input stream from which to read game state. * * @return input stream that can be processed for board and pocket cards. * @throws FileNotFoundException if {@link Application#filepath} cannot be found. */ InputStream createInputStream() throws FileNotFoundException { InputStream result = null; if (!StringUtils.isBlank(filepath)) { File inputFile = new File(filepath); result = new FileInputStream(inputFile); } return result; } }
package com.skraylabs.poker; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class Application { static final String MSG_TOO_FEW_ARGS = "Too few arguments"; static final String MSG_TOO_MANY_ARGS = "Too many arguments"; static final String MSG_USAGE = "Usage: PokerCalculator filepath"; static final String MSG_INVALID_INPUT = "Input is formatted incorrectly"; static final String MSG_FILE_NOT_OPENED = "File [%s] could not be opened"; static final int ERROR_CODE_BAD_ARGS = 1; static final int ERROR_INVALID_INPUT = 2; static final int ERROR_FILE_NOT_OPENED = 3; private static Application app; private String errorMessage; private String filepath; /** * Access the filepath where Application will attempt to read input from. * * @return relative filepath to input file */ public String getFilepath() { return filepath; } public static void main(String... args) { app = new Application(); app.execute(args); } /** * Execute application * * @param args should be exactly 1 string specifying the input filepath to read from. */ public void execute(String... args) { if (!validate(args)) { System.out.println(errorMessage); System.out.println(MSG_USAGE); exit(ERROR_CODE_BAD_ARGS); return; } else { // Create input stream from filepath this.filepath = args[0]; InputStream input = null; try { input = createInputStream(); } catch (FileNotFoundException e) { errorMessage = String.format(MSG_FILE_NOT_OPENED, filepath); System.out.println(errorMessage); exit(ERROR_FILE_NOT_OPENED); return; } // TODO: process input from file // Close input stream if (input != null) { try { input.close(); } catch (IOException e) { // Could not close input stream. } } } } /** * Terminate execution with a given error code. * @param errorCode nonzero for abnormal termination. */ public void exit(int errorCode) { System.exit(errorCode); } /** * Validate the command line arguments. Will set errorMessage to an appropriate value if * validation fails. * * @param args command line arguments * @return true if valid, false otherwise */ private boolean validate(String[] args) { boolean result = true; if (args.length < 1) { errorMessage = MSG_TOO_FEW_ARGS; result = false; } else if (args.length > 1) { errorMessage = MSG_TOO_MANY_ARGS; result = false; } return result; } /** * Helper method to create an input stream from which to read game state. * * @return input stream that can be processed for board and pocket cards. * @throws FileNotFoundException if {@link Application#filepath} cannot be found. */ InputStream createInputStream() throws FileNotFoundException { InputStream result = null; if (!StringUtils.isBlank(filepath)) { File inputFile = new File(filepath); result = new FileInputStream(inputFile); } return result; } }
package com.vesperin.reflects; import com.vesperin.utils.Immutable; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * @author Huascar Sanchez */ public class Classpath { private final Map<String, ClassDefinition> canonicalNameToDefinition; private final Map<String, Set<ClassDefinition>> classNameToDefinitionIndex; private final Map<ClassDefinition, Set<MethodDefinition>> classToMethodsIndex; private final Map<String, PackageDefinition> packageNameIndex; private final Map<PackageDefinition, Set<ClassDefinition>> packageToClassesIndex; private final Map<ClassDefinition, Set<PackageDefinition>> classToPackagesIndex; private final Map<ClassDefinition, Set<ClassDefinition>> classToSuperDefinitions; private final Map<ClassDefinition, Set<ClassDefinition>> classToSubDefinitions; /** * Creates a new Classpath object given a list of Java classes. * * @param classes Java classes */ private Classpath(List<Class<?>> classes){ this.classNameToDefinitionIndex = new HashMap<>(); this.canonicalNameToDefinition = new HashMap<>(); this.classToMethodsIndex = new HashMap<>(); this.packageNameIndex = new HashMap<>(); this.packageToClassesIndex = new HashMap<>(); this.classToPackagesIndex = new HashMap<>(); this.classToSuperDefinitions = new HashMap<>(); this.classToSubDefinitions = new HashMap<>(); if(classes != null && !classes.isEmpty()){ buildIndices(classes); } } /** * @return a new and empty classpath. */ public static Classpath emptyClasspath(){ return new Classpath(Immutable.list()); } /** * Creates a new (local) classpath. * * @return a new classpath object containing all JDK classes, * as well as other classes that are in one's local classpath. */ public static Classpath newClasspath(){ return new Classpath(Installer.CLASSES); } /** * Creates a new classpath from the classes of some jar files * located at the given path. * * @param jarLocation path to one or many Jar files. * @return a new class path. */ public static Classpath newClasspath(Path jarLocation){ return new Classpath(ClassCatcher.getClasspath(jarLocation)); } public static Classpath concat(Classpath... paths){ final Classpath result = new Classpath(new ArrayList<>()); for(Classpath each : paths){ if(Objects.isNull(each)) continue; for(ClassDefinition eachDefinition : each.classToSuperDefinitions.keySet()){ if(!result.classToSuperDefinitions.containsKey(eachDefinition)){ result.classToSuperDefinitions.put( eachDefinition, each.classToSuperDefinitions.get(eachDefinition)); } } for(ClassDefinition eachDefinition : each.classToSubDefinitions.keySet()){ if(!result.classToSubDefinitions.containsKey(eachDefinition)){ result.classToSubDefinitions.put( eachDefinition, each.classToSubDefinitions.get(eachDefinition)); } } for(String canonicalName : each.canonicalNameToDefinition.keySet()){ if(!result.canonicalNameToDefinition.containsKey(canonicalName)){ result.canonicalNameToDefinition.put( canonicalName, each.canonicalNameToDefinition.get(canonicalName) ); } } for(String typeName : each.classNameToDefinitionIndex.keySet()){ final Set<ClassDefinition> touchedClasses = each.classNameToDefinitionIndex.get(typeName); if(result.classNameToDefinitionIndex.containsKey(typeName)){ result.classNameToDefinitionIndex.get(typeName).addAll(touchedClasses); } else { result.classNameToDefinitionIndex.put(typeName, new HashSet<>(touchedClasses)); } } for(ClassDefinition classDef : each.classToMethodsIndex.keySet()){ final Set<MethodDefinition> touchedMethods = each.classToMethodsIndex.get(classDef); if(result.classToMethodsIndex.containsKey(classDef)){ result.classToMethodsIndex.get(classDef).addAll(touchedMethods); } else { result.classToMethodsIndex.put(classDef, new HashSet<>(touchedMethods)); } } for(String pkgDef : each.packageNameIndex.keySet()){ if(!result.packageNameIndex.containsKey(pkgDef)){ result.packageNameIndex.put(pkgDef, each.packageNameIndex.get(pkgDef)); } } for(PackageDefinition pkgDef : each.packageToClassesIndex.keySet()){ final Set<ClassDefinition> touchedImports = each.packageToClassesIndex.get(pkgDef); if(result.packageToClassesIndex.containsKey(pkgDef)){ result.packageToClassesIndex.get(pkgDef).addAll(touchedImports); } else { result.packageToClassesIndex.put(pkgDef, new HashSet<>(touchedImports)); } } for(ClassDefinition clsDef : each.classToPackagesIndex.keySet()){ final Set<PackageDefinition> touchedClasses = each.classToPackagesIndex.get(clsDef); if(result.classToPackagesIndex.containsKey(clsDef)){ result.classToPackagesIndex.get(clsDef).addAll(touchedClasses); } else { result.classToPackagesIndex.put(clsDef, new HashSet<>(touchedClasses)); } } } return result; } /** * @return true if the classpath is empty; false otherwise. */ public boolean isEmpty(){ return getClassNameToDefinitionIndex().isEmpty(); } private void buildIndices(List<Class<?>> classes){ for(Class<?> eachClass : classes){ final ClassDefinition definition = ClassDefinition.forceGeneric(eachClass); canonicalNameToDefinition.put(definition.getCanonicalName(), definition); if(!classNameToDefinitionIndex.containsKey(definition.getClassName())){ final Set<ClassDefinition> setOfDefinitions = new HashSet<>(); setOfDefinitions.add(definition); this.classNameToDefinitionIndex.put( definition.getClassName(), setOfDefinitions ); classToMethodsIndex.put(definition, methodDefinitions(eachClass)); } else { this.classNameToDefinitionIndex .get(definition.getClassName()) .add(definition); if(!classToMethodsIndex.containsKey(definition)){ classToMethodsIndex.put(definition, methodDefinitions(eachClass)); } } final PackageDefinition pkgDef = definition.getPackageDefinition(); if(!packageNameIndex.containsKey(pkgDef.getName())){ packageNameIndex.put(pkgDef.getName(), pkgDef); final Set<ClassDefinition> first = new HashSet<>(); first.add(definition); packageToClassesIndex.put(pkgDef, first); } else { packageToClassesIndex.get(pkgDef).add(definition); } if(!classToPackagesIndex.containsKey(definition)){ final Set<PackageDefinition> pkgDefs = new HashSet<>(); pkgDefs.add(pkgDef); classToPackagesIndex.put(definition, pkgDefs); } else { classToPackagesIndex.get(definition).add(pkgDef); } if(!classToSuperDefinitions.containsKey(definition)){ final Set<ClassDefinition> supers = ClassDefinition.getSuperClassDefinitions(eachClass); classToSuperDefinitions.put(definition, new HashSet<>(supers)); for(ClassDefinition eachSuper : supers){ if(classToSubDefinitions.containsKey(eachSuper)){ classToSubDefinitions.get(eachSuper).add(definition); } else { classToSubDefinitions.put( eachSuper, new HashSet<>(Collections.singleton(definition)) ); } } } } } private static Set<MethodDefinition> methodDefinitions(Class<?> eachClass){ return Immutable.setOf(MethodDefinition.allMethods(eachClass) .filter(MethodDefinition.isRelevantMethodDefinition())); } public static Classpath getClasspath(){ return new Classpath(Installer.CLASSES); } Map<ClassDefinition, Set<MethodDefinition>> getClassToMethodsIndex(){ return classToMethodsIndex; } Map<ClassDefinition, Set<ClassDefinition>> getClassToSuperDefinitions(){ return classToSuperDefinitions; } Map<ClassDefinition, Set<ClassDefinition>> getClassToSubDefinitions(){ return classToSubDefinitions; } Map<String, Set<ClassDefinition>> getClassNameToDefinitionIndex(){ return classNameToDefinitionIndex; } Map<String, PackageDefinition> getPackageNameIndex(){ return packageNameIndex; } Map<PackageDefinition, Set<ClassDefinition>> getPackageToClassesIndex(){ return packageToClassesIndex; } Map<ClassDefinition, Set<PackageDefinition>> getClassToPackagesIndex(){ return classToPackagesIndex; } Map<String, ClassDefinition> getCanonicalNameToDefinition(){ return canonicalNameToDefinition; } synchronized Classpath clearClasspath(){ getClassNameToDefinitionIndex().clear(); getClassToMethodsIndex().clear(); getPackageNameIndex().clear(); getPackageToClassesIndex().clear(); getClassToPackagesIndex().clear(); return this; } // lazy loaded singleton static class Installer { static List<Class<?>> CLASSES = ClassCatcher.getClasspath(); } }
package com.zenplanner; import com.thinkaurelius.titan.core.TitanGraph; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.ir.*; import jdk.nashorn.internal.parser.Lexer; import org.apache.commons.lang.NotImplementedException; import java.io.File; import java.util.List; import java.util.Map; public class StatementScanner { private final TitanGraph graph; private final File root; private final File file; private final File folder; private final String path; private final Vertex vertex; private final Map<String, Vertex> map; public StatementScanner(TitanGraph graph, Map<String, Vertex> map, File root, File file) { this.graph = graph; this.map = map; this.root = root; this.file = file; this.folder = file.getParentFile(); this.path = StatementScanner.makeRelative(root, file); String className = namify(path); this.vertex = addOrGet(graph, className); } public void scan(FunctionNode stmt) throws Exception { processFunctionNode(stmt); } private void processFunctionNode(FunctionNode node) { Block body = node.getBody(); IdentNode in = node.getIdent(); List<IdentNode> args = node.getParameters(); String funcName = in.getName(); if(!"runScript".equals(funcName) && !funcName.contains(":")) { // Nashhorn wrapper & Anonymous methods Vertex funcVert = addOrGet(graph, funcName); Edge edge = graph.addEdge(null, this.vertex, funcVert, "declares"); edge.setProperty("relation", "declares"); } processBlock(body); processIdentNode(in); for(IdentNode arg : args) { processIdentNode(arg); } } private void processBlock(Block block) { if(block == null) { return; } List<Statement> statements = block.getStatements(); for(Statement stmt : statements) { processStatement(stmt); } } private void processStatement(Statement stmt) { Class<?> clazz = stmt.getClass(); if(clazz == VarNode.class) { processVarNode((VarNode)stmt); return; } if(clazz == ReturnNode.class) { processReturnNode((ReturnNode) stmt); return; } if(clazz == IfNode.class) { processIfNode((IfNode) stmt); return; } if(clazz == ForNode.class) { processForNode((ForNode) stmt); return; } if(clazz == ExpressionStatement.class) { processExpressionStatement((ExpressionStatement) stmt); return; } if(clazz == BlockStatement.class) { processBlockStatement((BlockStatement) stmt); return; } if(clazz == TryNode.class) { processTryNode((TryNode) stmt); return; } if(clazz == CatchNode.class) { processCatchNode((CatchNode) stmt); return; } if(clazz == BreakNode.class) { processBreakNode((BreakNode) stmt); return; } if(clazz == WhileNode.class) { processWhileNode((WhileNode) stmt); return; } if(clazz == ThrowNode.class) { processThrowNode((ThrowNode) stmt); return; } if(clazz == ContinueNode.class) { processContinueNode((ContinueNode) stmt); return; } throw new NotImplementedException(); } private void processContinueNode(ContinueNode node) { IdentNode lbl = node.getLabel(); processIdentNode(lbl); } private void processThrowNode(ThrowNode node) { Expression exp = node.getExpression(); processExpression(exp); } private void processWhileNode(WhileNode node) { Expression test = node.getTest(); Block blk = node.getBody(); processExpression(test); processBlock(blk); } private void processBreakNode(BreakNode node) { IdentNode lbl = node.getLabel(); processIdentNode(lbl); } private void processTryNode(TryNode node) { Block body = node.getBody(); List<Block> catcheBlocks = node.getCatchBlocks(); List<CatchNode> catches = node.getCatches(); Block fnlly = node.getFinallyBody(); processBlock(body); for(Block blk : catcheBlocks) { processBlock(blk); } for(CatchNode cth : catches) { processCatchNode(cth); } processBlock(fnlly); } private void processCatchNode(CatchNode node) { Block body = node.getBody(); IdentNode ex = node.getException(); Expression except = node.getExceptionCondition(); processBlock(body); processIdentNode(ex); processExpression(except); } private void processBlockStatement(BlockStatement stmt) { Block blk = stmt.getBlock(); processBlock(blk); } private void processForNode(ForNode node) { Expression init = node.getInit(); Expression test = node.getTest(); Expression mod = node.getModify(); Block body = node.getBody(); processExpression(init); processExpression(test); processExpression(mod); processBlock(body); } private void processIfNode(IfNode node) { Expression test = node.getTest(); Block pass = node.getPass(); Block fail = node.getFail(); processExpression(test); processBlock(pass); processBlock(fail); } private void processReturnNode(ReturnNode node) { Expression exp = node.getExpression(); processExpression(exp); } private void processExpressionStatement(ExpressionStatement stmt) { Expression exp = stmt.getExpression(); processExpression(exp); } // var x = y; private void processVarNode(VarNode node) { IdentNode in = node.getName(); Expression exp = node.getInit(); String varName = in.getName(); if("self".equals(varName)) { // Nashhorn wrapper & Anonymous methods if(exp.getClass() == UnaryNode.class) { UnaryNode un = (UnaryNode)exp; Expression rhs = un.rhs(); if(rhs.getClass() == CallNode.class) { CallNode call = (CallNode)rhs; Expression func = call.getFunction(); if(func.getClass() == IdentNode.class) { IdentNode ine = (IdentNode)func; String funcName = ine.getName(); Vertex funcVert = addOrGet(graph, funcName); Edge edge = graph.addEdge(null, this.vertex, funcVert, "extends"); edge.setProperty("relation", "extends"); } } } } processIdentNode(in); processExpression(exp); } private void processIdentNode(IdentNode node) { if(node == null) { return; } String name = node.getName(); // Do something with the variable name if we want } private void processExpression(Expression exp) { if(exp == null) { return; } Class<?> clazz = exp.getClass(); if(clazz == ObjectNode.class) { processObjectNode((ObjectNode) exp); return; } if(clazz == IdentNode.class) { processIdentNode((IdentNode) exp); return; } if(clazz == CallNode.class) { processCallNode((CallNode) exp); return; } if(clazz == AccessNode.class) { processAccessNode((AccessNode) exp); return; } if(exp instanceof LiteralNode) { processLiteralNode((LiteralNode) exp); return; } if(clazz == FunctionNode.class) { processFunctionNode((FunctionNode) exp); return; } if(clazz == BinaryNode.class) { processBinaryNode((BinaryNode) exp); return; } if(clazz == UnaryNode.class) { processUnaryNode((UnaryNode) exp); return; } if(clazz == IndexNode.class) { processIndexNode((IndexNode) exp); return; } if(clazz == TernaryNode.class) { processTernaryNode((TernaryNode) exp); return; } throw new NotImplementedException(); } private void processTernaryNode(TernaryNode node) { Expression test = node.getTest(); Expression tru = node.getTrueExpression(); Expression fal = node.getFalseExpression(); processExpression(test); processExpression(tru); processExpression(fal); } private void processIndexNode(IndexNode node) { Expression base = node.getBase(); Expression idx = node.getIndex(); processExpression(base); processExpression(idx); } private void processUnaryNode(UnaryNode node) { Expression exp = node.rhs(); processExpression(exp); } private void processBinaryNode(BinaryNode node) { Expression src = node.rhs(); Expression dst = node.lhs(); processExpression(src); processExpression(dst); } private void processAccessNode(AccessNode node) { Expression base = node.getBase(); IdentNode prop = node.getProperty(); processExpression(base); processIdentNode(prop); } // myFunc(arg1, arg2); private void processCallNode(CallNode node) { Expression func = node.getFunction(); List<Expression> exps = node.getArgs(); if(func instanceof IdentNode) { IdentNode in = (IdentNode)func; String funcName = in.getName(); Vertex funcVert = addOrGet(graph, funcName); Edge edge = graph.addEdge(null, this.vertex, funcVert, "invokes"); edge.setProperty("relation", "invokes"); if("require".equals(funcName) || "define".equals(funcName)) { if(exps.size() == 2 && exps.get(0) instanceof LiteralNode.ArrayLiteralNode) { // require([path1, path2], callback) {} LiteralNode.ArrayLiteralNode arg0 = (LiteralNode.ArrayLiteralNode)exps.get(0); Expression[] paths = arg0.getValue(); for(Expression pathExp : paths) { if(pathExp instanceof LiteralNode) { LiteralNode ln = (LiteralNode)pathExp; Object obj = ln.getObject(); if(obj instanceof String) { String path = ((String)obj); String className = namify(path); Vertex child = addOrGet(graph, className); Edge e = graph.addEdge(null, this.vertex, child, "requires"); e.setProperty("relation", "requires"); } } } } } } processExpression(func); for(Expression exp : exps) { processExpression(exp); } } private String namify(String path) { String[] parts = path.split("/"); String className = parts[parts.length-1]; parts = className.split("\\."); className = parts[0]; return className; } private void processLiteralNode(LiteralNode node) { Object val = node.getObject(); if(val == null) { return; } Class clazz = val.getClass(); if(clazz == String.class) { String str = (String)val; return; } if(clazz == Integer.class) { Integer i = (Integer)val; return; } if(clazz == Boolean.class) { Boolean b = (Boolean)val; return; } if(clazz == Expression.class) { Expression exp = (Expression)val; processExpression(exp); return; } if(clazz == Expression[].class) { Expression[] exps = (Expression[])val; for(Expression exp : exps) { processExpression(exp); } return; } if(clazz == Lexer.RegexToken.class) { processRegexToken((Lexer.RegexToken)val); return; } throw new NotImplementedException(); } private void processRegexToken(Lexer.RegexToken token) { String options = token.getOptions(); String regex = token.getExpression(); } // var x = {y: 1, z: 2} private void processObjectNode(ObjectNode node) { List<PropertyNode> elems = node.getElements(); for(PropertyNode pn : elems) { processPropertyNode(pn); } } // { key: value } private void processPropertyNode(PropertyNode node) { Expression key = node.getKey(); Expression value = node.getValue(); processExpression(key); processExpression(value); } public static String makeRelative(File root, File child) { String path = root.toURI().relativize(child.toURI()).getPath(); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } private Vertex addOrGet(TitanGraph graph, String path) { if (map.containsKey(path)) { return map.get(path); } Vertex vert = graph.addVertex(path); vert.setProperty("path", path); map.put(path, vert); return vert; } }
package com.zenplanner.sql; import com.google.common.base.Charsets; import com.google.common.io.Resources; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; public class DbComparator { private final AtomicInteger tableCount = new AtomicInteger(); private final AtomicInteger currentTable = new AtomicInteger(); private final Set<ActionListener> listeners = Collections.synchronizedSet(new HashSet<ActionListener>()); public enum ChangeType { INSERT, UPDATE, DELETE, NONE } public DbComparator() { } /** * Takes connections to two databases, compares deltas, and upserts appropriate data to get them in sync * * @param scon The source connection * @param dcon The destination connection * @param filterValue A value with which to filter partition data */ public void synchronize(Connection scon, Connection dcon, Map<String,Object> filters, List<String> ignoreTables) { try { // Get the intersection of the tables Map<String, Table> srcTables = filterTables(getTables(scon)); Map<String, Table> dstTables = getTables(dcon); Set<String> tableNames = new HashSet<>(); tableNames.addAll(srcTables.keySet()); tableNames.retainAll(dstTables.keySet()); tableNames.removeAll(ignoreTables); tableCount.set(tableNames.size()); currentTable.set(0); // Synchronize them try { setConstraints(dcon, dstTables.values(), false); for(String tableName : tableNames) { Table srcTable = srcTables.get(tableName); Table dstTable = dstTables.get(tableName); System.out.println("Comparing table: " + srcTable.getName()); syncTables(scon, dcon, srcTable, dstTable, filters); currentTable.incrementAndGet(); fireProgress(); } } catch (Exception ex) { throw ex; } finally { setConstraints(dcon, dstTables.values(), true); } } catch (Exception ex) { throw new RuntimeException("Error comparing databases!", ex); } currentTable.incrementAndGet(); fireProgress(); } /** * Turns all constraints on or off * * @param con The connection on which to enable or disable constraints * @param tables A collection of tables on which to operate * @param enabled A flag indicating if constraints should be enabled or disabled */ private static void setConstraints(Connection con, Collection<Table> tables, boolean enabled) { for (Table table : tables) { table.setConstraints(con, enabled); } } /** * Retrieves a map of Tables from the database schema * * @param con The connection to use to query the DB for its schema * @return A map of Tables from the database schema * @throws Exception */ private static Map<String, Table> getTables(Connection con) throws Exception { Map<String, Table> tables = new HashMap<>(); try (Statement stmt = con.createStatement()) { String sql = Resources.toString(Resources.getResource("GetTables.sql"), Charsets.UTF_8); try (ResultSet rs = stmt.executeQuery(sql)) { while (rs.next()) { String tableName = rs.getString("table_name"); if (!tables.containsKey(tableName)) { tables.put(tableName, new Table(tableName)); } Table table = tables.get(tableName); Column col = new Column(); String colName = rs.getString("column_name").toLowerCase(); col.setColumnName(colName); col.setDataType(rs.getString("data_type")); col.setPrimaryKey(rs.getBoolean("primary_key")); table.put(colName, col); } } } for(Table table : tables.values()) { if(table.size() == 0) { throw new IllegalStateException("Table has no columns: " + table.getName()); } } return tables; } /** * Compares two tables and syncronizes the results * * @param scon The source connection * @param dcon The destination connection * @param srcTable The source table * @param dstTable The destination table * @throws Exception */ private static void syncTables(Connection scon, Connection dcon, Table srcTable, Table dstTable, Map<String,Object> filters) throws Exception { Table lcd = findLcd(srcTable, dstTable); String sql = lcd.writeHashedQuery(filters); //int i = 0; // TODO: Threading and progress indicator try (PreparedStatement stmt = scon.prepareStatement(sql); PreparedStatement dtmt = dcon.prepareStatement(sql)) { // Set filter parameters if(lcd.hasAllColumns(filters.keySet())) { int i = 1; for(Object val : filters.values()) { stmt.setObject(i, val); dtmt.setObject(i, val); i++; } } // Make changes try (ResultSet srs = stmt.executeQuery(); ResultSet drs = dtmt.executeQuery()) { srs.next(); drs.next(); Map<ChangeType, Set<Key>> changes = new HashMap<>(); changes.put(ChangeType.INSERT, new HashSet<>()); changes.put(ChangeType.UPDATE, new HashSet<>()); changes.put(ChangeType.DELETE, new HashSet<>()); while (srs.getRow() > 0 || drs.getRow() > 0) { ChangeType change = lcd.detectChange(srs, drs); Key key = lcd.getPk(srs, drs); Set<Key> changeset = changes.get(change); if (changeset != null) { changeset.add(key); } advance(srcTable, dstTable, srs, drs); } lcd.insertRows(scon, dcon, changes.get(ChangeType.INSERT)); lcd.updateRows(scon, dcon, changes.get(ChangeType.UPDATE)); lcd.deleteRows(dcon, changes.get(ChangeType.DELETE)); } catch (Exception ex) { throw new RuntimeException("Error selecting hashed rows: " + sql, ex); } } } /** * Takes two RecordSets, and advances one cursor, or the other, or both to keep the PKs in sync * * @param srcTable The source table * @param dstTable The destination table * @param srs The source RecordSet * @param drs The destination RecordSet * @throws Exception */ private static void advance(Table srcTable, Table dstTable, ResultSet srs, ResultSet drs) throws Exception { Key spk = srcTable.getPk(srs); Key dpk = dstTable.getPk(drs); int val = Key.compare(spk, dpk); if (val < 0) { srs.next(); return; } if (val > 0) { drs.next(); return; } srs.next(); drs.next(); } /** * Creates a virtual table that contains the intersection of the columns of two other real tables * * @param srcTable The source table * @param dstTable The destination table * @return a virtual table that contains the intersection of the columns of two other real tables */ private static Table findLcd(Table srcTable, Table dstTable) { Table table = new Table(srcTable.getName()); Set<String> colNames = new HashSet<>(); colNames.addAll(srcTable.keySet()); colNames.addAll(dstTable.keySet()); for (String colName : colNames) { if (!srcTable.containsKey(colName) || !dstTable.containsKey(colName)) { continue; } table.put(colName, srcTable.get(colName)); } if(table.size() == 0) { throw new IllegalStateException("Table has no columns: " + table.getName()); } return table; } /** * Filters a map of database tables and returns only the ones that are sync-able * * @param in The map to filter * @return The filtered map */ private static Map<String, Table> filterTables(Map<String, Table> in) { Map<String, Table> out = new HashMap<>(); for (Map.Entry<String, Table> entry : in.entrySet()) { String name = entry.getKey(); Table table = entry.getValue(); if (table.getPk().size() > 0) { out.put(name, table); } } return out; } public int getCurrentTable() { return currentTable.get(); } public int getTableCount() { return tableCount.get(); } private void fireProgress() { ActionEvent ae = new ActionEvent(this, getCurrentTable(), null); for(ActionListener pl : listeners) { pl.actionPerformed(ae); } } public void addListener(ActionListener val) { listeners.add(val); } }
package de.dhbw.humbuch.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import com.lowagie.text.BadElementException; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.Image; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.Rectangle; import com.lowagie.text.RectangleReadOnly; import com.lowagie.text.pdf.ColumnText; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfPageEventHelper; import com.lowagie.text.pdf.PdfWriter; import com.vaadin.server.StreamResource.StreamSource; public abstract class PDFHandler { private Document document; private HeaderFooter event; protected static float TABLEWIDTH = 418f; /** * * @param path * links to the directory where the PDF file should be saved */ public PDFHandler(String path) { this.document = new Document(); } public PDFHandler() { this.document = new Document(new RectangleReadOnly(595,842), 10, 10, 25, 35); } /** * Creates the pdf with the information in the object that was passed to the * constructor previously. * * @param path * where the file will be saved */ public void savePDF(String path) { try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path)); event = new HeaderFooter(); writer.setBoxSize("art", new Rectangle(36, 54, 559, 788)); writer.setPageEvent(event); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } this.document.open(); this.addMetaData(document); this.insertDocumentParts(document); this.document.close(); } /** * User can choose a printer where this pdf is printed then. The pdf * contains the information stored in the object that was send to the * constructor previously. * */ public void printPDF() { ByteArrayOutputStream byteArrayOutputStream; try { byteArrayOutputStream = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream); event = new HeaderFooter(); writer.setBoxSize("art", new Rectangle(36, 54, 559, 788)); writer.setPageEvent(event); this.document.open(); this.addMetaData(document); this.insertDocumentParts(document); this.document.close(); new PDFPrinter(byteArrayOutputStream); } catch (DocumentException e) { e.printStackTrace(); } } /** * Creates a ByteArrayOutputStream which contains the PDF as a byte array. * * @return the byteArrayOutputStream the PDF is stored in, null if an error * occurred. */ public ByteArrayOutputStream createByteArrayOutputStreamForPDF() { ByteArrayOutputStream byteArrayOutputStream; try { byteArrayOutputStream = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream); event = new HeaderFooter(); writer.setBoxSize("art", new Rectangle(36, 54, 559, 788)); writer.setPageEvent(event); this.document.open(); this.addMetaData(document); int initialDocumentSize = writer.getCurrentDocumentSize(); this.insertDocumentParts(document); if (byteArrayOutputStream.size() > 0 || writer.getCurrentDocumentSize() > initialDocumentSize) { this.document.close(); } else { return null; } return byteArrayOutputStream; } catch (DocumentException e) { System.err.println("Could not create ByteArrayOutputStream of PDF data. " + e.getMessage()); } return null; } private void addMetaData(Document document) { document.addTitle("Humbuch Schule"); document.addSubject("Using iText"); document.addKeywords("Java, PDF, iText"); document.addAuthor("Schlager"); document.addCreator("Schlager"); } /** * Set the logo of Humboldt on the left corner and the current date on the * right corner * * @param document * reference of the pdfDocument object */ protected void addHeading(Document document) { Paragraph paragraph = new Paragraph(); PdfPTable table = createMyStandardTable(2); table.setTotalWidth(TABLEWIDTH); PdfPCell cell; try { Image img = Image.getInstance("./res/Logo_Humboldt_Gym_70_klein_3.png"); img.setAlignment(Element.ALIGN_BOTTOM); cell = new PdfPCell(img); cell.setBorder(0); table.addCell(cell); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (BadElementException e) { e.printStackTrace(); } String date = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN).format(Calendar.getInstance().getTime()); cell = new PdfPCell(new Phrase(date)); cell.setBorder(0); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); table.addCell(cell); cell = new PdfPCell(new Phrase("")); cell.setBorder(Rectangle.BOTTOM); table.addCell(cell); cell = new PdfPCell(new Phrase("")); cell.setBorder(Rectangle.BOTTOM); table.addCell(cell); paragraph.add(table); addEmptyLine(paragraph, 1); try { document.add(paragraph); } catch (DocumentException e) { e.printStackTrace(); } } /** * Adds a signature field with a date field to the document. Should be the * last part that is added to the document. * * @param document * represents the PDF before it is saved * @param role * word for the kind of person that shall sign the paper */ protected void addSignatureField(Document document, String role) { Paragraph paragraph = new Paragraph(); //this table contains the signatureTable and the dataTable. // this purpose makes it easier to format PdfPTable table = createMyStandardTable(2); //the first column is double times greater than the second column try { table.setWidths(new float[] { 10f, 20f }); } catch (DocumentException e) { e.printStackTrace(); } //create and fill date table PdfPTable dateTable = new PdfPTable(1); PdfPCell cell = new PdfPCell(new Phrase("")); //just the bottom border will be displayed (line for date) cell.setBorderWidthTop(0); cell.setBorderWidthLeft(0); cell.setBorderWidthRight(0); dateTable.addCell(cell); cell = new PdfPCell(new Phrase("Datum")); cell.setBorder(0); dateTable.addCell(cell); //put date table into the 'parent' table cell = new PdfPCell(dateTable); cell.setBorder(0); table.addCell(cell); //create and fill signature table PdfPTable signatureTable = new PdfPTable(1); cell = new PdfPCell(new Phrase("")); //just the bottom border will be displayed (line for signature) cell.setBorderWidthTop(0); cell.setBorderWidthLeft(0); cell.setBorderWidthRight(0); signatureTable.addCell(cell); cell = new PdfPCell(new Phrase("Unterschrift " + role)); cell.setBorder(0); signatureTable.addCell(cell); //put signature table into the 'parent' table cell = new PdfPCell(signatureTable); cell.setBorder(0); table.addCell(cell); paragraph.add(table); try { document.add(paragraph); } catch (DocumentException e) { e.printStackTrace(); } } /** * A table is generated with the header: Klasse, Bezeichnung Lehrmittel, * Unterschrift * * @return PdfPTable */ protected PdfPTable createTableWithRentalInformationHeader() { PdfPTable table = createMyStandardTable(3, new float[] { 3f, 1f, 1f }); Font font = FontFactory.getFont("Helvetica", 12, Font.BOLD); new PDFHandler.TableBuilder(table, new String[] { "Bezeichnung Lehrmittel", "bis Klasse", "Unterschrift" }).withBorder(true) .isCenterAligned(true).font(font).fillTable(); return table; } /** * A table is generated with the header: Klasse, Bezeichnung Lehrmittel, * Unterschrift * * @return PdfPTable */ protected PdfPTable createTableWithRentalInformationHeaderWithoutSignColumn() { PdfPTable table = createMyStandardTable(2, new float[] { 3f, 1f}); Font font = FontFactory.getFont("Helvetica", 12, Font.BOLD); new PDFHandler.TableBuilder(table, new String[] { "Bezeichnung Lehrmittel", "bis Klasse"}).withBorder(true) .isCenterAligned(true).font(font).fillTable(); return table; } /** * A table is generated with the header: Bezeichnung Lehrmittel, Anzahl * * @return PdfPTable */ protected PdfPTable createTableWithRentalInformationHeaderForClass() { PdfPTable table = createMyStandardTable(2, new float[] { 3f, 1f }); Font font = FontFactory.getFont("Helvetica", 12, Font.BOLD); new PDFHandler.TableBuilder(table, new String[] { "Bezeichnung Lehrmittel", "Anzahl" }).withBorder(true).font(font).fillTable(); return table; } protected void addInformationAboutDocument(Document document, String informationText) { PdfPTable table = createMyStandardTable(1); new PDFHandler.TableBuilder(table, new String[] { informationText }) .font(FontFactory.getFont("Times New Roman", 14, Font.BOLD)).fillTable(); try { document.add(table); PDFHandler.addEmptyLineToDocument(document, 1); } catch (DocumentException e) { e.printStackTrace(); } } protected void resetPageNumber() { this.event.resetPageNumber(); } protected static void addEmptyLine(Paragraph paragraph, int number) { for (int i = 0; i < number; i++) { paragraph.add(new Paragraph(" ")); } } protected static void addEmptyLineToDocument(Document document, int number) { Paragraph paragraph = new Paragraph(); for (int i = 0; i < number; i++) { paragraph.add(new Paragraph(" ")); } try { document.add(paragraph); } catch (DocumentException e) { System.err.println("Could not add empty line to documnet " + e.getStackTrace()); } } /** * Create a standard table with constant table width. * * @param columnNumber * set how many columns the table will have * @return table */ protected static PdfPTable createMyStandardTable(int columnNumber) { PdfPTable table = new PdfPTable(columnNumber); table.setLockedWidth(true); table.setTotalWidth(TABLEWIDTH); return table; } /** * Create a standard table with constant table width. * * @param columnNumber * set how many columns the table will have * @param columnWidths * set the ratio between the columns. If null, all columns will * be equal. * @return table */ protected static PdfPTable createMyStandardTable(int columnNumber, float[] columnWidths) { PdfPTable table = new PdfPTable(columnNumber); table.setLockedWidth(true); table.setTotalWidth(TABLEWIDTH); if (!(columnWidths == null) && (columnWidths.length != 0)) { try { table.setWidths(columnWidths); } catch (DocumentException e) { System.err.println("Could not set columnWidths of standardTable " + e.getStackTrace()); } } return table; } /** * Convenience method to add content to a table in a standard way * * @param table * @param withBorder * if true a standard border is used, if false no border is used * @param contentArray * an array with all cell contents * @param isAlignedCenter * if true the content is horizontally and vertically aligned */ @Deprecated protected static void fillTableWithContent(PdfPTable table, boolean withBorder, String[] contentArray, boolean isAlignedCenter) { PdfPCell cell = null; for (int i = 0; i < contentArray.length; i++) { //append '\n' to each String to have an empty space-line before cell ends cell = new PdfPCell(new Phrase(contentArray[i] + "\n ")); cell.setLeading(1.25f, 1.25f); if (isAlignedCenter) { cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); } if (withBorder == false) { cell.setBorder(0); } cell.setPadding(0f); table.addCell(cell); } } /** * Convenience method to add content to a table in a standard way * * @param table * @param withBorder * if true a standard border is used, if false no border is used * @param contentArray * an array with all cell contents * @param font * set a font for the cell content */ @Deprecated protected static void fillTableWithContent(PdfPTable table, boolean withBorder, String[] contentArray, Font font) { PdfPCell cell = null; for (int i = 0; i < contentArray.length; i++) { //append '\n' to each String to have an empty space-line before cell ends cell = new PdfPCell(new Phrase(contentArray[i] + "\n ", font)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); if (withBorder == false) { cell.setBorder(0); } table.addCell(cell); } } /** * Convenience method to add content to a table in a standard way * * @param table * @param withBorder * if true a standard border is used, if false no border is used * @param contentArray * an array with all cell contents * @param isAlignedCenter * if true the content is horizontally and vertically aligned */ @Deprecated protected static void fillTableWithContent(PdfPTable table, boolean withBorder, String[] contentArray, boolean isAlignedCenter, Font font) { PdfPCell cell = null; for (int i = 0; i < contentArray.length; i++) { //append '\n' to each String to have an empty space-line before cell ends cell = new PdfPCell(new Phrase(contentArray[i] + "\n ", font)); cell.setLeading(1.25f, 1.25f); if (isAlignedCenter) { cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); } if (withBorder == false) { cell.setBorder(0); } cell.setPadding(0f); table.addCell(cell); } } /** * Convenience method to add content to a table in a standard way * * @param table * @param withBorder * if true a standard border is used, if false no border is used * @param contentArray * an array with all cell contents * @param font * set a font for the cell content */ @Deprecated protected static void fillTableWithContentWithoutAlignment(PdfPTable table, boolean withBorder, String[] contentArray, Font font) { PdfPCell cell = null; for (int i = 0; i < contentArray.length; i++) { //append '\n' to each String to have an empty space-line before cell ends cell = new PdfPCell(new Phrase(contentArray[i] + "\n ", font)); if (withBorder == false) { cell.setBorder(0); } table.addCell(cell); } } /** * Cell entry is not followed by \n * * @param table * @param withBorder * if true a standard border is used, if false no border is used * @param contentArray * an array with all cell contents */ @Deprecated protected static void fillTableWithContentWithoutSpace(PdfPTable table, boolean withBorder, String[] contentArray, boolean isAlignedCenter, float padding) { PdfPCell cell = null; for (int i = 0; i < contentArray.length; i++) { cell = new PdfPCell(new Phrase(contentArray[i])); if (isAlignedCenter) { cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); } if (withBorder == false) { cell.setBorder(0); } cell.setPadding(padding); table.addCell(cell); } } private static void fillTableWithContent(TableBuilder tableBuilder) { PdfPCell cell = null; for (int i = 0; i < tableBuilder.contentArray.length; i++) { if (tableBuilder.font != null) { cell = new PdfPCell(new Phrase(tableBuilder.contentArray[i], tableBuilder.font)); } else { cell = new PdfPCell(new Phrase(tableBuilder.contentArray[i])); } if (tableBuilder.isAlignedCentrally) { cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); } if (!tableBuilder.withBorder) { cell.setBorder(0); } if (tableBuilder.padding != 0f) { cell.setPadding(tableBuilder.padding); } if (tableBuilder.leading != 0f) { cell.setLeading(tableBuilder.leading, tableBuilder.leading); } tableBuilder.table.addCell(cell); } } /** * In this method all parts of the document shall be 'put' together. * * @param document * represents the PDF before it is saved */ protected abstract void insertDocumentParts(Document document); /** * In this method the PDF-specific information shall be inserted into the * document. * * @param document * represents the PDF before it is saved */ protected abstract void addContent(Document document); class TableBuilder { private PdfPTable table; private String[] contentArray; private boolean withBorder; private boolean isAlignedCentrally; private float padding; private Font font; private float leading; public TableBuilder(PdfPTable table, String[] contentArray) { this.table = table; this.contentArray = contentArray; } public TableBuilder withBorder(boolean withBorder) { this.withBorder = withBorder; return this; } public TableBuilder isCenterAligned(boolean isCenterAligned) { this.isAlignedCentrally = isCenterAligned; return this; } public TableBuilder padding(float padding) { this.padding = padding; return this; } public TableBuilder font(Font font) { this.font = font; return this; } public TableBuilder leading(float leading) { this.leading = leading; return this; } public void fillTable() { PDFHandler.fillTableWithContent(this); } } /** Inner class to add a header and a footer. */ class HeaderFooter extends PdfPageEventHelper { /** Alternating phrase for the header. */ Phrase[] header = new Phrase[2]; /** Current page number (will be reset for every chapter). */ int pagenumber; /** * Initialize one of the headers. * * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.text.Document) */ public void onOpenDocument(PdfWriter writer, Document document) { header[0] = new Phrase("Movie history"); } /** * Initialize one of the headers, based on the chapter title; reset the * page number. * * @see com.itextpdf.text.pdf.PdfPageEventHelper#onChapter(com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.text.Document, float, com.itextpdf.text.Paragraph) */ public void onChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { header[1] = new Phrase(title.getContent()); pagenumber = 1; } /** * Increase the page number. * * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.text.Document) */ public void onStartPage(PdfWriter writer, Document document) { pagenumber++; } /** * Adds the header and the footer. * * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); // switch(writer.getPageNumber() % 2) { // case 0: // ColumnText.showTextAligned(writer.getDirectContent(), // Element.ALIGN_RIGHT, header[0], // rect.getRight(), rect.getTop(), 0); // break; // case 1: // ColumnText.showTextAligned(writer.getDirectContent(), // Element.ALIGN_LEFT, header[0], // rect.getLeft(), rect.getTop(), 0); // break; ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(String.format("- Seite %d -", pagenumber)), (rect.getLeft() + rect.getRight()) / 2, 20, 0); } public void resetPageNumber() { this.pagenumber = 1; } } public static class PDFStreamSource implements StreamSource { private static final long serialVersionUID = 1L; ByteArrayOutputStream byteArrayOutputstream; public PDFStreamSource(ByteArrayOutputStream byteArrayOutputStream) { this.byteArrayOutputstream = byteArrayOutputStream; } @Override public InputStream getStream() { // Here we return the pdf contents as a byte-array return new ByteArrayInputStream(this.byteArrayOutputstream.toByteArray()); } } }
package de.galan.commons.util; import static de.galan.commons.util.Sugar.*; import static org.apache.commons.lang3.StringUtils.*; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import de.galan.commons.func.exceptional.ExceptionalRunnable; import de.galan.commons.logging.Say; import de.galan.commons.time.Durations; import de.galan.commons.time.Sleeper; /** * Invokes a Callable/ExceptionalRunnable until it runs without Exception the specified times of retries. */ public class Retryable { public static final String DEFAULT_WAIT_TIME = "1s"; public static final long INFINITE = -1; private long numberOfRetries; // total number of tries private long numberOfTriesLeft; // number left private String timeToWait; // wait interval private String message; // message to identify retry Retryable(long numberOfRetries) { retries(numberOfRetries); } public static Retryable retry(long numberOfRetries) { return new Retryable(numberOfRetries); } public static Retryable infinite() { return new Retryable(INFINITE); } public Retryable timeToWait(String timeToWaitBetween) { timeToWait = timeToWaitBetween; return this; } public Retryable timeToWait(long millis) { timeToWait = Durations.humanize(millis); return this; } public Retryable retries(long retries) { numberOfRetries = retries; numberOfTriesLeft = numberOfRetries + 1; return this; } public Retryable message(String msg) { message = msg; return this; } public <V> V call(Callable<V> callable) throws Exception { while(Thread.currentThread().isAlive()) { try { return callable.call(); } catch (InterruptedException e) { throw e; } catch (CancellationException e) { throw e; } catch (Exception e) { numberOfTriesLeft if (numberOfRetries != INFINITE) { if (numberOfTriesLeft == 0) { throw new RetryException(numberOfRetries + " attempts to retry, failed at " + timeToWait + " interval for " + message, e, numberOfRetries, timeToWait, message); } if (isBlank(message)) { Say.info("Retrying {numberOfRetriesLeft}/{numberOfRetries} in {timeToWait}", numberOfRetries - numberOfTriesLeft + 1, numberOfRetries, timeToWait); } else { Say.info("Retrying {numberOfRetriesLeft}/{numberOfRetries} in {timeToWait} for {message}", numberOfRetries - numberOfTriesLeft + 1, numberOfRetries, timeToWait, message); } } else { if (isBlank(message)) { Say.info("Retrying {} in {}", Math.abs(numberOfTriesLeft + 1), timeToWait); } else { Say.info("Retrying {} in {} for {}", Math.abs(numberOfTriesLeft + 1), timeToWait, message); } } Sleeper.sleep(optional(timeToWait).orElse(DEFAULT_WAIT_TIME)); } } throw new InterruptedException("Thread with retry is not longer alive"); // Edge-case where Thread was killed and the Exception was catched by the caller } public void run(ExceptionalRunnable runnable) throws Exception { call(() -> { runnable.run(); return null; }); } }
package de.otto.edison.hal; import java.util.List; import java.util.Optional; public class CuriTemplate { private static final String REL_PLACEHOLDER = "{rel}"; private final String relPrefix; private final String relSuffix; private final Link curi; private CuriTemplate(final Link curi) { if (!curi.getRel().equals("curies")) { throw new IllegalArgumentException("Parameter is not a CURI link."); } if (!curi.getHref().contains(REL_PLACEHOLDER)) { throw new IllegalArgumentException("Href of the CURI does not contain the required {rel} placeholder."); } final String curiHref = curi.getHref(); relPrefix = curi.getHref().substring(0, curiHref.indexOf(REL_PLACEHOLDER)); relSuffix = curi.getHref().substring(curiHref.indexOf(REL_PLACEHOLDER) + REL_PLACEHOLDER.length(), curiHref.length()); this.curi = curi; } public static CuriTemplate curiTemplateFor(final Link curi) { return new CuriTemplate(curi); } /** * Returns a CuriTemplate that is {@link #matches matching} the rel parameter, or empty if no matching CURI is found. * * @param curies a List of curies Links * @param rel the link-relation type to check against the curies * @return optional CuriTemplate */ public static Optional<CuriTemplate> matchingCuriTemplateFor(final List<Link> curies, final String rel) { return curies .stream() .map(CuriTemplate::curiTemplateFor) .filter(t->t.matches(rel)) .findAny(); } /** * Returns true, if the given link-relation type is matching the CuriTemplate pattern, false if not. * * @param rel a link-relation type. * @return boolean */ public boolean matches(final String rel) { return rel.startsWith(relPrefix) && rel.endsWith(relSuffix); } public String relPlaceHolderFrom(final String rel) { if (matches(rel)) { return rel.substring(relPrefix.length(), rel.length() - relSuffix.length()); } else { throw new IllegalArgumentException("Rel is not matching the CURI template."); } } public String curiedRelFrom(final String rel) { if (matches(rel)) { return curi.getName() + ":" + relPlaceHolderFrom(rel); } else { throw new IllegalArgumentException("Rel is not matching the CURI template."); } } /** * Returns an expanded / full URI for a link-relation type. * * @param rel the - possibly curied - link-relation type to expand. * @return URL */ public String expand(final String rel) { return curi.getHrefAsTemplate().set("rel", relPlaceHolderFrom(rel)).expand(); } }
package dev.osm.mapsplit; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.TreeSet; import org.jetbrains.annotations.NotNull; /*- * provides implementation aspects shared between multiple {@link OsmMap} subtypes, * particularly relating to the interpretation of the map's values. * * Structure of the values: * * 6 4 3 2 2 2 * 3 7 1 6 4 3 * XXXX XXXX XXXX XXXX YYYY YYYY YYYY YYYY 1uuu uNNE nnnn nnnn nnnn nnnn nnnn nnnn * * X - tile number * Y - tile number * u - unused * 1 - always set to 1. This ensures that the value can be distinguished from empty positions in an array. * N - bits indicating immediate "neigbours" * E - extended "neighbour" list used * n - bits for "short" neighbour index, in long list mode used as index * * Tiles indexed in "short" list (T original tile) * - - * 2 1 0 1 2 * * -2 0 1 2 3 4 * -1 5 6 7 8 9 * 0 10 11 T 12 13 * 1 14 15 16 17 18 * 2 19 20 21 22 23 */ public abstract class AbstractOsmMap implements OsmMap { // see HEAPMAP.md for details static final int TILE_X_SHIFT = 48; static final int TILE_Y_SHIFT = 32; private static final long TILE_X_MASK = Const.MAX_TILE_NUMBER << TILE_X_SHIFT; private static final long TILE_Y_MASK = Const.MAX_TILE_NUMBER << TILE_Y_SHIFT; private static final int TILE_EXT_SHIFT = 24; private static final long TILE_EXT_MASK = 1l << TILE_EXT_SHIFT; private static final long TILE_MARKER_MASK = 0xFFFFFFl; private static final int NEIGHBOUR_SHIFT = TILE_EXT_SHIFT + 1; private static final long NEIGHBOUR_MASK = 3l << NEIGHBOUR_SHIFT; private static final int ONE_BIT_SHIFT = 31; private static final long ONE_BIT_MASK = 1l << ONE_BIT_SHIFT; private static final int INITIAL_EXTENDED_SET_SIZE = 1000; private int extendedBuckets = 0; private int[][] extendedSet = new int[INITIAL_EXTENDED_SET_SIZE][]; @Override public int tileX(long value) { return (int) ((value & TILE_X_MASK) >>> TILE_X_SHIFT); } @Override public int tileY(long value) { return (int) ((value & TILE_Y_MASK) >>> TILE_Y_SHIFT); } @Override public int neighbour(long value) { return (int) ((value & NEIGHBOUR_MASK) >> NEIGHBOUR_SHIFT); } /* * (non-Javadoc) * * @see OsmMap#getAllTiles(long) */ @Override public List<Integer> getAllTiles(long key) { long value = get(key); if (value == 0) { return null; } int tx = tileX(value); int ty = tileY(value); int neighbour = neighbour(value); List<Integer> result; if ((value & TILE_EXT_MASK) != 0) { int idx = (int) (value & TILE_MARKER_MASK); result = new ArrayList<>(asList(extendedSet[idx])); } else { result = parseMarker(value); } // TODO: some tiles (neighbour-tiles) might be double-included in the list, is this a problem?! // add the tile (and possible neighbours) result.add(TileCoord.encode(tx, ty)); if ((neighbour & OsmMap.NEIGHBOURS_EAST) != 0) { result.add(TileCoord.encode(tx + 1, ty)); } if ((neighbour & OsmMap.NEIGHBOURS_SOUTH) != 0) { result.add(TileCoord.encode(tx, ty + 1)); } if ((neighbour & OsmMap.NEIGHBOURS_SOUTH_EAST) == OsmMap.NEIGHBOURS_SOUTH_EAST) { result.add(TileCoord.encode(tx + 1, ty + 1)); } return result; } @Override public void updateInt(long key, Collection<Integer> tiles) { List<Long> longTiles = tiles.stream().map(tile -> createValue(TileCoord.decodeX(tile), TileCoord.decodeY(tile), NEIGHBOURS_NONE)).collect(toList()); this.update(key, longTiles); } /** * creates a value (representing a set of tile coords) from a pair of x/y tile coords and maybe some neighbors * * @param tileX x tile number * @param tileY y tile number * @param neighbours bit encoded neighbours * @return the value encoding the set of tiles represented by the parameters */ protected long createValue(int tileX, int tileY, int neighbours) { return ((long) tileX) << TILE_X_SHIFT | ((long) tileY) << TILE_Y_SHIFT | ((long) neighbours) << NEIGHBOUR_SHIFT | ONE_BIT_MASK; } /** * updates a value by adding a set of tiles to it. Might "overflow" into the list of additional tiles and modify it * accordingly. * * This can be used to implement {@link #update(long, Collection)}. * * @param originalValue the original value * @param tiles a collection of tiles to add * @return the updated value */ protected long updateValue(long originalValue, @NotNull Collection<Long> tiles) { long val = originalValue; int tx = tileX(val); int ty = tileY(val); // neighbour list is already too large so we use the "large store" if ((val & TILE_EXT_MASK) != 0) { int idx = (int) (val & TILE_MARKER_MASK); appendNeighbours(idx, tiles); return originalValue; } // create a expanded temp set for neighbourhood tiles Collection<Integer> expanded = new TreeSet<>(); for (long tile : tiles) { int x = tileX(tile); int y = tileY(tile); int neighbour = neighbour(tile); expanded.add(TileCoord.encode(x, y)); if ((neighbour & NEIGHBOURS_EAST) != 0) { expanded.add(TileCoord.encode(x + 1, y)); } if ((neighbour & NEIGHBOURS_SOUTH) != 0) { expanded.add(TileCoord.encode(x, y + 1)); } if (neighbour == NEIGHBOURS_SOUTH_EAST) { expanded.add(TileCoord.encode(x + 1, y + 1)); } } // now we use the 24 reserved bits for the tiles list.. for (int tile : expanded) { int tmpX = TileCoord.decodeX(tile); int tmpY = TileCoord.decodeY(tile); if (tmpX == tx && tmpY == ty) { continue; } int dx = tmpX - tx + 2; int dy = tmpY - ty + 2; int idx = dy * 5 + dx; if (idx >= 12) { idx } if (dx < 0 || dy < 0 || dx > 4 || dy > 4) { // .. damn, not enough space for "small store" // -> use "large store" instead return extendToNeighbourSet(originalValue, tiles); } else { val |= 1l << idx; } } return val; } /** * Start using the list of additional tiles instead of the bits directly in the value * * @param val the value to extend * @param tiles the List of additional tiles * @return the updated value */ private long extendToNeighbourSet(long val, @NotNull Collection<Long> tiles) { if ((val & TILE_MARKER_MASK) != 0) { // add current stuff to tiles list List<Integer> tmpList = parseMarker(val); for (int i : tmpList) { long tx = TileCoord.decodeX(i); long ty = TileCoord.decodeY(i); long temp = tx << TILE_X_SHIFT | ty << TILE_Y_SHIFT; tiles.add(temp); } // delete old marker from val val &= ~TILE_MARKER_MASK; } int cur = extendedBuckets++; // if we don't have enough sets, increase the array... if (cur >= extendedSet.length) { if (extendedSet.length >= TILE_MARKER_MASK / 2) { // assumes TILE_MARKER_MASK starts at 0 throw new IllegalStateException("Too many extended tile entries to expand"); } int[][] tmp = new int[2 * extendedSet.length][]; System.arraycopy(extendedSet, 0, tmp, 0, extendedSet.length); extendedSet = tmp; } val |= 1l << TILE_EXT_SHIFT; val |= (long) cur; extendedSet[cur] = new int[0]; appendNeighbours(cur, tiles); return val; } /** * Add tiles to the extended tile list for an element * * @param index the index in to the array of the tile lists * @param tiles a List containing the tile numbers */ private void appendNeighbours(int index, @NotNull Collection<Long> tiles) { int[] old = extendedSet[index]; int[] set = new int[4 * tiles.size()]; int pos = 0; for (long l : tiles) { int tx = tileX(l); int ty = tileY(l); int neighbour = neighbour(l); set[pos++] = TileCoord.encode(tx, ty); if ((neighbour & NEIGHBOURS_EAST) != 0) { set[pos++] = TileCoord.encode(tx + 1, ty); } if ((neighbour & NEIGHBOURS_SOUTH) != 0) { set[pos++] = TileCoord.encode(tx, ty + 1); } if (neighbour == NEIGHBOURS_SOUTH_EAST) { set[pos++] = TileCoord.encode(tx + 1, ty + 1); } } int[] result = merge(old, set, pos); extendedSet[index] = result; } /** * Get neighboring tiles from bit values * * @param value the encoded value * @return a list of tiles encoded in an int */ private List<Integer> parseMarker(long value) { List<Integer> result = new ArrayList<>(); int tx = tileX(value); int ty = tileY(value); for (int i = 0; i < 24; i++) { // if bit is not set, continue.. if (((value >> i) & 1) == 0) { continue; } int v = i >= 12 ? i + 1 : i; int tmpX = v % 5 - 2; int tmpY = v / 5 - 2; result.add(TileCoord.encode(tx + tmpX, ty + tmpY)); } return result; } /** * Merge two int arrays, removing dupes * * @param old the original array * @param add the additional array * @param len the additional number of ints to allocate * @return the new array */ private static int[] merge(@NotNull int[] old, @NotNull int[] add, int len) { int curLen = old.length; int[] tmp = new int[curLen + len]; System.arraycopy(old, 0, tmp, 0, old.length); for (int i = 0; i < len; i++) { int toAdd = add[i]; boolean contained = false; for (int j = 0; j < curLen; j++) { if (toAdd == tmp[j]) { contained = true; break; } } if (!contained) { tmp[curLen++] = toAdd; } } int[] result = new int[curLen]; System.arraycopy(tmp, 0, result, 0, curLen); return result; } /** * Return a list with the contents of an int array * * @param set the array * @return a List of Integer */ @NotNull private static List<Integer> asList(@NotNull int[] set) { List<Integer> result = new ArrayList<>(); for (int i = 0; i < set.length; i++) { result.add(set[i]); } return result; } }
package ee.jiss.commons.lang; import java.io.File; import java.util.Collection; import java.util.Map; import java.util.function.Consumer; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; public class CheckUtils { public static boolean isTrue(final Boolean value) { return TRUE.equals(value); } public static boolean isTrueOrNull(final Boolean value) { return ! FALSE.equals(value); } public static boolean isFalse(final Boolean value) { return FALSE.equals(value); } public static boolean isFalseOrNull(final Boolean value) { return ! TRUE.equals(value); } public static boolean isEmptyCollection(final Collection<?> value) { return value == null || value.isEmpty(); } public static boolean isNotEmptyCollection(final Collection<?> value) { return ! isEmptyCollection(value); } public static boolean isEmptyMap(final Map<?, ?> value) { return value == null || value.isEmpty(); } public static boolean isNotEmptyMap(final Map<?, ?> value) { return ! isEmptyMap(value); } public static boolean isSizeOfCollection(final Collection<?> value, final int size) { return size == 0 ? isEmptyCollection(value) : value != null && value.size() == size; } public static boolean isNotSizeOfCollection(final Collection<?> value, final int size) { return ! isSizeOfCollection(value, size); } public static boolean isEmptyArray(final Object[] value) { return value == null || value.length == 0; } public static boolean isNotEmptyArray(final Object[] value) { return ! isEmptyArray(value); } public static boolean isSizeOfArray(final Object[] value, final int size) { return size == 0 ? isEmptyArray(value) : value.length == size; } public static boolean isNotSizeOfArray(final Object[] value, final int size) { return ! isSizeOfArray(value, size); } public static boolean isEmptyString(final String value) { return value == null || value.isEmpty(); } public static boolean isNotEmptyString(final String value) { return ! isEmptyString(value); } public static void ifEmptyString(final String value, final Consumer<String> consumer) { if (isEmptyString(value)) consumer.accept(value); } public static void ifNotEmptyString(final String value, final Consumer<String> consumer) { if (isNotEmptyString(value)) consumer.accept(value); } public static boolean isSizeOfString(final String value, final int size) { return size == 0 ? isEmptyString(value) : value.length() == size; } public static boolean isNotSizeOfString(final String value, final int size) { return ! isSizeOfString(value, size); } public static boolean exists(final File value) { return value != null && value.exists(); } public static boolean notExists(final File value) { return ! exists(value); } public static boolean isDirectory(final File value) { return value != null && value.isDirectory(); } public static boolean isFile(final File value) { return value != null && value.isFile(); } }
package eu.freme.broker.eservices; import java.io.ByteArrayInputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import eu.freme.broker.exception.BadRequestException; import eu.freme.broker.exception.InternalServerErrorException; import eu.freme.broker.exception.InvalidNIFException; import eu.freme.broker.exception.InvalidTemplateEndpointException; import eu.freme.broker.tools.NIFParameterSet; import eu.freme.broker.tools.TemplateValidator; import eu.freme.conversion.rdf.RDFConstants; import eu.freme.conversion.rdf.RDFConstants.RDFSerialization; import eu.freme.eservices.elink.api.DataEnricher; import eu.freme.eservices.elink.Exporter; import eu.freme.eservices.elink.Template; import eu.freme.eservices.elink.TemplateDAO; import eu.freme.eservices.elink.exceptions.TemplateNotFoundException; import org.apache.commons.validator.routines.UrlValidator; @RestController public class ELink extends BaseRestController { @Autowired DataEnricher dataEnricher; @Autowired TemplateDAO templateDAO; @Autowired TemplateValidator templateValidator; // Enriching using a template. // POST /e-link/enrich/ @RequestMapping(value = "/e-link/documents", method = RequestMethod.POST) public ResponseEntity<String> enrich( @RequestParam(value = "templateid", required=true) String templateIdStr, @RequestHeader(value = "Accept", required=false) String acceptHeader, @RequestHeader(value = "Content-Type", required=false) String contentTypeHeader, @RequestBody String postBody, @RequestParam Map<String,String> allParams) { try { int templateId = validateTemplateID(templateIdStr); String informat = null; String f = null; String outformat = null; String o = null; HashMap<String, String> templateParams = new HashMap(); for (Map.Entry<String, String> entry : allParams.entrySet()) { switch(entry.getKey()) { case "informat": informat = entry.getValue(); break; case "f": f = entry.getValue(); break; case "outformat": outformat = entry.getValue(); break; case "o": o = entry.getValue(); break; default: templateParams.put(entry.getKey(), entry.getValue()); break; } } // merge long and short parameters - long parameters override short parameters. if( informat == null ){ informat = f; } if( outformat == null ){ outformat = o; } if( postBody == null || postBody.trim().length() == 0 ){ throw new eu.freme.broker.exception.BadRequestException("No data to process could be found in the input."); } NIFParameterSet parameters = this.normalizeNif(postBody, informat, outformat, postBody, acceptHeader, contentTypeHeader, null); Model inModel = ModelFactory.createDefaultModel(); switch(parameters.getInformat()) { case TURTLE: inModel.read(new ByteArrayInputStream(postBody.getBytes()), null, "TTL"); break; case JSON_LD: inModel.read(new ByteArrayInputStream(postBody.getBytes()), null, "JSON-LD"); break; case RDF_XML: inModel.read(new ByteArrayInputStream(postBody.getBytes()), null, "RDF/XML"); break; case N_TRIPLES: inModel.read(new ByteArrayInputStream(postBody.getBytes()), null, "N-TRIPLE"); break; case N3: inModel.read(new ByteArrayInputStream(postBody.getBytes()), null, "N3"); break; } // System.out.println(inModel); // System.out.println(inModel.size()); inModel = dataEnricher.enrichNIF(inModel, templateId, templateParams); // System.out.println(inModel); // System.out.println(inModel.size()); HttpHeaders responseHeaders = new HttpHeaders(); String serialization; switch(parameters.getOutformat()) { case TURTLE: serialization = rdfConversionService.serializeRDF(inModel, RDFSerialization.TURTLE); responseHeaders.add("Content-Type", "text/turtle"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case JSON_LD: serialization = rdfConversionService.serializeRDF(inModel, RDFSerialization.JSON_LD); responseHeaders.add("Content-Type", "application/ld+json"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case RDF_XML: serialization = rdfConversionService.serializeRDF(inModel, RDFSerialization.RDF_XML); responseHeaders.add("Content-Type", "application/rdf+xml"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N_TRIPLES: serialization = rdfConversionService.serializeRDF(inModel, RDFSerialization.N_TRIPLES); responseHeaders.add("Content-Type", "application/n-triples"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N3: serialization = rdfConversionService.serializeRDF(inModel, RDFSerialization.N3); responseHeaders.add("Content-Type", "text/n3"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); } } catch (TemplateNotFoundException ex) { logger.warn("The template with the specified ID has not been found.", ex); throw new TemplateNotFoundException("The template with the specified ID has not been found."); } catch (org.apache.jena.riot.RiotException ex) { logger.error("Invalid NIF document.", ex); throw new InvalidNIFException(ex.getMessage()); } catch (BadRequestException ex) { logger.error(ex.getMessage(), ex); throw ex; } catch (Exception ex) { logger.error("Internal service problem. Please contact the service provider.", ex); throw new InternalServerErrorException("Unknown problem. Please contact us."); } throw new InternalServerErrorException("Unknown problem. Please contact us."); } // Creating a template. // POST /e-link/templates/ @RequestMapping(value = "/e-link/templates", method = RequestMethod.POST) public ResponseEntity<String> createTemplate( @RequestHeader(value = "Accept", required=false) String acceptHeader, @RequestHeader(value = "Content-Type", required=false) String contentTypeHeader, @RequestParam(value = "informat", required=false) String informat, @RequestParam(value = "f", required=false) String f, @RequestParam(value = "outformat", required=false) String outformat, @RequestParam(value = "o", required=false) String o, @RequestBody String postBody) { try { if( informat == null ){ informat = f; } if( outformat == null ){ outformat = o; } if( postBody == null || postBody.trim().length() == 0 ) { return new ResponseEntity<String>("Empty body of the request.", HttpStatus.BAD_REQUEST); } // Checking the informat parameter RDFSerialization thisInformat; if (informat == null && contentTypeHeader == null) { thisInformat = RDFSerialization.JSON; } else if (informat != null) { if (!rdfELinkSerializationFormats.containsKey(informat)) { throw new BadRequestException( "The parameter informat has invalid value \"" + informat + "\""); } thisInformat = rdfELinkSerializationFormats.get(informat); } else { if (!rdfELinkSerializationFormats.containsKey(contentTypeHeader)) { throw new BadRequestException("Content-Type header has invalid value \"" + contentTypeHeader + "\""); } thisInformat = rdfELinkSerializationFormats.get(contentTypeHeader); } // END: Checking the informat parameter // Checking the outformat parameter RDFSerialization thisOutformat; if( acceptHeader != null && acceptHeader.equals("*/*")) { acceptHeader = "text/turtle"; } if (outformat == null && acceptHeader == null) { thisOutformat = RDFSerialization.JSON; } else if (outformat != null) { if (!rdfELinkSerializationFormats.containsKey(outformat)) { throw new BadRequestException("Parameter outformat has invalid value \"" + outformat + "\""); } thisOutformat = rdfELinkSerializationFormats.get(outformat); } else { if (!rdfELinkSerializationFormats.containsKey(acceptHeader)) { throw new BadRequestException("Parameter outformat has invalid value \"" + acceptHeader + "\""); } thisOutformat = rdfELinkSerializationFormats.get(acceptHeader); } // END: Checking the outformat parameter Template t = null; Model model = ModelFactory.createDefaultModel(); switch(thisInformat) { case JSON: JSONObject jsonObj = new JSONObject(postBody); templateValidator.validateTemplateEndpoint(jsonObj.getString("endpoint")); t = new Template( templateDAO.generateTemplateId(), jsonObj.getString("endpoint"), jsonObj.getString("query"), jsonObj.getString("label"), jsonObj.getString("description") ); break; case TURTLE: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "TTL"); t = Exporter.getInstance().model2OneTemplate(model); templateValidator.validateTemplateEndpoint(t.getEndpoint()); t.setId(templateDAO.generateTemplateId()); break; case JSON_LD: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "JSON-LD"); t = Exporter.getInstance().model2OneTemplate(model); templateValidator.validateTemplateEndpoint(t.getEndpoint()); t.setId(templateDAO.generateTemplateId()); break; case RDF_XML: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "RDF/XML"); t = Exporter.getInstance().model2OneTemplate(model); templateValidator.validateTemplateEndpoint(t.getEndpoint()); t.setId(templateDAO.generateTemplateId()); break; case N_TRIPLES: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "N-Triples"); t = Exporter.getInstance().model2OneTemplate(model); templateValidator.validateTemplateEndpoint(t.getEndpoint()); t.setId(templateDAO.generateTemplateId()); break; case N3: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "N3"); t = Exporter.getInstance().model2OneTemplate(model); templateValidator.validateTemplateEndpoint(t.getEndpoint()); t.setId(templateDAO.generateTemplateId()); break; } templateDAO.addTemplate(t); HttpHeaders responseHeaders = new HttpHeaders(); URI location = new URI("/e-link/templates/"+t.getId()); responseHeaders.setLocation(location); Model outModel; String serialization; switch(thisOutformat) { case JSON: responseHeaders.set("Content-Type", "application/json"); return new ResponseEntity<String>(Exporter.getInstance().convertOneTemplate2JSON(t).toString(), responseHeaders, HttpStatus.OK); case TURTLE: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.TURTLE); responseHeaders.set("Content-Type", "text/turtle"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case JSON_LD: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.JSON_LD); responseHeaders.set("Content-Type", "application/ld+json"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case RDF_XML: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.RDF_XML); responseHeaders.set("Content-Type", "application/rdf+xml"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N_TRIPLES: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.N_TRIPLES); responseHeaders.set("Content-Type", "application/n-triples"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N3: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.N3); responseHeaders.set("Content-Type", "text/n3"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); } } catch (URISyntaxException ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); throw new BadRequestException(ex.getMessage()); } catch (org.json.JSONException ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); throw new BadRequestException(ex.getMessage()); } catch (InvalidTemplateEndpointException ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); throw new InvalidTemplateEndpointException(ex.getMessage()); } catch (Exception ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); throw new InternalServerErrorException(ex.getMessage()); } throw new InternalServerErrorException("Unknown problem. Please contact us."); } // Get one template. // GET /e-link/templates/{template-id} @RequestMapping(value = "/e-link/templates/{templateid}", method = RequestMethod.GET) public ResponseEntity<String> getTemplateById( @RequestHeader(value = "Accept", required=false) String acceptHeader, @PathVariable("templateid") String idStr, @RequestParam(value = "outformat", required=false) String outformat, @RequestParam(value = "o", required=false) String o) { try { if( outformat == null ){ outformat = o; } int id = validateTemplateID(idStr); // Checking the outformat parameter RDFSerialization thisOutformat; if( acceptHeader != null && acceptHeader.equals("*/*")) { acceptHeader = "application/json"; } if (outformat == null && acceptHeader == null) { thisOutformat = RDFSerialization.JSON; } else if (outformat != null) { if (!rdfELinkSerializationFormats.containsKey(outformat)) { throw new BadRequestException("Parameter outformat has invalid value \"" + outformat + "\""); } thisOutformat = rdfELinkSerializationFormats.get(outformat); } else { if (!rdfELinkSerializationFormats.containsKey(acceptHeader)) { throw new BadRequestException("Parameter outformat has invalid value \"" + acceptHeader + "\""); } thisOutformat = rdfELinkSerializationFormats.get(acceptHeader); } // END: Checking the outformat parameter Template t = templateDAO.getTemplateById(id+""); HttpHeaders responseHeaders = new HttpHeaders(); Model model = ModelFactory.createDefaultModel(); String serialization; switch(thisOutformat) { case JSON: responseHeaders.set("Content-Type", "application/json"); return new ResponseEntity<String>(Exporter.getInstance().convertOneTemplate2JSON(t).toString(4), responseHeaders, HttpStatus.OK); case TURTLE: model = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.TURTLE); responseHeaders.set("Content-Type", "text/turtle"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case JSON_LD: model = templateDAO.getTemplateInRDFById(id+""); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.JSON_LD); responseHeaders.set("Content-Type", "application/ld+json"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case RDF_XML: model = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.RDF_XML); responseHeaders.set("Content-Type", "application/rdf+xml"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N_TRIPLES: model = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.N_TRIPLES); responseHeaders.set("Content-Type", "application/n-triples"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N3: model = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.N3); responseHeaders.set("Content-Type", "text/n3"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); } } catch (TemplateNotFoundException e){ throw new TemplateNotFoundException("Template not found."); } catch (BadRequestException ex) { logger.error(ex.getMessage(), ex); throw ex; } catch (Exception ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); } throw new InternalServerErrorException("Unknown problem. Please contact us."); } // Retrieve all templates. // GET /e-link/templates/ @RequestMapping(value = "/e-link/templates", method = RequestMethod.GET) public ResponseEntity<String> getAllTemplates( @RequestHeader(value = "Accept", required=false) String acceptHeader, @RequestHeader(value = "Content-Type", required=false) String contentTypeHeader, @RequestParam(value = "outformat", required=false) String outformat, @RequestParam(value = "o", required=false) String o) { try { if( outformat == null ) { outformat = o; } // Checking the outformat parameter RDFSerialization thisOutformat = null; thisOutformat = checkOutFormat(outformat, acceptHeader); // END: Checking the outformat parameter HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_JSON); String serialization; Model model = ModelFactory.createDefaultModel(); switch(thisOutformat) { case JSON: responseHeaders.set("Content-Type", "application/json"); return new ResponseEntity<String>(Exporter.getInstance().convertTemplates2JSON(templateDAO.getAllTemplates()).toString(4), responseHeaders, HttpStatus.OK); case TURTLE: model = templateDAO.getAllTemplatesInRDF(); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.TURTLE); responseHeaders.set("Content-Type", "text/turtle"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case JSON_LD: model = templateDAO.getAllTemplatesInRDF(); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.JSON_LD); responseHeaders.set("Content-Type", "application/ld+json"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case RDF_XML: model = templateDAO.getAllTemplatesInRDF(); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.RDF_XML); responseHeaders.set("Content-Type", "application/rdf+xml"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N_TRIPLES: model = templateDAO.getAllTemplatesInRDF(); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.N_TRIPLES); responseHeaders.set("Content-Type", "application/n-triples"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N3: model = templateDAO.getAllTemplatesInRDF(); serialization = rdfConversionService.serializeRDF(model, RDFConstants.RDFSerialization.N3); responseHeaders.set("Content-Type", "text/n3"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); } } catch (BadRequestException ex) { throw new BadRequestException(ex.getMessage()); } catch (Exception ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); } throw new InternalServerErrorException("Unknown problem. Please contact us."); // return new ResponseEntity<String>("Unknown problem. Please contact us.", HttpStatus.INTERNAL_SERVER_ERROR); } // Update one template. // PUT /e-link/templates/{template-id} @RequestMapping(value = "/e-link/templates/{templateid}", method = RequestMethod.PUT) public ResponseEntity<String> updateTemplateById( @RequestHeader(value = "Accept", required=false) String acceptHeader, @RequestHeader(value = "Content-Type", required=false) String contentTypeHeader, @RequestParam(value = "informat", required=false) String informat, @RequestParam(value = "f", required=false) String f, @RequestParam(value = "outformat", required=false) String outformat, @RequestParam(value = "o", required=false) String o, @PathVariable("templateid") String templateId, @RequestBody String postBody) { try { if( informat == null ){ informat = f; } if( outformat == null ){ outformat = o; } if( postBody == null || postBody.trim().length() == 0 ) { return new ResponseEntity<String>("Empty body of the request.", HttpStatus.BAD_REQUEST); } // Checking the informat parameter RDFSerialization thisInformat; if (informat == null && contentTypeHeader == null) { thisInformat = RDFSerialization.JSON; } else if (informat != null) { if (!rdfELinkSerializationFormats.containsKey(informat)) { throw new BadRequestException( "The parameter informat has invalid value \"" + informat + "\""); } thisInformat = rdfELinkSerializationFormats.get(informat); } else { if (!rdfELinkSerializationFormats.containsKey(contentTypeHeader)) { throw new BadRequestException("Content-Type header has invalid value \"" + contentTypeHeader + "\""); } thisInformat = rdfELinkSerializationFormats.get(contentTypeHeader); } // END: Checking the informat parameter // Checking the outformat parameter RDFSerialization thisOutformat; if( acceptHeader != null && acceptHeader.equals("*/*")) { acceptHeader = "text/turtle"; } if (outformat == null && acceptHeader == null) { thisOutformat = RDFSerialization.JSON; } else if (outformat != null) { if (!rdfELinkSerializationFormats.containsKey(outformat)) { throw new BadRequestException("Parameter outformat has invalid value \"" + outformat + "\""); } thisOutformat = rdfELinkSerializationFormats.get(outformat); } else { if (!rdfELinkSerializationFormats.containsKey(acceptHeader)) { throw new BadRequestException("Parameter outformat has invalid value \"" + acceptHeader + "\""); } thisOutformat = rdfELinkSerializationFormats.get(acceptHeader); } // Checking the outformat parameter Template t = null; Model model = ModelFactory.createDefaultModel(); switch(thisInformat) { case JSON: JSONObject jsonObj = new JSONObject(postBody); t = new Template( templateId, jsonObj.getString("endpoint"), jsonObj.getString("query"), jsonObj.getString("label"), jsonObj.getString("description") ); break; case TURTLE: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "TTL"); t = Exporter.getInstance().model2OneTemplate(model); break; case JSON_LD: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "JSON-LD"); t = Exporter.getInstance().model2OneTemplate(model); break; case RDF_XML: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "RDF/XML"); t = Exporter.getInstance().model2OneTemplate(model); break; case N_TRIPLES: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "N-Triples"); t = Exporter.getInstance().model2OneTemplate(model); break; case N3: model.read(new ByteArrayInputStream(postBody.getBytes()), null, "N3"); t = Exporter.getInstance().model2OneTemplate(model); break; } templateDAO.updateTemplate(t); HttpHeaders responseHeaders = new HttpHeaders(); URI location = new URI("/e-link/templates/"+t.getId()); responseHeaders.setLocation(location); Model outModel; String serialization; switch(thisOutformat) { case JSON: responseHeaders.set("Content-Type", "application/json"); return new ResponseEntity<String>(Exporter.getInstance().convertOneTemplate2JSON(t).toString(), responseHeaders, HttpStatus.OK); case TURTLE: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.TURTLE); responseHeaders.set("Content-Type", "text/turtle"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case JSON_LD: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.JSON_LD); responseHeaders.set("Content-Type", "application/ld+json"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case RDF_XML: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.RDF_XML); responseHeaders.set("Content-Type", "application/rdf+xml"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N_TRIPLES: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.N_TRIPLES); responseHeaders.set("Content-Type", "application/n-triples"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); case N3: outModel = templateDAO.getTemplateInRDFById(t.getId()); serialization = rdfConversionService.serializeRDF(outModel, RDFConstants.RDFSerialization.N3); responseHeaders.set("Content-Type", "text/n3"); return new ResponseEntity<String>(serialization, responseHeaders, HttpStatus.OK); } } catch (URISyntaxException ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); } catch (org.json.JSONException ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); throw new BadRequestException("The JSON object is incorrectly formatted. Problem description: " + ex.getMessage()); } catch (Exception ex) { Logger.getLogger(ELink.class.getName()).log(Level.SEVERE, null, ex); } throw new InternalServerErrorException("Unknown problem. Please contact us."); } // Removing a template. // DELETE /e-link/templates/{template-id} @RequestMapping(value = "/e-link/templates/{templateid}", method = RequestMethod.DELETE) public ResponseEntity<String> removeTemplateById(@PathVariable("templateid") String id) { if(templateDAO.removeTemplateById(id)) { return new ResponseEntity<String>("The template was sucessfully removed.", HttpStatus.NO_CONTENT); } else { throw new TemplateNotFoundException("A template with such id was not found."); } } private RDFSerialization checkOutFormat(String outformat, String acceptHeader) { if( acceptHeader != null && acceptHeader.equals("*/*")) { acceptHeader = "text/turtle"; } if (outformat == null && acceptHeader == null) { return RDFSerialization.JSON; } else if (outformat != null) { if (!rdfELinkSerializationFormats.containsKey(outformat)) { throw new BadRequestException("Parameter outformat has invalid value \"" + outformat + "\""); } return rdfELinkSerializationFormats.get(outformat); } else { if (!rdfELinkSerializationFormats.containsKey(acceptHeader)) { throw new BadRequestException("Parameter outformat has invalid value \"" + acceptHeader + "\""); } return rdfELinkSerializationFormats.get(acceptHeader); } } private int validateTemplateID(String templateId) { if(templateId.isEmpty()){ throw new BadRequestException("Empty templateid parameter."); } for(int i = 0; i < templateId.length(); i++) { if(i == 0 && templateId.charAt(i) == '-') { if(templateId.length() == 1) { throw new BadRequestException("The templateid parameter is not integer."); } else continue; } if(Character.digit(templateId.charAt(i),10) < 0) { throw new BadRequestException("The templateid parameter is not integer."); } } return Integer.parseInt(templateId); } }
package eu.rekawek.coffeegb.timer; import eu.rekawek.coffeegb.AddressSpace; import eu.rekawek.coffeegb.cpu.InterruptManager; import eu.rekawek.coffeegb.cpu.SpeedMode; public class Timer implements AddressSpace { private final SpeedMode speedMode; private final InterruptManager interruptManager; private static final int[] FREQ_TO_BIT = {9, 3, 5, 7}; private int div, tac, tma, tima; private boolean previousBit; private boolean overflow; private int ticksSinceOverflow; public Timer(InterruptManager interruptManager, SpeedMode speedMode) { this.speedMode = speedMode; this.interruptManager = interruptManager; } public void tick() { updateDiv((div + 1) & 0xffff); if (overflow) { ticksSinceOverflow++; if (ticksSinceOverflow == 4) { interruptManager.requestInterrupt(InterruptManager.InterruptType.Timer); } if (ticksSinceOverflow == 5) { tima = tma; } if (ticksSinceOverflow == 6) { tima = tma; overflow = false; ticksSinceOverflow = 0; } } } private void incTima() { tima++; tima %= 0x100; if (tima == 0) { overflow = true; ticksSinceOverflow = 0; } } private void updateDiv(int newDiv) { this.div = newDiv; int bitPos = FREQ_TO_BIT[tac & 0b11]; bitPos <<= speedMode.getSpeedMode() - 1; boolean bit = (div & (1 << bitPos)) != 0; bit &= (tac & (1 << 2)) != 0; if (!bit && previousBit) { incTima(); } previousBit = bit; } @Override public boolean accepts(int address) { return address >= 0xff04 && address <= 0xff07; } @Override public void setByte(int address, int value) { switch (address) { case 0xff04: updateDiv(0); break; case 0xff05: if (ticksSinceOverflow < 5) { tima = value; overflow = false; ticksSinceOverflow = 0; } break; case 0xff06: tma = value; break; case 0xff07: tac = value; break; } } @Override public int getByte(int address) { switch (address) { case 0xff04: return div >> 8; case 0xff05: return tima; case 0xff06: return tma; case 0xff07: return tac; } throw new IllegalArgumentException(); } }
package ev3dev.hardware; import ev3dev.hardware.EV3DevPlatformsImpl; import ev3dev.hardware.EV3DevScreenInfo; import lejos.hardware.port.MotorPort; import lejos.hardware.port.Port; import lejos.hardware.port.SensorPort; import java.util.Properties; public class EV3DevPlatforms { private static EV3DevPlatformsImpl globalInstance = null; private EV3DevPlatformsImpl instance = null; public EV3DevPlatforms() { synchronized(EV3DevPlatforms.class) { if (globalInstance == null) { globalInstance = new EV3DevPlatformsImpl(); } } instance = globalInstance; } public EV3DevPlatforms(EV3DevPlatform platform) { instance = new EV3DevPlatformsImpl(platform); } public EV3DevPlatform getPlatform() { return instance.getPlatform(); } public String getMotorPort(final Port port) { // TODO: review in detail return instance.getMotorPort(port); } public String getSensorPort(final Port port) { return instance.getSensorPort(port); } public EV3DevScreenInfo getFramebufferInfo() { return instance.getFramebufferInfo(); } public String getProperty(String base) { return instance.getProperty(base); } }
package io.github.classgraph; import java.io.File; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.regex.Pattern; import nonapi.io.github.classgraph.classpath.SystemJarFinder; import nonapi.io.github.classgraph.concurrency.AutoCloseableExecutorService; import nonapi.io.github.classgraph.concurrency.InterruptionChecker; import nonapi.io.github.classgraph.scanspec.ScanSpec; import nonapi.io.github.classgraph.scanspec.WhiteBlackList; import nonapi.io.github.classgraph.utils.JarUtils; import nonapi.io.github.classgraph.utils.LogNode; import nonapi.io.github.classgraph.utils.VersionFinder; public class ClassGraph { /** The scanning specification. */ ScanSpec scanSpec = new ScanSpec(); /** * The default number of worker threads to use while scanning. This number gave the best results on a relatively * modern laptop with SSD, while scanning a large classpath. */ static final int DEFAULT_NUM_WORKER_THREADS = Math.max( // Always scan with at least 2 threads 2, (int) Math.ceil( // Num IO threads (top out at 4, since most I/O devices won't scale better than this) Math.min(4.0, Runtime.getRuntime().availableProcessors() * 0.75) + // Num scanning threads (higher than available processors, because some threads can be blocked) Runtime.getRuntime().availableProcessors() * 1.25) ); /** If non-null, log while scanning. */ private LogNode topLevelLog; /** Construct a ClassGraph instance. */ public ClassGraph() { // Initialize ScanResult, if this is the first call to ClassGraph constructor ScanResult.init(); } /** * Get the version number of ClassGraph. * * @return the ClassGraph version, or "unknown" if it could not be determined. */ public static String getVersion() { return VersionFinder.getVersion(); } /** * Switches on verbose logging to System.err. * * @return this (for method chaining). */ public ClassGraph verbose() { if (topLevelLog == null) { topLevelLog = new LogNode(); } return this; } /** * Switches on verbose logging to System.err if verbose is true. * * @param verbose * if true, enable verbose logging. * @return this (for method chaining). */ public ClassGraph verbose(final boolean verbose) { if (verbose) { verbose(); } return this; } /** * Enables the scanning of all classes, fields, methods, annotations, and static final field constant * initializer values, and ignores all visibility modifiers, so that both public and non-public classes, fields * and methods are all scanned. * * <p> * Calls {@link #enableClassInfo()}, {@link #enableFieldInfo()}, {@link #enableMethodInfo()}, * {@link #enableAnnotationInfo()}, {@link #enableStaticFinalFieldConstantInitializerValues()}, * {@link #ignoreClassVisibility()}, {@link #ignoreFieldVisibility()}, and {@link #ignoreMethodVisibility()}. * * @return this (for method chaining). */ public ClassGraph enableAllInfo() { enableClassInfo(); enableFieldInfo(); enableMethodInfo(); enableAnnotationInfo(); enableStaticFinalFieldConstantInitializerValues(); ignoreClassVisibility(); ignoreFieldVisibility(); ignoreMethodVisibility(); return this; } /** * Enables the scanning of classfiles, producing {@link ClassInfo} objects in the {@link ScanResult}. * * @return this (for method chaining). */ public ClassGraph enableClassInfo() { scanSpec.enableClassInfo = true; return this; } /** * Causes class visibility to be ignored, enabling private, package-private and protected classes to be scanned. * By default, only public classes are scanned. (Automatically calls {@link #enableClassInfo()}.) * * @return this (for method chaining). */ public ClassGraph ignoreClassVisibility() { enableClassInfo(); scanSpec.ignoreClassVisibility = true; return this; } /** * Enables the saving of method info during the scan. This information can be obtained using * {@link ClassInfo#getMethodInfo()} etc. By default, method info is not scanned. (Automatically calls * {@link #enableClassInfo()}.) * * @return this (for method chaining). */ public ClassGraph enableMethodInfo() { enableClassInfo(); scanSpec.enableMethodInfo = true; return this; } /** * Causes method visibility to be ignored, enabling private, package-private and protected methods to be * scanned. By default, only public methods are scanned. (Automatically calls {@link #enableClassInfo()} and * {@link #enableMethodInfo()}.) * * @return this (for method chaining). */ public ClassGraph ignoreMethodVisibility() { enableClassInfo(); enableMethodInfo(); scanSpec.ignoreMethodVisibility = true; return this; } /** * Enables the saving of field info during the scan. This information can be obtained using * {@link ClassInfo#getFieldInfo()}. By default, field info is not scanned. (Automatically calls * {@link #enableClassInfo()}.) * * @return this (for method chaining). */ public ClassGraph enableFieldInfo() { enableClassInfo(); scanSpec.enableFieldInfo = true; return this; } /** * Causes field visibility to be ignored, enabling private, package-private and protected fields to be scanned. * By default, only public fields are scanned. (Automatically calls {@link #enableClassInfo()} and * {@link #enableFieldInfo()}.) * * @return this (for method chaining). */ public ClassGraph ignoreFieldVisibility() { enableClassInfo(); enableFieldInfo(); scanSpec.ignoreFieldVisibility = true; return this; } /** * Enables the saving of static final field constant initializer values. By default, constant initializer values * are not scanned. If this is enabled, you can obtain the constant field initializer values from * {@link FieldInfo#getConstantInitializerValue()}. * * <p> * Note that constant initializer values are usually only of primitive type, or String constants (or values that * can be computed and reduced to one of those types at compiletime). * * <p> * Also note that it is up to the compiler as to whether or not a constant-valued field is assigned as a * constant in the field definition itself, or whether it is assigned manually in static class initializer * blocks -- so your mileage may vary in being able to extract constant initializer values. * * <p> * In fact in Kotlin, even constant initializers for non-static / non-final fields are stored in a field * attribute in the classfile (and so these values may be picked up by ClassGraph by calling this method), * although any field initializers for non-static fields are supposed to be ignored by the JVM according to the * classfile spec, so the Kotlin compiler may change in future to stop generating these values, and you probably * shouldn't rely on being able to get the initializers for non-static fields in Kotlin. (As far as non-final * fields, javac simply does not add constant initializer values to the field attributes list for non-final * fields, even if they are static, but the spec doesn't say whether or not the JVM should ignore constant * initializers for non-final fields.) * * <p> * Automatically calls {@link #enableClassInfo()} and {@link #enableFieldInfo()}. * * @return this (for method chaining). */ public ClassGraph enableStaticFinalFieldConstantInitializerValues() { enableClassInfo(); enableFieldInfo(); scanSpec.enableStaticFinalFieldConstantInitializerValues = true; return this; } /** * Enables the saving of annotation info (for class, field, method and method parameter annotations) during the * scan. This information can be obtained using {@link ClassInfo#getAnnotationInfo()}, * {@link FieldInfo#getAnnotationInfo()}, and {@link MethodParameterInfo#getAnnotationInfo()}. By default, * annotation info is not scanned. (Automatically calls {@link #enableClassInfo()}.) * * @return this (for method chaining). */ public ClassGraph enableAnnotationInfo() { enableClassInfo(); scanSpec.enableAnnotationInfo = true; return this; } /** * Enables the determination of inter-class dependencies, which may be read by calling * {@link ClassInfo#getClassDependencies()}, {@link ScanResult#getClassDependencyMap()} or * {@link ScanResult#getReverseClassDependencyMap()}. (Automatically calls {@link #enableClassInfo()}, * {@link #enableFieldInfo()}, {@link #enableMethodInfo()}, {@link #enableAnnotationInfo()}, * {@link #ignoreClassVisibility()}, {@link #ignoreFieldVisibility()} and {@link #ignoreMethodVisibility()}.) * * @return this (for method chaining). */ public ClassGraph enableInterClassDependencies() { enableClassInfo(); enableFieldInfo(); enableMethodInfo(); enableAnnotationInfo(); ignoreClassVisibility(); ignoreFieldVisibility(); ignoreMethodVisibility(); scanSpec.enableInterClassDependencies = true; return this; } /** * Causes only runtime visible annotations to be scanned (causes runtime invisible annotations to be ignored). * (Automatically calls {@link #enableClassInfo()}.) * * @return this (for method chaining). */ public ClassGraph disableRuntimeInvisibleAnnotations() { enableClassInfo(); scanSpec.disableRuntimeInvisibleAnnotations = true; return this; } /** * Disables the scanning of jarfiles. * * @return this (for method chaining). */ public ClassGraph disableJarScanning() { scanSpec.scanJars = false; return this; } /** * Disables the scanning of nested jarfiles (jarfiles within jarfiles). * * @return this (for method chaining). */ public ClassGraph disableNestedJarScanning() { scanSpec.scanNestedJars = false; return this; } /** * Disables the scanning of directories. * * @return this (for method chaining). */ public ClassGraph disableDirScanning() { scanSpec.scanDirs = false; return this; } /** * Disables the scanning of modules. * * @return this (for method chaining). */ public ClassGraph disableModuleScanning() { scanSpec.scanModules = false; return this; } /** * Causes ClassGraph to return classes that are not in the whitelisted packages, but that are directly referred * to by classes within whitelisted packages as a superclass, implemented interface or annotation. * (Automatically calls {@link #enableClassInfo()}.) * * @return this (for method chaining). */ public ClassGraph enableExternalClasses() { enableClassInfo(); scanSpec.enableExternalClasses = true; return this; } /** * Causes classes loaded using {@link ClassInfo#loadClass()} to be are initialized after class loading (the * default is to not initialize classes). * * @return this (for method chaining). */ public ClassGraph initializeLoadedClasses() { scanSpec.initializeLoadedClasses = true; return this; } /** * Remove temporary files, including nested jarfiles (jarfiles within jarfiles, which have to be extracted * during scanning in order to be read) from their temporary directory as soon as the scan has completed. The * default is for temporary files to be removed by the {@link ScanResult} finalizer, or on JVM exit. * * @return this (for method chaining). */ public ClassGraph removeTemporaryFilesAfterScan() { scanSpec.removeTemporaryFilesAfterScan = true; return this; } /** * Override the automatically-detected classpath with a custom path, with path elements separated by * File.pathSeparatorChar. Causes system ClassLoaders and the java.class.path system property to be ignored. * Also causes modules not to be scanned. * * <p> * If this method is called, nothing but the provided classpath will be scanned, i.e. this causes ClassLoaders * to be ignored, as well as the java.class.path system property. * * @param overrideClasspath * The custom classpath to use for scanning, with path elements separated by File.pathSeparatorChar. * @return this (for method chaining). */ public ClassGraph overrideClasspath(final String overrideClasspath) { if (overrideClasspath.isEmpty()) { throw new IllegalArgumentException("Can't override classpath with an empty path"); } for (final String classpathElement : JarUtils.smartPathSplit(overrideClasspath, scanSpec)) { scanSpec.addClasspathOverride(classpathElement); } return this; } /** * Override the automatically-detected classpath with a custom path. Causes system ClassLoaders and the * java.class.path system property to be ignored. Also causes modules not to be scanned. * * <p> * Works for Iterables of any type whose toString() method resolves to a classpath element string, e.g. String, * File or Path. * * @param overrideClasspathElements * The custom classpath to use for scanning, with path elements separated by File.pathSeparatorChar. * @return this (for method chaining). */ public ClassGraph overrideClasspath(final Iterable<?> overrideClasspathElements) { if (!overrideClasspathElements.iterator().hasNext()) { throw new IllegalArgumentException("Can't override classpath with an empty path"); } for (final Object classpathElement : overrideClasspathElements) { scanSpec.addClasspathOverride(classpathElement); } return this; } /** * Override the automatically-detected classpath with a custom path. Causes system ClassLoaders and the * java.class.path system property to be ignored. Also causes modules not to be scanned. * * <p> * Works for arrays of any member type whose toString() method resolves to a classpath element string, e.g. * String, File or Path. * * @param overrideClasspathElements * The custom classpath to use for scanning, with path elements separated by File.pathSeparatorChar. * @return this (for method chaining). */ public ClassGraph overrideClasspath(final Object... overrideClasspathElements) { if (overrideClasspathElements.length == 0) { throw new IllegalArgumentException("Can't override classpath with an empty path"); } for (final Object classpathElement : overrideClasspathElements) { scanSpec.addClasspathOverride(classpathElement); } return this; } /** * Add a classpath element filter. The includeClasspathElement method should return true if the path string * passed to it is a path you want to scan. */ @FunctionalInterface public interface ClasspathElementFilter { /** * Whether or not to include a given classpath element in the scan. * * @param classpathElementPathStr * The path string of a classpath element, normalized so that the path separator is '/'. This * will usually be a file path, but could be a URL, or it could be a path for a nested jar, where * the paths are separated using '!', in Java convention. "jar:" and/or "file:" will have been * stripped from the beginning, if they were present in the classpath. * @return true if the path string passed is a path you want to scan. */ boolean includeClasspathElement(String classpathElementPathStr); } /** * Add a classpath element filter. The provided ClasspathElementFilter should return true if the path string * passed to it is a path you want to scan. * * @param classpathElementFilter * The filter function to use. This function should return true if the classpath element path should * be scanned, and false if not. * @return this (for method chaining). */ public ClassGraph filterClasspathElements(final ClasspathElementFilter classpathElementFilter) { scanSpec.filterClasspathElements(classpathElementFilter); return this; } /** * Add a ClassLoader to the list of ClassLoaders to scan. * * <p> * This call is ignored if {@link #overrideClasspath(String)} is also called, or if this method is called before * {@link #overrideClassLoaders(ClassLoader...)}. * * @param classLoader * The additional ClassLoader to scan. * @return this (for method chaining). */ public ClassGraph addClassLoader(final ClassLoader classLoader) { scanSpec.addClassLoader(classLoader); return this; } /** * Completely override (and ignore) system ClassLoaders and the java.class.path system property. Also causes * modules not to be scanned. Note that you may want to use this together with * {@link #ignoreParentClassLoaders()} to extract classpath URLs from only the classloaders you specified in the * parameter to `overrideClassLoaders`, and not their parent classloaders. * * <p> * This call is ignored if {@link #overrideClasspath(String)} is called. * * @param overrideClassLoaders * The ClassLoaders to scan instead of the automatically-detected ClassLoaders. * @return this (for method chaining). */ public ClassGraph overrideClassLoaders(final ClassLoader... overrideClassLoaders) { scanSpec.overrideClassLoaders(overrideClassLoaders); return this; } /** * Ignore parent classloaders (i.e. only obtain paths to scan from classloaders that are not the parent of * another classloader). * * @return this (for method chaining). */ public ClassGraph ignoreParentClassLoaders() { scanSpec.ignoreParentClassLoaders = true; return this; } /** * Add a ModuleLayer to the list of ModuleLayers to scan. Use this method if you define your own ModuleLayer, * but the scanning code is not running within that custom ModuleLayer. * * <p> * This call is ignored if it is called before {@link #overrideModuleLayers(Object...)}. * * @param moduleLayer * The additional ModuleLayer to scan. (The parameter is of type {@link Object} for backwards * compatibility with JDK 7 and JDK 8, but the argument should be of type ModuleLayer.) * @return this (for method chaining). */ public ClassGraph addModuleLayer(final Object moduleLayer) { scanSpec.addModuleLayer(moduleLayer); return this; } /** * Completely override (and ignore) the visible ModuleLayers, and instead scan the requested ModuleLayers. * * <p> * This call is ignored if overrideClasspath() is called. * * @param overrideModuleLayers * The ModuleLayers to scan instead of the automatically-detected ModuleLayers. (The parameter is of * type {@link Object}[] for backwards compatibility with JDK 7 and JDK 8, but the argument should be * of type ModuleLayer[].) * @return this (for method chaining). */ public ClassGraph overrideModuleLayers(final Object... overrideModuleLayers) { scanSpec.overrideModuleLayers(overrideModuleLayers); return this; } /** * Ignore parent module layers (i.e. only scan module layers that are not the parent of another module layer). * * @return this (for method chaining). */ public ClassGraph ignoreParentModuleLayers() { scanSpec.ignoreParentModuleLayers = true; return this; } /** * Scan one or more specific packages and their sub-packages. * * <p> * N.B. Automatically calls {@link #enableClassInfo()} -- call {@link #whitelistPaths(String...)} instead if you * only need to scan resources. * * @param packageNames * The fully-qualified names of packages to scan (using '.' as a separator). May include a glob * wildcard ({@code '*'}). * @return this (for method chaining). */ public ClassGraph whitelistPackages(final String... packageNames) { enableClassInfo(); for (final String packageName : packageNames) { final String packageNameNormalized = WhiteBlackList.normalizePackageOrClassName(packageName); if (packageNameNormalized.startsWith("!") || packageNameNormalized.startsWith("-")) { throw new IllegalArgumentException( "This style of whitelisting/blacklisting is no longer supported: " + packageNameNormalized); } // Whitelist package scanSpec.packageWhiteBlackList.addToWhitelist(packageNameNormalized); final String path = WhiteBlackList.packageNameToPath(packageNameNormalized); scanSpec.pathWhiteBlackList.addToWhitelist(path + "/"); if (packageNameNormalized.isEmpty()) { scanSpec.pathWhiteBlackList.addToWhitelist(""); } if (!packageNameNormalized.contains("*")) { // Whitelist sub-packages if (packageNameNormalized.isEmpty()) { scanSpec.packagePrefixWhiteBlackList.addToWhitelist(""); scanSpec.pathPrefixWhiteBlackList.addToWhitelist(""); } else { scanSpec.packagePrefixWhiteBlackList.addToWhitelist(packageNameNormalized + "."); scanSpec.pathPrefixWhiteBlackList.addToWhitelist(path + "/"); } } } return this; } /** * Scan one or more specific paths, and their sub-directories or nested paths. * * @param paths * The paths to scan, relative to the package root of the classpath element (with '/' as a * separator). May include a glob wildcard ({@code '*'}). * @return this (for method chaining). */ public ClassGraph whitelistPaths(final String... paths) { for (final String path : paths) { final String pathNormalized = WhiteBlackList.normalizePath(path); // Whitelist path final String packageName = WhiteBlackList.pathToPackageName(pathNormalized); scanSpec.packageWhiteBlackList.addToWhitelist(packageName); scanSpec.pathWhiteBlackList.addToWhitelist(pathNormalized + "/"); if (pathNormalized.isEmpty()) { scanSpec.pathWhiteBlackList.addToWhitelist(""); } if (!pathNormalized.contains("*")) { // Whitelist sub-directories / nested paths if (pathNormalized.isEmpty()) { scanSpec.packagePrefixWhiteBlackList.addToWhitelist(""); scanSpec.pathPrefixWhiteBlackList.addToWhitelist(""); } else { scanSpec.packagePrefixWhiteBlackList.addToWhitelist(packageName + "."); scanSpec.pathPrefixWhiteBlackList.addToWhitelist(pathNormalized + "/"); } } } return this; } /** * Scan one or more specific packages, without recursively scanning sub-packages unless they are themselves * whitelisted. * * <p> * N.B. Automatically calls {@link #enableClassInfo()} -- call {@link #whitelistPathsNonRecursive(String...)} * instead if you only need to scan resources. * * <p> * This may be particularly useful for scanning the package root ("") without recursively scanning everything in * the jar, dir or module. * * @param packageNames * The fully-qualified names of packages to scan (with '.' as a separator). May not include a glob * wildcard ({@code '*'}). * * @return this (for method chaining). */ public ClassGraph whitelistPackagesNonRecursive(final String... packageNames) { enableClassInfo(); for (final String packageName : packageNames) { final String packageNameNormalized = WhiteBlackList.normalizePackageOrClassName(packageName); if (packageNameNormalized.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + packageNameNormalized); } // Whitelist package, but not sub-packages scanSpec.packageWhiteBlackList.addToWhitelist(packageNameNormalized); scanSpec.pathWhiteBlackList .addToWhitelist(WhiteBlackList.packageNameToPath(packageNameNormalized) + "/"); if (packageNameNormalized.isEmpty()) { scanSpec.pathWhiteBlackList.addToWhitelist(""); } } return this; } /** * Scan one or more specific paths, without recursively scanning sub-directories or nested paths unless they are * themselves whitelisted. * * <p> * This may be particularly useful for scanning the package root ("") without recursively scanning everything in * the jar, dir or module. * * @param paths * The paths to scan, relative to the package root of the classpath element (with '/' as a * separator). May not include a glob wildcard ({@code '*'}). * @return this (for method chaining). */ public ClassGraph whitelistPathsNonRecursive(final String... paths) { for (final String path : paths) { if (path.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + path); } final String pathNormalized = WhiteBlackList.normalizePath(path); // Whitelist path, but not sub-directories / nested paths scanSpec.packageWhiteBlackList.addToWhitelist(WhiteBlackList.pathToPackageName(pathNormalized)); scanSpec.pathWhiteBlackList.addToWhitelist(pathNormalized + "/"); if (pathNormalized.isEmpty()) { scanSpec.pathWhiteBlackList.addToWhitelist(""); } } return this; } /** * Prevent the scanning of one or more specific packages and their sub-packages. * * <p> * N.B. Automatically calls {@link #enableClassInfo()} -- call {@link #blacklistPaths(String...)} instead if you * only need to scan resources. * * @param packageNames * The fully-qualified names of packages to blacklist (with '.' as a separator). May include a glob * wildcard ({@code '*'}). * @return this (for method chaining). */ public ClassGraph blacklistPackages(final String... packageNames) { enableClassInfo(); for (final String packageName : packageNames) { final String packageNameNormalized = WhiteBlackList.normalizePackageOrClassName(packageName); if (packageNameNormalized.isEmpty()) { throw new IllegalArgumentException( "Blacklisting the root package (\"\") will cause nothing to be scanned"); } // Blacklisting always prevents further recursion, no need to blacklist sub-packages scanSpec.packageWhiteBlackList.addToBlacklist(packageNameNormalized); final String path = WhiteBlackList.packageNameToPath(packageNameNormalized); scanSpec.pathWhiteBlackList.addToBlacklist(path + "/"); if (!packageNameNormalized.contains("*")) { // Blacklist sub-packages (zipfile entries can occur in any order) scanSpec.packagePrefixWhiteBlackList.addToBlacklist(packageNameNormalized + "."); scanSpec.pathPrefixWhiteBlackList.addToBlacklist(path + "/"); } } return this; } /** * Prevent the scanning of one or more specific paths and their sub-directories / nested paths. * * @param paths * The paths to blacklist (with '/' as a separator). May include a glob wildcard ({@code '*'}). * @return this (for method chaining). */ public ClassGraph blacklistPaths(final String... paths) { for (final String path : paths) { final String pathNormalized = WhiteBlackList.normalizePath(path); if (pathNormalized.isEmpty()) { throw new IllegalArgumentException( "Blacklisting the root package (\"\") will cause nothing to be scanned"); } // Blacklisting always prevents further recursion, no need to blacklist sub-directories / nested paths final String packageName = WhiteBlackList.pathToPackageName(pathNormalized); scanSpec.packageWhiteBlackList.addToBlacklist(packageName); scanSpec.pathWhiteBlackList.addToBlacklist(pathNormalized + "/"); if (!pathNormalized.contains("*")) { // Blacklist sub-directories / nested paths scanSpec.packagePrefixWhiteBlackList.addToBlacklist(packageName + "."); scanSpec.pathPrefixWhiteBlackList.addToBlacklist(pathNormalized + "/"); } } return this; } /** * Scan one or more specific classes, without scanning other classes in the same package unless the package is * itself whitelisted. * * <p> * N.B. Automatically calls {@link #enableClassInfo()}. * * * @param classNames * The fully-qualified names of classes to scan (using '.' as a separator). May not include a glob * wildcard ({@code '*'}). * @return this (for method chaining). */ public ClassGraph whitelistClasses(final String... classNames) { enableClassInfo(); for (final String className : classNames) { if (className.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + className); } final String classNameNormalized = WhiteBlackList.normalizePackageOrClassName(className); // Whitelist the class itself scanSpec.classWhiteBlackList.addToWhitelist(classNameNormalized); scanSpec.classfilePathWhiteBlackList .addToWhitelist(WhiteBlackList.classNameToClassfilePath(classNameNormalized)); final String packageName = PackageInfo.getParentPackageName(classNameNormalized); // Record the package containing the class, so we can recurse to this point even if the package // is not itself whitelisted scanSpec.classPackageWhiteBlackList.addToWhitelist(packageName); scanSpec.classPackagePathWhiteBlackList .addToWhitelist(WhiteBlackList.packageNameToPath(packageName) + "/"); } return this; } /** * Specifically blacklist one or more specific classes, preventing them from being scanned even if they are in a * whitelisted package. * * <p> * N.B. Automatically calls {@link #enableClassInfo()}. * * @param classNames * The fully-qualified names of classes to blacklist (using '.' as a separator). May not include a * glob wildcard ({@code '*'}). * @return this (for method chaining). */ public ClassGraph blacklistClasses(final String... classNames) { enableClassInfo(); for (final String className : classNames) { if (className.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + className); } final String classNameNormalized = WhiteBlackList.normalizePackageOrClassName(className); scanSpec.classWhiteBlackList.addToBlacklist(classNameNormalized); scanSpec.classfilePathWhiteBlackList .addToBlacklist(WhiteBlackList.classNameToClassfilePath(classNameNormalized)); } return this; } /** * Whitelist one or more jars. This will cause only the whitelisted jars to be scanned. * * @param jarLeafNames * The leafnames of the jars that should be scanned (e.g. {@code "mylib.jar"}). May contain a * wildcard glob ({@code "mylib-*.jar"}). * @return this (for method chaining). */ public ClassGraph whitelistJars(final String... jarLeafNames) { for (final String jarLeafName : jarLeafNames) { final String leafName = JarUtils.leafName(jarLeafName); if (!leafName.equals(jarLeafName)) { throw new IllegalArgumentException("Can only whitelist jars by leafname: " + jarLeafName); } scanSpec.jarWhiteBlackList.addToWhitelist(leafName); } return this; } /** * Blacklist one or more jars, preventing them from being scanned. * * @param jarLeafNames * The leafnames of the jars that should be scanned (e.g. {@code "badlib.jar"}). May contain a * wildcard glob ({@code "badlib-*.jar"}). * @return this (for method chaining). */ public ClassGraph blacklistJars(final String... jarLeafNames) { for (final String jarLeafName : jarLeafNames) { final String leafName = JarUtils.leafName(jarLeafName); if (!leafName.equals(jarLeafName)) { throw new IllegalArgumentException("Can only blacklist jars by leafname: " + jarLeafName); } scanSpec.jarWhiteBlackList.addToBlacklist(leafName); } return this; } /** * Add lib or ext jars to whitelist or blacklist. * * @param whitelist * if true, add to whitelist, otherwise add to blacklist. * @param jarLeafNames * the jar leaf names to whitelist */ private void whitelistOrBlacklistLibOrExtJars(final boolean whitelist, final String... jarLeafNames) { if (jarLeafNames.length == 0) { // If no jar leafnames are given, whitelist or blacklist all lib or ext jars for (final String libOrExtJar : SystemJarFinder.getJreLibOrExtJars()) { whitelistOrBlacklistLibOrExtJars(whitelist, JarUtils.leafName(libOrExtJar)); } } else { for (final String jarLeafName : jarLeafNames) { final String leafName = JarUtils.leafName(jarLeafName); if (!leafName.equals(jarLeafName)) { throw new IllegalArgumentException("Can only " + (whitelist ? "whitelist" : "blacklist") + " jars by leafname: " + jarLeafName); } if (jarLeafName.contains("*")) { // Compare wildcarded pattern against all jars in lib and ext dirs final Pattern pattern = WhiteBlackList.globToPattern(jarLeafName); boolean found = false; for (final String libOrExtJarPath : SystemJarFinder.getJreLibOrExtJars()) { final String libOrExtJarLeafName = JarUtils.leafName(libOrExtJarPath); if (pattern.matcher(libOrExtJarLeafName).matches()) { // Check for "*" in filename to prevent infinite recursion (shouldn't happen) if (!libOrExtJarLeafName.contains("*")) { whitelistOrBlacklistLibOrExtJars(whitelist, libOrExtJarLeafName); } found = true; } } if (!found && topLevelLog != null) { topLevelLog.log("Could not find lib or ext jar matching wildcard: " + jarLeafName); } } else { // No wildcards, just whitelist or blacklist the named jar, if present boolean found = false; for (final String libOrExtJarPath : SystemJarFinder.getJreLibOrExtJars()) { final String libOrExtJarLeafName = JarUtils.leafName(libOrExtJarPath); if (jarLeafName.equals(libOrExtJarLeafName)) { if (whitelist) { scanSpec.libOrExtJarWhiteBlackList.addToWhitelist(jarLeafName); } else { scanSpec.libOrExtJarWhiteBlackList.addToBlacklist(jarLeafName); } if (topLevelLog != null) { topLevelLog.log((whitelist ? "Whitelisting" : "Blacklisting") + " lib or ext jar: " + libOrExtJarPath); } found = true; break; } } if (!found && topLevelLog != null) { topLevelLog.log("Could not find lib or ext jar: " + jarLeafName); } } } } } /** * Whitelist one or more jars in a JRE/JDK "lib/" or "ext/" directory (these directories are not scanned unless * {@link #enableSystemJarsAndModules()} is called, by association with the JRE/JDK). * * @param jarLeafNames * The leafnames of the lib/ext jar(s) that should be scanned (e.g. {@code "mylib.jar"}). May contain * a wildcard glob ({@code '*'}). Note that if you call this method with no parameters, all JRE/JDK * "lib/" or "ext/" jars will be whitelisted. * @return this (for method chaining). */ public ClassGraph whitelistLibOrExtJars(final String... jarLeafNames) { whitelistOrBlacklistLibOrExtJars(/* whitelist = */ true, jarLeafNames); return this; } /** * Blacklist one or more jars in a JRE/JDK "lib/" or "ext/" directory, preventing them from being scanned. * * @param jarLeafNames * The leafnames of the lib/ext jar(s) that should not be scanned (e.g. * {@code "jre/lib/badlib.jar"}). May contain a wildcard glob ({@code '*'}). If you call this method * with no parameters, all JRE/JDK {@code "lib/"} or {@code "ext/"} jars will be blacklisted. * @return this (for method chaining). */ public ClassGraph blacklistLibOrExtJars(final String... jarLeafNames) { whitelistOrBlacklistLibOrExtJars(/* whitelist = */ false, jarLeafNames); return this; } /** * Whitelist one or more modules to scan. * * @param moduleNames * The names of the modules that should be scanned. May contain a wildcard glob ({@code '*'}). * @return this (for method chaining). */ public ClassGraph whitelistModules(final String... moduleNames) { for (final String moduleName : moduleNames) { scanSpec.moduleWhiteBlackList.addToWhitelist(WhiteBlackList.normalizePackageOrClassName(moduleName)); } return this; } /** * Blacklist one or more modules, preventing them from being scanned. * * @param moduleNames * The names of the modules that should not be scanned. May contain a wildcard glob ({@code '*'}). * @return this (for method chaining). */ public ClassGraph blacklistModules(final String... moduleNames) { for (final String moduleName : moduleNames) { scanSpec.moduleWhiteBlackList.addToBlacklist(WhiteBlackList.normalizePackageOrClassName(moduleName)); } return this; } /** * Whitelist classpath elements based on resource paths. Only classpath elements that contain resources with * paths matching the whitelist will be scanned. * * @param resourcePaths * The resource paths, any of which must be present in a classpath element for the classpath element * to be scanned. May contain a wildcard glob ({@code '*'}). * @return this (for method chaining). */ public ClassGraph whitelistClasspathElementsContainingResourcePath(final String... resourcePaths) { for (final String resourcePath : resourcePaths) { final String resourcePathNormalized = WhiteBlackList.normalizePath(resourcePath); scanSpec.classpathElementResourcePathWhiteBlackList.addToWhitelist(resourcePathNormalized); } return this; } /** * Blacklist classpath elements based on resource paths. Classpath elements that contain resources with paths * matching the blacklist will not be scanned. * * @param resourcePaths * The resource paths which cause a classpath not to be scanned if any are present in a classpath * element for the classpath element. May contain a wildcard glob ({@code '*'}). * @return this (for method chaining). */ public ClassGraph blacklistClasspathElementsContainingResourcePath(final String... resourcePaths) { for (final String resourcePath : resourcePaths) { final String resourcePathNormalized = WhiteBlackList.normalizePath(resourcePath); scanSpec.classpathElementResourcePathWhiteBlackList.addToBlacklist(resourcePathNormalized); } return this; } /** * Enable classpath elements to be fetched from remote ("http:"/"https:") URLs (or URLs with custom schemes). * Equivalent to: * * <p> * {@code new ClassGraph().enableURLScheme("http").enableURLScheme("https");} * * <p> * Scanning from http(s) URLs is disabled by default, as this may present a security vulnerability, since * classes from downloaded jars can be subsequently loaded using {@link ClassInfo#loadClass}. * * @return this (for method chaining). */ public ClassGraph enableRemoteJarScanning() { scanSpec.enableURLScheme("http"); scanSpec.enableURLScheme("https"); return this; } /** * Enable classpath elements to be fetched from {@link URL} connections with the specified URL scheme (also * works for any custom URL schemes that have been defined, as long as they have more than two characters, in * order to not conflict with Windows drive letters). * * @param scheme * the URL scheme string, e.g. "resource" for a custom "resource:" URL scheme. * @return this (for method chaining). */ public ClassGraph enableURLScheme(final String scheme) { scanSpec.enableURLScheme(scheme); return this; } /** * Enables the scanning of system packages ({@code "java.*"}, {@code "javax.*"}, {@code "javafx.*"}, * {@code "jdk.*"}, {@code "oracle.*"}, {@code "sun.*"}) -- these are not scanned by default for speed. * * <p> * N.B. Automatically calls {@link #enableClassInfo()}. * * @return this (for method chaining). */ public ClassGraph enableSystemJarsAndModules() { enableClassInfo(); scanSpec.enableSystemJarsAndModules = true; return this; } public ClassGraph setMaxBufferedJarRAMSize(final int maxBufferedJarRAMSize) { scanSpec.maxBufferedJarRAMSize = maxBufferedJarRAMSize; return this; } /** * If true, use a {@link MappedByteBuffer} rather than the {@link FileChannel} API to open files, which may be * faster for large classpaths consisting of many large jarfiles, but uses up virtual memory space. * * @return this (for method chaining). */ public ClassGraph enableMemoryMapping() { scanSpec.enableMemoryMapping = true; return this; } /** * Enables logging by calling {@link #verbose()}, and then sets the logger to "realtime logging mode", where log * entries are written out immediately to stderr, rather than only after the scan has completed. Can help to * identify problems where scanning is stuck in a loop, or where one scanning step is taking much longer than it * should, etc. * * @return this (for method chaining). */ public ClassGraph enableRealtimeLogging() { verbose(); LogNode.logInRealtime(true); return this; } /** A callback used to process the result of a successful asynchronous scan. */ @FunctionalInterface public interface ScanResultProcessor { /** * Process the result of an asynchronous scan after scanning has completed. * * @param scanResult * the {@link ScanResult} to process. */ void processScanResult(ScanResult scanResult); } /** A callback used to handle failure during an asynchronous scan. */ @FunctionalInterface public interface FailureHandler { /** * Called on scanning failure during an asynchronous scan. * * @param throwable * the {@link Throwable} that was thrown during scanning. */ void onFailure(Throwable throwable); } /** * Asynchronously scans the classpath, calling a {@link ScanResultProcessor} callback on success or a * {@link FailureHandler} callback on failure. * * @param executorService * A custom {@link ExecutorService} to use for scheduling worker tasks. * @param numParallelTasks * The number of parallel tasks to break the work into during the most CPU-intensive stage of * classpath scanning. Ideally the ExecutorService will have at least this many threads available. * @param scanResultProcessor * A {@link ScanResultProcessor} callback to run on successful scan. * @param failureHandler * A {@link FailureHandler} callback to run on failed scan. This is passed any {@link Throwable} * thrown during the scan. */ public void scanAsync(final ExecutorService executorService, final int numParallelTasks, final ScanResultProcessor scanResultProcessor, final FailureHandler failureHandler) { if (scanResultProcessor == null) { // If scanResultProcessor is null, the scan won't do anything after completion, and the ScanResult will // simply be lost. throw new IllegalArgumentException("scanResultProcessor cannot be null"); } if (failureHandler == null) { // The result of the Future<ScanObject> object returned by launchAsyncScan is discarded below, so we // force the addition of a FailureHandler so that exceptions are not silently swallowed. throw new IllegalArgumentException("failureHandler cannot be null"); } // Use execute() rather than submit(), since a ScanResultProcessor and FailureHandler are used executorService.execute(new Runnable() { @Override public void run() { try { // Call scanner, but ignore the returned ScanResult new Scanner(/* performScan = */ true, scanSpec, executorService, numParallelTasks, scanResultProcessor, failureHandler, topLevelLog).call(); } catch (final InterruptedException | CancellationException | ExecutionException e) { // Call failure handler failureHandler.onFailure(e); } } }); } /** * Asynchronously scans the classpath for matching files, returning a {@code Future<ScanResult>}. You should * assign the wrapped {@link ScanResult} in a try-with-resources statement, or manually close it when you are * finished with it. * * @param performScan * If true, performing a scan. If false, only fetching the classpath. * @param executorService * A custom {@link ExecutorService} to use for scheduling worker tasks. * @param numParallelTasks * The number of parallel tasks to break the work into during the most CPU-intensive stage of * classpath scanning. Ideally the ExecutorService will have at least this many threads available. * @return a {@code Future<ScanResult>}, that when resolved using get() yields a new {@link ScanResult} object * representing the result of the scan. */ private Future<ScanResult> scanAsync(final boolean performScan, final ExecutorService executorService, final int numParallelTasks) { try { return executorService.submit(new Scanner(performScan, scanSpec, executorService, numParallelTasks, /* scanResultProcessor = */ null, /* failureHandler = */ null, topLevelLog)); } catch (final InterruptedException e) { // Interrupted during the Scanner constructor's execution (specifically, by getModuleOrder(), // which is unlikely to ever actually be interrupted -- but this exception needs to be caught). return executorService.submit(new Callable<ScanResult>() { @Override public ScanResult call() throws Exception { throw e; } }); } } /** * Asynchronously scans the classpath for matching files, returning a {@code Future<ScanResult>}. You should * assign the wrapped {@link ScanResult} in a try-with-resources statement, or manually close it when you are * finished with it. * * @param executorService * A custom {@link ExecutorService} to use for scheduling worker tasks. * @param numParallelTasks * The number of parallel tasks to break the work into during the most CPU-intensive stage of * classpath scanning. Ideally the ExecutorService will have at least this many threads available. * @return a {@code Future<ScanResult>}, that when resolved using get() yields a new {@link ScanResult} object * representing the result of the scan. */ public Future<ScanResult> scanAsync(final ExecutorService executorService, final int numParallelTasks) { return scanAsync(/* performScan = */ true, executorService, numParallelTasks); } /** * Scans the classpath using the requested {@link ExecutorService} and the requested degree of parallelism, * blocking until the scan is complete. You should assign the returned {@link ScanResult} in a * try-with-resources statement, or manually close it when you are finished with it. * * @param executorService * A custom {@link ExecutorService} to use for scheduling worker tasks. This {@link ExecutorService} * should start tasks in FIFO order to avoid a deadlock during scan, i.e. be sure to construct the * {@link ExecutorService} with a {@link LinkedBlockingQueue} as its task queue. (This is the default * for {@link Executors#newFixedThreadPool(int)}.) * @param numParallelTasks * The number of parallel tasks to break the work into during the most CPU-intensive stage of * classpath scanning. Ideally the ExecutorService will have at least this many threads available. * @return a {@link ScanResult} object representing the result of the scan. * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ public ScanResult scan(final ExecutorService executorService, final int numParallelTasks) { try { // Start the scan and wait for completion // Return the scanResult, then block waiting for the result final ScanResult scanResult = scanAsync(executorService, numParallelTasks).get(); // // Test serialization/deserialization by serializing and then deserializing the ScanResult // if (scanSpec.enableClassInfo && scanSpec.performScan) { // final String scanResultJson = scanResult.toJSON(2); // final ScanResult scanResultFromJson = ScanResult.fromJSON(scanResultJson); // final String scanResultJson2 = scanResult.toJSON(2); // if (!scanResultJson2.equals(scanResultJson)) { // throw new RuntimeException("Serialization mismatch"); // scanResult = scanResultFromJson; // The resulting scanResult cannot be null, but check for null to keep SpotBugs happy if (scanResult == null) { throw new NullPointerException(); } return scanResult; } catch (final InterruptedException | CancellationException e) { throw ClassGraphException.newClassGraphException("Scan interrupted", e); } catch (final ExecutionException e) { throw ClassGraphException.newClassGraphException("Uncaught exception during scan", InterruptionChecker.getCause(e)); } } /** * Scans the classpath with the requested number of threads, blocking until the scan is complete. You should * assign the returned {@link ScanResult} in a try-with-resources statement, or manually close it when you are * finished with it. * * @param numThreads * The number of worker threads to start up. * @return a {@link ScanResult} object representing the result of the scan. * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ public ScanResult scan(final int numThreads) { try (AutoCloseableExecutorService executorService = new AutoCloseableExecutorService(numThreads)) { return scan(executorService, numThreads); } } /** * Scans the classpath, blocking until the scan is complete. You should assign the returned {@link ScanResult} * in a try-with-resources statement, or manually close it when you are finished with it. * * @return a {@link ScanResult} object representing the result of the scan. * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ public ScanResult scan() { return scan(DEFAULT_NUM_WORKER_THREADS); } /** * Get a {@link ScanResult} that can be used for determining the classpath. * * @param executorService * The executor service. * @return a {@link ScanResult} object representing the result of the scan (can only be used for determining * classpath). * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ ScanResult getClasspathScanResult(final AutoCloseableExecutorService executorService) { try { final ScanResult scanResult = scanAsync(/* performScan = */ false, executorService, DEFAULT_NUM_WORKER_THREADS).get(); // The resulting scanResult cannot be null, but check for null to keep SpotBugs happy if (scanResult == null) { throw new NullPointerException(); } return scanResult; } catch (final InterruptedException | CancellationException e) { throw ClassGraphException.newClassGraphException("Scan interrupted", e); } catch (final ExecutionException e) { throw ClassGraphException.newClassGraphException("Uncaught exception during scan", InterruptionChecker.getCause(e)); } } /** * Returns the list of all unique File objects representing directories or zip/jarfiles on the classpath, in * classloader resolution order. Classpath elements that do not exist as a file or directory are not included in * the returned list. * * @return a {@code List<File>} consisting of the unique directories and jarfiles on the classpath, in classpath * resolution order. * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ public List<File> getClasspathFiles() { try (AutoCloseableExecutorService executorService = new AutoCloseableExecutorService( DEFAULT_NUM_WORKER_THREADS); ScanResult scanResult = getClasspathScanResult(executorService)) { return scanResult.getClasspathFiles(); } } /** * Returns the list of all unique File objects representing directories or zip/jarfiles on the classpath, in * classloader resolution order, in the form of a classpath path string. Classpath elements that do not exist as * a file or directory are not included in the returned list. Note that the returned string contains only base * files, and does not include package roots or nested jars within jars, since the path separator (':') * conflicts with the URL scheme separator character (also ':') on Linux and Mac OS X. Call * {@link #getClasspathURIs()} to get the full URIs for classpath elements and modules. * * @return a classpath path string consisting of the unique directories and jarfiles on the classpath, in * classpath resolution order. * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ public String getClasspath() { return JarUtils.pathElementsToPathStr(getClasspathFiles()); } /** * Returns the ordered list of all unique {@link URI} objects representing directory/jar classpath elements and * modules. Classpath elements representing jarfiles or directories that do not exist are not included in the * returned list. * * @return the unique classpath elements and modules, as a list of {@link URI} objects. * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ public List<URI> getClasspathURIs() { try (AutoCloseableExecutorService executorService = new AutoCloseableExecutorService( DEFAULT_NUM_WORKER_THREADS); ScanResult scanResult = getClasspathScanResult(executorService)) { return scanResult.getClasspathURIs(); } } /** * Returns the ordered list of all unique {@link URL} objects representing directory/jar classpath elements and * modules. Classpath elements representing jarfiles or directories that do not exist, as well as modules with * unknown (null) location or with {@code jrt:} location URI scheme, are not included in the returned list. * * @return the unique classpath elements and modules, as a list of {@link URL} objects. * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ public List<URL> getClasspathURLs() { try (AutoCloseableExecutorService executorService = new AutoCloseableExecutorService( DEFAULT_NUM_WORKER_THREADS); ScanResult scanResult = getClasspathScanResult(executorService)) { return scanResult.getClasspathURLs(); } } /** * Returns {@link ModuleRef} references for all the visible modules. * * @return a list of {@link ModuleRef} references for all the visible modules. * @throws ClassGraphException * if any of the worker threads throws an uncaught exception, or the scan was interrupted. */ public List<ModuleRef> getModules() { try (AutoCloseableExecutorService executorService = new AutoCloseableExecutorService( DEFAULT_NUM_WORKER_THREADS); ScanResult scanResult = getClasspathScanResult(executorService)) { return scanResult.getModules(); } } /** * Get the module path info provided on the commandline with {@code --module-path}, {@code --add-modules}, * {@code --patch-module}, {@code --add-exports}, {@code --add-opens}, and {@code --add-reads}. * * <p> * Note that the returned {@link ModulePathInfo} object does not include classpath entries from the traditional * classpath or system modules. Use {@link #getModules()} to get all visible modules, including anonymous, * automatic and system modules. * * <p> * Also, {@link ModulePathInfo#addExports} and {@link ModulePathInfo#addOpens} will not contain * {@code Add-Exports} or {@code Add-Opens} entries from jarfile manifest files encountered during scanning, * unless you obtain the {@link ModulePathInfo} by calling {@link ScanResult#getModulePathInfo()} rather than by * calling {@link ClassGraph#getModulePathInfo()} before {@link ClassGraph#scan()}. * * @return The {@link ModulePathInfo}. */ public ModulePathInfo getModulePathInfo() { return scanSpec.modulePathInfo; } }
package io.github.classgraph; import java.io.Closeable; import java.io.File; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import nonapi.io.github.classgraph.classpath.ClasspathFinder; import nonapi.io.github.classgraph.concurrency.AutoCloseableExecutorService; import nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler; import nonapi.io.github.classgraph.json.JSONDeserializer; import nonapi.io.github.classgraph.json.JSONSerializer; import nonapi.io.github.classgraph.scanspec.AcceptReject; import nonapi.io.github.classgraph.scanspec.ScanSpec; import nonapi.io.github.classgraph.utils.Assert; import nonapi.io.github.classgraph.utils.CollectionUtils; import nonapi.io.github.classgraph.utils.FileUtils; import nonapi.io.github.classgraph.utils.JarUtils; import nonapi.io.github.classgraph.utils.LogNode; /** * The result of a scan. You should assign a ScanResult in a try-with-resources block, or manually close it when you * have finished with the result of a scan. */ public final class ScanResult implements Closeable, AutoCloseable { /** The order of raw classpath elements. */ private List<String> rawClasspathEltOrderStrs; /** The order of classpath elements, after inner jars have been extracted to temporary files, etc. */ private List<ClasspathElement> classpathOrder; /** A list of all files that were found in accepted packages. */ private ResourceList allAcceptedResourcesCached; /** The number of times {@link #getResourcesWithPath(String)} has been called. */ private final AtomicInteger getResourcesWithPathCallCount = new AtomicInteger(); /** * The map from path (relative to package root) to a list of {@link Resource} elements with the matching path. */ private Map<String, ResourceList> pathToAcceptedResourcesCached; /** The map from class name to {@link ClassInfo}. */ Map<String, ClassInfo> classNameToClassInfo; /** The map from package name to {@link PackageInfo}. */ private Map<String, PackageInfo> packageNameToPackageInfo; /** The map from class name to {@link ClassInfo}. */ private Map<String, ModuleInfo> moduleNameToModuleInfo; /** * The file, directory and jarfile resources timestamped during a scan, along with their timestamp at the time * of the scan. For jarfiles, the timestamp represents the timestamp of all files within the jar. May be null, * if this ScanResult object is the result of a call to ClassGraph#getUniqueClasspathElementsAsync(). */ private Map<File, Long> fileToLastModified; /** If true, this {@link ScanResult} was produced by {@link ScanResult#fromJSON(String)}. */ private boolean isObtainedFromDeserialization; /** A custom ClassLoader that can load classes found during the scan. */ private ClassGraphClassLoader classGraphClassLoader; /** The {@link ClasspathFinder}. */ ClasspathFinder classpathFinder; /** The nested jar handler instance. */ private NestedJarHandler nestedJarHandler; /** The scan spec. */ ScanSpec scanSpec; /** If true, this ScanResult has already been closed. */ private final AtomicBoolean closed = new AtomicBoolean(false); /** The toplevel log. */ private final LogNode topLevelLog; /** The {@link WeakReference} for this ScanResult. */ private final WeakReference<ScanResult> weakReference; /** * The set of WeakReferences to non-closed ScanResult objects. Uses WeakReferences so that garbage collection is * not blocked. (Bug #233) */ private static Set<WeakReference<ScanResult>> nonClosedWeakReferences = Collections .newSetFromMap(new ConcurrentHashMap<WeakReference<ScanResult>, Boolean>()); /** If true, ScanResult#staticInit() has been run. */ private static final AtomicBoolean initialized = new AtomicBoolean(false); /** The current serialization format. */ private static final String CURRENT_SERIALIZATION_FORMAT = "10"; /** A class to hold a serialized ScanResult along with the ScanSpec that was used to scan. */ private static class SerializationFormat { /** The serialization format. */ public String format; /** The scan spec. */ public ScanSpec scanSpec; /** The classpath, as a list of URL strings. */ public List<String> classpath; /** The list of all {@link ClassInfo} objects. */ public List<ClassInfo> classInfo; /** The list of all {@link PackageInfo} objects. */ public List<PackageInfo> packageInfo; /** The list of all {@link ModuleInfo} objects. */ public List<ModuleInfo> moduleInfo; /** * Constructor. */ @SuppressWarnings("unused") public SerializationFormat() { // Empty } /** * Constructor. * * @param serializationFormatStr * the serialization format string * @param scanSpec * the scan spec * @param classInfo * the list of all {@link ClassInfo} objects * @param packageInfo * the list of all {@link PackageInfo} objects * @param moduleInfo * the list of all {@link ModuleInfo} objects * @param classpath * the classpath as a list of URL strings */ public SerializationFormat(final String serializationFormatStr, final ScanSpec scanSpec, final List<ClassInfo> classInfo, final List<PackageInfo> packageInfo, final List<ModuleInfo> moduleInfo, final List<String> classpath) { this.format = serializationFormatStr; this.scanSpec = scanSpec; this.classpath = classpath; this.classInfo = classInfo; this.packageInfo = packageInfo; this.moduleInfo = moduleInfo; } } // Shutdown hook init code /** * Static initialization (warm up classloading), called when the ClassGraph class is initialized. */ static void init() { if (!initialized.getAndSet(true)) { // Pre-load non-system classes necessary for calling scanResult.close(), so that classes that need // to be loaded to close resources are already loaded and cached. This was originally for use in // a shutdown hook (#331), which has now been removed, but it is probably still a good idea to // ensure that classes needed to unmap DirectByteBuffer instances are available at init. // We achieve this by mmap'ing a file and then closing it, since the only problematic classes are // the PriviledgedAction anonymous inner classes used by FileUtils::closeDirectByteBuffer. FileUtils.closeDirectByteBuffer(ByteBuffer.allocateDirect(32), /* log = */ null); } } // Constructor /** * The result of a scan. Make sure you call complete() after calling the constructor. * * @param scanSpec * the scan spec * @param classpathOrder * the classpath order * @param rawClasspathEltOrderStrs * the raw classpath element order * @param classpathFinder * the {@link ClasspathFinder} * @param classNameToClassInfo * a map from class name to class info * @param packageNameToPackageInfo * a map from package name to package info * @param moduleNameToModuleInfo * a map from module name to module info * @param fileToLastModified * a map from file to last modified time * @param nestedJarHandler * the nested jar handler * @param topLevelLog * the toplevel log */ ScanResult(final ScanSpec scanSpec, final List<ClasspathElement> classpathOrder, final List<String> rawClasspathEltOrderStrs, final ClasspathFinder classpathFinder, final Map<String, ClassInfo> classNameToClassInfo, final Map<String, PackageInfo> packageNameToPackageInfo, final Map<String, ModuleInfo> moduleNameToModuleInfo, final Map<File, Long> fileToLastModified, final NestedJarHandler nestedJarHandler, final LogNode topLevelLog) { this.scanSpec = scanSpec; this.rawClasspathEltOrderStrs = rawClasspathEltOrderStrs; this.classpathOrder = classpathOrder; this.classpathFinder = classpathFinder; this.fileToLastModified = fileToLastModified; this.classNameToClassInfo = classNameToClassInfo; this.packageNameToPackageInfo = packageNameToPackageInfo; this.moduleNameToModuleInfo = moduleNameToModuleInfo; this.nestedJarHandler = nestedJarHandler; this.topLevelLog = topLevelLog; if (classNameToClassInfo != null) { indexResourcesAndClassInfo(topLevelLog); } if (classNameToClassInfo != null) { // Handle @Repeatable annotations final Set<String> allRepeatableAnnotationNames = new HashSet<>(); for (final ClassInfo classInfo : classNameToClassInfo.values()) { if (classInfo.isAnnotation() && classInfo.annotationInfo != null) { final AnnotationInfo repeatableMetaAnnotation = classInfo.annotationInfo .get("java.lang.annotation.Repeatable"); if (repeatableMetaAnnotation != null) { final AnnotationParameterValueList vals = repeatableMetaAnnotation.getParameterValues(); if (!vals.isEmpty()) { final Object val = vals.getValue("value"); if (val instanceof AnnotationClassRef) { final AnnotationClassRef classRef = (AnnotationClassRef) val; final String repeatableAnnotationName = classRef.getName(); if (repeatableAnnotationName != null) { allRepeatableAnnotationNames.add(repeatableAnnotationName); } } } } } } if (!allRepeatableAnnotationNames.isEmpty()) { for (final ClassInfo classInfo : classNameToClassInfo.values()) { classInfo.handleRepeatableAnnotations(allRepeatableAnnotationNames); } } } // Define a new ClassLoader that can load the classes found during the scan this.classGraphClassLoader = new ClassGraphClassLoader(this); // Provide the shutdown hook with a weak reference to this ScanResult this.weakReference = new WeakReference<>(this); nonClosedWeakReferences.add(this.weakReference); } /** * Index {@link Resource} and {@link ClassInfo} objects. * * @param log * the log */ private void indexResourcesAndClassInfo(final LogNode log) { // Add backrefs from Info objects back to this ScanResult final Collection<ClassInfo> allClassInfo = classNameToClassInfo.values(); for (final ClassInfo classInfo : allClassInfo) { classInfo.setScanResult(this); } // If inter-class dependencies are enabled, create placeholder ClassInfo objects for any referenced // classes that were not scanned if (scanSpec.enableInterClassDependencies) { for (final ClassInfo ci : new ArrayList<>(classNameToClassInfo.values())) { final Set<ClassInfo> refdClassesFiltered = new HashSet<>(); for (final ClassInfo refdClassInfo : ci.findReferencedClassInfo(log)) { // Don't add self-references, or references to Object if (refdClassInfo != null && !ci.equals(refdClassInfo) && !refdClassInfo.getName().equals("java.lang.Object") // Only add class to result if it is accepted, or external classes are enabled && (!refdClassInfo.isExternalClass() || scanSpec.enableExternalClasses)) { refdClassInfo.setScanResult(this); refdClassesFiltered.add(refdClassInfo); } } ci.setReferencedClasses(new ClassInfoList(refdClassesFiltered, /* sortByName = */ true)); } } } // Classpath / module path /** * Returns the list of File objects for unique classpath elements (directories or jarfiles), in classloader * resolution order. * * @return The unique classpath elements. */ public List<File> getClasspathFiles() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final List<File> classpathElementOrderFiles = new ArrayList<>(); for (final ClasspathElement classpathElement : classpathOrder) { final File file = classpathElement.getFile(); if (file != null) { classpathElementOrderFiles.add(file); } } return classpathElementOrderFiles; } /** * Returns all unique directories or zip/jarfiles on the classpath, in classloader resolution order, as a * classpath string, delineated with the standard path separator character. * * @return a the unique directories and jarfiles on the classpath, in classpath resolution order, as a path * string. */ public String getClasspath() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } return JarUtils.pathElementsToPathStr(getClasspathFiles()); } /** * Returns an ordered list of unique classpath element and module URIs. * * @return The unique classpath element and module URIs. */ public List<URI> getClasspathURIs() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final List<URI> classpathElementOrderURIs = new ArrayList<>(); for (final ClasspathElement classpathElement : classpathOrder) { try { for (final URI uri : classpathElement.getAllURIs()) { if (uri != null) { classpathElementOrderURIs.add(uri); } } } catch (final IllegalArgumentException e) { // Skip null location URIs } } return classpathElementOrderURIs; } /** * Returns an ordered list of unique classpath element and module URLs. Will skip any system modules or modules * that are part of a jlink'd runtime image, since {@link URL} does not support the {@code jrt:} {@link URI} * scheme. * * @return The unique classpath element and module URLs. */ public List<URL> getClasspathURLs() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final List<URL> classpathElementOrderURLs = new ArrayList<>(); for (final URI uri : getClasspathURIs()) { try { classpathElementOrderURLs.add(uri.toURL()); } catch (final IllegalArgumentException | MalformedURLException e) { // Skip "jrt:" URIs and malformed URLs } } return classpathElementOrderURLs; } /** * Get {@link ModuleRef} references for all visible modules. * * @return {@link ModuleRef} references for all visible modules. */ public List<ModuleRef> getModules() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final List<ModuleRef> moduleRefs = new ArrayList<>(); for (final ClasspathElement classpathElement : classpathOrder) { if (classpathElement instanceof ClasspathElementModule) { moduleRefs.add(((ClasspathElementModule) classpathElement).getModuleRef()); } } return moduleRefs; } /** * Get the module path info provided on the commandline with {@code --module-path}, {@code --add-modules}, * {@code --patch-module}, {@code --add-exports}, {@code --add-opens}, and {@code --add-reads}, and also the * {@code Add-Exports} and {@code Add-Opens} entries from jarfile manifest files encountered during scanning. * * <p> * Note that the returned {@link ModulePathInfo} object does not include classpath entries from the traditional * classpath or system modules. Use {@link #getModules()} to get all visible modules, including anonymous, * automatic and system modules. * * @return The {@link ModulePathInfo}. */ public ModulePathInfo getModulePathInfo() { return scanSpec.modulePathInfo; } // Resources /** * Get the list of all resources. * * @return A list of all resources (including classfiles and non-classfiles) found in accepted packages. */ public ResourceList getAllResources() { if (allAcceptedResourcesCached == null) { // Index Resource objects by path final ResourceList acceptedResourcesList = new ResourceList(); for (final ClasspathElement classpathElt : classpathOrder) { acceptedResourcesList.addAll(classpathElt.acceptedResources); } // Set atomically for thread safety allAcceptedResourcesCached = acceptedResourcesList; } return allAcceptedResourcesCached; } /** * Get a map from resource path to {@link Resource} for all resources (including classfiles and non-classfiles) * found in accepted packages. * * @return The map from resource path to {@link Resource} for all resources (including classfiles and * non-classfiles) found in accepted packages. */ public Map<String, ResourceList> getAllResourcesAsMap() { if (pathToAcceptedResourcesCached == null) { final Map<String, ResourceList> pathToAcceptedResourceListMap = new HashMap<>(); for (final Resource res : getAllResources()) { ResourceList resList = pathToAcceptedResourceListMap.get(res.getPath()); if (resList == null) { pathToAcceptedResourceListMap.put(res.getPath(), resList = new ResourceList()); } resList.add(res); } // Set atomically for thread safety pathToAcceptedResourcesCached = pathToAcceptedResourceListMap; } return pathToAcceptedResourcesCached; } /** * Get the list of all resources found in accepted packages that have the given path, relative to the package * root of the classpath element. May match several resources, up to one per classpath element. * * @param resourcePath * A complete resource path, relative to the classpath entry package root. * @return A list of all resources found in accepted packages that have the given path, relative to the package * root of the classpath element. May match several resources, up to one per classpath element. */ public ResourceList getResourcesWithPath(final String resourcePath) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final String path = FileUtils.sanitizeEntryPath(resourcePath, /* removeInitialSlash = */ true, /* removeFinalSlash = */ true); if (getResourcesWithPathCallCount.incrementAndGet() > 3) { // If numerous calls are made, produce and cache a single HashMap for O(1) access time return getAllResourcesAsMap().get(path); } else { // If just a few calls are made, directly search for resource with the requested path ResourceList matchingResources = null; for (final ClasspathElement classpathElt : classpathOrder) { for (final Resource res : classpathElt.acceptedResources) { if (res.getPath().equals(path)) { if (matchingResources == null) { matchingResources = new ResourceList(); } matchingResources.add(res); } } } return matchingResources == null ? ResourceList.EMPTY_LIST : matchingResources; } } /** * Get the list of all resources found in any classpath element, <i>whether in accepted packages or not (as long * as the resource is not rejected)</i>, that have the given path, relative to the package root of the classpath * element. May match several resources, up to one per classpath element. Note that this may not return a * non-accepted resource, particularly when scanning directory classpath elements, because recursive scanning * terminates once there are no possible accepted resources below a given directory. However, resources in * ancestral directories of accepted directories can be found using this method. * * @param resourcePath * A complete resource path, relative to the classpath entry package root. * @return A list of all resources found in any classpath element, <i>whether in accepted packages or not (as * long as the resource is not rejected)</i>, that have the given path, relative to the package root of * the classpath element. May match several resources, up to one per classpath element. */ public ResourceList getResourcesWithPathIgnoringAccept(final String resourcePath) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final String path = FileUtils.sanitizeEntryPath(resourcePath, /* removeInitialSlash = */ true, /* removeFinalSlash = */ true); final ResourceList matchingResources = new ResourceList(); for (final ClasspathElement classpathElt : classpathOrder) { final Resource matchingResource = classpathElt.getResource(path); if (matchingResource != null) { matchingResources.add(matchingResource); } } return matchingResources; } /** * Use {@link #getResourcesWithPathIgnoringAccept(String)} instead. * * @param resourcePath * A complete resource path, relative to the classpath entry package root. * @return A list of all resources found in any classpath element, <i>whether in accepted packages or not (as * long as the resource is not rejected)</i>, that have the given path, relative to the package root of * the classpath element. May match several resources, up to one per classpath element. * @deprecated Use {@link #getResourcesWithPathIgnoringAccept(String)} instead. */ @Deprecated public ResourceList getResourcesWithPathIgnoringWhitelist(final String resourcePath) { return getResourcesWithPathIgnoringAccept(resourcePath); } /** * Get the list of all resources found in accepted packages that have the requested leafname. * * @param leafName * A resource leaf filename. * @return A list of all resources found in accepted packages that have the requested leafname. */ public ResourceList getResourcesWithLeafName(final String leafName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final ResourceList allAcceptedResources = getAllResources(); if (allAcceptedResources.isEmpty()) { return ResourceList.EMPTY_LIST; } else { final ResourceList filteredResources = new ResourceList(); for (final Resource classpathResource : allAcceptedResources) { final String relativePath = classpathResource.getPath(); final int lastSlashIdx = relativePath.lastIndexOf('/'); if (relativePath.substring(lastSlashIdx + 1).equals(leafName)) { filteredResources.add(classpathResource); } } return filteredResources; } } /** * Get the list of all resources found in accepted packages that have the requested filename extension. * * @param extension * A filename extension, e.g. "xml" to match all resources ending in ".xml". * @return A list of all resources found in accepted packages that have the requested filename extension. */ public ResourceList getResourcesWithExtension(final String extension) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final ResourceList allAcceptedResources = getAllResources(); if (allAcceptedResources.isEmpty()) { return ResourceList.EMPTY_LIST; } else { String bareExtension = extension; while (bareExtension.startsWith(".")) { bareExtension = bareExtension.substring(1); } final ResourceList filteredResources = new ResourceList(); for (final Resource classpathResource : allAcceptedResources) { final String relativePath = classpathResource.getPath(); final int lastSlashIdx = relativePath.lastIndexOf('/'); final int lastDotIdx = relativePath.lastIndexOf('.'); if (lastDotIdx > lastSlashIdx && relativePath.substring(lastDotIdx + 1).equalsIgnoreCase(bareExtension)) { filteredResources.add(classpathResource); } } return filteredResources; } } /** * Get the list of all resources found in accepted packages that have a path matching the requested regexp * pattern. See also {{@link #getResourcesMatchingWildcard(String)}. * * @param pattern * A pattern to match {@link Resource} paths with. * @return A list of all resources found in accepted packages that have a path matching the requested pattern. */ public ResourceList getResourcesMatchingPattern(final Pattern pattern) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final ResourceList allAcceptedResources = getAllResources(); if (allAcceptedResources.isEmpty()) { return ResourceList.EMPTY_LIST; } else { final ResourceList filteredResources = new ResourceList(); for (final Resource classpathResource : allAcceptedResources) { final String relativePath = classpathResource.getPath(); if (pattern.matcher(relativePath).matches()) { filteredResources.add(classpathResource); } } return filteredResources; } } /** * Get the list of all resources found in accepted packages that have a path matching the requested wildcard * string. The wildcard string may contain globs (asterisk wildcards). No other character has a special meaning. * * <p> * The wildcard string is translated in a simplistic way into a regex. If you need more complex pattern * matching, use a regex directly, via {@link #getResourcesMatchingPattern(Pattern)}. * * @param wildcardString * A wildcard (glob) pattern to match {@link Resource} paths with. * @return A list of all resources found in accepted packages that have a path matching the requested wildcard * string. */ public ResourceList getResourcesMatchingWildcard(final String wildcardString) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } return getResourcesMatchingPattern(AcceptReject.globToPattern(wildcardString)); } // Modules /** * Get the {@link ModuleInfo} object for the named module, or null if no module of the requested name was found * during the scan. * * @param moduleName * The module name. * @return The {@link ModuleInfo} object for the named module, or null if the module was not found. */ public ModuleInfo getModuleInfo(final String moduleName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return moduleNameToModuleInfo.get(moduleName); } /** * Get all modules found during the scan. * * @return A list of all modules found during the scan, or the empty list if none. */ public ModuleInfoList getModuleInfo() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return new ModuleInfoList(moduleNameToModuleInfo.values()); } // Packages /** * Get the {@link PackageInfo} object for the named package, or null if no package of the requested name was * found during the scan. * * @param packageName * The package name. * @return The {@link PackageInfo} object for the named package, or null if the package was not found. */ public PackageInfo getPackageInfo(final String packageName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return packageNameToPackageInfo.get(packageName); } /** * Get all packages found during the scan. * * @return A list of all packages found during the scan, or the empty list if none. */ public PackageInfoList getPackageInfo() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return new PackageInfoList(packageNameToPackageInfo.values()); } // Class dependencies /** * Get a map from the {@link ClassInfo} object for each accepted class to a list of the classes referenced by * that class (i.e. returns a map from dependents to dependencies). Note that you need to call * {@link ClassGraph#enableInterClassDependencies()} before {@link ClassGraph#scan()} for this method to work. * You should also call {@link ClassGraph#enableExternalClasses()} before {@link ClassGraph#scan()} if you want * non-accepted classes to appear in the result. See also {@link #getReverseClassDependencyMap()}, which inverts * the map. * * @return A map from a {@link ClassInfo} object for each accepted class to a list of the classes referenced by * that class (i.e. returns a map from dependents to dependencies). Each map value is the result of * calling {@link ClassInfo#getClassDependencies()} on the corresponding key. */ public Map<ClassInfo, ClassInfoList> getClassDependencyMap() { final Map<ClassInfo, ClassInfoList> map = new HashMap<>(); for (final ClassInfo ci : getAllClasses()) { map.put(ci, ci.getClassDependencies()); } return map; } /** * Get the reverse class dependency map, i.e. a map from the {@link ClassInfo} object for each dependency class * (accepted or not) to a list of the accepted classes that referenced that class as a dependency (i.e. returns * a map from dependencies to dependents). Note that you need to call * {@link ClassGraph#enableInterClassDependencies()} before {@link ClassGraph#scan()} for this method to work. * You should also call {@link ClassGraph#enableExternalClasses()} before {@link ClassGraph#scan()} if you want * non-accepted classes to appear in the result. See also {@link #getClassDependencyMap}. * * @return A map from a {@link ClassInfo} object for each dependency class (accepted or not) to a list of the * accepted classes that referenced that class as a dependency (i.e. returns a map from dependencies to * dependents). */ public Map<ClassInfo, ClassInfoList> getReverseClassDependencyMap() { final Map<ClassInfo, Set<ClassInfo>> revMapSet = new HashMap<>(); for (final ClassInfo ci : getAllClasses()) { for (final ClassInfo dep : ci.getClassDependencies()) { Set<ClassInfo> set = revMapSet.get(dep); if (set == null) { revMapSet.put(dep, set = new HashSet<>()); } set.add(ci); } } final Map<ClassInfo, ClassInfoList> revMapList = new HashMap<>(); for (final Entry<ClassInfo, Set<ClassInfo>> ent : revMapSet.entrySet()) { revMapList.put(ent.getKey(), new ClassInfoList(ent.getValue(), /* sortByName = */ true)); } return revMapList; } // Classes /** * Get the {@link ClassInfo} object for the named class, or null if no class of the requested name was found in * an accepted/non-rejected package during the scan. * * @param className * The class name. * @return The {@link ClassInfo} object for the named class, or null if the class was not found. */ public ClassInfo getClassInfo(final String className) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return classNameToClassInfo.get(className); } /** * Get all classes, interfaces and annotations found during the scan. * * @return A list of all accepted classes found during the scan, or the empty list if none. */ public ClassInfoList getAllClasses() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return ClassInfo.getAllClasses(classNameToClassInfo.values(), scanSpec); } /** * Get all {@link Enum} classes found during the scan. * * @return A list of all {@link Enum} classes found during the scan, or the empty list if none. */ public ClassInfoList getAllEnums() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return ClassInfo.getAllEnums(classNameToClassInfo.values(), scanSpec); } /** * Get all {@code record} classes found during the scan (JDK 14+). * * @return A list of all {@code record} classes found during the scan, or the empty list if none. */ public ClassInfoList getAllRecords() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return ClassInfo.getAllRecords(classNameToClassInfo.values(), scanSpec); } /** * Get a map from class name to {@link ClassInfo} object for all classes, interfaces and annotations found * during the scan. * * @return The map from class name to {@link ClassInfo} object for all classes, interfaces and annotations found * during the scan. */ public Map<String, ClassInfo> getAllClassesAsMap() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return classNameToClassInfo; } /** * Get all standard (non-interface/non-annotation) classes found during the scan. * * @return A list of all accepted standard classes found during the scan, or the empty list if none. */ public ClassInfoList getAllStandardClasses() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return ClassInfo.getAllStandardClasses(classNameToClassInfo.values(), scanSpec); } /** * Get all subclasses of the superclass. * * @param superclass * The superclass. * @return A list of subclasses of the superclass, or the empty list if none. */ public ClassInfoList getSubclasses(final Class<?> superclass) { return getSubclasses(superclass.getName()); } /** * Get all subclasses of the named superclass. * * @param superclassName * The name of the superclass. * @return A list of subclasses of the named superclass, or the empty list if none. */ public ClassInfoList getSubclasses(final String superclassName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } if (superclassName.equals("java.lang.Object")) { // Return all standard classes (interfaces don't extend Object) return getAllStandardClasses(); } else { final ClassInfo superclass = classNameToClassInfo.get(superclassName); return superclass == null ? ClassInfoList.EMPTY_LIST : superclass.getSubclasses(); } } /** * Get superclasses of the named subclass. * * @param subclassName * The name of the subclass. * @return A list of superclasses of the named subclass, or the empty list if none. */ public ClassInfoList getSuperclasses(final String subclassName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } final ClassInfo subclass = classNameToClassInfo.get(subclassName); return subclass == null ? ClassInfoList.EMPTY_LIST : subclass.getSuperclasses(); } /** * Get superclasses of the subclass. * * @param subclass * The subclass. * @return A list of superclasses of the named subclass, or the empty list if none. */ public ClassInfoList getSuperclasses(final Class<?> subclass) { return getSuperclasses(subclass.getName()); } /** * Get classes that have a method with an annotation of the named type. * * @param methodAnnotation * the method annotation. * @return A list of classes with a method that has an annotation of the named type, or the empty list if none. */ public ClassInfoList getClassesWithMethodAnnotation(final Class<? extends Annotation> methodAnnotation) { Assert.isAnnotation(methodAnnotation); return getClassesWithMethodAnnotation(methodAnnotation.getName()); } /** * Get classes that have a method with an annotation of the named type. * * @param methodAnnotationName * the name of the method annotation. * @return A list of classes with a method that has an annotation of the named type, or the empty list if none. */ public ClassInfoList getClassesWithMethodAnnotation(final String methodAnnotationName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableMethodInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo(), #enableMethodInfo(), " + "and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(methodAnnotationName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithMethodAnnotation(); } /** * Get classes that have a method with a parameter that is annotated with an annotation of the named type. * * @param methodParameterAnnotation * the method parameter annotation. * @return A list of classes that have a method with a parameter annotated with the named annotation type, or * the empty list if none. */ public ClassInfoList getClassesWithMethodParameterAnnotation( final Class<? extends Annotation> methodParameterAnnotation) { Assert.isAnnotation(methodParameterAnnotation); return getClassesWithMethodParameterAnnotation(methodParameterAnnotation.getName()); } /** * Get classes that have a method with a parameter that is annotated with an annotation of the named type. * * @param methodParameterAnnotationName * the name of the method parameter annotation. * @return A list of classes that have a method with a parameter annotated with the named annotation type, or * the empty list if none. */ public ClassInfoList getClassesWithMethodParameterAnnotation(final String methodParameterAnnotationName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableMethodInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo(), #enableMethodInfo(), " + "and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(methodParameterAnnotationName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithMethodParameterAnnotation(); } /** * Get classes that have a field with an annotation of the named type. * * @param fieldAnnotation * the field annotation. * @return A list of classes that have a field with an annotation of the named type, or the empty list if none. */ public ClassInfoList getClassesWithFieldAnnotation(final Class<? extends Annotation> fieldAnnotation) { Assert.isAnnotation(fieldAnnotation); return getClassesWithFieldAnnotation(fieldAnnotation.getName()); } /** * Get classes that have a field with an annotation of the named type. * * @param fieldAnnotationName * the name of the field annotation. * @return A list of classes that have a field with an annotation of the named type, or the empty list if none. */ public ClassInfoList getClassesWithFieldAnnotation(final String fieldAnnotationName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableFieldInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo(), #enableFieldInfo(), " + "and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(fieldAnnotationName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithFieldAnnotation(); } // Interfaces /** * Get all interface classes found during the scan (not including annotations, which are also technically * interfaces). See also {@link #getAllInterfacesAndAnnotations()}. * * @return A list of all accepted interfaces found during the scan, or the empty list if none. */ public ClassInfoList getAllInterfaces() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return ClassInfo.getAllImplementedInterfaceClasses(classNameToClassInfo.values(), scanSpec); } /** * Get all interfaces implemented by the named class or by one of its superclasses, if the named class is a * standard class, or the superinterfaces extended by this interface, if it is an interface. * * @param className * The class name. * @return A list of interfaces implemented by the named class (or superinterfaces extended by the named * interface), or the empty list if none. */ public ClassInfoList getInterfaces(final String className) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(className); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getInterfaces(); } /** * Get all interfaces implemented by the class or by one of its superclasses, if the given class is a standard * class, or the superinterfaces extended by this interface, if it is an interface. * * @param classRef * The class. * @return A list of interfaces implemented by the given class (or superinterfaces extended by the given * interface), or the empty list if none. */ public ClassInfoList getInterfaces(final Class<?> classRef) { return getInterfaces(classRef.getName()); } /** * Get all classes that implement (or have superclasses that implement) the interface (or one of its * subinterfaces). * * @param interfaceClass * The interface class. * @return A list of all classes that implement the interface, or the empty list if none. */ public ClassInfoList getClassesImplementing(final Class<?> interfaceClass) { Assert.isInterface(interfaceClass); return getClassesImplementing(interfaceClass.getName()); } /** * Get all classes that implement (or have superclasses that implement) the named interface (or one of its * subinterfaces). * * @param interfaceName * The interface name. * @return A list of all classes that implement the named interface, or the empty list if none. */ public ClassInfoList getClassesImplementing(final String interfaceName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(interfaceName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesImplementing(); } // Annotations /** * Get all annotation classes found during the scan. See also {@link #getAllInterfacesAndAnnotations()}. * * @return A list of all annotation classes found during the scan, or the empty list if none. */ public ClassInfoList getAllAnnotations() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException( "Please call ClassGraph#enableClassInfo() and #enableAnnotationInfo() before #scan()"); } return ClassInfo.getAllAnnotationClasses(classNameToClassInfo.values(), scanSpec); } /** * Get all interface or annotation classes found during the scan. (Annotations are technically interfaces, and * they can be implemented.) * * @return A list of all accepted interfaces found during the scan, or the empty list if none. */ public ClassInfoList getAllInterfacesAndAnnotations() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException( "Please call ClassGraph#enableClassInfo() and #enableAnnotationInfo() before #scan()"); } return ClassInfo.getAllInterfacesOrAnnotationClasses(classNameToClassInfo.values(), scanSpec); } /** * Get classes with the class annotation or meta-annotation. * * @param annotation * The class annotation or meta-annotation. * @return A list of all non-annotation classes that were found with the class annotation during the scan, or * the empty list if none. */ public ClassInfoList getClassesWithAnnotation(final Class<? extends Annotation> annotation) { Assert.isAnnotation(annotation); return getClassesWithAnnotation(annotation.getName()); } /** * Get classes with the named class annotation or meta-annotation. * * @param annotationName * The name of the class annotation or meta-annotation. * @return A list of all non-annotation classes that were found with the named class annotation during the scan, * or the empty list if none. */ public ClassInfoList getClassesWithAnnotation(final String annotationName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException( "Please call ClassGraph#enableClassInfo() and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(annotationName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithAnnotation(); } /** * Get annotations on the named class. This only returns the annotating classes; to read annotation parameters, * call {@link #getClassInfo(String)} to get the {@link ClassInfo} object for the named class, then if the * {@link ClassInfo} object is non-null, call {@link ClassInfo#getAnnotationInfo()} to get detailed annotation * info. * * @param className * The name of the class. * @return A list of all annotation classes that were found with the named class annotation during the scan, or * the empty list if none. */ public ClassInfoList getAnnotationsOnClass(final String className) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException( "Please call ClassGraph#enableClassInfo() and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(className); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getAnnotations(); } // Classpath modification tests /** * Determine whether the classpath contents have been modified since the last scan. Checks the timestamps of * files and jarfiles encountered during the previous scan to see if they have changed. Does not perform a full * scan, so cannot detect the addition of directories that newly match accept criteria -- you need to perform a * full scan to detect those changes. * * @return true if the classpath contents have been modified since the last scan. */ public boolean classpathContentsModifiedSinceScan() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (fileToLastModified == null) { return true; } else { for (final Entry<File, Long> ent : fileToLastModified.entrySet()) { if (ent.getKey().lastModified() != ent.getValue()) { return true; } } return false; } } /** * Find the maximum last-modified timestamp of any accepted file/directory/jarfile encountered during the scan. * Checks the current timestamps, so this should increase between calls if something changes in accepted paths. * Assumes both file and system timestamps were generated from clocks whose time was accurate. Ignores * timestamps greater than the system time. * * <p> * This method cannot in general tell if classpath has changed (or modules have been added or removed) if it is * run twice during the same runtime session. * * @return the maximum last-modified time for accepted files/directories/jars encountered during the scan. */ public long classpathContentsLastModifiedTime() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } long maxLastModifiedTime = 0L; if (fileToLastModified != null) { final long currTime = System.currentTimeMillis(); for (final long timestamp : fileToLastModified.values()) { if (timestamp > maxLastModifiedTime && timestamp < currTime) { maxLastModifiedTime = timestamp; } } } return maxLastModifiedTime; } // Classloading /** * Get the ClassLoader order, respecting parent-first/parent-last delegation order. * * @return the class loader order. */ ClassLoader[] getClassLoaderOrderRespectingParentDelegation() { return classpathFinder.getClassLoaderOrderRespectingParentDelegation(); } public Class<?> loadClass(final String className, final boolean returnNullIfClassNotFound) throws IllegalArgumentException { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (className == null || className.isEmpty()) { throw new NullPointerException("className cannot be null or empty"); } try { return Class.forName(className, scanSpec.initializeLoadedClasses, classGraphClassLoader); } catch (final ClassNotFoundException | LinkageError e) { if (returnNullIfClassNotFound) { return null; } else { throw new IllegalArgumentException("Could not load class " + className + " : " + e, e); } } } public <T> Class<T> loadClass(final String className, final Class<T> superclassOrInterfaceType, final boolean returnNullIfClassNotFound) throws IllegalArgumentException { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (className == null || className.isEmpty()) { throw new NullPointerException("className cannot be null or empty"); } if (superclassOrInterfaceType == null) { throw new NullPointerException("superclassOrInterfaceType parameter cannot be null"); } final Class<?> loadedClass; try { loadedClass = Class.forName(className, scanSpec.initializeLoadedClasses, classGraphClassLoader); } catch (final ClassNotFoundException | LinkageError e) { if (returnNullIfClassNotFound) { return null; } else { throw new IllegalArgumentException("Could not load class " + className + " : " + e); } } if (loadedClass != null && !superclassOrInterfaceType.isAssignableFrom(loadedClass)) { if (returnNullIfClassNotFound) { return null; } else { throw new IllegalArgumentException("Loaded class " + loadedClass.getName() + " cannot be cast to " + superclassOrInterfaceType.getName()); } } @SuppressWarnings("unchecked") final Class<T> castClass = (Class<T>) loadedClass; return castClass; } // Serialization / deserialization /** * Deserialize a ScanResult from previously-serialized JSON. * * @param json * The JSON string for the serialized {@link ScanResult}. * @return The deserialized {@link ScanResult}. */ @SuppressWarnings("null") public static ScanResult fromJSON(final String json) { final Matcher matcher = Pattern.compile("\\{[\\n\\r ]*\"format\"[ ]?:[ ]?\"([^\"]+)\"").matcher(json); if (!matcher.find()) { throw new IllegalArgumentException("JSON is not in correct format"); } if (!CURRENT_SERIALIZATION_FORMAT.equals(matcher.group(1))) { throw new IllegalArgumentException( "JSON was serialized in a different format from the format used by the current version of " + "ClassGraph -- please serialize and deserialize your ScanResult using " + "the same version of ClassGraph"); } // Deserialize the JSON final SerializationFormat deserialized = JSONDeserializer.deserializeObject(SerializationFormat.class, json); if (deserialized == null || !deserialized.format.equals(CURRENT_SERIALIZATION_FORMAT)) { // Probably the deserialization failed before now anyway, if fields have changed, etc. throw new IllegalArgumentException("JSON was serialized by newer version of ClassGraph"); } // Perform a new "scan" with performScan set to false, which resolves all the ClasspathElement objects // and scans classpath element paths (needed for classloading), but does not scan the actual classfiles final ClassGraph classGraph = new ClassGraph(); classGraph.scanSpec = deserialized.scanSpec; final ScanResult scanResult; try (AutoCloseableExecutorService executorService = new AutoCloseableExecutorService( ClassGraph.DEFAULT_NUM_WORKER_THREADS)) { scanResult = classGraph.getClasspathScanResult(executorService); } scanResult.rawClasspathEltOrderStrs = deserialized.classpath; // Set the fields related to ClassInfo in the new ScanResult, based on the deserialized JSON scanResult.scanSpec = deserialized.scanSpec; scanResult.classNameToClassInfo = new HashMap<>(); if (deserialized.classInfo != null) { for (final ClassInfo ci : deserialized.classInfo) { scanResult.classNameToClassInfo.put(ci.getName(), ci); ci.setScanResult(scanResult); } } scanResult.moduleNameToModuleInfo = new HashMap<>(); if (deserialized.moduleInfo != null) { for (final ModuleInfo mi : deserialized.moduleInfo) { scanResult.moduleNameToModuleInfo.put(mi.getName(), mi); } } scanResult.packageNameToPackageInfo = new HashMap<>(); if (deserialized.packageInfo != null) { for (final PackageInfo pi : deserialized.packageInfo) { scanResult.packageNameToPackageInfo.put(pi.getName(), pi); } } // Index Resource and ClassInfo objects scanResult.indexResourcesAndClassInfo(/* log = */ null); scanResult.isObtainedFromDeserialization = true; return scanResult; } /** * Serialize a ScanResult to JSON. * * @param indentWidth * If greater than 0, JSON will be formatted (indented), otherwise it will be minified (un-indented). * @return This {@link ScanResult}, serialized as a JSON string. */ public String toJSON(final int indentWidth) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } final List<ClassInfo> allClassInfo = new ArrayList<>(classNameToClassInfo.values()); CollectionUtils.sortIfNotEmpty(allClassInfo); final List<PackageInfo> allPackageInfo = new ArrayList<>(packageNameToPackageInfo.values()); CollectionUtils.sortIfNotEmpty(allPackageInfo); final List<ModuleInfo> allModuleInfo = new ArrayList<>(moduleNameToModuleInfo.values()); CollectionUtils.sortIfNotEmpty(allModuleInfo); return JSONSerializer.serializeObject(new SerializationFormat(CURRENT_SERIALIZATION_FORMAT, scanSpec, allClassInfo, allPackageInfo, allModuleInfo, rawClasspathEltOrderStrs), indentWidth, false); } /** * Serialize a ScanResult to minified (un-indented) JSON. * * @return This {@link ScanResult}, serialized as a JSON string. */ public String toJSON() { return toJSON(0); } /** * Checks if this {@link ScanResult} was obtained from JSON by deserialization, by calling * {@link #fromJSON(String)}. * * @return True if this {@link ScanResult} was obtained from JSON by deserialization. */ public boolean isObtainedFromDeserialization() { return isObtainedFromDeserialization; } @Override public void close() { if (!closed.getAndSet(true)) { nonClosedWeakReferences.remove(weakReference); if (classpathOrder != null) { classpathOrder.clear(); classpathOrder = null; } if (allAcceptedResourcesCached != null) { for (final Resource classpathResource : allAcceptedResourcesCached) { classpathResource.close(); } allAcceptedResourcesCached.clear(); allAcceptedResourcesCached = null; } if (pathToAcceptedResourcesCached != null) { pathToAcceptedResourcesCached.clear(); pathToAcceptedResourcesCached = null; } classGraphClassLoader = null; if (classNameToClassInfo != null) { // Don't clear classNameToClassInfo, since it may be used by ClassGraphClassLoader (#399). // Just rely on the garbage collector to collect these once the ScanResult goes out of scope. // classNameToClassInfo.clear(); // classNameToClassInfo = null; } if (packageNameToPackageInfo != null) { packageNameToPackageInfo.clear(); packageNameToPackageInfo = null; } if (moduleNameToModuleInfo != null) { moduleNameToModuleInfo.clear(); moduleNameToModuleInfo = null; } if (fileToLastModified != null) { fileToLastModified.clear(); fileToLastModified = null; } // nestedJarHandler should be closed last, since it needs to have all MappedByteBuffer refs // dropped before it tries to delete any temporary files that were written to disk if (nestedJarHandler != null) { nestedJarHandler.close(topLevelLog); nestedJarHandler = null; } classGraphClassLoader = null; classpathFinder = null; // Flush log on exit, in case additional log entries were generated after scan() completed if (topLevelLog != null) { topLevelLog.flush(); } } } /** * Close all {@link ScanResult} instances that have not yet been closed. Note that this will close all open * {@link ScanResult} instances for any class that uses the classloader that the {@link ScanResult} class is * cached in -- so if you call this method, you need to ensure that the lifecycle of the classloader matches the * lifecycle of your application, or that two concurrent applications don't share the same classloader, * otherwise one application might close another application's {@link ScanResult} instances while they are still * in use. */ public static void closeAll() { for (final WeakReference<ScanResult> nonClosedWeakReference : new ArrayList<>(nonClosedWeakReferences)) { final ScanResult scanResult = nonClosedWeakReference.get(); if (scanResult != null) { scanResult.close(); } } } }
package me.ilinskiy.chess.game; import me.ilinskiy.chess.annotations.NotNull; import me.ilinskiy.chess.chessBoard.*; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import static me.ilinskiy.chess.chessBoard.ImmutableBoard.*; import static me.ilinskiy.chess.chessBoard.PieceColor.Black; import static me.ilinskiy.chess.chessBoard.PieceColor.White; public class GameUtil { @NotNull public static synchronized List<Move> getAvailableMoves(@NotNull PieceColor color, @NotNull ImmutableBoard board) { List<Move> result = new ArrayList<>(); List<Coordinates> allPiecesOfCorrectColor = getAllPieces(color, board); for (Coordinates pos : allPiecesOfCorrectColor) { result.addAll(getAvailableMovesForPiece(pos, board)); } return result; } @NotNull public static List<Coordinates> getAllPieces(PieceColor color, @NotNull ImmutableBoard board) { ArrayList<Coordinates> allPiecesOfCorrectColor = new ArrayList<>(BOARD_SIZE * 2); //should use default instead? for (int row = 0; row < BOARD_SIZE; row++) { for (int col = 0; col < BOARD_SIZE; col++) { Coordinates c = new Coordinates(row, col); if (board.getPieceAt(c).getColor() == color) { allPiecesOfCorrectColor.add(c); } } } return allPiecesOfCorrectColor; } public static int getDirectionForPlayer(@NotNull PieceColor color) { if (color == PieceColor.White) { return WHITE_DIRECTION; } else { assert color == PieceColor.Black; return BLACK_DIRECTION; } } /** * If board.getPieceAt(pos) is EmptyCell returns an empty list */ @NotNull public static List<Move> getAvailableMovesForPiece(@NotNull Coordinates pos, @NotNull ImmutableBoard board) { //todo: use set instead of list? List<Move> result = getAllMovesForPiece(pos, board); //filter out the ones when king is attacked Iterator<Move> moveIterator = result.iterator(); while (moveIterator.hasNext()) { if (kingIsAttackedAfterMove(board.getPieceAt(pos).getColor(), board, moveIterator.next())) { moveIterator.remove(); } } return result; } /** * Get all available moves for piece without considering if the king will be attacked */ @NotNull private static List<Move> getAllMovesForPiece(@NotNull Coordinates pos, @NotNull ImmutableBoard board) { ChessElement element = board.getPieceAt(pos); List<Move> result = new LinkedList<>(); PieceColor color = element.getColor(); switch (element.getType()) { case Pawn: assert (color == White || color == Black); int dir = getDirectionForPlayer(color); Coordinates newC = new Coordinates(pos.getX(), pos.getY() + dir); assert !ChessBoardUtil.isOutOfBounds(newC); //should've been promoted if (board.getPieceAt(newC) instanceof EmptyCell) { result.add(new Move(pos, newC)); boolean hasNotMoved = ChessBoardUtil.isOutOfBounds(new Coordinates(pos.getX(), pos.getY() - 2 * dir)); Coordinates longMove = new Coordinates(pos.getX(), pos.getY() + 2 * dir); if (hasNotMoved && (board.getPieceAt(longMove) instanceof EmptyCell)) { result.add(new Move(pos, longMove)); } } Coordinates[] eatLocations = new Coordinates[]{new Coordinates(pos.getX() + 1, pos.getY() + dir), new Coordinates(pos.getX() - 1, pos.getY() + dir)}; for (Coordinates eatLocation : eatLocations) { boolean outOfBounds = ChessBoardUtil.isOutOfBounds(eatLocation); if (!outOfBounds && board.getPieceAt(eatLocation).getColor() == ChessBoardUtil.inverse(color)) { result.add(new Move(pos, eatLocation)); } } break; case Knight: int[] xChange = new int[]{1, -1, 2, 2, -2, -2, 1, -1}; int[] yChange = new int[]{2, 2, 1, -1, 1, -1, -2, -2}; assert xChange.length == yChange.length; for (int c = 0; c < xChange.length; c++) { Coordinates newPos = new Coordinates(pos.getX() + xChange[c], pos.getY() + yChange[c]); if (!ChessBoardUtil.isOutOfBounds(newPos) && board.getPieceAt(newPos).getColor() != color) { result.add(new Move(pos, newPos)); } } break; case Bishop: result = getBishopMoves(pos, board); break; case Rook: result = getRookMoves(pos, board); break; case Queen: result = getRookMoves(pos, board); result.addAll(getBishopMoves(pos, board)); break; case King: result = getKingMoves(pos, board); break; case Empty: break; } return result; } @NotNull private static List<Move> getRookMoves(@NotNull Coordinates pos, @NotNull ImmutableBoard board) { int[] xChange = new int[]{0, 0, 1, -1}; int[] yChange = new int[]{1, -1, 0, 0}; return getBishopOrRookMoves(pos, board, xChange, yChange); } @NotNull private static List<Move> getBishopMoves(@NotNull Coordinates pos, @NotNull ImmutableBoard board) { int[] xChange = new int[]{-1, -1, 1, 1}; int[] yChange = new int[]{1, -1, 1, -1}; return getBishopOrRookMoves(pos, board, xChange, yChange); } private static List<Move> getBishopOrRookMoves(@NotNull Coordinates pos, @NotNull ImmutableBoard board, @NotNull int[] xChange, @NotNull int[] yChange) { assert xChange.length == yChange.length; List<Move> result = new ArrayList<>(); assert board.getPieceAt(pos) instanceof Piece; Piece p = (Piece) board.getPieceAt(pos); for (int i = 0; i < xChange.length; i++) { Coordinates c = new Coordinates(pos.getX() + xChange[i], pos.getY() + yChange[i]); Coordinates copy = c.copy(); while (!ChessBoardUtil.isOutOfBounds(c) && board.getPieceAt(c) instanceof EmptyCell) { result.add(new Move(pos, c)); c = new Coordinates(c.getX() + xChange[i], c.getY() + yChange[i]); } c = copy; //restore if (!ChessBoardUtil.isOutOfBounds(c)) { PieceColor color = board.getPieceAt(c).getColor(); if (!ChessBoardUtil.isOutOfBounds(c) && color == ChessBoardUtil.inverse(p.getColor())) { result.add(new Move(pos, c)); } } } return result; } @NotNull private static List<Move> getKingMoves(@NotNull Coordinates kingPos, @NotNull ImmutableBoard board) { int[] xChange = new int[]{-1, 0, 1, -1, 0, 1, -1, 0, 1}; int[] yChange = new int[]{-1, -1, -1, 0, 0, 0, 1, 1, 1}; List<Move> result = new ArrayList<>(); assert xChange.length == yChange.length; assert board.getPieceAt(kingPos) instanceof Piece; PieceColor kingColor = board.getPieceAt(kingPos).getColor(); for (int i = 0; i < xChange.length; i++) { Coordinates c = new Coordinates(kingPos.getX() + xChange[i], kingPos.getY() + yChange[i]); if (!ChessBoardUtil.isOutOfBounds(c)) { boolean correctColor = board.getPieceAt(c).getColor() != kingColor; if (correctColor && !kingAround(c, board, ChessBoardUtil.inverse(kingColor))) { result.add(new Move(kingPos, c)); //all the situation when king is attacked will be filtered out later } } } if (!board.pieceHasMovedSinceStartOfGame(kingPos)) { //check for castling List<Coordinates> rooks = findPiecesByTypeAndColor(PieceType.Rook, kingColor, board); assert rooks.size() <= 2; for (Coordinates rookPos : rooks) { if (!board.pieceHasMovedSinceStartOfGame(rookPos)) { assert rookPos.getY() == kingPos.getY(); int direction; if (rookPos.getX() > kingPos.getX()) { direction = 1; } else { assert rookPos.getX() < kingPos.getX(); direction = -1; } boolean canCastle = true; Coordinates castleCells = kingPos; while (!castleCells.equals(rookPos) && canCastle) { ChessElement piece = board.getPieceAt(castleCells); if (!(piece instanceof EmptyCell) && piece != board.getPieceAt(kingPos)) { canCastle = false; } castleCells = new Coordinates(castleCells.getX() + direction, castleCells.getY()); } if (canCastle) { Coordinates kingNewPos = new Coordinates(kingPos.getX() + direction * 2, rookPos.getY()); Coordinates rookNewPos = new Coordinates(kingPos.getX() + direction, rookPos.getY()); Castling move = new Castling(kingPos, kingNewPos, rookPos, rookNewPos); result.add(move); } } } } return result; } private static boolean kingAround(@NotNull Coordinates pos, @NotNull ImmutableBoard board, PieceColor opposingKingColor) { int[] xChange = new int[]{-1, 0, 1, -1, 0, 1, -1, 0, 1}; int[] yChange = new int[]{-1, -1, -1, 0, 0, 0, 1, 1, 1}; assert xChange.length == yChange.length; for (int i = 0; i < xChange.length; i++) { Coordinates c = new Coordinates(pos.getX() + xChange[i], pos.getY() + yChange[i]); if (!ChessBoardUtil.isOutOfBounds(c)) { ChessElement elem = board.getPieceAt(c); if (elem.getType() == PieceType.King && elem.getColor() == opposingKingColor) { return true; } } } return false; } public static boolean kingIsAttacked(@NotNull PieceColor kingColor, @NotNull ImmutableBoard board) { List<Coordinates> allOpponentPieces = getAllPieces(ChessBoardUtil.inverse(kingColor), board); Coordinates kingPos = findKing(kingColor, board); for (Coordinates pos : allOpponentPieces) { List<Move> availableMovesForPiece = getAllMovesForPiece(pos, board); for (Move m : availableMovesForPiece) { if (m.getNewPosition().equals(kingPos)) { return true; } } } return false; } private static boolean kingIsAttackedAfterMove(@NotNull PieceColor color, @NotNull ImmutableBoard b, @NotNull Move m) { if (m instanceof Castling) { Castling castling = (Castling) m; Coordinates kingInitialPosition = castling.getKingInitialPosition(); Coordinates rookInitialPosition = castling.getRookInitialPosition(); int dir; if (kingInitialPosition.getX() < rookInitialPosition.getX()) { dir = 1; } else { assert kingInitialPosition.getX() > rookInitialPosition.getX(); dir = -1; } assert kingInitialPosition.getY() == rookInitialPosition.getY(); for (Coordinates c = kingInitialPosition; c.getX() != rookInitialPosition.getX(); c = new Coordinates(c.getX() + dir, c.getY())) { if (ChessBoardUtil.makeMoveAndEvaluate(b, m, board -> kingIsAttacked(color, board))) { return true; } } return false; } else { return ChessBoardUtil.makeMoveAndEvaluate(b, m, board -> kingIsAttacked(color, board)); } } @NotNull private static Coordinates findKing(@NotNull PieceColor kingColor, @NotNull ImmutableBoard board) { List<Coordinates> kingLocation = findPiecesByTypeAndColor(PieceType.King, kingColor, board); assert kingLocation.size() == 1 : "Wrong number of kings on the board: " + kingLocation; return kingLocation.get(0); } @NotNull public static List<Coordinates> findPiecesByTypeAndColor(@NotNull PieceType type, @NotNull PieceColor color, @NotNull ImmutableBoard board) { ChessElement elemToFind = new Piece(color, type); List<Coordinates> result = new ArrayList<>(); for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { Coordinates coordinates = new Coordinates(i, j); if (board.getPieceAt(coordinates).equals(elemToFind)) { result.add(coordinates); } } } return result; } }
package me.nallar.modpatcher; import com.google.common.base.Charsets; import com.google.common.io.Resources; import me.nallar.javapatcher.patcher.Patcher; import net.minecraft.launchwrapper.LaunchClassLoader; import net.minecraftforge.fml.relauncher.ReflectionHelper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.nio.file.FileSystem; import java.nio.file.*; import java.util.*; import java.util.concurrent.*; /** * ModPatcher API * * This class is the public facing API of ModPatcher * * It automatically downloads ModPatcher if the file is missing from the libs folder, or a coremod depends on * a newer version of modpatcher than the installed version * * This behaviour can be disabled by creating the file "libs/modpatcher/NEVER_UPDATE.txt" */ public class ModPatcher { private static final int API_VERSION = 0; private static final Logger log = LogManager.getLogger("ModPatcher"); private static final String mcVersion = "@MC_VERSION@"; private static final Path neverUpdatePath = Paths.get("./mods/ModPatcher/NEVER_UPDATE.txt").toAbsolutePath(); private static final Path modPatcherPath = Paths.get("./mods/ModPatcher/ModPatcher.lib").toAbsolutePath(); private static final Future<Boolean> defaultUpdateRequired = CompletableFuture.completedFuture(!Files.exists(modPatcherPath)); private static final String DOWNLOAD_URL_PROPERTY = "modpatcher.downloadUrl"; private static final String REQUIRED_VERSION_PROPERTY = "modpatcher.requiredVersion"; private static final String RELEASE_PROPERTY = "modpatcher.release"; private static final String VERSION_URL_PROPERTY = "modpatcher.versionUrl"; private static final String NEVER_UPDATE_PROPERTY = "modpatcher.neverUpdate"; private static final String DEFAULT_RELEASE = "stable"; private static String modPatcherRelease; private static Future<Boolean> updateRequired = defaultUpdateRequired; private static Version requiredVersion; private static Version lastVersion; /** * Gets the name of the setup class to use in your IFMLLoadingPlugin * * @return Name of the ModPatcher setup class */ public static String getSetupClass() { return getSetupClass(null); } /** * Gets the name of the setup class to use in your IFMLLoadingPlugin * * @param versionString Minimum version of ModPatcher required. Special value "latest" always uses latest version * @return Name of the ModPatcher setup class */ public static String getSetupClass(String versionString) { return getSetupClass(versionString, null); } /** * Gets the name of the setup class to use in your IFMLLoadingPlugin * * @param versionString Minimum version of ModPatcher required. Special value "latest" always uses latest version * @param release Release stream to use * @return Name of the ModPatcher setup class */ public static String getSetupClass(String versionString, String release) { requireVersion(versionString, release); return "me.nallar.modpatcher.ModPatcherSetup"; } /** * Load JavaPatcher patches * * @param inputStream stream to load patches from */ public static void loadPatches(InputStream inputStream) { getPatcher().loadPatches(inputStream); } /** * Load JavaPatcher patches * * @param patches String to load patches from */ public static void loadPatches(String patches) { getPatcher().loadPatches(patches); } /** * Gets the JavaPatcher Patcher instance * * @return the Patcher * @deprecated Use specific methods such as loadPatches(InputStream) */ @Deprecated public static Patcher getPatcher() { checkClassLoading(); return ModPatcherTransformer.getPatcher(); } /** * Loads mixins from the given package. * The package must have a package-info.java with @Mixin annotation * * @param mixinPackage Package to load mixins from */ public static void loadMixins(String mixinPackage) { checkClassLoading(); ModPatcherTransformer.getMixinApplicator().addSource(mixinPackage); } /** * Loads all mixins from the given path, regardless of package * * @param path Path to load mixins from */ public static void loadMixins(Path path) { checkClassLoading(); ModPatcherTransformer.getMixinApplicator().addSource(path); } /** * Loads all mixins from the given path, if they match the given package * * @param path Path to load mixins from */ public static void loadMixins(Path path, String packageName) { checkClassLoading(); ModPatcherTransformer.getMixinApplicator().addSource(path, packageName); } /** * Gets the default patches directory. Any patches in this directory are loaded by ModPatcher on startup. * * @return default patches directory */ public static String getDefaultPatchesDirectory() { checkClassLoading(); return ModPatcherTransformer.getDefaultPatchesDirectory(); } private static void requireVersion(String versionString, String release) { if (updateRequired == null) throw new Error("Modpatcher has already been loaded, it is too late to call getSetupClass"); versionString = System.getProperty(REQUIRED_VERSION_PROPERTY, versionString); release = System.getProperty(RELEASE_PROPERTY, release); if (release != null && versionString == null) throw new IllegalArgumentException("versionString must be non-null if release is non-null"); boolean startCheck = false; if (release != null) { if (modPatcherRelease == null) { modPatcherRelease = release; startCheck = true; } else { log.warn("Conflicting ModPatcher release requests. Set to " + modPatcherRelease + ", requested: " + release); } } if (versionString != null) { Version requested = Version.of(versionString); if (requested.compareTo(requiredVersion) > 0) { requiredVersion = requested; startCheck = true; } } if (startCheck) startVersionCheck(); } private static void loadModPatcher() { download(); updateRequired = null; addToCurrentClassLoader(); checkClassLoading(false); } private static String getModPatcherRelease() { return mcVersion + '-' + (modPatcherRelease == null ? DEFAULT_RELEASE : modPatcherRelease); } @SuppressWarnings("unchecked") private static void addToCurrentClassLoader() { ClassLoader cl = ModPatcher.class.getClassLoader(); try { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); if (cl instanceof LaunchClassLoader) { LaunchClassLoader lcl = (LaunchClassLoader) cl; lcl.addTransformerExclusion("me.nallar.modpatcher"); method = LaunchClassLoader.class.getDeclaredMethod("addURL", URL.class); Set<String> invalidClasses = ReflectionHelper.<Set<String>, LaunchClassLoader>getPrivateValue(LaunchClassLoader.class, lcl, "invalidClasses"); invalidClasses.removeIf(it -> it.contains("nallar")); } method.setAccessible(true); method.invoke(cl, modPatcherPath.toUri().toURL()); } catch (Exception e) { throw new Error(e); } } static boolean neverUpdate() { return "true".equals(System.getProperty(NEVER_UPDATE_PROPERTY)) || Files.exists(neverUpdatePath); } private static boolean isDownloadNeeded() { if (neverUpdate()) return false; try { return updateRequired.get(); } catch (InterruptedException | ExecutionException e) { log.warn("Failed to check if updates are required", e); } return false; } private static void download() { if (!isDownloadNeeded()) return; try (InputStream in = new URL(System.getProperty(DOWNLOAD_URL_PROPERTY, "https://modpatcher.nallar.me/" + getModPatcherRelease() + "/ModPatcher-lib.jar")).openConnection().getInputStream()) { Files.deleteIfExists(modPatcherPath); Files.createDirectories(modPatcherPath.getParent()); Files.copy(in, modPatcherPath); } catch (IOException e) { log.error("Failed to download ModPatcher", e); } } private static void checkClassLoading() { checkClassLoading(true); } private static void checkClassLoading(boolean load) { try { ModPatcherLoadHook.loadHook(requiredVersion, getModPatcherRelease(), API_VERSION); } catch (NoClassDefFoundError e) { if (!load) throw e; loadModPatcher(); } } private static void startVersionCheck() { if (neverUpdate() || requiredVersion == null) return; updateRequired.cancel(true); try { if (!updateRequired.isDone() || updateRequired.isCancelled() || !updateRequired.get()) { updateRequired = new FutureTask<>(() -> { Version current = getLastVersion(); if (requiredVersion.newerThan(current)) { try { Version online = new Version(Resources.toString(new URL(System.getProperty(VERSION_URL_PROPERTY, "https://modpatcher.nallar.me/" + getModPatcherRelease() + "/version.txt")), Charsets.UTF_8).trim()); return online.compareTo(current) > 0; } catch (InterruptedIOException ignored) { } catch (Throwable t) { log.warn("Failed to check for update", t); } } return false; }); } } catch (InterruptedException | ExecutionException e) { log.warn("Interrupted when checking done/not cancelled future", e); } } static Version getLastVersion() { if (lastVersion != null) return lastVersion; if (!Files.exists(modPatcherPath)) return Version.NONE; try (FileSystem fs = FileSystems.newFileSystem(modPatcherPath, null)) { return lastVersion = new Version(Files.readAllLines(fs.getPath("modpatcher.version"), Charsets.UTF_8).get(0)); } catch (IOException e) { throw new IOError(e); } } static class Version implements Comparable<Version> { public static final Version LATEST = new Version(String.valueOf(Integer.MAX_VALUE)); public static final Version NONE = new Version("0"); private String version; private Version(String version) { if (version == null) throw new IllegalArgumentException("Version can not be null"); if (!version.matches("[0-9]+(\\.[0-9]+)*")) throw new IllegalArgumentException("Invalid version format"); this.version = version; } static Version of(String s) { if (s.equalsIgnoreCase("latest")) { return LATEST; } return new Version(s); } public final String get() { return this.version; } @Override public int compareTo(Version that) { if (that == null) return 1; if (this == that || version.equals(that.version)) return 0; String[] thisParts = this.get().split("\\."); String[] thatParts = that.get().split("\\."); int length = Math.max(thisParts.length, thatParts.length); for (int i = 0; i < length; i++) { int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0; int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0; if (thisPart < thatPart) return -1; if (thisPart > thatPart) return 1; } return 0; } @Override public int hashCode() { return version.hashCode(); } @Override public boolean equals(Object that) { return this == that || that != null && this.getClass() == that.getClass() && this.compareTo((Version) that) == 0; } public boolean newerThan(Version other) { return compareTo(other) > 0; } } }
package ml.iamwhatiam.tao.ddd; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SQLParser { private static final char TAB = '\t';//0x09 private static final char CARRIAGE_RETURN = '\r';//0x0D private static final char LINE_FEED = '\n';//0x0A private static final char SPACE = ' ';//0x20 private static final char DOT = '.'; private static final char COMMA = ','; private Logger log = LoggerFactory.getLogger(SQLParser.class); protected Table table; private Dialect dialect; private StringBuilder sb; private char quote; private int position; public SQLParser(Dialect dialect) { this.dialect = dialect; if(dialect == Dialect.MYSQL) quote = '`'; else quote = '"'; } public Table parse(InputStream is) { return parse(is, "UTF-8"); } public Table parse(InputStream is, String charset) { table = new Table(dialect); BufferedReader br = null; sb = new StringBuilder(); //remove comment, CR/*comment*/EATE syntax error could not be check! FIXME analyze(is, charset, br); if(log.isDebugEnabled()) log.debug(sb.toString()); //keyword match match(nextWord(), "CREATE"); parseTablePrefixInfo(); match(nextWord(), "TABLE"); //table name Stack<String> names = parseTableName(); table.setName(names.pop()); if(!names.empty()) table.setSchema(names.pop()); if(!names.empty()) table.setCatalog(names.pop()); //table columns and same block constraint parseColumns(); parseTableSuffixInfo(); //comment, constraint in alter clause parseComment(); parseConstraint(); if(log.isDebugEnabled()) log.debug("accepted ddl: {}", table.toSQL()); return table; } protected void analyze(InputStream is, String charset, BufferedReader br) { try { boolean ignore = false; boolean literal = false; boolean special = false; CommentType type = null; br = new BufferedReader(new InputStreamReader(is, charset)); int current = -1; int prev = -1; while((current = br.read()) != -1) { switch(current) { case '/'://block comment end? if(prev == '*' && type == CommentType.BLOCK && !literal) { type = null; ignore = false; prev = SPACE; continue; } break; case '-'://line comment start if(prev == '-' && !literal && !ignore) { type = CommentType.LINE; ignore = true; sb.deleteCharAt(sb.length() - 1); continue; } break; case '\n': if(ignore && type == CommentType.LINE) { type = null; ignore = false; prev = SPACE; continue; } break; case '*'://block comment begin? if(prev == '/' && !ignore && !literal) { type = CommentType.BLOCK; ignore = true; sb.deleteCharAt(sb.length() - 1); if(sb.length() - 2 > 0) prev = sb.charAt(sb.length() - 2); else prev = -1; continue; } break; case '\\': if(!ignore) special = !special; break; case '\''://text? if(!ignore && !special) literal = !literal; break; } if(isSpace((char) prev) && isSpace((char) current)) { prev = SPACE; continue; } if(!ignore) { if(isSpace((char) current) && sb.length() != 0) current = SPACE; sb.append((char) current); } prev = current; } } catch (UnsupportedEncodingException e) { log.error("bad charset", e); } catch (IOException e) { log.error(e.getMessage(), e); } finally { if(br != null) { try { br.close(); } catch (IOException e) { log.warn("cannot close read buffer", e); } } } } public void error(int line, int position) { throw new RuntimeException(String.format("syntax error %d:%d", line, position)); } private String nextWord() { int offset = position; for(; position < sb.length(); position++) { if(shouldStop(sb.charAt(position))) { return sb.substring(offset, position++); } } if(position >= sb.length()) throw new RuntimeException("exceed string length"); return sb.substring(offset, position); } private String nextWord(int position, int length) { return nextWord(position, length, SPACE); } private String nextWord(int position, int length, char stop) {//stop: ',', '(', ')', ' ' int offset = position; boolean quoted = false; for(; position < sb.length() && position < length; position++) { if(sb.charAt(position) == '\'') quoted = !quoted; if(shouldStop(sb.charAt(position), stop) && !quoted) { return sb.substring(offset, position); } } if(position >= sb.length()) throw new RuntimeException("exceed string length"); return sb.substring(offset, position); } protected void parseTablePrefixInfo() { int offset = position; String notSure = nextWord(); while(!"TABLE".equalsIgnoreCase(notSure)) { offset = position; notSure = nextWord(); } position = offset; } protected Stack<String> parseTableName() { Stack<String> names = new Stack<String>(); char[] identifier = nextWord().toCharArray(); if(log.isDebugEnabled()) log.debug("table name to parse: {}", new String(identifier)); boolean quoted = false; int pos = 0; for(int i = 0; i < identifier.length; i++) { if(identifier[i] == quote) { quoted = !quoted; } if(identifier[i] == DOT && !quoted) { names.push(new String(identifier, pos, i - pos)); pos = i + 1; continue; } if(i == identifier.length - 1) { names.push(new String(identifier, pos, i - pos + 1)); } } return names; } protected void parseColumns() { List<Table.Column> columns = new ArrayList<Table.Column>(); table.setColumns(columns);//constraint can be same block with columns! int deep = 0; int offset = position + 1; for(; position < sb.length(); position++) { if(sb.charAt(position) == '(') { deep++; continue; } if(sb.charAt(position) == ')') { deep if(deep == 0) { String intro = nextWord(offset + 1, position); if("PRIMARY".equalsIgnoreCase(intro) || "INDEX".equalsIgnoreCase(intro) || "CHECK".equalsIgnoreCase(intro) || "CONSTRAINT".equalsIgnoreCase(intro) || "UNIQUE".equalsIgnoreCase(intro)) {//constraint parseConstraint(offset + 1, position); offset = ++position; break; } Table.Column column = parseColumn(offset, position); offset = ++position; columns.add(column); break; } continue; } if(sb.charAt(position) == COMMA && deep == 1) { String intro = nextWord(offset + 1, position); if("PRIMARY".equalsIgnoreCase(intro) || "INDEX".equalsIgnoreCase(intro) || "CHECK".equalsIgnoreCase(intro) || "CONSTRAINT".equalsIgnoreCase(intro) || "UNIQUE".equalsIgnoreCase(intro)) {//constraint parseConstraint(offset + 1, position); offset = position + 1; continue; } Table.Column column = parseColumn(offset, position); offset = position + 1; columns.add(column); } } } protected Table.Column parseColumn(int offset, int length) { if(log.isDebugEnabled()) log.debug("column to parse: {}", sb.substring(offset, length)); if(sb.charAt(offset) == SPACE) offset += 1; String name = parseColumnName(offset, length); Table.Column.DataType dataType = parseColumnDataType(offset + name.length() + 1, length); Table.Column column = new Table.Column(name, dataType); column.setTable(table); Boolean nullable = null, autoIncrement = null; String defaultValue = null, comment = null; for(int start = offset + name.length() + 1; start < length; ) { String unknow = nextWord(start, length); start = start + unknow.length() + 1; if("DEFAULT".equalsIgnoreCase(unknow)) { defaultValue = nextWord(start, length); } else if("NOT".equalsIgnoreCase(unknow)) { String tmp = nextWord(start, length); start = start + tmp.length() + 1; if("NULL".equalsIgnoreCase(tmp)) nullable = Boolean.FALSE; } else if("NULL".equalsIgnoreCase(unknow)) nullable = Boolean.TRUE; else if("AUTO_INCREMENT".equalsIgnoreCase(unknow) && dialect == Dialect.MYSQL) autoIncrement = Boolean.TRUE; else if("COMMENT".equalsIgnoreCase(unknow)) comment = nextWord(start, length); } if(nullable != null) column.setNullable(nullable.booleanValue()); column.setDefaultValue(defaultValue); if(autoIncrement != null) column.setAutoIncrement(autoIncrement.booleanValue()); column.setComment(comment); return column; } protected String parseColumnName(int offset, int length) { return nextWord(offset, length); } protected Table.Column.DataType parseColumnDataType(int offset, int length) { String type = nextWord(offset, length); boolean enumerable = false; int len = type.length(); String[] names = null; Integer precision = null, scale = null; Integer intervalType = null, iPrecision = null, iScale = null; Boolean withTimeZone = null; Boolean unsigned = null, zerofill = null; int leftBracket = type.indexOf("("); int rightBracket = type.indexOf(")"); int comma = type.indexOf(","); if(type.indexOf("[") > 0 && type.indexOf("]") > 0) {//hack for pg! int dimension = 0; names = new String[1]; names[0] = type.substring(0, type.indexOf("[")); for(int start = offset + type.indexOf("["); start < length; start += 2) { if(sb.charAt(start) == '[' && sb.charAt(start + 1) == ']') dimension++; else log.error("bad data type: {}", type); } type = "ARRAY"; precision = Integer.valueOf(dimension); } if(leftBracket > 0 && ("SET".equalsIgnoreCase(type.substring(0, leftBracket)) || "ENUM".equalsIgnoreCase(type.substring(0, leftBracket)))) enumerable = true; if(enumerable) {//enum, set names = type.substring(leftBracket + 1, rightBracket).split(","); type = type.substring(0, leftBracket); } else {//character, number, datetime if(leftBracket > 0) { if(comma > 0) { precision = Integer.valueOf(type.substring(leftBracket + 1, comma).trim()); scale = Integer.valueOf(type.substring(comma + 1, rightBracket).trim()); } else { precision = Integer.valueOf(type.substring(leftBracket + 1, rightBracket).trim()); } type = type.substring(0, leftBracket); } } type = type.toUpperCase(); for(int start = offset + len + 1; start < length;) { String guess = nextWord(start, length); start = start + guess.length() + 1; if("INTERVAL".equals(type)) { String prev = nextWord(start, length); int __length = prev.length(); int lbracket = prev.indexOf("("); int rbracket = prev.indexOf(")"); if(lbracket != -1 && rbracket != -1) { iPrecision = Integer.valueOf(prev.substring(lbracket + 1, rbracket).trim()); prev = prev.substring(0, lbracket); } if("YEAR".equalsIgnoreCase(prev)) { String to = nextWord(start + __length + 1, length); match(to, "TO"); String __type = nextWord(start + __length + 1 + to.length() + 1, length); match(__type, "MONTH"); int lb = __type.indexOf("("); int rb = __type.indexOf(")"); if(lb != -1 && rb != -1) { iScale = Integer.valueOf(__type.substring(lb + 1, rb)); } intervalType = Integer.valueOf(0); } else if("DAY".equalsIgnoreCase(prev)) { String to = nextWord(start + __length + 1, length); match(to, "TO"); String __type = nextWord(start + __length + 1 + to.length() + 1, length); int lb = __type.indexOf("("); int rb = __type.indexOf(")"); if(lb != -1 && rb != -1) { iScale = Integer.valueOf(__type.substring(lb + 1, rb)); __type = __type.substring(0, lb); } if("HOUR".equalsIgnoreCase(__type)) { intervalType = Integer.valueOf(1); } else if("MINUTE".equalsIgnoreCase(__type)) { intervalType = Integer.valueOf(2); } else if("SECOND".equalsIgnoreCase(__type)) { intervalType = Integer.valueOf(3); } } else if("HOUR".equalsIgnoreCase(prev)) { String to = nextWord(start + __length + 1, length); match(to, "TO"); String __type = nextWord(start + __length + 1 + to.length() + 1, length); if("MINUTE".equalsIgnoreCase(__type)) { intervalType = Integer.valueOf(4); } else if("SECOND".equalsIgnoreCase(__type)) { intervalType = Integer.valueOf(5); } } else if("MINUTE".equalsIgnoreCase(prev)) { String to = nextWord(start + __length + 1, length); match(to, "TO"); String __type = nextWord(start + __length + 1 + to.length() + 1, length); if("SECOND".equalsIgnoreCase(__type)) { intervalType = Integer.valueOf(5); } } } else if("TIME".equals(type) || "TIMESTAMP".equals(type)) { if(guess.toUpperCase().indexOf("WITH") != -1) { if("WITH".equalsIgnoreCase(guess)) withTimeZone = Boolean.TRUE; else if("WITHOUT".equalsIgnoreCase(guess)) withTimeZone = Boolean.FALSE; String time = nextWord(start + guess.length() + 1, length); match(time, "TIME"); match(nextWord(start + guess.length() + 6, length), "ZONE"); } } if("UNSIGNED".equalsIgnoreCase(guess)) { unsigned = true; } if("ZEROFILL".equalsIgnoreCase(guess)) { zerofill = true; } } Table.Column.DataType dataType = null; switch(dialect) { case MYSQL: Table.Column.MySQLDataType mysql = new Table.Column.MySQLDataType(type); if(names != null) mysql.set(names); if(precision != null) { if(scale != null) { if(unsigned != null && zerofill != null) mysql.set(precision.intValue(), scale.intValue(), unsigned.booleanValue(), zerofill.booleanValue()); else if(unsigned != null) mysql.set(precision.intValue(), scale.intValue(), unsigned.booleanValue(), false); else if(zerofill != null) mysql.set(precision.intValue(), scale.intValue(), false, zerofill.booleanValue()); else mysql.set(precision.intValue(), scale.intValue()); } else { if(unsigned != null && zerofill != null) mysql.set(precision.intValue(), unsigned.booleanValue(), zerofill.booleanValue()); else if(unsigned != null) mysql.set(precision.intValue(), unsigned.booleanValue(), false); else if(zerofill != null) mysql.set(precision.intValue(), false, zerofill.booleanValue()); else mysql.set(precision.intValue()); } } dataType = mysql; break; case POSTGRES: Table.Column.PostgresDataType pg = new Table.Column.PostgresDataType(type); if(names != null) pg.set(names); if(precision != null) { if(scale != null) pg.set(precision.intValue(), scale.intValue()); else pg.set(precision.intValue()); } if(intervalType != null) { if(iPrecision != null && iScale != null) pg.set(iPrecision.intValue(), intervalType.intValue(), iScale.intValue()); else if(iPrecision != null) pg.set(iPrecision.intValue(), intervalType.intValue(), 0); else pg.set(intervalType.intValue()); } if(withTimeZone != null) { if(precision != null) pg.set(precision.intValue(), withTimeZone.booleanValue()); else pg.set(withTimeZone.booleanValue()); } dataType = pg; break; case ORACLE: Table.Column.OracleDataType oracle = new Table.Column.OracleDataType(type); if(precision != null) { if(scale != null) oracle.set(precision.intValue(), scale.intValue()); else oracle.set(precision.intValue()); } if(intervalType != null) { if(iPrecision != null && iScale != null) oracle.set(iPrecision.intValue(), intervalType.intValue(), iScale.intValue()); else if(iPrecision != null) oracle.set(iPrecision.intValue(), intervalType.intValue(), 0); else oracle.set(intervalType.intValue()); } if(withTimeZone != null) { if(precision != null) oracle.set(precision.intValue(), withTimeZone.booleanValue()); else oracle.set(withTimeZone.booleanValue()); } dataType = oracle; break; default://TODO } return dataType; } protected void parseConstraint(int offset, int length) { if(log.isDebugEnabled()) log.debug("constraint to parse: {}", sb.substring(offset, length)); int origin = position; position = offset; Table.Constraint constraint = null; String keyword = nextWord(); //mysql way if("PRIMARY".equalsIgnoreCase(keyword)) { match(nextWord(), "KEY"); constraint = table.new PrimaryKey(); } else if("UNIQUE".equalsIgnoreCase(keyword)) { match(nextWord(), "INDEX"); constraint = table.new UniqueKey(); } else if("INDEX".equalsIgnoreCase(keyword)) { constraint = table.new Index(); } else if("CONSTRAINT".equalsIgnoreCase(keyword)) { constraint = table.new ForeignKey(); } else if("CHECK".equalsIgnoreCase(keyword)) { constraint = table.new Check(); } if(sb.charAt(position) != '(') {//may not exist! String name = nextWord(); constraint.setName(name); } if(constraint instanceof Table.ForeignKey) { match(nextWord(), "FOREIGN"); match(nextWord(), "KEY"); } else if(constraint instanceof Table.Check) { addConstraint((Table.Check) constraint); return; } String[] columnNames = findColumnNames(); Table.Column[] columns = new Table.Column[columnNames.length]; for(int i = 0; i < columnNames.length; i++) columns[i] = findColumn(columnNames[i]); constraint.setColumns(columns); if(constraint instanceof Table.ForeignKey) { parseForeignKey((Table.ForeignKey) constraint); } else if(constraint instanceof Table.Index) { parseIndex((Table.Index) constraint); } else if(constraint instanceof Table.Check) { parseCheck((Table.Check) constraint); } else addConstraint(constraint);//common process position = origin; } protected void addConstraint(Table.Constraint constaint) { table.addConstraint(constaint); } protected void parseForeignKey(Table.ForeignKey fk) { position++; match(nextWord(), "REFERENCES"); Table reference = new Table(dialect); Stack<String> names = parseTableName(); reference.setName(names.pop()); if(!names.empty()) reference.setSchema(names.pop()); if(!names.empty()) reference.setCatalog(names.pop()); String[] columnNames = findColumnNames(); Table.Column[] columns = new Table.Column[columnNames.length]; for(int i = 0; i < columnNames.length; i++) { columns[i] = new Table.Column(columnNames[i], null); columns[i].setTable(reference); } fk.setReferences(columns); table.addConstraint(fk); } protected void parseIndex(Table.Index index) { String guess = nextWord(); if("USING".equalsIgnoreCase(guess)) { index.setAlgorithm(nextWord()); } table.addConstraint(index); } protected void parseCheck(Table.Check check) { int deep = 0, lb = 0, rb = 0; boolean quoted = false; for(; position < sb.length(); position++) { if(sb.charAt(position) == '(' && !quoted) { if(deep == 0) lb = position; deep++; } else if(sb.charAt(position) == ')' && !quoted) { deep if(deep == 0) { rb = position; check.setSearchCondition(sb.substring(lb + 1, rb)); table.addConstraint(check); break; } } else if(sb.charAt(position) == '\'') quoted = !quoted; } } /** * COLLATE, COMMENT, ENGINE etc. * param=value */ protected void parseTableSuffixInfo() { String total = nextWord(position, sb.length(), ';'); int length = position + total.length(); while(position < length) { String param = nextWord(position, length, '=');//mysql position = position + param.length() + 1; if(sb.charAt(position) == ' ') position++; String value = nextWord(position, sb.length()); if("COMMENT".equalsIgnoreCase(param.trim())) table.setComment(value); position = position + value.length() + 1; } position = length + 1; } protected void parseComment() { if(position < sb.length() && sb.charAt(position) == SPACE) position++; if(position == sb.length())//maybe not exist! return; int offset = position; String test = nextWord(); if(!"COMMENT".equalsIgnoreCase(test)) { position = offset; if("ALTER".equalsIgnoreCase(test) || "CREATE".equalsIgnoreCase(test)) parseConstraint(); else skip(offset); return; } match(nextWord(), "ON"); String type = nextWord(); if("TABLE".equalsIgnoreCase(type)) parseTableComment(); else if("COLUMN".equalsIgnoreCase(type)) parseColumnComment(); position++; if(position < sb.length()) parseComment(); } protected void parseTableComment() { Stack<String> names = parseTableName(); match(Table.unquote(names.pop()), table.getName()); match(nextWord(), "IS"); table.setComment(nextWord()); } protected void parseColumnComment() { Stack<String> names = parseTableName(); String columnName = Table.unquote(names.pop()); match(Table.unquote(names.pop()), table.getName()); match(nextWord(), "IS"); for(Table.Column column : table.getColumns()) { if(column.getName().equals(columnName)) column.setComment(nextWord()); } } protected void parseConstraint() { if(position < sb.length() && sb.charAt(position) == SPACE) position++; if(position == sb.length())//maybe not exist! return; int offset = position; String test = nextWord(); if("CREATE".equalsIgnoreCase(test)) { parseIndex(); position++; } else if("ALTER".equalsIgnoreCase(test)) { match(nextWord(), "TABLE"); Stack<String> names = parseTableName(); match(Table.unquote(names.pop()), table.getName()); String tmp = nextWord(); if(!"ADD".equalsIgnoreCase(tmp)) { skip(offset); return; } match(nextWord(), "CONSTRAINT"); String unknow = nextWord(); String name = null; Table.Constraint constraint = null; if(!"PRIMARY".equalsIgnoreCase(unknow) && !"UNIQUE".equalsIgnoreCase(unknow) && !"FOREIGN".equalsIgnoreCase(unknow) && !"CHECK".equalsIgnoreCase(unknow)) { name = unknow; unknow = nextWord(); } if("PRIMARY".equalsIgnoreCase(unknow)) { match(nextWord(), "KEY"); constraint = table.new PrimaryKey(); } else if("UNIQUE".equalsIgnoreCase(unknow)) { if(sb.charAt(position) != '(') match(nextWord(), "INDEX"); constraint = table.new UniqueKey(); } else if("FOREIGN".equalsIgnoreCase(unknow)) { match(nextWord(), "KEY"); constraint = table.new ForeignKey(); } else if("CHECK".equalsIgnoreCase(unknow)) {//FIXME constraint = table.new Check(); } constraint.setName(name); String[] columnNames = findColumnNames(); Table.Column[] columns = new Table.Column[columnNames.length]; for(int i = 0; i < columnNames.length; i++) { columns[i] = findColumn(columnNames[i]); } constraint.setColumns(columns); if("FOREIGN".equalsIgnoreCase(unknow)) { if(position < sb.length() && sb.charAt(position) == SPACE) position++; match(nextWord(), "REFERENCES"); Table reference = new Table(dialect); reference.setName(parseTableName().pop()); String[] refColumns = findColumnNames(); Table.Column[] cols = new Table.Column[refColumns.length]; for(int i = 0; i < refColumns.length; i++) { cols[i] = new Table.Column(refColumns[i], null); cols[i].setTable(reference); } ((Table.ForeignKey) constraint).setReferences(cols); } table.addConstraint(constraint); position++; } else if("COMMENT".equalsIgnoreCase(test)){ position = offset; parseComment(); return; } else { skip(offset); } if(position < sb.length()) parseConstraint(); } protected void parseIndex() { String test = nextWord(); if("UNIQUE".equalsIgnoreCase(test)) test = nextWord(); if(!"INDEX".equalsIgnoreCase(test)) {//synonym for(; position < sb.length(); position++) if(sb.charAt(position) == ';') return; } Table.Index index = table.new Index(); String unknow = nextWord(); if(!"ON".equalsIgnoreCase(unknow)) { index.setName(unknow); match(nextWord(), "ON"); } Stack<String> names = parseTableName(); match(Table.unquote(names.pop()), table.getName()); if(sb.charAt(position) != '(') { String guess = nextWord(); if("USING".equalsIgnoreCase(guess)) index.setAlgorithm(nextWord()); } String[] columnNames = findColumnNames(); Table.Column[] columns = new Table.Column[columnNames.length]; for(int i = 0; i < columnNames.length; i++) { columns[i] = findColumn(columnNames[i]); } index.setColumns(columns); table.addIndex(index); } private boolean isSpace(char c) { return c == SPACE || c == LINE_FEED || c == CARRIAGE_RETURN || c == TAB; } private boolean shouldStop(char c) { return shouldStop(c, SPACE); } private boolean shouldStop(char actual, char expect) { return actual == expect; } private void match(String actual, String expect) { if(!actual.equalsIgnoreCase(expect)) throw new RuntimeException(String.format("syntax error, keyword [%s] expected, but actual is [%s]", expect, actual)); } private String[] findColumnNames() { List<String> columnNames = new ArrayList<String>(); int deep = 0, offset = position + 1; for(; position < sb.length(); position++) { if(sb.charAt(position) == '(') { deep++; } if(sb.charAt(position) == ')') { deep if(deep == 0) { columnNames.add(sb.substring(offset, position++).trim()); break; } } if(sb.charAt(position) == ',') { columnNames.add(sb.substring(offset, position).trim()); offset = position + 1; } } String[] result = new String[columnNames.size()]; return columnNames.toArray(result); } private Table.Column findColumn(String name) { return findColumn(name, table); } private Table.Column findColumn(String name, Table table) { for(Table.Column column : table.getColumns()) { if(column.getName().equals(Table.unquote(name)) || (dialect != Dialect.POSTGRES && column.getName().equalsIgnoreCase(Table.unquote(name)))) return column; } log.error("column [{}] not find", name); return null; } private void skip() { int offset = position; for(; position < sb.length(); position++) { if(sb.charAt(position) == ';') { position++; break; } } skip(offset, position); } private void skip(int start) { position = start; skip(); } private void skip(int start, int end) { if(log.isDebugEnabled()) log.debug("skip some ddl information: {}", sb.substring(start, end)); } private enum CommentType { LINE, BLOCK } }
package net.mollywhite.mbta.api; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; public enum Station { ALEWIFE ("Alewife", Pattern.compile("alewife"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), DAVIS ("Davis", Pattern.compile("davis[^\\w]"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), PORTER ("Porter", Pattern.compile("porter[^\\w]"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), HARVARD ("Harvard", Pattern.compile("harvard (?!ave)"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), CENTRAL ("Central", Pattern.compile("central (?!ave)"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), KENDALLMIT ("Kendall/MIT", Pattern.compile("(kendall|[^\\w]mit[^\\w])"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), CHARLESMGH ("Charles/MGH", Pattern.compile("(charles|[^\\w]mgh[^\\w])"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), PARKST ("Park Street", Pattern.compile("[^\\w]park[^\\w]"), Lists.newArrayList(Line.RED, Line.GREEN), Lists.newArrayList(Branch.B, Branch.C, Branch.D, Branch.E, Branch.ASHMONT, Branch.BRAINTREE)), DOWNTOWNCROSSING ("Downtown Crossing", Pattern.compile("downtown"), Lists.newArrayList(Line.RED, Line.ORANGE), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), SOUTHSTATION ("South Station", Pattern.compile("south st(?!reet)"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), BROADWAY ("Broadway", Pattern.compile("broadway"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), ANDREW ("Andrew", Pattern.compile("[^\\w]andrew[^\\w]"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), JFKUMASS ("JFK/UMass", Pattern.compile("(jfk|umass)"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT, Branch.BRAINTREE)), SAVINHILL ("Savin Hill", Pattern.compile("savin"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT)), FIELDSCORNER ("Fields Corner", Pattern.compile("[^\\w]fields[^\\w]"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT)), SHAWMUT ("Shawmut", Pattern.compile("shawmut"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT)), ASHMONT ("Ashmont", Pattern.compile("ashmont"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.ASHMONT)), CEDARGROVE ("Cedar Grove", Pattern.compile("[^\\w]cedar[^\\w]"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.MATTAPAN)), BUTLER ("Butler", Pattern.compile("[^\\w]butler[^\\w]"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.MATTAPAN)), MILTON ("Milton", Pattern.compile("[^\\w]milton[^\\w]"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.MATTAPAN)), CENTRALAVE ("Central Avenue", Pattern.compile("central ave"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.MATTAPAN)), VALLEYRD ("Valley Road", Pattern.compile("valley"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.MATTAPAN)), CAPENST ("Capen Street", Pattern.compile(" capen[^\\w]"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.MATTAPAN)), MATTAPAN ("Mattapan", Pattern.compile("mattapan"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.MATTAPAN)), NORTHQUINCY ("North Quincy", Pattern.compile("n(orth|o\\.?|\\.)? quincy"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.BRAINTREE)), WOLLASTON ("Wollaston", Pattern.compile("wollaston"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.BRAINTREE)), QUINCYCENTER ("Quincy Center", Pattern.compile("quincy c"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.BRAINTREE)), QUINCYADAMS ("Quincy Adams", Pattern.compile("quincy adams"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.BRAINTREE)), BRAINTREE ("Braintree", Pattern.compile("braintree"), Lists.newArrayList(Line.RED), Lists.newArrayList(Branch.BRAINTREE)), OAKGROVE ("Oak Grove", Pattern.compile("oak grove"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), MALDENCENTER ("Malden Center", Pattern.compile("malden"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), WELLINGTON ("Wellington", Pattern.compile("wellington"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), ASSEMBLY ("Assembly", Pattern.compile("assembly"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), SULLIVANSQ ("Sullivan Square", Pattern.compile("sullivan"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), COMMUNITYCOLLEGE ("Community College", Pattern.compile("comm(unity)?\\.? college"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), NORTHSTATION ("North Station", Pattern.compile("n(orth|o\\.?|\\.)? st"), Lists.newArrayList(Line.ORANGE, Line.GREEN), Lists.newArrayList(Branch.C, Branch.E)), HAYMARKET ("Haymarket", Pattern.compile("haymarket"), Lists.newArrayList(Line.ORANGE, Line.GREEN), Lists.newArrayList(Branch.C, Branch.E)), STATE ("State", Pattern.compile("[^\\w]state[^\\w]"), Lists.newArrayList(Line.ORANGE, Line.BLUE), Collections.<Branch>emptyList()), CHINATOWN ("Chinatown", Pattern.compile("chinatown"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), TUFTSMEDICALCENTER ("Tufts Medical Center", Pattern.compile("tufts"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), BACKBAY ("Back Bay", Pattern.compile("back bay"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), MASSAVE ("Massachusetts Avenue", Pattern.compile("mass(achusetts)?\\.? ave"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), RUGGLES ("Ruggles", Pattern.compile("ruggles"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), ROXBURYCROSSING ("Roxbury Crossing", Pattern.compile("roxbury cr"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), JACKSONSQ ("Jackson Square", Pattern.compile("[^\\w]jackson"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), STONYBROOK ("Stony Brook", Pattern.compile("[^\\w]stony"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), GREENST ("Green Street", Pattern.compile("green st"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), FORESTHILLS ("Forest Hills", Pattern.compile("forest hills"), Lists.newArrayList(Line.ORANGE), Collections.<Branch>emptyList()), WONDERLAND ("Wonderland", Pattern.compile("wonderland"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), REVEREBEACH ("Revere Beach", Pattern.compile("revere"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), BEACHMONT ("Beachmont", Pattern.compile("beachmont"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), SUFFOLKDOWNS ("Suffolk Downs", Pattern.compile("suffolk downs"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), ORIENTHEIGHTS ("Orient Heights", Pattern.compile("orient"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), WOODISLAND ("Wood Island", Pattern.compile("wood island"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), AIRPORT ("Airport", Pattern.compile("airport st"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), MAVERICK ("Maverick", Pattern.compile("maverick"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), AQUARIUM ("Aquarium", Pattern.compile("aquarium"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), GOVTCTR ("Government Center", Pattern.compile("gov(ernment|t\\.?) (center|ctr)"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), BOWDOIN ("Bowdoin", Pattern.compile("bowdoin"), Lists.newArrayList(Line.BLUE), Collections.<Branch>emptyList()), LECHMERE ("Lechmere", Pattern.compile("lechmere"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), SCIENCEPARKWESTEND ("Science Park/West End", Pattern.compile("science park"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), BOYLSTON ("Boylston", Pattern.compile("boylston"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B, Branch.C, Branch.D, Branch.E)), ARLINGTON ("Arlington", Pattern.compile("arlington"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B, Branch.C, Branch.D, Branch.E)), COPLEY ("Copley", Pattern.compile("copley"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B, Branch.C, Branch.D, Branch.E)), PRUDENTIAL ("Prudential", Pattern.compile("pru(dential)?[^\\w]"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), SYMPHONY ("Symphony", Pattern.compile("symphony"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), NORTHEASTERN ("Northeastern", Pattern.compile("northeastern"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), MUSEUMOFFINEARTS ("Museum of Fine Arts", Pattern.compile("museum|mofa"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), LONGWOODMEDICALAREA ("Longwood Medical Area", Pattern.compile("longwood"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), BRIGHAMCIRCLE ("Brigham Circle", Pattern.compile("brigham"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), FENWOODRD ("Fenwood Road", Pattern.compile("fenwood"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), MISSIONPARK ("Mission Park", Pattern.compile("mission park"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), RIVERWAY ("Riverway", Pattern.compile("riverway"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), BACKOFTHEHILL ("Back of the Hill", Pattern.compile("back of the hill"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), HEATH ("Heath", Pattern.compile("heath"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.E)), HYNESCONVENTIONCTR ("Hynes Convention Center", Pattern.compile("hynes"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B, Branch.C, Branch.D)), KENMORE ("Kenmore", Pattern.compile("kenmore"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B, Branch.C, Branch.D)), FENWAY ("Fenway", Pattern.compile("fenway"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), LONGWOOD ("Longwood", Pattern.compile("longwood"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), BROOKLINEVILLAGE ("Brookline Village", Pattern.compile("brookline village"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), BROOKLINEHILLS ("Brookline Hills", Pattern.compile("brookline hills"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), BEACONSFIELD ("Beaconsfield", Pattern.compile("beaconsfield"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), RESERVOIR ("Reservoir", Pattern.compile("reservoir"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), CHESTNUTHILL ("Chestnut Hill", Pattern.compile("chestnut"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), NEWTONCENTRE ("Newton Centre", Pattern.compile("newton c"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), NEWTONHIGHLANDS ("Newton Highlands", Pattern.compile("newton high"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), ELIOT ("Eliot", Pattern.compile("[^\\w]eliot"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), WABAN ("Waban", Pattern.compile("waban"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), WOODLAND ("Woodland", Pattern.compile("woodland"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), RIVERSIDE ("Riverside", Pattern.compile("riverside"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.D)), STMARYSST ("St. Marys Street", Pattern.compile("[^\\w]s(t\\.?|aint)[^\\w]mary"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), HAWESST ("Hawes Street", Pattern.compile("[^\\w]hawes[^\\w]"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), KENTST ("Kent Street", Pattern.compile("[^\\w]kent[^\\w]"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), STPAULSTC ("St. Paul Street", Pattern.compile("[^\\w]s(t\\.?|aint)[^\\w]paul"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), COOLIDGECORNER ("Coolidge Corner", Pattern.compile("coolidge"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), SUMMITAVE ("Summit Avenue", Pattern.compile("[^\\w]summit"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), BRANDONHALL ("Brandon Hall", Pattern.compile("brandon hall"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), FAIRBANKSST ("Fairbanks", Pattern.compile("fairbank"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), WASHINGTONSQ ("Washington Square", Pattern.compile("washington sq"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), TAPPANST ("Tappan Street", Pattern.compile("tappan"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), DEANRD ("Dean Road", Pattern.compile("[^\\w]dean[^\\w]"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), ENGLEWOODAVE ("Englewood Avenue", Pattern.compile("eng(le|el)wood"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), CLEVELANDCIRCLE ("Cleveland Circle", Pattern.compile("cleveland"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.C)), BLANDFORDST ("Blandford Street", Pattern.compile("blandford"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), BUEAST ("Boston University East", Pattern.compile("[^\\w](bu|b\\.u\\.|boston univ(ersity)?)[^\\w] e"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), BUCENTRAL ("Boston University Central", Pattern.compile("[^\\w](bu|b\\.u\\.|boston univ(ersity)?)[^\\w] cent"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), BUWEST ("Boston University West", Pattern.compile("[^\\w](bu|b\\.u\\.|boston univ(ersity)?)[^\\w] w"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), STPAULSTB ("St. Paul Street", Pattern.compile("[^\\w]s(t\\.?|aint)[^\\w]paul"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), PLEASANTST ("Pleasant Street", Pattern.compile("pleasant"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), BABCOCKST ("Babcock Street", Pattern.compile("babcock"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), PACKARDSCORNER ("Packards Corner", Pattern.compile("packards"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), HARVARDAVE ("Harvard Avenue", Pattern.compile("harvard av"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), GRIGGSST ("Griggs Street/Long Avenue", Pattern.compile("griggs"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), ALLSTONST ("Allston Street", Pattern.compile("allston st"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), WARRENST ("Warren Street", Pattern.compile("[^\\w]warren[^\\w]"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), WASHINGTONST ("Washington Street", Pattern.compile("washington st"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), SUTHERLANDRD ("Sutherland Road", Pattern.compile("sutherland"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), CHISWICKRD ("Chiswick Road", Pattern.compile("chiswick"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), CHESTNUTHILLAVE ("Chestnut Hill Avenue", Pattern.compile("chestnut"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), SOUTHST ("South Street", Pattern.compile("[^\\w]south st"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)), BOSTONCOLLEGE ("Boston College", Pattern.compile("([^\\w]bc[^\\w]|boston college)"), Lists.newArrayList(Line.GREEN), Lists.newArrayList(Branch.B)); private final String name; private final Pattern searchTerm; private final List<Line> lines; private final List<Branch> branches; Station(String name, Pattern searchTerm, List<Line> lines, List<Branch> branches) { this.name = name; this.searchTerm = searchTerm; this.lines = lines; this.branches = branches; } public String getName() { return name; } public Pattern getSearchTerm() { return searchTerm; } public List<Line> getLines() { return lines; } public List<Branch> getBranches() { return branches; } }
package org.animotron.manipulator; import org.animotron.exception.AnimoException; import org.animotron.io.PipedOutput; import org.animotron.statement.Statement; import org.animotron.statement.Statements; import org.animotron.statement.operator.AN; import org.animotron.statement.operator.Reference; import org.animotron.statement.operator.Utils; import org.animotron.statement.relation.USE; import org.animotron.utils.MessageDigester; import org.jetlang.channels.Channel; import org.jetlang.channels.MemoryChannel; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.traversal.Evaluation; import org.neo4j.graphdb.traversal.Evaluator; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.kernel.Traversal; import org.neo4j.kernel.Uniqueness; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.concurrent.CountDownLatch; import static org.animotron.graph.RelationshipTypes.REF; import static org.animotron.graph.RelationshipTypes.RESULT; import static org.neo4j.graphdb.Direction.OUTGOING; import static org.neo4j.graphdb.traversal.Evaluation.*; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class PFlow { private final Manipulator m; public final Channel<QCAVector> answer = new MemoryChannel<QCAVector>(); public final Channel<PFlow> question = new MemoryChannel<PFlow>(); public final Channel<Throwable> stop = new MemoryChannel<Throwable>(); protected final PFlow parent; private Relationship op = null; private Node opNode = null; private Vector<QCAVector> path = new Vector<QCAVector>(); public PFlow(Manipulator m) { parent = null; this.m = m; } public PFlow(Manipulator m, Relationship op) { parent = null; this.m = m; this.op = op; path.add(new QCAVector(op)); } public PFlow(PFlow parent) { this.parent = parent; this.m = parent.m; //XXX: maybe, clone faster? path.addAll(parent.path); } @Deprecated //use one with vector public PFlow(PFlow parent, Relationship op) throws AnimoException { // System.out.print("new PFlow "); // System.out.println("this = "+Utils.shortID(this)+" parent = "+Utils.shortID(parent)); // System.out.print(" "+(new IOException()).getStackTrace()[1]); // System.out.println(" "+op); this.parent = parent; this.m = parent.m; //XXX: maybe, clone faster? path.addAll(parent.path); cyclingDetection(op); if (path.isEmpty()) path.add(new QCAVector(op)); else if (!path.firstElement().getQuestion().equals(op)) path.add(new QCAVector(op, path.firstElement())); this.op = op; } public PFlow(PFlow parent, Node opNode) { this.parent = parent; this.m = parent.m; //XXX: maybe, clone faster? path.addAll(parent.path); this.opNode = opNode; } public PFlow(PFlow parent, QCAVector vector) { this.parent = parent; this.m = parent.m; //XXX: maybe, clone faster? path.addAll(parent.path); addContextPoint(vector); this.op = vector.getUnrelaxedClosest(); } protected void cyclingDetection() throws AnimoException { cyclingDetection(getOP()); } private void cyclingDetection(Relationship op) throws AnimoException { int deep = 0; int count = 0; for (QCAVector v : path) { if (deep > 0 && v.haveRelationship(op)) { if (count > 2) throw new AnimoException(op, "cycling detected "+path); else count++; } deep++; } } public PFlow getParent() { return parent; } public Relationship getOP() { return op; } //XXX: still required? public Relationship getStartOP() { return path.lastElement().getQuestion(); } //XXX: still required? public Node getStartNode() { return path.lastElement().getQuestion().getEndNode(); } public Node getOPNode() { if (opNode != null) return opNode; return op.getEndNode(); } protected void setOPNode(Node opNode) { this.opNode = opNode; this.op = null; } public void sendAnswer(QCAVector r) { if (parent == null) { System.out.println("WORNG - no parent"); throw new IllegalArgumentException("NULL parent @pflow"); } else { parent.answer.publish(r); } } public void sendAnswer(Relationship answer) { sendAnswer(answer, RESULT, getPathHash()); } public void sendAnswer(Relationship answer, RelationshipType rType, byte[] hash) { if (parent == null) { System.out.println("WORNG - no parent"); throw new IllegalArgumentException("NULL parent @pflow"); } else { //System.out.println("send answer to "+parent.answer+" (parent = "+parent+")"); Relationship createdAnswer = Utils.createResult( this, op.getEndNode(), answer, rType, hash ); parent.answer.publish(path.firstElement().answered(createdAnswer)); } } public void sendAnswer(QCAVector answerVector, RelationshipType rType) { if (parent == null) { System.out.println("WORNG - no parent"); throw new IllegalArgumentException("NULL parent @pflow"); } else { //System.out.println("send answer to "+parent.answer+" (parent = "+parent+")"); Relationship answer = Utils.createResult(this, answerVector.getContext(), op.getEndNode(), answerVector.getAnswer(), rType); parent.answer.publish(new QCAVector(op, answer, answerVector.getContext(), answerVector.getPrecedingSibling())); } } public void sendAnswer(Relationship answer, QCAVector context) { Relationship createdAnswer = Utils.createResult(this, op.getEndNode(), answer, RESULT); sendAnswer(op, context, createdAnswer); } public void sendAnswer(Relationship question, QCAVector context, Relationship answer) { if (parent == null) { System.out.println("WORNG - no parent"); throw new IllegalArgumentException("NULL parent @pflow"); } else { //System.out.println("send answer to "+parent.answer+" (parent = "+parent+")"); parent.answer.publish(new QCAVector(question, context, answer)); } } public void sendException(Throwable t) { t.printStackTrace(); AnimoException ae; if (t instanceof AnimoException) { ae = (AnimoException) t; ae.addToStack(op); } else { ae = new AnimoException(op, t); } parent.stop.publish(ae); done(); } public void done() { if (parent == null) answer.publish(null); else parent.answer.publish(null); } protected CountDownLatch waitBeforeClosePipe = null; public void waitBeforeClosePipe(int count) { //System.out.println("waitBeforeClosePipe "+count+" "+this); waitBeforeClosePipe = new CountDownLatch(count); // if (parent == null) answer.publish(null); // else parent.answer.publish(null); } public void countDown() { if (waitBeforeClosePipe == null) waitBeforeClosePipe(1); waitBeforeClosePipe.countDown(); //System.out.println("countDown "+waitBeforeClosePipe.getCount()+" "+this); } public void countDown(PipedOutput<?> out) { if (waitBeforeClosePipe == null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } return; } waitBeforeClosePipe.countDown(); if (waitBeforeClosePipe.getCount() == 0) try { out.close(); } catch (IOException e) { e.printStackTrace(); } //System.out.println("countDown "+waitBeforeClosePipe.getCount()+" "+this); } public void await() { if (waitBeforeClosePipe == null) return; try { waitBeforeClosePipe.await(); } catch (InterruptedException e) { sendException(e); e.printStackTrace(); } } public Manipulator getManipulator() { return m; } public List<QCAVector> getPFlowPath() { return path; } public Path getFlowPath() { // System.out.println("Path:"); // for (Relationship r : path) { // System.out.println(r); // int i = 0; // for (Path path : td_flow.traverse(getOPNode())) { // System.out.println(" path = "+path); //System.out.println("OPNode = "+getOPNode()); Path first = null; for (Path path : get_td_flow().traverse(getOPNode())) { if (first == null) { first = path; } boolean haveUse = false; for (Relationship r : path.relationships()) { if (r.isType(USE._)) { haveUse = true; break; } } if (!haveUse) return path; } return first; // Iterator<Path> it = td_flow.traverse(getOPNode()).iterator(); // if (it.hasNext()) // return it.next(); // else { // //what looks wrong! // return null; } public Iterable<Relationship> stack() { return new PFlowStack(); } private class PFlowStack implements Iterator<Relationship>, Iterable<Relationship> { private Iterator<Relationship> it = getFlowPath().relationships().iterator(); private Relationship pos = step(); private Relationship step() { while (it.hasNext()) { Relationship r = it.next(); if (r.isType(AN._)){ return r; } } return null; } @Override public boolean hasNext() { return pos != null; } @Override public Relationship next() { Relationship res = pos; pos = step(); return res; } @Override public void remove() { // TODO Auto-generated method stub } @Override public Iterator<Relationship> iterator() { return this; } } public Iterable<Relationship> getStackContext(Relationship r, boolean goDown) { // return td_context.traverse(node).relationships(); Node node = r.getEndNode(); if (goDown && r.isType(AN._)) { node = node.getSingleRelationship(REF, OUTGOING).getEndNode(); } return node.getRelationships(AN._, OUTGOING); } public QCAVector addContextPoint(QCAVector vector) { boolean debug = false; if (debug) System.out.print("adding "+this+" "+vector); // System.out.println(new IOException().getStackTrace()[1]); if (path.isEmpty()) { if (debug) System.out.println(" (added)"); path.insertElementAt(vector, 0); return vector; } else if (!path.isEmpty()) { QCAVector v = path.get(0); if (v.merged(vector)) { //path.set(0, vector); if (debug) System.out.println(" (merge)"); return vector; } else { path.insertElementAt(vector, 0); if (debug) System.out.println(" (added)"); return vector; } } if (debug) System.out.println(" (ignored)"); return null; } public QCAVector addContextPoint(Relationship r) { return addContextPoint(new QCAVector(r)); } public void popContextPoint(QCAVector vector) { //System.out.println("pop "+this+" "+path); if (vector == null) return; if (path.size() == 0) { System.out.println("WARNING - path is empty"); return; } if (path.get(0) == vector) path.remove(0); } public byte[] getPathHash() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); for (QCAVector p : path) { try { p.collectHash(dos); } catch (IOException e) { } } MessageDigest md = MessageDigester.md(); md.update(bos.toByteArray()); return md.digest(); } public byte[] getOpHash() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); try { dos.writeLong(getOP().getId()); } catch (IOException e) { } MessageDigest md = MessageDigester.md(); md.update(bos.toByteArray()); return md.digest(); } public Relationship getLastContext() { boolean debug = false; if (debug) System.out.print("PFlow get last context "); // for (QCAVector v : path) { // Relationship r = v.getQuestion(); // if (r.isType(AN._)) { // if (debug) System.out.println(r); // return r; // } else if (r.isType(REF)) { // if (debug) System.out.println(r); // return r; // } else if (r.isType(RESULT)) { // if (debug) System.out.println(r); // return r; if (debug) System.out.println(path.lastElement()); return path.lastElement().getQuestion(); } private TraversalDescription get_td_flow() { return Traversal.description().depthFirst(). uniqueness(Uniqueness.RELATIONSHIP_PATH). evaluator(new Evaluator(){ @Override public Evaluation evaluate(Path path) { //System.out.println(" "+path); if (path.length() > 0) { Relationship r = path.lastRelationship(); if (r.getStartNode().equals(path.endNode())) { if (r.equals(getStartOP())) { return INCLUDE_AND_PRUNE; } return EXCLUDE_AND_CONTINUE; //Allow ...<-IS->... } if (path.length() > 1 && r.isType(AN._)) { return EXCLUDE_AND_CONTINUE; } return EXCLUDE_AND_PRUNE; } return EXCLUDE_AND_CONTINUE; } }); } public boolean isInStack(Relationship r) { boolean debug = false; if (debug) System.out.println("IN STACK CHECK "+r+" in "+path+" "); for (QCAVector v : path) { if (v.haveRelationship(r)) { if (debug) System.out.println("FOUND!!!"); return true; } } if (debug) System.out.println("NOT FOUND"); return false; } public void debug() { StringBuilder sb = new StringBuilder(); sb.append("DEBUG PFlow "); //sb.append(Utils.shortID(this)); sb.append("\nPath = "); sb.append(Arrays.toString(path.toArray())); sb.append("\n"); sb.append("OPs "); ops(sb); System.out.println(sb.toString()); } private void ops(StringBuilder sb) { if (op != null) { sb.append(op); sb.append(" ");} if (parent != null) parent.ops(sb); } public QCAVector getVector() { return path.firstElement(); } }
package org.basex.api.jaxrx; import static org.basex.core.Text.*; import java.util.List; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response.ResponseBuilder; import org.basex.BaseXServer; import org.basex.core.Prop; import org.basex.core.Text; import org.basex.server.ClientSession; import org.basex.util.Args; import org.basex.util.Base64; import org.basex.util.Util; import org.jaxrx.JettyServer; import org.jaxrx.core.JaxRxConstants; import org.jaxrx.core.JaxRxException; import org.jaxrx.core.ResourcePath; import com.sun.jersey.core.spi.factory.ResponseBuilderImpl; public final class JaxRxServer extends BaseXServer { /** Configuration: User. */ static final String USER = "org.basex.user"; /** Configuration: Password. */ static final String PASSWORD = "org.basex.password"; /** Configuration: Server port. */ static final String SERVERPORT = "org.basex.serverport"; /** Configuration: JAX-RX path. */ static final String JAXRXPATH = "org.basex.jaxrxpath"; /** Configuration: serializer options. */ static final String SERIALIZER = "org.jaxrx.parameter.output"; /** JAX-RX String. */ static final String JAXRX = "JAX-RX"; /** Jetty server. */ private JettyServer jetty; /** Optional user. */ private String user; /** Optional password. */ private String pass; /** * Main method, launching the JAX-RX implementation. * @param args command-line arguments */ public static void main(final String[] args) { new JaxRxServer(args); } /** * Constructor. * @param args command-line arguments */ public JaxRxServer(final String... args) { super(args); if(!success || service) return; // set default ports and paths set(JAXRXPATH, context.prop.get(Prop.JAXRXPATH), false); set(SERVERPORT, context.prop.num(Prop.SERVERPORT), false); set(SERIALIZER, context.prop.get(Prop.SERIALIZER), false); // retrieve password on command-line if only the user was specified String p = pass; if(user != null) { while(p == null) { Util.out(SERVERPW + COLS); p = password(); } } // set data as system properties set(USER, user == null ? "" : user, user != null); set(PASSWORD, p == null ? "" : p, p != null); // try to login with specified data try { if(!System.getProperty(USER).isEmpty()) login(null).close(); } catch(final Exception ex) { Util.errln(ex.getMessage()); quit(false); return; } // define path and name of the JAX-RX implementation. set(JaxRxConstants.NAMEPROP, Text.NAMELC, false); set(JaxRxConstants.PATHPROP, BXJaxRx.class.getName(), false); // start Jetty server (if not done yet) try { jetty = new JettyServer(context.prop.num(Prop.JAXRXPORT)); Util.outln(JAXRX + ' ' + SERVERSTART); } catch(final Exception ex) { ex.printStackTrace(); Util.server(ex); } } @Override public void quit(final boolean u) { super.quit(u); if(jetty != null) jetty.stop(); } /** * Sets the specified value if property has not been set yet. * @param key property key * @param value property value * @param force force setting */ private void set(final String key, final Object value, final boolean force) { if(force || System.getProperty(key) == null) { System.setProperty(key, value.toString()); } } /** * Logs in and returns a client session. * @param path resource path; may be {@code null} * @return client session * @throws Exception exception */ static ClientSession login(final ResourcePath path) throws Exception { String[] id = updateIdentity(path); if(id == null) id = new String[] { System.getProperty(JaxRxServer.USER), System.getProperty(JaxRxServer.PASSWORD) }; final int p = Integer.parseInt(System.getProperty(JaxRxServer.SERVERPORT)); return new ClientSession(Text.LOCALHOST, p, id[0], id[1]); } /** * Reads user identity and user credentials from HTTP header. * @param path {@link ResourcePath} instance. * @return login/password combination or {@code null} if no user was * specified. */ private static String[] updateIdentity(final ResourcePath path) { if(path == null) return null; final HttpHeaders headers = path.getHttpHeaders(); final List<String> authorization = headers.getRequestHeader(HttpHeaders.AUTHORIZATION); if(authorization != null) { for(final String value : authorization) { final String[] values = value.split(" "); if(values[0].equalsIgnoreCase("basic")) { final String[] cred = Base64.decode(values[1]).split(":", 2); if(cred.length < 2) { final ResponseBuilder rb = new ResponseBuilderImpl(); rb.header(HttpHeaders.WWW_AUTHENTICATE, "Basic "); rb.status(401); rb.entity("No password specified."); throw new JaxRxException(rb.build()); } return cred; } throw new JaxRxException(500, "Unsupported authorization mode."); } } return null; } @Override public boolean parseArguments(final String[] args) { final Args arg = new Args(args, this, JAXRXINFO, Util.info(CONSOLE, JAXRX)); boolean daemon = false; final StringBuilder serial = new StringBuilder(); while(arg.more()) { if(arg.dash()) { final char c = arg.next(); if(c == 'D') { // hidden flag: daemon mode daemon = true; } else if(c == 'j') { // parse JAX-RX server port context.prop.set(Prop.JAXRXPORT, arg.num()); } else if(c == 'p') { // parse server port set(SERVERPORT, arg.num(), true); } else if(c == 'P') { // specify password pass = arg.string(); } else if(c == 's') { // set service flag service = !daemon; } else if(c == 'S') { // set/add serialization parameter if(serial.length() != 0) serial.append(','); serial.append(arg); set(SERIALIZER, serial, true); } else if(c == 'U') { // specify user name user = arg.string(); } else if(c == 'z') { // suppress logging quiet = true; } else { arg.check(false); } } else { arg.check(false); if(arg.string().equalsIgnoreCase("stop")) { stop(context.prop.num(Prop.SERVERPORT)); return false; } } } return arg.finish(); } }
package org.chocosolver.solver; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import org.chocosolver.solver.exception.SolverException; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.solver.variables.RealVar; import org.chocosolver.solver.variables.SetVar; import org.chocosolver.solver.variables.Variable; import java.util.Arrays; /** * Class which stores the value of each variable in a solution * <br/> * * @author Jean-Guillaume Fages * @author Charles Prud'homme * @since 05/06/2013 */ public class Solution implements ICause { /** No entry value for maps */ /** Set to <tt>true</tt> when this object is empty */ /** Maps of value for integer variable (id - value) */ /** Maps of value for real variable (id - value) */ /** Maps of value for set variable (id - values) */ /** Model to store */ /** Variables to store; */ /** * Create an empty solution object * able to store the value of each variable in <code>varsToStore</code> when calling <code>record()</code> * * @param model model of the solution * @param varsToStore variables to store in this object */ public Solution(Model model, Variable... varsToStore) { this.varsToStore = varsToStore; empty = true; this.model = model; } /** * Records the current solution of the solver * clears all previous recordings * @return this object */ public Solution record() { empty = false; boolean warn = false; if (varsToStore.length == 0) { varsToStore = model.getSolver().getSearch().getVariables(); } assert varsToStore.length > 0; if (intmap != null) { intmap.clear(); } if (realmap != null) { realmap.clear(); } if (setmap != null) { setmap.clear(); } for (Variable var : varsToStore) { if ((var.getTypeAndKind() & Variable.TYPE) != Variable.CSTE) { int kind = var.getTypeAndKind() & Variable.KIND; if (var.isInstantiated()) { switch (kind) { case Variable.INT: case Variable.BOOL: if (intmap == null) { intmap = new TIntIntHashMap(16, .5f, Solution.NO_ENTRY, Solution.NO_ENTRY); } IntVar v = (IntVar) var; intmap.put(v.getId(), v.getValue()); break; case Variable.REAL: if (realmap == null) { realmap = new TIntObjectHashMap<>(16, 05f, Solution.NO_ENTRY); } RealVar r = (RealVar) var; realmap.put(r.getId(), new double[]{r.getLB(), r.getUB()}); break; case Variable.SET: if (setmap == null) { setmap = new TIntObjectHashMap<>(16, 05f, Solution.NO_ENTRY); } SetVar s = (SetVar) var; setmap.put(s.getId(), s.getValue().toArray()); break; default: // do not throw exception to allow extending the solver with other variable kinds (e.g. graph) // that should then be stored externally to this object break; } } else { warn = true; } } } if (warn && varsToStore[0].getModel().getSettings().warnUser()) { model.getSolver().getOut().printf("Some non decision variables are not instantiated in the current solution."); } return this; } @Override public String toString() { if (empty) { return "Empty solution. No solution recorded yet"; } StringBuilder st = new StringBuilder("Solution: "); for (Variable var : varsToStore) { if ((var.getTypeAndKind() & Variable.TYPE) != Variable.CSTE) { int kind = var.getTypeAndKind() & Variable.KIND; switch (kind) { case Variable.INT: case Variable.BOOL: IntVar v = (IntVar) var; st.append(v.getName()).append("=").append(intmap.get(v.getId())).append(", "); break; case Variable.REAL: RealVar r = (RealVar) var; double[] bounds = realmap.get(r.getId()); st.append(r.getName()).append("=[").append(bounds[0]).append(",").append(bounds[1]).append("], "); break; case Variable.SET: SetVar s = (SetVar) var; st.append(s.getName()).append("=").append(Arrays.toString(setmap.get(s.getId()))).append(", "); break; default: // do not throw exception to allow extending the solver with other variable kinds (e.g. graph) // that should then be stored externally to this object break; } } } return st.toString(); } public Solution copySolution() { Solution ret = new Solution(model, varsToStore); ret.empty = empty; ret.intmap = new TIntIntHashMap(intmap); ret.realmap = new TIntObjectHashMap<>(realmap); ret.setmap = new TIntObjectHashMap<>(setmap); return ret; } /** * Get the value of variable v in this solution * * @param v IntVar (or BoolVar) * @return the value of variable v in this solution, or null if the variable is not instantiated in the solution */ public int getIntVal(IntVar v) { if (empty) { throw new SolverException("Cannot access value of "+v+": No solution has been recorded yet (empty solution). Make sure this.record() has been called."); } if (intmap.containsKey(v.getId())) { return intmap.get(v.getId()); } else { if ((v.getTypeAndKind() & Variable.TYPE) == Variable.CSTE) { return v.getValue(); } else { throw new SolverException("Cannot access value of "+v+": This variable has not been declared to be recorded in the Solution object (see Solution constructor)."); } } } /** * Set the value of variable v in this solution * * @param var IntVar (or BoolVar) * @param val its value */ public void setIntVal(IntVar var, int val) { if (intmap == null) { intmap = new TIntIntHashMap(16, .5f, Solution.NO_ENTRY, Solution.NO_ENTRY); } intmap.put(var.getId(), val); } /** * Get the value of variable s in this solution * * @param s SetVar * @return the value of variable s in this solution, or null if the variable is not instantiated in the solution */ public int[] getSetVal(SetVar s) { if (empty) { throw new SolverException("Cannot access value of "+s+": No solution has been recorded yet (empty solution). Make sure this.record() has been called."); } if (setmap.containsKey(s.getId())) { return setmap.get(s.getId()); } else if ((s.getTypeAndKind() & Variable.TYPE) == Variable.CSTE) { return s.getValue().toArray(); } else { throw new SolverException("Cannot access value of "+s+": This variable has not been declared to be recorded in the Solution object (see Solution constructor)."); } } /** * Set the value of variable v in this solution * * @param var SetVar * @param val its value */ public void setSetVal(SetVar var, int[] val) { if (setmap == null) { setmap = new TIntObjectHashMap<>(16, 05f, Solution.NO_ENTRY); } setmap.put(var.getId(), val); } /** * Get the bounds of r in this solution * * @param r RealVar * @return the bounds of r in this solution, or null if the variable is not instantiated in the solution */ public double[] getRealBounds(RealVar r) { if (empty) { throw new SolverException("Cannot access value of "+r+": No solution has been recorded yet (empty solution). Make sure this.record() has been called."); } if (realmap.containsKey(r.getId())) { return realmap.get(r.getId()); } else { if ((r.getTypeAndKind() & Variable.TYPE) == Variable.CSTE) { return new double[]{r.getLB(), r.getUB()}; } else { throw new SolverException("Cannot access value of "+r+": This variable has not been declared to be recorded in the Solution object (see Solution constructor)."); } } } /** * Set the value of variable v in this solution * * @param var RealVar * @param val its value */ public void setRealBounds(RealVar var, double[] val){ if (realmap == null) { realmap = new TIntObjectHashMap<>(16, 05f, Solution.NO_ENTRY); } if(val.length != 2){ throw new SolverException("wrong array size"); } realmap.put(var.getId(), val); } }
package org.graphwalker.core.model; import static org.graphwalker.core.model.Vertex.RuntimeVertex; /** * @author Nils Olsson */ public final class Edge extends CachedBuilder<Edge.RuntimeEdge> { private String name; private Vertex sourceVertex; private Vertex targetVertex; public Edge setName(String name) { this.name = name; invalidateCache(); return this; } public String getName() { return name; } public Edge setSourceVertex(Vertex vertex) { this.sourceVertex = vertex; invalidateCache(); return this; } public Vertex getSourceVertex() { return sourceVertex; } public Edge setTargetVertex(Vertex vertex) { this.targetVertex = vertex; invalidateCache(); return this; } public Vertex getTargetVertex() { return targetVertex; } @Override protected RuntimeEdge createCache() { return new RuntimeEdge(this); } public static final class RuntimeEdge extends NamedElement { private final RuntimeVertex sourceVertex; private final RuntimeVertex targetVertex; private RuntimeEdge(Edge edge) { super(edge.getName()); this.sourceVertex = build(edge.getSourceVertex()); this.targetVertex = build(edge.getTargetVertex()); } private <T> T build(Builder<T> builder) { return (null!=builder?builder.build():null); } public RuntimeVertex getSourceVertex() { return sourceVertex; } public RuntimeVertex getTargetVertex() { return targetVertex; } } }
package org.jabref.gui.desktop.os; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.Locale; import java.util.Optional; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.DialogService; import org.jabref.gui.JabRefExecutorService; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.util.StreamGobbler; import org.jabref.logic.l10n.Localization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @AllowedToUseAwt("Requires AWT to open a file with the native method") public class Linux implements NativeDesktop { private static final Logger LOGGER = LoggerFactory.getLogger(Linux.class); private void nativeOpenFile(String filePath) { JabRefExecutorService.INSTANCE.execute(() -> { try { File file = new File(filePath); Desktop.getDesktop().open(file); LOGGER.debug("Open file in default application with Desktop integration"); } catch (IllegalArgumentException e) { LOGGER.debug("Fail back to xdg-open"); try { String[] cmd = {"xdg-open", filePath}; Runtime.getRuntime().exec(cmd); } catch (Exception e2) { LOGGER.warn("Open operation not successful: " + e2); } } catch (IOException e) { LOGGER.warn("Native open operation not successful: " + e); } }); } @Override public void openFile(String filePath, String fileType) throws IOException { Optional<ExternalFileType> type = ExternalFileTypes.getInstance().getExternalFileTypeByExt(fileType); String viewer; if (type.isPresent() && !type.get().getOpenWithApplication().isEmpty()) { viewer = type.get().getOpenWithApplication(); ProcessBuilder processBuilder = new ProcessBuilder(viewer, filePath); Process process = processBuilder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LOGGER::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LOGGER::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } else { nativeOpenFile(filePath); } } @Override public void openFileWithApplication(String filePath, String application) throws IOException { // Use the given app if specified, and the universal "xdg-open" otherwise: String[] openWith; if ((application != null) && !application.isEmpty()) { openWith = application.split(" "); String[] cmdArray = new String[openWith.length + 1]; System.arraycopy(openWith, 0, cmdArray, 0, openWith.length); cmdArray[cmdArray.length - 1] = filePath; ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); Process process = processBuilder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LOGGER::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LOGGER::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } else { nativeOpenFile(filePath); } } @Override public void openFolderAndSelectFile(Path filePath) throws IOException { String desktopSession = System.getenv("DESKTOP_SESSION"); String absoluteFilePath = filePath.toAbsolutePath().toString(); String[] cmd = {"xdg-open", absoluteFilePath}; // default command if (desktopSession != null) { desktopSession = desktopSession.toLowerCase(Locale.ROOT); if (desktopSession.contains("gnome")) { cmd = new String[] {"nautilus", "--select", absoluteFilePath}; } else if (desktopSession.contains("kde") || desktopSession.contains("plasma")) { cmd = new String[] {"dolphin", "--select", absoluteFilePath}; } else if (desktopSession.contains("mate")) { cmd = new String[] {"caja", "--select", absoluteFilePath}; } else if (desktopSession.contains("cinnamon")) { cmd = new String[] {"nemo", absoluteFilePath}; // Although nemo is based on nautilus it does not support --select, it directly highlights the file } } ProcessBuilder processBuilder = new ProcessBuilder((cmd)); Process process = processBuilder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LOGGER::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LOGGER::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } @Override public void openConsole(String absolutePath, DialogService dialogService) throws IOException { if (!Files.exists(Path.of("/etc/alternatives/x-terminal-emulator"))) { dialogService.showErrorDialogAndWait(Localization.lang("Could not detect terminal automatically. Please define a custom terminal in the preferences.")); return; } ProcessBuilder processBuilder = new ProcessBuilder("readlink", "/etc/alternatives/x-terminal-emulator"); Process process = processBuilder.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String emulatorName = reader.readLine(); if (emulatorName != null) { emulatorName = emulatorName.substring(emulatorName.lastIndexOf(File.separator) + 1); String[] cmd = {}; if (emulatorName.contains("gnome")) { cmd = new String[] {"gnome-terminal", "--working-directory=", absolutePath}; } else if (emulatorName.contains("xfce4")) { cmd = new String[] {"xfce4-terminal", "--working-directory=", absolutePath}; } else if (emulatorName.contains("konsole")) { cmd = new String[] {"konsole", "--workdir=", absolutePath}; } else { cmd = new String[] {emulatorName, absolutePath}; } ProcessBuilder builder = new ProcessBuilder(cmd); builder.directory(new File(absolutePath)); builder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LOGGER::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LOGGER::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } } } @Override public String detectProgramPath(String programName, String directoryName) { return programName; } @Override public Path getApplicationDirectory() { return Path.of("/usr/lib/"); } }
package org.jboss.logmanager; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.ServiceLoader; import java.util.concurrent.atomic.AtomicBoolean; /** * Simplified log manager. Designed to work around the (many) design flaws of the JDK platform log manager. */ public final class LogManager extends java.util.logging.LogManager { /** * Construct a new logmanager instance. Attempts to plug a known memory leak in {@link java.util.logging.Level} as * well. */ public LogManager() { AccessController.doPrivileged(new PrivilegedAction<Void>() { @SuppressWarnings ({"unchecked"}) public Void run() { /* This mysterious-looking hack is designed to trick JDK logging into not leaking classloaders and so forth when adding levels, by simply shutting down the craptastic level name "registry" that it keeps. */ final Class<java.util.logging.Level> lc = java.util.logging.Level.class; try { synchronized(lc) { final Field knownField = lc.getDeclaredField("known"); knownField.setAccessible(true); final List<java.util.logging.Level> old = (List<java.util.logging.Level>) knownField.get(null); if (! (old instanceof ReadOnlyArrayList)) { knownField.set(null, new ReadOnlyArrayList<java.util.logging.Level>(Arrays.asList( Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL, java.util.logging.Level.ALL, java.util.logging.Level.FINEST, java.util.logging.Level.FINER, java.util.logging.Level.FINE, java.util.logging.Level.INFO, java.util.logging.Level.CONFIG, java.util.logging.Level.WARNING, java.util.logging.Level.SEVERE, java.util.logging.Level.OFF ))); } } } catch (Throwable e) { // ignore; just don't install } /* Next hack: the default Sun JMX implementation has a horribly inefficient log implementation which kills performance if a custom logmanager is used. We'll just blot that out. */ try { final Class<?> traceManagerClass = Class.forName("com.sun.jmx.trace.Trace"); final Field outField = traceManagerClass.getDeclaredField("out"); outField.setAccessible(true); outField.set(null, null); } catch (Throwable e) { // ignore; just skip it } /* Next hack: Replace the crappy MXBean on the system logmanager, if it's there. */ final Class<java.util.logging.LogManager> lmc = java.util.logging.LogManager.class; try { synchronized (lmc) { final Field loggingMXBean = lmc.getDeclaredField("loggingMXBean"); loggingMXBean.setAccessible(true); loggingMXBean.set(null, LogContext.getSystemLogContext().getLoggingMXBean()); } } catch (Throwable e) { // ignore; just skip it } return null; } }); } private static final class ReadOnlyArrayList<T> extends ArrayList<T> { private static final long serialVersionUID = -6048215349511680936L; private ReadOnlyArrayList(final Collection<? extends T> c) { super(c); } public T set(final int index, final T element) { // ignore return null; } public T remove(final int index) { // ignore return null; } public boolean remove(final Object o) { // ignore return false; } public void clear() { // ignore } protected void removeRange(final int fromIndex, final int toIndex) { // ignore } public Iterator<T> iterator() { final Iterator<T> superIter = super.iterator(); return new Iterator<T>() { public boolean hasNext() { return superIter.hasNext(); } public T next() { return superIter.next(); } public void remove() { // ignore } }; } public ListIterator<T> listIterator(final int index) { final ListIterator<T> superIter = super.listIterator(index); return new ListIterator<T>() { public boolean hasNext() { return superIter.hasNext(); } public T next() { return superIter.next(); } public boolean hasPrevious() { return superIter.hasPrevious(); } public T previous() { return superIter.previous(); } public int nextIndex() { return superIter.nextIndex(); } public int previousIndex() { return superIter.previousIndex(); } public void remove() { // ignore } public void set(final T o) { // ignore } public void add(final T o) { // ignore } }; } public boolean removeAll(final Collection<?> c) { // ignore return false; } public boolean retainAll(final Collection<?> c) { // ignore return false; } } // Configuration private final AtomicBoolean configured = new AtomicBoolean(); private static String tryGetProperty(String name, String defaultVal) { try { return System.getProperty(name, defaultVal); } catch (Throwable t) { return defaultVal; } } public void readConfiguration() throws IOException, SecurityException { checkAccess(); if (configured.getAndSet(true)) { return; } final String confLocClassName = tryGetProperty("org.jboss.logmanager.configurationLocator", null); ConfigurationLocator locator = null; if (confLocClassName != null) { locator = construct(ConfigurationLocator.class, confLocClassName); } else { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); if (tccl != null) { final ServiceLoader<ConfigurationLocator> loader = ServiceLoader.load(ConfigurationLocator.class, tccl); final Iterator<ConfigurationLocator> iterator = loader.iterator(); if (iterator.hasNext()) { locator = iterator.next(); } } if (locator == null) { final ServiceLoader<ConfigurationLocator> loader = ServiceLoader.load(ConfigurationLocator.class, tccl != null ? tccl : LogManager.class.getClassLoader()); final Iterator<ConfigurationLocator> iterator = loader.iterator(); if (iterator.hasNext()) { locator = iterator.next(); } else { locator = new DefaultConfigurationLocator(); } } } if (locator != null) { final InputStream configuration = locator.findConfiguration(); if (configuration != null) { readConfiguration(configuration); } } } /** * Configure the log manager. * * @param inputStream the input stream from which the logmanager should be configured */ public void readConfiguration(InputStream inputStream) throws IOException, SecurityException { try { checkAccess(); configured.set(true); final String confClassName = tryGetProperty("org.jboss.logmanager.configurator", null); Configurator configurator = null; if (confClassName != null) { configurator = construct(Configurator.class, confClassName); } else { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); if (tccl != null) { final ServiceLoader<Configurator> loader = ServiceLoader.load(Configurator.class, tccl); final Iterator<Configurator> iterator = loader.iterator(); if (iterator.hasNext()) { configurator = iterator.next(); } } if (configurator == null) { final ServiceLoader<Configurator> loader = ServiceLoader.load(Configurator.class, LogManager.class.getClassLoader()); final Iterator<Configurator> iterator = loader.iterator(); if (iterator.hasNext()) { configurator = iterator.next(); } else { configurator = new PropertyConfigurator(); } } } if (configurator != null) try { configurator.configure(inputStream); LogContext.getSystemLogContext().getLogger("").attach(Configurator.ATTACHMENT_KEY, configurator); } catch (Throwable t) { t.printStackTrace(); } } finally { try { inputStream.close(); } catch (Throwable ignored) {} } } static <T> T construct(Class<? extends T> type, String className) throws IOException { try { Class<?> clazz = null; try { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); if (tccl != null) { clazz = Class.forName(className, true, tccl); } } catch (ClassNotFoundException ignore) { } if (clazz == null) clazz = Class.forName(className, true, LogManager.class.getClassLoader()); return type.cast(clazz.getConstructor().newInstance()); } catch (Exception e) { final IOException ioe = new IOException("Unable to load configuration class " + className); ioe.initCause(e); throw ioe; } } /** * Do nothing. Properties and their listeners are not supported. * * @param l ignored */ public void addPropertyChangeListener(PropertyChangeListener l) { // no operation - properties are never changed } /** * Do nothing. Properties and their listeners are not supported. * * @param l ignored */ public void removePropertyChangeListener(PropertyChangeListener l) { // no operation - properties are never changed } /** * Does nothing. Properties are not supported. * * @param name ignored * @return {@code null} */ public String getProperty(String name) { // no properties return null; } /** * Does nothing. This method only causes trouble. */ public void reset() { // no operation! } /** * Does nothing. Logger names are not available. * * @return an empty enumeration */ public Enumeration<String> getLoggerNames() { return new Enumeration<String>() { public boolean hasMoreElements() { return false; } public String nextElement() { throw new NoSuchElementException("No elements"); } }; } /** * Do nothing. Loggers are only added/acquired via {@link #getLogger(String)}. * * @param logger ignored * @return {@code false} */ public boolean addLogger(java.util.logging.Logger logger) { return false; } /** * Get or create a logger with the given name. * * @param name the logger name * @return the corresponding logger */ public Logger getLogger(String name) { return LogContext.getLogContext().getLogger(name); } }
package org.jtrfp.trcl; import org.jtrfp.trcl.core.RenderList; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.mem.MemoryWindow; public class ObjectListWindow extends MemoryWindow { public ObjectListWindow(TR tr) { init(tr,"ObjectListWindow"); }// end constructor public final ByteArrayVariable opaqueIDs = new ByteArrayVariable( OBJECT_LIST_SIZE_BYTES_PER_PASS); public final ByteArrayVariable blendIDs = new ByteArrayVariable( OBJECT_LIST_SIZE_BYTES_PER_PASS); public final ByteArrayVariable pageFiller = new ByteArrayVariable(1024); public static final int OBJECT_LIST_SIZE_BYTES_PER_PASS = RenderList.NUM_BLOCKS_PER_PASS * 4; }// end GlobalObjectList
package org.lantern.proxy; import io.netty.handler.codec.http.HttpRequest; import java.net.InetSocketAddress; import javax.net.ssl.SSLSession; import org.lantern.ClientStats; import org.lantern.PeerFactory; import org.lantern.state.Model; import org.lantern.state.Peer; import org.littleshoot.proxy.ActivityTrackerAdapter; import org.littleshoot.proxy.FlowContext; import org.littleshoot.proxy.FullFlowContext; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.SSLEngineSource; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import com.google.inject.Inject; import com.google.inject.Singleton; /** * HTTP proxy server for remote requests to Lantern (i.e. in Give Mode). */ @Singleton public class GiveModeProxy extends AbstractHttpProxyServerAdapter { @Inject public GiveModeProxy( final ClientStats stats, final Model model, final SSLEngineSource sslEngineSource, final PeerFactory peerFactory) { super(DefaultHttpProxyServer .bootstrap() .withName("GiveModeProxy") .withPort(model.getSettings().getServerPort()) .withAllowLocalOnly(false) .withListenOnAllAddresses(false) .withSSLEngineSource(sslEngineSource) // Use a filter to deny requests to non-public ips .withFiltersSource(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new GiveModeHttpFilters(originalRequest); } }) // Keep stats up to date .plusActivityTracker(new ActivityTrackerAdapter() { @Override public void bytesReceivedFromClient( FlowContext flowContext, int numberOfBytes) { stats.addDownBytesFromPeers(numberOfBytes); Peer peer = peerFor(flowContext); if (peer != null) { peer.addBytesDn(numberOfBytes); } } @Override public void bytesSentToServer(FullFlowContext flowContext, int numberOfBytes) { stats.addUpBytesForPeers(numberOfBytes); } @Override public void bytesReceivedFromServer( FullFlowContext flowContext, int numberOfBytes) { stats.addDownBytesForPeers(numberOfBytes); } @Override public void bytesSentToClient(FlowContext flowContext, int numberOfBytes) { stats.addUpBytesToPeers(numberOfBytes); Peer peer = peerFor(flowContext); if (peer != null) { peer.addBytesUp(numberOfBytes); } } @Override public void clientDisconnected( InetSocketAddress clientAddress, SSLSession sslSession) { Peer peer = peerFor(sslSession); if (peer != null) { peer.disconnected(); } } @Override public void clientSSLHandshakeSucceeded( InetSocketAddress clientAddress, SSLSession sslSession) { Peer peer = peerFor(sslSession); if (peer != null) { peer.connected(); } } private Peer peerFor(FlowContext flowContext) { return peerFactory.peerForSession(flowContext .getClientSSLSession()); } private Peer peerFor(SSLSession sslSession) { return peerFactory.peerForSession(sslSession); } })); } }
package org.lightmare.deploy.fs; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.lightmare.cache.ConnectionContainer; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.config.Configuration; import org.lightmare.jpa.datasource.FileParsers; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.rest.providers.RestProvider; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.concurrent.ThreadFactoryUtil; import org.lightmare.utils.fs.WatchUtils; /** * Deployment manager, {@link Watcher#deployFile(URL)}, * {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and * {@link File} modification event handler for deployments if java version is * 1.7 or above * * @author levan * @since 0.0.45-SNAPSHOT */ public class Watcher implements Runnable { // Name of deployment watch service thread private static final String DEPLOY_THREAD_NAME = "watch_thread"; // Priority of deployment watch service thread private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5; // Sleep time of thread between watch service status scans private static final long SLEEP_TIME = 5500L; // Thread pool for watch service threads private static final ExecutorService DEPLOY_POOL = Executors .newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME, DEPLOY_POOL_PRIORITY)); // Sets of directories of application deployments private Set<DeploymentDirectory> deployments; // Sets of data source descriptor file paths private Set<String> dataSources; // Zero / default status for watch service private static final int ZERO_WATCH_STATUS = 0; // Error code for java main process exit private static final int ERROR_EXIT = -1; private static final Logger LOG = Logger.getLogger(Watcher.class); /** * Defines file types for watch service * * @author Levan * @since 0.0.45-SNAPSHOT */ private static enum WatchFileType { DATA_SOURCE, DEPLOYMENT, NONE; } /** * To filter only deployed sub files from directory * * @author levan * @since 0.0.45-SNAPSHOT */ private static class DeployFiletr implements FileFilter { @Override public boolean accept(File file) { boolean accept; try { URL url = file.toURI().toURL(); url = WatchUtils.clearURL(url); accept = MetaContainer.chackDeployment(url); } catch (MalformedURLException ex) { LOG.error(ex.getMessage(), ex); accept = false; } catch (IOException ex) { LOG.error(ex.getMessage(), ex); accept = false; } return accept; } } private Watcher() { deployments = getDeployDirectories(); dataSources = getDataSourcePaths(); } /** * Clears and gets file {@link URL} by file name * * @param fileName * @return {@link URL} * @throws IOException */ private static URL getAppropriateURL(String fileName) throws IOException { URL url; File file = new File(fileName); url = file.toURI().toURL(); url = WatchUtils.clearURL(url); return url; } /** * Gets {@link Set} of {@link DeploymentDirectory} instances from * configuration * * @return {@link Set}<code><DeploymentDirectory></code> */ private static Set<DeploymentDirectory> getDeployDirectories() { Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>(); Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<DeploymentDirectory> deploymetDirssCurrent; for (Configuration config : configs) { deploymetDirssCurrent = config.getDeploymentPath(); if (config.isWatchStatus() && CollectionUtils.valid(deploymetDirssCurrent)) { deploymetDirss.addAll(deploymetDirssCurrent); } } return deploymetDirss; } /** * Gets {@link Set} of data source paths from configuration * * @return {@link Set}<code><String></code> */ private static Set<String> getDataSourcePaths() { Set<String> paths = new HashSet<String>(); Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<String> pathsCurrent; for (Configuration config : configs) { pathsCurrent = config.getDataSourcePath(); if (config.isWatchStatus() && CollectionUtils.valid(pathsCurrent)) { paths.addAll(pathsCurrent); } } return paths; } /** * Checks and gets appropriated {@link WatchFileType} by passed file name * * @param fileName * @return {@link WatchFileType} */ private static WatchFileType checkType(String fileName) { WatchFileType type; File file = new File(fileName); String path = file.getPath(); String filePath = WatchUtils.clearPath(path); path = file.getParent(); String parentPath = WatchUtils.clearPath(path); Set<DeploymentDirectory> apps = getDeployDirectories(); Set<String> dss = getDataSourcePaths(); if (CollectionUtils.valid(apps)) { String deploymantPath; Iterator<DeploymentDirectory> iterator = apps.iterator(); boolean notDeployment = Boolean.TRUE; DeploymentDirectory deployment; while (iterator.hasNext() && notDeployment) { deployment = iterator.next(); deploymantPath = deployment.getPath(); notDeployment = ObjectUtils.notEquals(deploymantPath, parentPath); } if (notDeployment) { type = WatchFileType.NONE; } else { type = WatchFileType.DEPLOYMENT; } } else if (CollectionUtils.valid(dss) && dss.contains(filePath)) { type = WatchFileType.DATA_SOURCE; } else { type = WatchFileType.NONE; } return type; } private static void fillFileList(File[] files, List<File> list) { if (CollectionUtils.valid(files)) { for (File file : files) { list.add(file); } } } /** * Lists all deployed {@link File}s * * @return {@link List}<File> */ public static List<File> listDeployments() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>(); Set<DeploymentDirectory> deploymetDirssCurrent; for (Configuration config : configs) { deploymetDirssCurrent = config.getDeploymentPath(); if (CollectionUtils.valid(deploymetDirssCurrent)) { deploymetDirss.addAll(deploymetDirssCurrent); } } File[] files; List<File> list = new ArrayList<File>(); if (CollectionUtils.valid(deploymetDirss)) { String path; DeployFiletr filter = new DeployFiletr(); for (DeploymentDirectory deployment : deploymetDirss) { path = deployment.getPath(); files = new File(path).listFiles(filter); fillFileList(files, list); } } return list; } /** * Lists all data source {@link File}s * * @return {@link List}<File> */ public static List<File> listDataSources() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<String> paths = new HashSet<String>(); Set<String> pathsCurrent; for (Configuration config : configs) { pathsCurrent = config.getDataSourcePath(); if (CollectionUtils.valid(pathsCurrent)) { paths.addAll(pathsCurrent); } } File file; List<File> list = new ArrayList<File>(); if (CollectionUtils.valid(paths)) { for (String path : paths) { file = new File(path); list.add(file); } } return list; } /** * Deploys application or data source file by passed file name * * @param fileName * @throws IOException */ public static void deployFile(String fileName) throws IOException { WatchFileType type = checkType(fileName); if (type.equals(WatchFileType.DATA_SOURCE)) { FileParsers fileParsers = new FileParsers(); fileParsers.parseStandaloneXml(fileName); } else if (type.equals(WatchFileType.DEPLOYMENT)) { URL url = getAppropriateURL(fileName); deployFile(url); } } /** * Deploys application or data source file by passed {@link URL} instance * * @param url * @throws IOException */ public static void deployFile(URL url) throws IOException { URL[] archives = { url }; MetaContainer.getCreator().scanForBeans(archives); } /** * Removes from deployments application or data source file by passed * {@link URL} instance * * @param url * @throws IOException */ public static void undeployFile(URL url) throws IOException { boolean valid = MetaContainer.undeploy(url); if (valid && RestContainer.hasRest()) { RestProvider.reload(); } } /** * Removes from deployments application or data source file by passed file * name * * @param fileName * @throws IOException */ public static void undeployFile(String fileName) throws IOException { WatchFileType type = checkType(fileName); if (type.equals(WatchFileType.DATA_SOURCE)) { Initializer.undeploy(fileName); } else if (type.equals(WatchFileType.DEPLOYMENT)) { URL url = getAppropriateURL(fileName); undeployFile(url); } } /** * Removes from deployments and deploys again application or data source * file by passed file name * * @param fileName * @throws IOException */ public static void redeployFile(String fileName) throws IOException { undeployFile(fileName); deployFile(fileName); } /** * Handles file change event * * @param dir * @param currentEvent * @throws IOException */ private void handleEvent(Path dir, WatchEvent<Path> currentEvent) throws IOException { if (ObjectUtils.notNull(currentEvent)) { Path prePath = currentEvent.context(); Path path = dir.resolve(prePath); String fileName = path.toString(); int count = currentEvent.count(); Kind<?> kind = currentEvent.kind(); if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { LogUtils.info(LOG, "Modify: %s, count: %s\n", fileName, count); redeployFile(fileName); } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { LogUtils.info(LOG, "Delete: %s, count: %s\n", fileName, count); undeployFile(fileName); } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) { LogUtils.info(LOG, "Create: %s, count: %s\n", fileName, count); redeployFile(fileName); } } } /** * Runs file watch service * * @param watch * @throws IOException */ private void runService(WatchService watch) throws IOException { Path dir; boolean toRun = true; boolean valid; while (toRun) { try { WatchKey key; key = watch.take(); List<WatchEvent<?>> events = key.pollEvents(); WatchEvent<?> currentEvent = null; WatchEvent<Path> typedCurrentEvent; int times = ZERO_WATCH_STATUS; dir = (Path) key.watchable(); for (WatchEvent<?> event : events) { if (event.kind() == StandardWatchEventKinds.OVERFLOW) { continue; } if (times == ZERO_WATCH_STATUS || event.count() > currentEvent.count()) { currentEvent = event; } times++; valid = key.reset(); toRun = valid && key.isValid(); if (toRun) { Thread.sleep(SLEEP_TIME); typedCurrentEvent = ObjectUtils.cast(currentEvent); handleEvent(dir, typedCurrentEvent); } } } catch (InterruptedException ex) { throw new IOException(ex); } } } /** * Registers path to watch service * * @param fs * @param path * @param watch * @throws IOException */ private void registerPath(FileSystem fs, String path, WatchService watch) throws IOException { Path deployPath = fs.getPath(path); deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW, StandardWatchEventKinds.ENTRY_DELETE); runService(watch); } /** * Registers passed {@link File} array to watch service * * @param files * @param fs * @param watch * @throws IOException */ private void registerPaths(File[] files, FileSystem fs, WatchService watch) throws IOException { String path; for (File file : files) { path = file.getPath(); registerPath(fs, path, watch); } } /** * Registers deployments directories to watch service * * @param deploymentDirss * @param fs * @param watch * @throws IOException */ private void registerPaths(Collection<DeploymentDirectory> deploymentDirss, FileSystem fs, WatchService watch) throws IOException { String path; boolean scan; File directory; File[] files; for (DeploymentDirectory deployment : deploymentDirss) { path = deployment.getPath(); scan = deployment.isScan(); if (scan) { directory = new File(path); files = directory.listFiles(); if (CollectionUtils.valid(files)) { registerPaths(files, fs, watch); } } else { registerPath(fs, path, watch); } } } /** * Registers data source path to watch service * * @param paths * @param fs * @param watch * @throws IOException */ private void registerDsPaths(Collection<String> paths, FileSystem fs, WatchService watch) throws IOException { for (String path : paths) { registerPath(fs, path, watch); } } @Override public void run() { try { FileSystem fs = FileSystems.getDefault(); WatchService watch = null; try { watch = fs.newWatchService(); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); throw ex; } if (CollectionUtils.valid(deployments)) { registerPaths(deployments, fs, watch); } if (CollectionUtils.valid(dataSources)) { registerDsPaths(dataSources, fs, watch); } } catch (IOException ex) { LOG.fatal(ex.getMessage(), ex); LOG.fatal("system going to shut down cause of hot deployment"); try { ConnectionContainer.closeConnections(); } catch (IOException iex) { LOG.fatal(iex.getMessage(), iex); } System.exit(ERROR_EXIT); } finally { DEPLOY_POOL.shutdown(); } } /** * Starts watch service for application and data source files */ public static void startWatch() { Watcher watcher = new Watcher(); DEPLOY_POOL.submit(watcher); } }
package org.lightmare.remote.rpc; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import java.io.IOException; import org.lightmare.config.ConfigKeys; import org.lightmare.config.Configuration; import org.lightmare.remote.rcp.RcpHandler; import org.lightmare.remote.rcp.decoders.RcpDecoder; import org.lightmare.remote.rcp.wrappers.RcpWrapper; import org.lightmare.remote.rpc.decoders.RpcEncoder; import org.lightmare.remote.rpc.wrappers.RpcWrapper; import org.lightmare.utils.concurrent.ThreadFactoryUtil; /** * Client class to produce remote procedure call * * @author Levan Tsinadze * @since 0.0.21-SNAPSHOT */ public class RPCall { private String host; private int port; private RcpHandler handler; private static int timeout; private static int workerPoolSize; private static EventLoopGroup worker; private static final int ZERO_TIMEOUT = 0; /** * Implementation of {@link ChannelInitializer} on {@link SocketChannel} for * RPC service client * * @author Levan * */ protected static class ChannelInitializerImpl extends ChannelInitializer<SocketChannel> { private RcpHandler handler; public ChannelInitializerImpl(RcpHandler handler) { this.handler = handler; } @Override public void initChannel(SocketChannel ch) throws Exception { RpcEncoder rpcEncoder = new RpcEncoder(); RcpDecoder rcpDecoder = new RcpDecoder(); ch.pipeline().addLast(rpcEncoder, rcpDecoder, handler); } } public RPCall(String host, int port) { this.host = host; this.port = port; } /** * Configures RPC service client * * @param config */ public static void configure(Configuration config) { if (worker == null) { workerPoolSize = config.getIntValue(ConfigKeys.WORKER_POOL.key); timeout = config.getIntValue(ConfigKeys.CONNECTION_TIMEOUT.key); worker = new NioEventLoopGroup(workerPoolSize, new ThreadFactoryUtil("netty-worker-thread", (Thread.MAX_PRIORITY - 1))); } } /** * Prepares {@link Bootstrap} for RPC service client connection * * @return {@link Bootstrap} */ private Bootstrap getBootstrap() { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(worker); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE); if (timeout > ZERO_TIMEOUT) { bootstrap.option(ChannelOption.SO_TIMEOUT, timeout); } handler = new RcpHandler(); bootstrap.handler(new ChannelInitializerImpl(handler)); return bootstrap; } /** * Calls RPC service for passed {@link RcpWrapper} instance * * @param wrapper * @return {@link Object} * @throws IOException */ public Object call(RpcWrapper wrapper) throws IOException { Object value; try { Bootstrap bootstrap = getBootstrap(); try { ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().closeFuture().sync(); } catch (InterruptedException ex) { throw new IOException(ex); } value = handler.getWrapper(); } finally { worker.shutdownGracefully(); } return value; } }
package org.lightmare.utils; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Array; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Utility class to help with general object checks * * @author levan * */ public class ObjectUtils { public static final int EMPRTY_ARRAY_LENGTH = 0; public static final Object[] EMPTY_ARRAY = {}; private static final int FIRST_INDEX = 0; public static final String EMPTY_STRING = ""; public static boolean notTrue(boolean statement) { return !statement; } public static boolean isFalse(Boolean data) { return !data; } public static boolean notNull(Object data) { return (data != null); } public static boolean notNullAll(Object... datas) { boolean valid = datas != null; if (valid) { int length = datas.length; for (int i = 0; i < length && valid; i++) { valid = datas[i] != null; } } return valid; } public static boolean notEmpty(Collection<?> collection) { return !collection.isEmpty(); } /** * Checks if passed {@link Collection} instance on null and on emptiness * * @param collection * @return <code></code> */ public static boolean available(Collection<?> collection) { return collection != null && !collection.isEmpty(); } /** * Checks passed {@link Map} instance on null and emptiness * * @param map * @return <code>boolean</code> */ public static boolean available(Map<?, ?> map) { return map != null && !map.isEmpty(); } public static boolean notAvailable(Map<?, ?> map) { return !available(map); } public static boolean notAvailable(Collection<?> collection) { return !available(collection); } public static boolean notAvailable(Collection<?>... collections) { return !available(collections); } public static boolean availableAll(Map<?, ?>... maps) { boolean avaliable = notNull(maps); if (avaliable) { Map<?, ?> map; for (int i = 0; i < maps.length && avaliable; i++) { map = maps[i]; avaliable = avaliable && available(map); } } return avaliable; } public static boolean available(Object[] collection) { return collection != null && collection.length > 0; } public static boolean notAvailable(Object[] collection) { return !available(collection); } public static boolean available(CharSequence chars) { return chars != null && chars.length() > 0; } public static boolean notAvailable(CharSequence chars) { return !available(chars); } public static boolean availableAll(Collection<?>... collections) { boolean avaliable = notNull(collections); if (avaliable) { Collection<?> collection; for (int i = 0; i < collections.length && avaliable; i++) { collection = collections[i]; avaliable = avaliable && available(collection); } } return avaliable; } public static boolean availableAll(Object[]... collections) { boolean avaliable = notNull(collections); if (avaliable) { Object[] collection; for (int i = 0; i < collections.length && avaliable; i++) { collection = collections[i]; avaliable = avaliable && available(collection); } } return avaliable; } /** * Converts passed {@link Collection} to array of appropriated {@link Class} * type * * @param collection * @param type * @return <code>T[]</code> */ @SuppressWarnings("unchecked") public static <T> T[] toArray(Collection<T> collection, Class<T> type) { T[] array; if (notNull(collection)) { array = (T[]) Array.newInstance(type, collection.size()); array = collection.toArray(array); } else { array = null; } return array; } /** * Creates empty array of passed type * * @param type * @return <code>T[]</code> */ public static <T> T[] emptyArray(Class<T> type) { @SuppressWarnings("unchecked") T[] empty = (T[]) Array.newInstance(type, EMPRTY_ARRAY_LENGTH); return empty; } /** * Peaks first element from list * * @param list * @return T */ private static <T> T getFirstFromList(List<T> list) { T value; if (available(list)) { value = list.get(FIRST_INDEX); } else { value = null; } return value; } /** * Peaks first element from collection * * @param collection * @return T */ public static <T> T getFirst(Collection<T> collection) { T value; if (available(collection)) { if (collection instanceof List) { value = getFirstFromList(((List<T>) collection)); } else { Iterator<T> iterator = collection.iterator(); value = iterator.next(); } } else { value = null; } return value; } /** * Peaks first element from array * * @param collection * @return T */ public static <T> T getFirst(T[] values) { T value; if (available(values)) { value = values[FIRST_INDEX]; } else { value = null; } return value; } /** * Checks if passed {@link Closeable} instance is not null and if not calls * {@link Closeable#close()} method * * @param closeable * @throws IOException */ public static void close(Closeable closeable) throws IOException { if (ObjectUtils.notNull(closeable)) { closeable.close(); } } }
package org.myrobotlab.service; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.interfaces.NameProvider; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.math.Mapper; import org.myrobotlab.math.MathUtils; import org.myrobotlab.service.abstracts.AbstractEncoder; import org.myrobotlab.service.data.PinData; import org.myrobotlab.service.interfaces.EncoderControl; import org.myrobotlab.service.interfaces.MotorControl; import org.myrobotlab.service.interfaces.PinArrayControl; import org.myrobotlab.service.interfaces.PinListener; import org.myrobotlab.service.interfaces.ServoControl; import org.myrobotlab.service.interfaces.ServoController; import org.slf4j.Logger; public class DiyServo extends Service implements ServoControl, PinListener { /** * Sweeper - thread used to sweep motor back and forth * */ public class Sweeper extends Thread { public Sweeper(String name) { super(String.format("%s.sweeper", name)); } @Override public void run() { double sweepMin = 0.0; double sweepMax = 0.0; // start in the middle double sweepPos = mapper.getMinX() + (mapper.getMaxX() - mapper.getMinX()) / 2; isSweeping = true; try { while (isSweeping) { // set our range to be inside 'real' min & max input sweepMin = mapper.getMinX() + 1; sweepMax = mapper.getMaxX() - 1; // if pos is too small or too big flip direction if (sweepPos >= sweepMax || sweepPos <= sweepMin) { sweepStep = sweepStep * -1; } sweepPos += sweepStep; moveTo(sweepPos); Thread.sleep(sweepDelay); } } catch (Exception e) { isSweeping = false; } } } /** * MotorUpdater The control loop to update the MotorControl with new values * based on the PID calculations * */ public class MotorUpdater extends Thread { double lastOutput = 0.0; /** * In most cases TargetPos is never reached So we need to emulate it ! if * currentPosInput is the same since X we guess it is reached based on * targetPosAngleTolerence */ private int nbSamePosInputSinceX = 0; private double lastCurrentPosInput = 0; // goal is to not use this private double targetPosAngleTolerence = 15; public MotorUpdater(String name) { super(String.format("%s.motorUpdater", name)); } @Override public void run() { try { while (isEnabled()) { if (motorControl != null) { // Calculate the new value for the motor if (pid.compute(pidKey)) { // double setPoint = pid.getSetpoint(pidKey); // TEMP SANTA TRICK TO CONTROL MAX VELOCITY deltaVelocity = 1; if (currentVelocity > maxVelocity && maxVelocity > 0) { deltaVelocity = currentVelocity / maxVelocity; } // END TEMP SANTA TRICK double output = pid.getOutput(pidKey) / deltaVelocity; motorControl.setPowerLevel(output); // log.debug(String.format("setPoint(%s), processVariable(%s), // output(%s)", setPoint, processVariable, output)); if (output != lastOutput) { motorControl.move(output); lastOutput = output; if (isMoving()) { // tolerance if (currentPosInput == lastCurrentPosInput && Math.abs(targetPos - getCurrentPosOutput()) <= targetPosAngleTolerence) { nbSamePosInputSinceX += 1; } else { nbSamePosInputSinceX = 0; } // ok targetPos is reached ( with tolerance ) if (nbSamePosInputSinceX >= 3 || getCurrentPosOutput() == targetPos) { onServoEvent(SERVO_EVENT_STOPPED, getCurrentPosOutput()); } else { if (getCurrentPosOutput() != targetPos) { onServoEvent(SERVO_EVENT_POSITION_UPDATE, getCurrentPosOutput()); } } } } } lastCurrentPosInput = currentPosInput; Thread.sleep(1000 / sampleTime); } } } catch (Exception e) { if (e instanceof InterruptedException) { // info("Shutting down MotorUpdater"); } else { log.error("motor updater threw", e); } } } } public class EncoderUpdater extends Thread { public EncoderUpdater(String name) { super(String.format("%s.encoderUpdater", name)); } public void run() { // here we want to poll the encoder control to keep our "currentPosition" value up to date.. // effectively this replaces onPin ... while (true) { currentPosInput = ((AbstractEncoder)encoderControl).lastPosition; try { // someting to keep the cpu from thrashing. pid.setInput(pidKey, currentPosInput); Thread.sleep(1); } catch (InterruptedException e) { // TODO: clean this up. e.printStackTrace(); break; } } } } private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(DiyServo.class); /** * controls low level methods of the motor */ transient MotorControl motorControl; public String motorControlName = "motor"; /** * Reference to the Analog input service */ public List<String> pinArrayControls; /** * // Handle to the selected analog input service and it's name */ transient PinArrayControl pinArrayControl; public String pinControlName; transient EncoderControl encoderControl; /** * List of available pins on the analog input service */ public List<Integer> pinList = new ArrayList<Integer>(); public Integer pin; /** * mapper to be able to remap input values */ Mapper mapper; Double rest = 90.0; long lastActivityTime = 0; double currentVelocity = 0; /** * the requested INPUT position of the servo */ Double targetPos; /** * the calculated output for the servo */ double targetOutput; /** * Round pos values based on this digit count useful later to compare * target>pos */ int roundPos = 0; /** * list of names of possible controllers */ public List<String> controllers; // FIXME - currently is only computer control - needs to be either // microcontroller or computer boolean isSweeping = false; double sweepMin = 0.0; double sweepMax = 180.0; int sweepDelay = 1; double sweepStep = 1.0; boolean sweepOneWay = false; double lastPos; transient Thread sweeper = null; /** * feedback of both incremental position and stops. would allow blocking * moveTo if desired */ boolean isEventsEnabled = false; private double maxVelocity = -1; private boolean isAttached = false; private boolean isControllerSet = false; private boolean isPinArrayControlSet = false; // Initial parameters for PID. static final public int MODE_AUTOMATIC = 1; static final public int MODE_MANUAL = 0; public int mode = MODE_MANUAL; public Pid pid; private String pidKey; private double kp = 0.020; private double ki = 0.001; // 0.020; private double kd = 0.0; // 0.020; public double setPoint = 90.0; // Intial // setpoint // corresponding // centered // servo // The // pinListener // value // depends // the // hardwawe // behind // the // value // from // the /** * AD converter needs to be remapped to 0 - 180. D1024 is the default for the * Arduino */ double resolution = 1024; /** * Sample time 20 ms = 50 Hz */ int sampleTime = 20; transient MotorUpdater motorUpdater = null; transient EncoderUpdater encoderUpdater = null; double powerLevel = 0; double maxPower = 1.0; double minPower = -1.0; Mapper powerMap = new Mapper(-1.0, 1.0, -255.0, 255.0); public String disableDelayIfVelocity; public String defaultDisableDelayNoVelocity; Double currentPosInput = 0.0; double deltaVelocity = 1; private boolean moving = false; private boolean autoDisable; private boolean overrideAutoDisable = false; private transient Timer autoDisableTimer; transient Object moveToBlocked = new Object(); /** * disableDelayGrace : a timer is launched after targetpos reached * * @param disableDelayGrace * - milliSeconds * @default - 1000 */ public int disableDelayGrace = 1000; public transient static final int SERVO_EVENT_STOPPED = 1; public transient static final int SERVO_EVENT_POSITION_UPDATE = 2; /** * Constructor * * @param n * name of the service */ public DiyServo(String n) { super(n); refreshPinArrayControls(); motorControl = (MotorControl) createPeer("motor", "MotorDualPwm"); initPid(); subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered"); lastActivityTime = System.currentTimeMillis(); this.addServoEventListener(this); } /* * Update the list of PinArrayControls */ public void onRegistered(ServiceInterface s) { refreshPinArrayControls(); broadcastState(); } /** * Initiate the PID controller */ void initPid() { pid = (Pid) createPeer("pid"); pidKey = this.getName(); pid.setPID(pidKey, kp, ki, kd); // Create a PID with the name of this // service instance pid.setMode(pidKey, MODE_AUTOMATIC); // Initial mode is manual pid.setOutputRange(pidKey, -1.0, 1.0); // Set the Output range to match // the // Motor input pid.setSampleTime(pidKey, sampleTime); // Sets the sample time pid.setSetpoint(pidKey, setPoint); pid.startService(); } @Override public void addServoEventListener(NameProvider service) { addListener("publishServoEvent", service.getName(), "onServoEvent"); } /** * Re-attach to servo's current pin. The pin must have be set previously. * Equivalent to Arduino's Servo.attach(currentPin) In this service it stops * the motor and PID is set to manual mode */ @Override public void attach() { attach(pin); broadcastState(); } /** * Equivalent to Arduino's Servo.attach(pin). It energizes the servo sending * pulses to maintain its current position. */ @Override public void attach(int pin) { // TODO Activate the motor and PID lastActivityTime = System.currentTimeMillis(); isAttached = true; broadcastState(); } /** * Equivalent to Arduino's Servo.detach() it de-energizes the servo */ @Override // TODO DeActivate the motor and PID public void detach() { if (motorControl != null) { motorControl.stop(); } isAttached = false; broadcastState(); } /* * Method to check if events are enabled or not */ public boolean eventsEnabled(boolean b) { isEventsEnabled = b; broadcastState(); return b; } public long getLastActivityTime() { return lastActivityTime; } public double getMax() { return mapper.getMaxX(); } public double getPos() { if (targetPos == null) { return rest; } else { return MathUtils.round(targetPos, roundPos); } } public double getRest() { return rest; } // FIXME - change to enabled() public boolean isAttached() { return isAttached; } public boolean isControllerSet() { return isControllerSet; } public boolean isPinArrayControlSet() { return isPinArrayControlSet; } public boolean isInverted() { return mapper.isInverted(); } public void map(double minX, double maxX, double minY, double maxY) { if (mapper == null) { mapper = new Mapper(0, 180, 0, 180); } if (minX != mapper.getMinX() || maxX != mapper.getMaxX() || minY != mapper.getMinY() || maxY != mapper.getMaxY()) { mapper = new Mapper(minX, maxX, minY, maxY); broadcastState(); } } /** * The most important method, that tells the servo what position it should * move to */ public void moveTo(double pos) { synchronized (moveToBlocked) { moveToBlocked.notify(); // Will wake up MoveToBlocked.wait() } deltaVelocity = 1; double lastPosInput = mapper.calcInput(lastPos); if (motorControl == null) { error(String.format("%s's controller is not set", getName())); return; } if (!isEnabled()) { if (pos != lastPosInput || overrideAutoDisable || !getAutoDisable()) { enable(); } } if (lastPosInput != pos) { moving = true; if (motorUpdater == null) { // log.info("Starting MotorUpdater"); motorUpdater = new MotorUpdater(getName()); motorUpdater.start(); // log.info("MotorUpdater started"); } if (encoderUpdater == null) { encoderUpdater = new EncoderUpdater(getName()); encoderUpdater.start(); } } targetPos = pos; targetOutput = getTargetOutput(); pid.setSetpoint(pidKey, targetOutput); lastActivityTime = System.currentTimeMillis(); // if (isEventsEnabled) { // update others of our position change invoke("publishServoEvent", targetOutput); broadcastState(); } /* * basic move command of the servo - usually is 0 - 180 valid range but can be * adjusted and / or re-mapped with min / max and map commands * * TODO - moveToBlocking - blocks until servo sends "ARRIVED_TO_POSITION" * response */ // uber good public Double publishServoEvent(Double position) { return position; } public List<String> refreshPinArrayControls() { pinArrayControls = Runtime.getServiceNamesFromInterface(PinArrayControl.class); return pinArrayControls; } @Override public void releaseService() { // FYI - super.releaseService() calls detach // detach(); if (motorUpdater != null) { // shutting down motor updater thread motorUpdater.interrupt(); } super.releaseService(); } @Override public void startService() { super.startService(); if (mapper == null) { mapper = new Mapper(0, 180, 0, 180); } } public void rest() { moveTo(rest); } public void setInverted(boolean invert) { mapper.setInverted(invert); motorControl.setInverted(invert); broadcastState(); } @Override public void setMinMax(double min, double max) { map(min, max, min, max); } public void setRest(double rest) { this.rest = rest; } public void setSweepDelay(int delay) { sweepDelay = delay; } /* * (non-Javadoc) * * @see org.myrobotlab.service.interfaces.ServoControl#stopServo() */ @Override public void stop() { isSweeping = false; sweeper = null; // TODO Replace with internal logic for motor and PID // getController().servoSweepStop(this); broadcastState(); } public void sweep() { double min = mapper.getMinX(); double max = mapper.getMaxX(); sweep(min, max, 50, 1.0); } public void sweep(double min, double max) { sweep(min, max, 1, 1.0); } // FIXME - is it really speed control - you don't currently thread for // fractional speed values public void sweep(double min, double max, int delay, double step) { sweep(min, max, delay, step, false); } public void sweep(double min, double max, int delay, double step, boolean oneWay) { this.sweepMin = min; this.sweepMax = max; this.sweepDelay = delay; this.sweepStep = step; this.sweepOneWay = oneWay; if (isSweeping) { stop(); } sweeper = new Sweeper(getName()); sweeper.start(); isSweeping = true; broadcastState(); } /** * Writes a value in microseconds (uS) to the servo, controlling the shaft * accordingly. On a standard servo, this will set the angle of the shaft. On * standard servos a parameter value of 1000 is fully counter-clockwise, 2000 * is fully clockwise, and 1500 is in the middle. * * Note that some manufactures do not follow this standard very closely so * that servos often respond to values between 700 and 2300. Feel free to * increase these endpoints until the servo no longer continues to increase * its range. Note however that attempting to drive a servo past its endpoints * (often indicated by a growling sound) is a high-current state, and should * be avoided. * * Continuous-rotation servos will respond to the writeMicrosecond function in * an analogous manner to the write function. * * @param uS * - the microseconds value */ public void writeMicroseconds(Integer uS) { // log.info("writeMicroseconds({})", uS); // TODO. This need to be remapped to Motor and PID internal to this // Service // getController().servoWriteMicroseconds(this, uS); lastActivityTime = System.currentTimeMillis(); broadcastState(); } /* * @Override public void setPin(int pin) { this.pin = pin; } */ @Override public Integer getPin() { return this.pin; } @Override public double getMin() { return mapper.getMinX(); } @Override public double getTargetOutput() { if (targetPos == null) { targetPos = rest; } targetOutput = mapper.calcOutput(targetPos); return targetOutput; } /* * public void attach(String controllerName) throws Exception { * attach((MotorController) Runtime.getService(controllerName)); } */ @Override public void detach(String controllerName) { ServiceInterface si = Runtime.getService(controllerName); if (si instanceof PinArrayControl) { detach((PinArrayControl) Runtime.getService(controllerName)); } } public void detach(PinArrayControl pinArrayControl) { if (this.pinArrayControl == pinArrayControl) { this.pinArrayControl = null; isPinArrayControlSet = false; broadcastState(); } } public void setMaxVelocity(double velocity) { this.maxVelocity = velocity; broadcastState(); } @Override public double getMaxVelocity() { return maxVelocity; } @Override public void onPin(PinData pindata) { int inputValue = pindata.value; currentPosInput = 180 * inputValue / resolution; // log.debug(String.format("onPin received value %s converted to // %s",inputValue, processVariable)); // we need to read here real angle / seconds // before try to control velocity currentVelocity = MathUtils.round(Math.abs(((currentPosInput - lastPos) * (500 / sampleTime))), roundPos); // log.info("currentPosInput : " + currentPosInput); // info(currentVelocity + " " + currentPosInput); pid.setInput(pidKey, currentPosInput); // offline feedback ! if diy servo is disabled // useful to "learn" gestures ( later ... ) or simply start a moveTo() at // real lastPos & sync with UI if (!isEnabled() && MathUtils.round(lastPos, roundPos) != MathUtils.round(currentPosInput, roundPos)) { targetPos = mapper.calcInput(lastPos); broadcastState(); } lastPos = currentPosInput; } public void attach(EncoderControl encoder) { // TODO: do i need anything else? this.encoderControl = encoder; } public void attach(String pinArrayControlName, Integer pin) throws Exception { // myServo = (DiyServo) Runtime.getService(boundServiceName); attach((PinArrayControl) Runtime.getService(pinArrayControlName), (int) pin); } public void attach(PinArrayControl pinArrayControl, int pin) throws Exception { this.pinArrayControl = pinArrayControl; if (pinArrayControl != null) { pinControlName = pinArrayControl.getName(); isPinArrayControlSet = true; this.pin = pin; } // TODO The resolution is a property of the AD converter and should be // fetched thru a method call like controller.getADResolution() if (pinArrayControl instanceof Arduino) { resolution = 1024; } if (pinArrayControl instanceof Ads1115) { resolution = 65536; } // log.debug(String.format("Detected %s %s. Setting AD resolution to // %s",pinArrayControl.getClass(), pinArrayControl.getName(),resolution)); int rate = 1000 / sampleTime; pinArrayControl.attach(this, pin); pinArrayControl.enablePin(pin, rate); broadcastState(); } public void setPowerLevel(double power) { this.powerLevel = power; } /** * // A bunch of unimplemented methods from ServoControl. // Perhaps I should * create a new // DiyServoControl interface. // I was hoping to be able to * avoid that, but might be a better solution */ @Override @Deprecated public void setSpeed(double speed) { log.error("speed is depreciated, use setVelocity instead"); } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(DiyServo.class.getCanonicalName()); meta.addDescription("Controls a motor so that it can be used as a Servo"); meta.addCategory("control", "servo"); meta.addPeer("motor", "MotorDualPwm", "MotorControl service"); meta.addPeer("pid", "Pid", "PID service"); return meta; } @Override public void setPin(int pin) { // This method should never be used in DiyServo since it's a method specific // to the Servo service } @Override public double getAcceleration() { return 1.0; } @Override public void setVelocity(double velocity) { warn("TODO !"); } @Override public double getVelocity() { // TODO Auto-generated method stub return 0; } @Override public double getMinInput() { return mapper.getMinInput(); } @Override public double getMaxInput() { return mapper.getMaxInput(); } @Override public void addIKServoEventListener(NameProvider service) { // TODO Auto-generated method stub } @Override public void sync(ServoControl sc) { // TODO Auto-generated method stub } // None of the methods below can or should be implemented in DiyServo // DiyServo uses a Motor peer @Override public void attachServoController(ServoController controller) throws Exception { // TODO Auto-generated method stub } @Override public void detachServoController(ServoController controller) throws Exception { // TODO Auto-generated method stub } @Override public boolean isAttachedServoController(ServoController controller) { // TODO Auto-generated method stub return false; } @Override public void attach(ServoController controller, int pin) throws Exception { // TODO Auto-generated method stub } @Override public void attach(ServoController controller, int pin, double pos) throws Exception { // TODO Auto-generated method stub } @Override public void attach(ServoController controller, int pin, double pos, double speed) throws Exception { // TODO Auto-generated method stub } @Override public void setAutoDisable(boolean autoDisable) { this.autoDisable = autoDisable; } @Override public boolean getAutoDisable() { return this.autoDisable; } @Override public boolean moveToBlocking(double pos) { targetPos = pos; this.moveTo(pos); // breakMoveToBlocking=false; waitTargetPos(); return true; } @Override public void setOverrideAutoDisable(boolean overrideAutoDisable) { // TODO Auto-generated method stub } @Override public void waitTargetPos() { if (isMoving()) { synchronized (moveToBlocked) { try { // Will block until moveToBlocked.notify() is called on another // thread. log.info("servo {} moveToBlocked was initiate", getName()); moveToBlocked.wait(15000);// 30s timeout security delay } catch (InterruptedException e) { log.info("servo {} moveToBlocked was interrupted", getName()); } } } } @Override public void onServoEvent(Integer eventType, double currentPos) { if (eventType == SERVO_EVENT_STOPPED) { moving = false; } else { moving = true; } onServoEvent(currentPos); } public void onServoEvent(double currentPos) { if (!isMoving() && isEnabled()) { delayDisable(); } } private void delayDisable() { if (!isMoving()) { log.info("AutoDisable called"); if (autoDisable) { if (autoDisableTimer != null) { autoDisableTimer.cancel(); autoDisableTimer = null; } autoDisableTimer = new Timer(); autoDisableTimer.schedule(new TimerTask() { @Override public void run() { if (!overrideAutoDisable && !isMoving()) { disable(); targetPos = getCurrentPosOutput(); } synchronized (moveToBlocked) { moveToBlocked.notify(); // Will wake up MoveToBlocked.wait() } } }, (long) disableDelayGrace); } else { synchronized (moveToBlocked) { moveToBlocked.notify(); // Will wake up MoveToBlocked.wait() } targetPos = getCurrentPosOutput(); } } broadcastState(); } /** * getCurrentPos() - return the calculated position of the servo use * lastActivityTime and velocity for the computation * * @return the current position of the servo */ public Double getCurrentPos() { return MathUtils.round(currentPosInput, roundPos); } @Override public double getCurrentPosOutput() { return MathUtils.round(mapper.calcInput(getCurrentPos()), roundPos); } public double getMinOutput() { return mapper.getMinOutput(); } public double getMaxOutput() { return mapper.getMaxOutput(); } public boolean isEnabled() { return !motorControl.isLocked(); } public boolean isSweeping() { return isSweeping; } public boolean isEventsEnabled() { // TODO Auto-generated method stub return false; } /** * getCurrentVelocity() - return Current velocity ( realtime / based on * frequency) * * @return degrees / second */ public double getCurrentVelocity() { return currentVelocity; } public boolean isMoving() { return moving; } public void setDisableDelayGrace(int disableDelayGrace) { this.disableDelayGrace = disableDelayGrace; } @Override public void enable() { motorControl.unlock(); if (motorUpdater == null) { motorUpdater = new MotorUpdater(getName()); } if (!motorUpdater.isAlive()) { motorUpdater.start(); } broadcastState(); } @Override public void disable() { motorControl.stopAndLock(); if (motorUpdater != null) { motorUpdater.interrupt(); motorUpdater = null; } broadcastState(); } @Override public void stopService() { super.stopService(); disable(); } @Override public String getControllerName() { // TODO Auto-generated method stub return null; } public static void main(String[] args) throws InterruptedException { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); try { // Runtime.start("webgui", "WebGui"); Runtime.start("gui", "SwingGui"); // VirtualArduino virtual = (VirtualArduino) Runtime.start("virtual", "VirtualArduino"); // virtual.connect("COM3"); // boolean done = false; // if (done) { // return; String port = "COM4"; Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino"); // arduino.setBoardUno(); arduino.connect(port); // Adafruit16CServoDriver adafruit16CServoDriver = // (Adafruit16CServoDriver) Runtime.start("adafruit16CServoDriver", // "Adafruit16CServoDriver"); // adafruit16CServoDriver.attach(arduino,"1","0x40"); // Ads1115 ads = (Ads1115) Runtime.start("ads", "Ads1115"); // ads.attach(arduino,"2","0x40"); MotorDualPwm motor = (MotorDualPwm) Runtime.start("diyServo.motor", "MotorDualPwm"); int leftPwmPin = 6; int rightPwmPin = 7; motor.setPwmPins(leftPwmPin, rightPwmPin); motor.attach(arduino); Thread.sleep(1000); // let's start the encoder!! Amt203Encoder encoder = new Amt203Encoder("encoder"); encoder.pin = 3; arduino.attach(encoder); Thread.sleep(1000); // Ads1115 ads = (Ads1115) Runtime.start("Ads1115", "Ads1115"); // ads.setController(arduino, "1", "0x48"); DiyServo diyServo = (DiyServo) Runtime.create("diyServo", "DiyServo"); Python python = (Python) Runtime.start("python", "Python"); // diyServo.attachServoController((ServoController)arduino); // diyServo.attach((ServoController)arduino); // diyServo.map(0, 180, 60, 175); diyServo = (DiyServo) Runtime.start("diyServo", "DiyServo"); diyServo.pid.setPID("diyServo", 1.0, 0.2, 0.1); // diyServo.pid.setOutputRange("diyServo", 1, -1); // diyServo.pid.setOutput("diyS, Output); // diyServo.attach((PinArrayControl) arduino, 14); // PIN 14 = A0 // diyServo.setInverted(true); diyServo.attach(encoder); diyServo.setMaxVelocity(-1); // diyServo.setAutoDisable(true); // diyServo.setMaxVelocity(10); // diyServo.moveToBlocking(0); // diyServo.moveToBlocking(180); // diyServo.setMaxVelocity(-1); // diyServo.moveTo(0); // Servo Servo = (Servo) Runtime.start("Servo", "Servo"); // servo.test(); } catch (Exception e) { Logging.logError(e); } } }
package org.neo4j.kernel.impl.ha; public interface Broker { Master getMaster(); SlaveContext getSlaveContext(); void setLastCommittedTxId( long txId ); boolean thisIsMaster(); }
package org.numenta.nupic.network; import java.math.BigDecimal; import java.math.MathContext; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import org.joda.time.DateTime; import org.numenta.nupic.ComputeCycle; import org.numenta.nupic.Connections; import org.numenta.nupic.FieldMetaType; import org.numenta.nupic.Parameters; import org.numenta.nupic.Parameters.KEY; import org.numenta.nupic.Persistable; import org.numenta.nupic.SDR; import org.numenta.nupic.algorithms.Anomaly; import org.numenta.nupic.algorithms.CLAClassifier; import org.numenta.nupic.algorithms.Classification; import org.numenta.nupic.algorithms.SpatialPooler; import org.numenta.nupic.algorithms.TemporalMemory; import org.numenta.nupic.encoders.DateEncoder; import org.numenta.nupic.encoders.Encoder; import org.numenta.nupic.encoders.EncoderTuple; import org.numenta.nupic.encoders.MultiEncoder; import org.numenta.nupic.model.Cell; import org.numenta.nupic.network.sensor.FileSensor; import org.numenta.nupic.network.sensor.HTMSensor; import org.numenta.nupic.network.sensor.ObservableSensor; import org.numenta.nupic.network.sensor.Sensor; import org.numenta.nupic.network.sensor.SensorParams; import org.numenta.nupic.network.sensor.SensorParams.Keys; import org.numenta.nupic.network.sensor.URISensor; import org.numenta.nupic.util.ArrayUtils; import org.numenta.nupic.util.NamedTuple; import org.numenta.nupic.util.SparseBinaryMatrix; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.Transformer; import rx.Observer; import rx.Subscriber; import rx.Subscription; import rx.functions.Func1; import rx.subjects.PublishSubject; /** * <p> * Implementation of the biological layer of a region in the neocortex. Here, a * {@code Layer} contains the physical structure (columns, cells, dendrites etc) * shared by a sequence of algorithms which serve to implement the predictive * inferencing present in this, the allegory to its biological equivalent. * </p> * <p> * <b>COMPOSITION:</b> A Layer is constructed with {@link Parameters} which * configure the behavior of most of the key algorithms a Layer may contain. It * is also <em>optionally</em> constructed with each of the algorithms in turn. * A Layer that includes an {@link Encoder} is always initially configured with * a {@link MultiEncoder}. The child encoders contained within the MultiEncoder * are configured from the Map included with the specified Parameters, keyed by * {@link Parameters.KEY#FIELD_ENCODING_MAP}. * </p> * <p> * A field encoding map consists of one map for each of the fields to be * encoded. Each individual map in the field encoding map contains the typical * {@link Encoder} parameters, plus a few "meta" parameters needed to describe * the field and its data type as follows: * </p> * * <pre> * Map&lt;String, Map&lt;String, Object&gt;&gt; fieldEncodings = new HashMap&lt;&gt;(); * * Map&lt;String, Object&gt; inner = new HashMap&lt;&gt;(); * inner.put("n", n); * inner.put("w", w); * inner.put("minVal", min); * inner.put("maxVal", max); * inner.put("radius", radius); * inner.put("resolution", resolution); * inner.put("periodic", periodic); * inner.put("clip", clip); * inner.put("forced", forced); * // These are meta info to aid in Encoder construction * inner.put("fieldName", fieldName); * inner.put("fieldType", fieldType); (see {@link FieldMetaType} for type examples) * inner.put("encoderType", encoderType); (i.e. ScalarEncoder, SDRCategoryEncoder, DateEncoder...etc.) * * Map&lt;String, Object&gt; inner2 = new HashMap&lt;&gt;(); * inner.put("n", n); * inner.put("w", w); * inner.put("minVal", min); * inner.put("maxVal", max); * inner.put("radius", radius); * inner.put("resolution", resolution); * inner.put("periodic", periodic); * inner.put("clip", clip); * inner.put("forced", forced); * // These are meta info to aid in Encoder construction * inner.put("fieldName", fieldName); * inner.put("fieldType", fieldType); (see {@link FieldMetaType} for type examples) * inner.put("encoderType", encoderType); (i.e. ScalarEncoder, SDRCategoryEncoder, DateEncoder...etc.) * * fieldEncodings.put("consumption", inner); // Where "consumption" is an example field name (field name is "generic" in above code) * fieldEncodings.put("temperature", inner2); * * Parameters p = Parameters.getDefaultParameters(); * p.setParameterByKey(KEY.FIELD_ENCODING_MAP, fieldEncodings); * </pre> * * For an example of how to create the field encodings map in a reusable way, * see NetworkTestHarness and its usage within the LayerTest class. * * <p> * The following is an example of Layer construction with everything included * (i.e. Sensor, SpatialPooler, TemporalMemory, CLAClassifier, Anomaly * (computer)) * * <pre> * // See the test harness for more information * Parameters p = NetworkTestHarness.getParameters(); * * // How to merge (union) two {@link Parameters} objects. This one merges * // the Encoder parameters into default parameters. * p = p.union(NetworkTestHarness.getHotGymTestEncoderParams()); * * // You can overwrite parameters as needed like this * p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42)); * p.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 2048 }); * p.setParameterByKey(KEY.POTENTIAL_RADIUS, 200); * p.setParameterByKey(KEY.INHIBITION_RADIUS, 50); * p.setParameterByKey(KEY.GLOBAL_INHIBITIONS, true); * * Map&lt;String, Object&gt; params = new HashMap&lt;&gt;(); * params.put(KEY_MODE, Mode.PURE); * params.put(KEY_WINDOW_SIZE, 3); * params.put(KEY_USE_MOVING_AVG, true); * Anomaly anomalyComputer = Anomaly.create(params); * * Layer&lt;?&gt; l = Network.createLayer(&quot;TestLayer&quot;, p).alterParameter(KEY.AUTO_CLASSIFY, true).add(anomalyComputer).add(new TemporalMemory()).add(new SpatialPooler()) * .add(Sensor.create(FileSensor::create, SensorParams.create(Keys::path, &quot;&quot;, ResourceLocator.path(&quot;rec-center-hourly-small.csv&quot;)))); * </pre> * * * * * @author David Ray */ public class Layer<T> implements Persistable { private static final long serialVersionUID = 1L; protected static final Logger LOGGER = LoggerFactory.getLogger(Layer.class); protected Network parentNetwork; protected Region parentRegion; protected Parameters params; protected SensorParams sensorParams; protected Connections connections; protected HTMSensor<?> sensor; protected MultiEncoder encoder; protected SpatialPooler spatialPooler; protected TemporalMemory temporalMemory; private Boolean autoCreateClassifiers; private Anomaly anomalyComputer; private transient ConcurrentLinkedQueue<Observer<Inference>> subscribers = new ConcurrentLinkedQueue<Observer<Inference>>(); private transient PublishSubject<T> publisher = null; private transient Observable<Inference> userObservable; private transient Subscription subscription; private volatile Inference currentInference; FunctionFactory factory; /** Active columns in the {@link SpatialPooler} at time "t" */ protected int[] feedForwardActiveColumns; /** Active column indexes from the {@link SpatialPooler} at time "t" */ private int[] feedForwardSparseActives; /** Predictive {@link Cell}s in the {@link TemporalMemory} at time "t - 1" */ private Set<Cell> previousPredictiveCells; /** Predictive {@link Cell}s in the {@link TemporalMemory} at time "t" */ private Set<Cell> predictiveCells; /** Active {@link Cell}s in the {@link TemporalMemory} at time "t" */ private Set<Cell> activeCells; /** Used to track and document the # of records processed */ private int recordNum = -1; /** Keeps track of number of records to skip on restart */ private int skip = -1; private String name; private volatile boolean isClosed; private volatile boolean isHalted; private volatile boolean isPostSerialized; protected volatile boolean isLearn = true; private Layer<Inference> next; private Layer<Inference> previous; private transient List<Observer<Inference>> observers = new ArrayList<Observer<Inference>>(); private transient CheckPointOperator<?> checkPointOp; private transient List<Observer<byte[]>> checkPointOpObservers = new ArrayList<>(); /** * Retains the order of added items - for use with interposed * {@link Observable} */ private List<Object> addedItems = new ArrayList<>(); /** Indicates whether there is a generic processing node entered */ private boolean hasGenericProcess; /** * List of {@link Encoders} used when storing bucket information see * {@link #doEncoderBucketMapping(Inference, Map)} */ private List<EncoderTuple> encoderTuples; private transient Map<Class<T>, Observable<ManualInput>> observableDispatch = Collections.synchronizedMap(new HashMap<Class<T>, Observable<ManualInput>>()); /** This layer's thread */ private transient Thread LAYER_THREAD; static final byte SPATIAL_POOLER = 1; static final byte TEMPORAL_MEMORY = 2; static final byte CLA_CLASSIFIER = 4; static final byte ANOMALY_COMPUTER = 8; private byte algo_content_mask = 0; /** * Creates a new {@code Layer} using the {@link Network} level * {@link Parameters} * * @param n * the parent {@link Network} */ public Layer(Network n) { this(n, n.getParameters()); } /** * Creates a new {@code Layer} using the specified {@link Parameters} * * @param n * the parent {@link Network} * @param p * the {@link Parameters} to use with this {@code Layer} */ public Layer(Network n, Parameters p) { this("[Layer " + System.currentTimeMillis() + "]", n, p); } /** * Creates a new {@code Layer} using the specified {@link Parameters} * * @param name the name identifier of this {@code Layer} * @param n the parent {@link Network} * @param p the {@link Parameters} to use with this {@code Layer} */ public Layer(String name, Network n, Parameters p) { this.name = name; this.parentNetwork = n; this.params = p; connections = new Connections(); this.autoCreateClassifiers = (Boolean)p.getParameterByKey(KEY.AUTO_CLASSIFY); factory = new FunctionFactory(); observableDispatch = createDispatchMap(); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Layer<T> preSerialize() { isPostSerialized = false; return this; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Layer<T> postDeSerialize() { recreateSensors(); FunctionFactory old = factory; factory = new FunctionFactory(); factory.inference = old.inference.postDeSerialize(old.inference); checkPointOpObservers = new ArrayList<>(); if(sensor != null) { sensor.setLocalParameters(params); // Initialize encoders and recreate encoding index mapping. sensor.postDeSerialize(); }else{ // Dispatch functions (Observables) are transient & non-serializable so they must be rebuilt. observableDispatch = createDispatchMap(); // Dispatch chain will not propagate unless it has subscribers. parentNetwork.addDummySubscriber(); } // Flag which lets us know to skip or do certain setups during initialization. isPostSerialized = true; observers = new ArrayList<Observer<Inference>>(); return this; } /** * Sets the parent {@link Network} on this {@code Layer} * * @param network */ public void setNetwork(Network network) { this.parentNetwork = network; } /** * Creates a new {@code Layer} initialized with the specified algorithmic * components. * * @param params A {@link Parameters} object containing configurations for a * SpatialPooler, TemporalMemory, and Encoder (all or none may be used). * @param e (optional) The Network API only uses a {@link MultiEncoder} at * the top level because of its ability to delegate to child encoders. * @param sp (optional) {@link SpatialPooler} * @param tm (optional) {@link TemporalMemory} * @param autoCreateClassifiers (optional) Indicates that the {@link Parameters} object * contains the configurations necessary to create the required encoders. * @param a (optional) An {@link Anomaly} computer. */ public Layer(Parameters params, MultiEncoder e, SpatialPooler sp, TemporalMemory tm, Boolean autoCreateClassifiers, Anomaly a) { // Make sure we have a valid parameters object if(params == null) { throw new IllegalArgumentException("No parameters specified."); } // Check to see if the Parameters include the encoder configuration. if(params.getParameterByKey(KEY.FIELD_ENCODING_MAP) == null && e != null) { throw new IllegalArgumentException("The passed in Parameters must contain a field encoding map " + "specified by org.numenta.nupic.Parameters.KEY.FIELD_ENCODING_MAP"); } this.params = params; this.encoder = e; this.spatialPooler = sp; this.temporalMemory = tm; this.autoCreateClassifiers = autoCreateClassifiers; this.anomalyComputer = a; connections = new Connections(); factory = new FunctionFactory(); observableDispatch = createDispatchMap(); initializeMask(); if(LOGGER.isDebugEnabled()) { LOGGER.debug("Layer successfully created containing: {}{}{}{}{}", (encoder == null ? "" : "MultiEncoder,"), (spatialPooler == null ? "" : "SpatialPooler,"), (temporalMemory == null ? "" : "TemporalMemory,"), (autoCreateClassifiers == null ? "" : "Auto creating CLAClassifiers for each input field."), (anomalyComputer == null ? "" : "Anomaly")); } } /** * USED INTERNALLY, DO NOT CALL. * @return */ public CheckPointOp<byte[]> delegateCheckPointCall() { if(parentNetwork != null) { return parentNetwork.getCheckPointOperator(); } return null; } /** * Sets the parent region which contains this {@code Layer} * * @param r */ public void setRegion(Region r) { this.parentRegion = r; } /** * Finalizes the initialization in one method call so that side effect * operations to share objects and other special initialization tasks can * happen all at once in a central place for maintenance ease. */ @SuppressWarnings("unchecked") public Layer<T> close() { if(isClosed) { LOGGER.warn("Close called on Layer " + getName() + " which is already closed."); return this; } params.apply(connections); if(sensor != null) { encoder = encoder == null ? sensor.getEncoder() : encoder; sensor.initEncoder(params); connections.setNumInputs(encoder.getWidth()); if(parentNetwork != null && parentRegion != null) { parentNetwork.setSensorRegion(parentRegion); Object supplier; if((supplier = sensor.getSensorParams().get("ONSUB")) != null) { if(supplier instanceof PublisherSupplier) { ((PublisherSupplier)supplier).setNetwork(parentNetwork); parentNetwork.setPublisher(((PublisherSupplier)supplier).get()); } } } } // Create Encoder hierarchy from definitions & auto create classifiers // if specified if(encoder != null) { if(encoder.getEncoders(encoder) == null || encoder.getEncoders(encoder).size() < 1) { if(params.getParameterByKey(KEY.FIELD_ENCODING_MAP) == null || ((Map<String, Map<String, Object>>)params.getParameterByKey(KEY.FIELD_ENCODING_MAP)).size() < 1) { LOGGER.error("No field encoding map found for specified MultiEncoder"); throw new IllegalStateException("No field encoding map found for specified MultiEncoder"); } encoder.addMultipleEncoders((Map<String, Map<String, Object>>)params.getParameterByKey(KEY.FIELD_ENCODING_MAP)); } // Make the declared column dimensions match the actual input // dimensions retrieved from the encoder int product = 0, inputLength = 0, columnLength = 0; if(((inputLength = ((int[])params.getParameterByKey(KEY.INPUT_DIMENSIONS)).length) != (columnLength = ((int[])params.getParameterByKey(KEY.COLUMN_DIMENSIONS)).length)) || encoder.getWidth() != (product = ArrayUtils.product((int[])params.getParameterByKey(KEY.INPUT_DIMENSIONS)))) { LOGGER.warn("The number of Input Dimensions (" + inputLength + ") != number of Column Dimensions " + "(" + columnLength + ") --OR-- Encoder width (" + encoder.getWidth() + ") != product of dimensions (" + product + ") -- now attempting to fix it."); int[] inferredDims = inferInputDimensions(encoder.getWidth(), columnLength); if(inferredDims != null && inferredDims.length > 0 && encoder.getWidth() == ArrayUtils.product(inferredDims)) { LOGGER.info("Input dimension fix successful!"); LOGGER.info("Using calculated input dimensions: " + Arrays.toString(inferredDims)); } params.setInputDimensions(inferredDims); connections.setInputDimensions(inferredDims); } } autoCreateClassifiers = autoCreateClassifiers != null && (autoCreateClassifiers | (Boolean)params.getParameterByKey(KEY.AUTO_CLASSIFY)); if(autoCreateClassifiers != null && autoCreateClassifiers.booleanValue() && (factory.inference.getClassifiers() == null || factory.inference.getClassifiers().size() < 1)) { factory.inference.classifiers(makeClassifiers(encoder == null ? parentNetwork.getEncoder() : encoder)); // Note classifier addition by setting content mask algo_content_mask |= CLA_CLASSIFIER; } // We must adjust this Layer's inputDimensions to the size of the input // received from the previous Region's output vector. if(parentRegion != null && parentRegion.getUpstreamRegion() != null) { int[] upstreamDims = new int[] { calculateInputWidth() }; params.setInputDimensions(upstreamDims); connections.setInputDimensions(upstreamDims); } else if(parentRegion != null && parentNetwork != null && parentRegion.equals(parentNetwork.getSensorRegion()) && encoder == null && spatialPooler != null) { Layer<?> curr = this; while((curr = curr.getPrevious()) != null) { if(curr.getEncoder() != null) { int[] dims = (int[])curr.getParameters().getParameterByKey(KEY.INPUT_DIMENSIONS); params.setInputDimensions(dims); connections.setInputDimensions(dims); } } } // Let the SpatialPooler initialize the matrix with its requirements if(spatialPooler != null) { // The exact dimensions don't have to be the same but the number of // dimensions do! int inputLength, columnLength = 0; if((inputLength = ((int[])params.getParameterByKey(KEY.INPUT_DIMENSIONS)).length) != (columnLength = ((int[])params.getParameterByKey(KEY.COLUMN_DIMENSIONS)).length)) { LOGGER.error("The number of Input Dimensions (" + inputLength + ") is not same as the number of Column Dimensions " + "(" + columnLength + ") in Parameters! - SpatialPooler not initialized!"); return this; } spatialPooler.init(connections); } // Let the TemporalMemory initialize the matrix with its requirements if(temporalMemory != null) { temporalMemory.init(connections); } this.feedForwardActiveColumns = new int[connections.getNumColumns()]; this.isClosed = true; LOGGER.debug("Layer " + name + " content initialize mask = " + Integer.toBinaryString(algo_content_mask)); return this; } /** * Called from {@link FunctionFactory#createSpatialFunc(SpatialPooler)} and from {@link #close()} * to calculate the size of the input vector given the output source either being a {@link TemporalMemory} * or a {@link SpatialPooler} - from this {@link Region} or a previous {@link Region}. * * @return the length of the input vector */ int calculateInputWidth() { // If no previous Layer, check upstream region for its output layer's output. if(previous == null) { if(parentRegion.getUpstreamRegion() != null) { // Upstream region with TM if((parentRegion.getUpstreamRegion().getHead().algo_content_mask & Layer.TEMPORAL_MEMORY) == Layer.TEMPORAL_MEMORY) { int out = -1; out = (parentRegion.getUpstreamRegion().getHead().getConnections().getCellsPerColumn() * (parentRegion.getUpstreamRegion().getHead().getConnections().getMemory().getMaxIndex() + 1)); return out; } // Upstream region but no TM, so input is the upstream region's SP return new SparseBinaryMatrix(parentRegion.getUpstreamRegion().getHead().getConnections().getColumnDimensions()).getMaxIndex() + 1; } // No previous Layer, and no upstream region // layer contains a TM so compute by cells; if(hasTM() && !hasSP()) { return getConnections().getCellsPerColumn() * (getConnections().getMemory().getMaxIndex() + 1); } // layer only contains a SP return connections.getNumInputs(); }else{ // There is a previous Layer and that layer contains a TM so compute by cells; if((previous.algo_content_mask & Layer.TEMPORAL_MEMORY) == Layer.TEMPORAL_MEMORY) { SparseBinaryMatrix matrix = new SparseBinaryMatrix(previous.getConnections().getColumnDimensions()); return previous.getConnections().getCellsPerColumn() * (matrix.getMaxIndex() + 1); } // Previous Layer but it has no TM so use the previous' column output (from SP) return new SparseBinaryMatrix(previous.getConnections().getColumnDimensions()).getMaxIndex() + 1; } } /** * For internal use only. Returns a flag indicating whether this {@link Layer} * contains a {@link TemporalMemory} * @return */ boolean hasTM() { return (algo_content_mask & Layer.TEMPORAL_MEMORY) == Layer.TEMPORAL_MEMORY; } /** * For internal use only. Returns a flag indicating whether this {@link Layer} * contains a {@link SpatialPooler} * @return */ boolean hasSP() { return (algo_content_mask & Layer.SPATIAL_POOLER) == Layer.SPATIAL_POOLER; } /** * Given an input field width and Spatial Pooler dimensionality; this method * will return an array of dimension sizes whose number is equal to the * number of column dimensions. The sum of the returned dimensions will be * equal to the flat input field width specified. * * This method should be called when a disparity in dimensionality between * the input field and the number of column dimensions is detected. * Otherwise if the input field dimensionality is correctly specified, this * method should <b>not</b> be used. * * @param inputWidth the flat input width of an {@link Encoder}'s output or the * vector used as input to the {@link SpatialPooler} * @param numDims a number specifying the number of dimensions that * should be returned. * @return */ public int[] inferInputDimensions(int inputWidth, int numDims) { double flatSize = inputWidth; double numColDims = numDims; int[] retVal = new int[(int)numColDims]; BigDecimal log = new BigDecimal(Math.log10(flatSize)); BigDecimal dimensions = new BigDecimal(numColDims); double sliceArrangement = new BigDecimal( Math.pow(10, log.divide(dimensions).doubleValue()), MathContext.DECIMAL32).doubleValue(); double remainder = sliceArrangement % (int)sliceArrangement; if(remainder > 0) { for(int i = 0;i < numColDims - 1;i++) retVal[i] = 1; retVal[(int)numColDims - 1] = (int)flatSize; } else { for(int i = 0;i < numColDims;i++) retVal[i] = (int)sliceArrangement; } return retVal; } /** * Returns an {@link Observable} that can be subscribed to, or otherwise * operated upon by another Observable or by an Observable chain. * * @return this {@code Layer}'s output {@link Observable} */ @SuppressWarnings("unchecked") public Observable<Inference> observe() { // This will be called again after the Network is halted so we have to prepare // for rebuild of the Observer chain if(isHalted) { clearSubscriberObserverLists(); } if(userObservable == null) { userObservable = Observable.create(new Observable.OnSubscribe<Inference>() { @Override public void call(Subscriber<? super Inference> t1) { if(observers == null) { observers = new ArrayList<Observer<Inference>>(); } observers.add((Observer<Inference>)t1); } }); } return userObservable; } /** * Called by the {@code Layer} client to receive output {@link Inference}s * from the configured algorithms. * * @param subscriber a {@link Subscriber} to be notified as data is published. * @return a {@link Subscription} */ public Subscription subscribe(final Observer<Inference> subscriber) { // This will be called again after the Network is halted so we have to prepare // for rebuild of the Observer chain if(isHalted) { clearSubscriberObserverLists(); } if(subscriber == null) { throw new IllegalArgumentException("Subscriber cannot be null."); } if(subscribers == null) { subscribers = new ConcurrentLinkedQueue<Observer<Inference>>(); } subscribers.add(subscriber); return createSubscription(subscriber); } /** * Allows the user to define the {@link Connections} object data structure * to use. Or possibly to share connections between two {@code Layer}s * * @param c the {@code Connections} object to use. * @return this Layer instance (in fluent-style) */ public Layer<T> using(Connections c) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } this.connections = c; return this; } /** * Allows the user to specify the {@link Parameters} object used by this * {@code Layer}. If the intent is to share Parameters across multiple * Layers, it must be kept in mind that two Layers containing the same * algorithm may require specification of locally different parameter * settings. In this case, one could use * {@link #alterParameter(KEY, Object)} method to change a local setting * without impacting the same setting in the source parameters object. This * is made possible because the {@link #alterParameter(KEY, Object)} method * first makes a local copy of the {@link Parameters} object, then modifies * the specified parameter. * * @param p the {@link Parameters} to use in this {@code Layer} * @return this {@code Layer} */ public Layer<T> using(Parameters p) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } this.params = p; return this; } /** * Adds an {@link HTMSensor} to this {@code Layer}. An HTMSensor is a regular * {@link Sensor} (i.e. {@link FileSensor}, {@link URISensor}, or {@link ObservableSensor}) * which has had an {@link Encoder} configured and added to it. HTMSensors are * HTM Aware, where as regular Sensors have no knowledge of HTM requirements. * * @param sensor the {@link HTMSensor} * @return this Layer instance (in fluent-style) */ @SuppressWarnings("rawtypes") public Layer<T> add(Sensor sensor) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } this.sensor = (HTMSensor<?>)sensor; // Configure the parent Network's reference to its sensor Region. if(parentNetwork != null && parentRegion != null) { parentNetwork.setSensorRegion(parentRegion); parentNetwork.setSensor(this.sensor); } // Store the SensorParams for Sensor rebuild after deserialization this.sensorParams = this.sensor.getSensorParams(); return this; } /** * Adds a {@link MultiEncoder} to this {@code Layer} * * @param encoder the added MultiEncoder * @return this Layer instance (in fluent-style) */ public Layer<T> add(MultiEncoder encoder) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } this.encoder = encoder; return this; } /** * Adds a {@link SpatialPooler} to this {@code Layer} * * @param sp the added SpatialPooler * @return this Layer instance (in fluent-style) */ public Layer<T> add(SpatialPooler sp) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } // Preserve addition order addedItems.add(sp); this.algo_content_mask |= SPATIAL_POOLER; this.spatialPooler = sp; return this; } /** * Adds a {@link TemporalMemory} to this {@code Layer} * * @param tm the added TemporalMemory * @return this Layer instance (in fluent-style) */ public Layer<T> add(TemporalMemory tm) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } // Preserve addition order addedItems.add(tm); this.algo_content_mask |= TEMPORAL_MEMORY; this.temporalMemory = tm; return this; } /** * Adds an {@link Anomaly} computer to this {@code Layer} * * @param anomalyComputer the Anomaly instance * @return this Layer instance (in fluent-style) */ public Layer<T> add(Anomaly anomalyComputer) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } // Preserve addition order addedItems.add(anomalyComputer); this.algo_content_mask |= ANOMALY_COMPUTER; this.anomalyComputer = anomalyComputer; return this; } /** * Adds a "generic" processing node into this {@code Layer}'s processing * chain. * * <em><b>NOTE: When adding a generic node, the order of calls to * the addXXX() methods becomes crucially important. Make sure you * have added items in a valid order in your "fluent" add call declarations.</b></em> * * @param func a {@link Func1} function to be performed at the point of * insertion within the {@code Layer}'s declaration. * @return this Layer instance (in fluent-style) */ public Layer<T> add(Func1<ManualInput, ManualInput> func) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } if(func == null) { throw new IllegalArgumentException("Cannot add a null Function"); } hasGenericProcess = true; // Preserve addition order addedItems.add(func); return this; } /** * Adds the ability to alter a given parameter in place during a fluent * creation statement. This {@code Layer}'s {@link Parameters} object is * copied and then the specified key/value pair are set on the internal * copy. This call does not affect the original Parameters object so that * local modifications may be made without having to reset them afterward * for subsequent use with another network structure. * * @param key the {@link Parameters} key. * @param value the value of the parameter * @return this Layer instance (in fluent-style) */ public Layer<T> alterParameter(KEY key, Object value) { if(isClosed) { throw new IllegalStateException("Layer already \"closed\""); } // Preserve any input dimensions that might have been set prior to this // previous layers int[] inputDims = (int[])params.getParameterByKey(KEY.INPUT_DIMENSIONS); this.params = this.params.copy(); this.params.setParameterByKey(key, value); this.params.setParameterByKey(KEY.INPUT_DIMENSIONS, inputDims); if(key == KEY.AUTO_CLASSIFY) { this.autoCreateClassifiers = value == null ? false : ((Boolean)value).booleanValue(); // Note the addition of a classifier algo_content_mask |= CLA_CLASSIFIER; } return this; } /** * Returns the configured {@link Sensor} if any exists in this {@code Layer}, * or null if one does not. * * @return any existing HTMSensor applied to this {@code Layer} */ public HTMSensor<?> getSensor() { return sensor; } /** * Returns the {@link Connections} object being used by this {@link Layer} * * @return this {@code Layer}'s {@link Connections} */ public Connections getConnections() { return this.connections; } /** * Processes a single element, sending the specified input up the configured * chain of algorithms or components within this {@code Layer}; resulting in * any {@link Subscriber}s or {@link Observer}s being notified of results * corresponding to the specified input (unless a {@link SpatialPooler} * "primer delay" has been configured). * * The first input to the Layer invokes a method to resolve the transformer * at the bottom of the input chain, therefore the "type" (&lt;T&gt;) of the * input cannot be changed once this method is called for the first time. * * @param t the input object who's type is generic. */ public void compute(T t) { if(!isClosed) { close(); } increment(); if(!dispatchCompleted()) { completeDispatch(t); } publisher.onNext(t); } /** * Stops the processing of this {@code Layer}'s processing thread. */ public void halt() { Object supplier = null; if(sensor != null && (supplier = sensor.getSensorParams().get("ONSUB")) != null) { if(supplier instanceof PublisherSupplier) { ((PublisherSupplier)supplier).clearSuppliedInstance(); } } // Signal the Observer chain to complete if(LAYER_THREAD == null) { publisher.onCompleted(); if(next != null) { next.halt(); } } this.isHalted = true; } /** * Returns a flag indicating whether this layer's processing thread has been * halted or not. * * @return */ public boolean isHalted() { return isHalted; } /** * Sets the learning mode. * * @param isLearn */ public void setLearn(boolean isLearn) { this.isLearn = isLearn; } /** * Returns the learning mode setting. * * @return */ public boolean isLearn() { return isLearn; } /** * Completes the dispatch chain of algorithm {@link Observable}s with * specialized {@link Transformer}s for each algorithm contained within this * Layer. This method then starts the output stream processing of its * {@link Sensor} in a separate {@link Thread} (if it exists) - logging this * event. * * Calling this method sets a flag on the underlying Sensor marking it as * "Terminal" meaning that it cannot be restarted and its output stream * cannot be accessed again. */ @SuppressWarnings("unchecked") public void start() { if(isHalted) { restart(true); return; } // Save boilerplate setup steps by automatically closing when start is // called. if(!isClosed) { close(); } if(sensor == null) { throw new IllegalStateException("A sensor must be added when the mode is not Network.Mode.MANUAL"); } this.encoder = encoder == null ? sensor.getEncoder() : encoder; try { completeDispatch((T)new int[] {}); } catch(Exception e) { notifyError(e); } startLayerThread(); LOGGER.debug("Start called on Layer thread {}", LAYER_THREAD); } /** * Restarts this {@code Layer} * * {@link #restart()} is to be called after a call to {@link #halt()}, to begin * processing again. The {@link Network} will continue from where it previously * left off after the last call to halt(). * * @param startAtIndex flag indicating whether the Layer should be started and * run from the previous save point or not. */ @SuppressWarnings("unchecked") public void restart(boolean startAtIndex) { isHalted = false; if(!isClosed) { start(); }else{ if(sensor == null) { throw new IllegalStateException("A sensor must be added when the mode is not Network.Mode.MANUAL"); } // Re-init the Sensor only if we're halted and haven't already been initialized // following a deserialization. if(!isPostSerialized) { // Recreate the Sensor and its underlying Stream recreateSensors(); } if(parentNetwork != null) { parentNetwork.setSensor(sensor); } observableDispatch = createDispatchMap(); this.encoder = encoder == null ? sensor.getEncoder() : encoder; skip = startAtIndex ? (sensor.getSensorParams().get("ONSUB")) != null ? -1 : recordNum : (recordNum = -1); try { completeDispatch((T)new int[] {}); } catch(Exception e) { notifyError(e); } startLayerThread(); LOGGER.debug("Re-Start called on Layer thread {}", LAYER_THREAD); } } /** * Sets a pointer to the "next" Layer in this {@code Layer}'s * {@link Observable} sequence. * * @param l */ public void next(Layer<Inference> l) { this.next = l; } /** * Returns the next Layer following this Layer in order of process flow. * * @return */ public Layer<Inference> getNext() { return next; } /** * Sets a pointer to the "previous" Layer in this {@code Layer}'s * {@link Observable} sequence. * * @param l */ public void previous(Layer<Inference> l) { this.previous = l; } /** * Returns the previous Layer preceding this Layer in order of process flow. * * @return */ public Layer<Inference> getPrevious() { return previous; } /** * Returns a flag indicating whether this {@code Layer} is configured with a * {@link Sensor} which requires starting up. * * @return */ public boolean hasSensor() { return sensor != null; } /** * Returns the {@link Thread} from which this {@code Layer} is currently * outputting data. * * <b> Warning: This method returns the current thread if the Layer's processing * thread has never been started and therefore is null!</b> * * @return */ public Thread getLayerThread() { if(LAYER_THREAD != null) { return LAYER_THREAD; } return Thread.currentThread(); } /** * Returns the {@link Parameters} used to configure this layer. * * @return */ public Parameters getParameters() { return this.params; } /** * Returns the current predictive {@link Cell}s * * @return the binary vector representing the current prediction. */ public Set<Cell> getPredictiveCells() { return predictiveCells; } /** * Returns the previous predictive {@link Cells} * * @return the binary vector representing the current prediction. */ public Set<Cell> getPreviousPredictiveCells() { return previousPredictiveCells; } /** * Returns the current (dense) array of column indexes which represent * columns which have become activated during the current input sequence * from the SpatialPooler. * * @return the array of active column indexes */ public int[] getFeedForwardActiveColumns() { return feedForwardActiveColumns; } /** * Returns the {@link Cell}s activated in the {@link TemporalMemory} at time * "t" * * @return */ public Set<Cell> getActiveCells() { return activeCells; } /** * Sets the sparse form of the {@link SpatialPooler} column activations and * returns the specified array. * * @param activesInSparseForm the sparse column activations * @return */ int[] feedForwardSparseActives(int[] activesInSparseForm) { this.feedForwardSparseActives = activesInSparseForm; return this.feedForwardSparseActives; } /** * Returns the SpatialPooler column activations in sparse form (indexes of * the on bits). * * @return */ public int[] getFeedForwardSparseActives() { return feedForwardSparseActives; } /** * Returns the {@link Connections} object being used as the structural * matrix and state. */ public Connections getMemory() { return connections; } /** * Returns the count of records historically inputted into this * {@code Layer} * * @return the current record input count */ public int getRecordNum() { return recordNum; } /** * Returns a flag indicating whether this {@code Layer} has had * its {@link #close} method called, or not. * @return */ public boolean isClosed() { return isClosed; } /** * Resets the internal record count to zero * * @return this {@code LayerImpl} */ public Layer<T> resetRecordNum() { recordNum = 0; return this; } /** * Resets the {@link TemporalMemory} if it exists. */ public void reset() { if(temporalMemory == null) { LOGGER.debug("Attempt to reset Layer: " + getName() + "without TemporalMemory"); } else { temporalMemory.reset(connections); } } /** * Returns a flag indicating whether this {@code Layer} contains a * {@link TemporalMemory}. * * @return */ public boolean hasTemporalMemory() { return temporalMemory != null; } /** * Increments the current record sequence number. */ public Layer<T> increment() { if(skip > -1) { --skip; } else { ++recordNum; } return this; } /** * Sets the name and returns this Layer. * * @param name * @return */ public Layer<T> name(String name) { this.name = name; return this; } /** * Returns the String identifier of this {@code Layer} * * @return */ public String getName() { return name; } /** * Returns the last computed {@link Inference} of this {@code Layer} * * @return the last computed inference. */ public Inference getInference() { return currentInference; } /** * Returns the resident {@link MultiEncoder} or the encoder residing in this * {@code Layer}'s {@link Sensor}, if any. * * @return */ public MultiEncoder getEncoder() { if(encoder != null) { return encoder; } if(hasSensor()) { return sensor.getEncoder(); } MultiEncoder e = parentNetwork.getEncoder(); if(e != null) { return e; } return null; } /** * Returns the values submitted to this {@code Layer} in an array whose * indexes correspond to the indexes of probabilities returned when calling * {@link #getAllPredictions(String, int)}. * * @param field The field name of the required prediction * @param step The step for the required prediction * @return */ @SuppressWarnings("unchecked") public <V> V[] getAllValues(String field, int step) { if(currentInference == null || currentInference.getClassifiers() == null) { throw new IllegalStateException("Predictions not available. " + "Either classifiers unspecified or inferencing has not yet begun."); } Classification<?> c = currentInference.getClassification(field); if(c == null) { LOGGER.debug("No ClassifierResult exists for the specified field: {}", field); } return (V[])c.getActualValues(); } /** * Returns a double[] containing a prediction confidence measure for each * bucket (unique entry as determined by an encoder). In order to relate the * probability to an actual value, call {@link #getAllValues(String, int)} * which returns an array containing the actual values submitted to this * {@code Layer} - the indexes of each probability will match the index of * each actual value entered. * * @param field The field name of the required prediction * @param step The step for the required prediction * @return */ public double[] getAllPredictions(String field, int step) { if(currentInference == null || currentInference.getClassifiers() == null) { throw new IllegalStateException("Predictions not available. " + "Either classifiers unspecified or inferencing has not yet begun."); } Classification<?> c = currentInference.getClassification(field); if(c == null) { LOGGER.debug("No ClassifierResult exists for the specified field: {}", field); } return c.getStats(step); } /** * Returns the value whose probability is calculated to be the highest for * the specified field and step. * * @param field The field name of the required prediction * @param step The step for the required prediction * @return */ @SuppressWarnings("unchecked") public <K> K getMostProbableValue(String field, int step) { if(currentInference == null || currentInference.getClassifiers() == null) { throw new IllegalStateException("Predictions not available. " + "Either classifiers unspecified or inferencing has not yet begun."); } Classification<?> c = currentInference.getClassification(field); if(c == null) { LOGGER.debug("No ClassifierResult exists for the specified field: {}", field); } return (K)c.getMostProbableValue(step); } /** * Returns the bucket index of the value with the highest calculated * probability for the specified field and step. * * @param field The field name of the required prediction * @param step The step for the required prediction * @return */ public int getMostProbableBucketIndex(String field, int step) { if(currentInference == null || currentInference.getClassifiers() == null) { throw new IllegalStateException("Predictions not available. " + "Either classifiers unspecified or inferencing has not yet begun."); } Classification<?> c = currentInference.getClassification(field); if(c == null) { LOGGER.debug("No ClassifierResult exists for the specified field: {}", field); } return c.getMostProbableBucketIndex(step); } // PRIVATE METHODS AND CLASSES BELOW HERE // /** * Notify all subscribers through the delegate that stream processing has * been completed or halted. */ void notifyComplete() { for(Observer<Inference> o : subscribers) { o.onCompleted(); } for(Observer<Inference> o : observers) { o.onCompleted(); } publisher.onCompleted(); } /** * Called internally to propagate the specified {@link Exception} up the * network hierarchy * * @param e the exception to notify users of */ void notifyError(Exception e) { for(Observer<Inference> o : subscribers) { o.onError(e); } for(Observer<Inference> o : observers) { o.onError(e); } publisher.onError(e); } /** * <p> * Returns the content mask used to indicate what algorithm contents this * {@code Layer} has. This is used to determine whether the * {@link Inference} object passed between layers should share values. * </p> * <p> * If any algorithms are repeated then {@link Inference}s will * <em><b>NOT</b></em> be shared between layers. {@link Regions} * <em><b>NEVER</b></em> share {@link Inference}s * </p> * * @return */ byte getMask() { return algo_content_mask; } /** * Initializes the algorithm content mask used for detection of repeated * algorithms among {@code Layer}s in a {@link Region}. see * {@link #getMask()} for more information. */ private void initializeMask() { algo_content_mask |= (this.spatialPooler == null ? 0 : SPATIAL_POOLER); algo_content_mask |= (this.temporalMemory == null ? 0 : TEMPORAL_MEMORY); algo_content_mask |= (this.autoCreateClassifiers == null || !autoCreateClassifiers ? 0 : CLA_CLASSIFIER); algo_content_mask |= (this.anomalyComputer == null ? 0 : ANOMALY_COMPUTER); } /** * Returns a flag indicating whether we've connected the first observable in * the sequence (which lazily does the input type of &lt;T&gt; to * {@link Inference} transformation) to the Observables connecting the rest * of the algorithm components. * * @return flag indicating all observables connected. True if so, false if * not */ private boolean dispatchCompleted() { return observableDispatch == null; } /** * Connects the first observable which does the transformation of input * types, to the rest of the sequence - then clears the helper map and sets * it to null. * * @param t */ private void completeDispatch(T t) { // Get the Input Transformer for the specified input type Observable<ManualInput> sequence = resolveObservableSequence(t); // If this Layer has a Sensor, map its encoder buckets sequence = mapEncoderBuckets(sequence); // Add the rest of the chain observables for the other added algorithms. sequence = fillInSequence(sequence); // All subscribers and observers are notified from a single delegate. if(subscribers == null) subscribers = new ConcurrentLinkedQueue<Observer<Inference>>(); subscribers.add(getDelegateObserver()); subscription = sequence.subscribe(getDelegateSubscriber()); // The map of input types to transformers is no longer needed. observableDispatch.clear(); observableDispatch = null; // Handle global network sensor access. if(sensor == null && parentNetwork != null && parentNetwork.isTail(this)) { sensor = parentNetwork == null ? null : parentNetwork.getSensor(); } else if(parentNetwork != null && sensor != null) { parentNetwork.setSensor(sensor); } } /** * We cannot create the {@link Observable} sequence all at once because the * first step is to transform the input type to the type the rest of the * sequence uses (Observable<b>&lt;Inference&gt;</b>). This can only happen * during the actual call to {@link #compute(Object)} which presents the * input type - so we create a map of all types of expected inputs, and then * connect the sequence at execution time; being careful to only incur the * cost of sequence assembly on the first call to {@link #compute(Object)}. * After the first call, we dispose of this map and its contents. * * @return the map of input types to {@link Transformer} */ @SuppressWarnings("unchecked") private Map<Class<T>, Observable<ManualInput>> createDispatchMap() { Map<Class<T>, Observable<ManualInput>> observableDispatch = Collections.synchronizedMap(new HashMap<Class<T>, Observable<ManualInput>>()); publisher = PublishSubject.create(); observableDispatch.put((Class<T>)Map.class, factory.createMultiMapFunc(publisher)); observableDispatch.put((Class<T>)ManualInput.class, factory.createManualInputFunc(publisher)); observableDispatch.put((Class<T>)String[].class, factory.createEncoderFunc(publisher)); observableDispatch.put((Class<T>)int[].class, factory.createVectorFunc(publisher)); return observableDispatch; } /** * If this Layer has a Sensor, map its encoder's buckets * * @param sequence * @return */ private Observable<ManualInput> mapEncoderBuckets(Observable<ManualInput> sequence) { if(hasSensor()) { if(getSensor().getMetaInfo().getFieldTypes().stream().anyMatch(ft -> { return ft == FieldMetaType.SARR || ft == FieldMetaType.DARR || ft == FieldMetaType.COORD || ft == FieldMetaType.GEO; })) { if(autoCreateClassifiers) { throw new IllegalStateException("Cannot autoclassify with raw array input or " + " Coordinate based encoders... Remove auto classify setting."); } return sequence; } sequence = sequence.map(m -> { doEncoderBucketMapping(m, getSensor().getInputMap()); return m; }); } return sequence; } /** * This method is necessary to be able to retrieve the mapped * {@link Observable} types to input types or their subclasses if any. * * @param t the input type. The "expected" types are: * <ul> * <li>{@link Map}</li> * <li>{@link ManualInput}</li> * <li>String[]</li> * <li>int[]</li> * </ul> * or their subclasses. * @return an Observable suitable for subscribing or operating on. */ private Observable<ManualInput> resolveObservableSequence(T t) { Observable<ManualInput> sequenceStart = null; if(observableDispatch == null) { observableDispatch = createDispatchMap(); } if(observableDispatch != null) { if(ManualInput.class.isAssignableFrom(t.getClass())) { sequenceStart = observableDispatch.get(ManualInput.class); } else if(Map.class.isAssignableFrom(t.getClass())) { sequenceStart = observableDispatch.get(Map.class); } else if(t.getClass().isArray()) { if(t.getClass().equals(String[].class)) { sequenceStart = observableDispatch.get(String[].class); } else if(t.getClass().equals(int[].class)) { sequenceStart = observableDispatch.get(int[].class); } } } // Insert skip observable operator if initializing with an advanced record number // (i.e. Serialized Network) if(recordNum > 0 && skip != -1) { sequenceStart = sequenceStart.skip(recordNum + 1); Integer skipCount; if(((skipCount = (Integer)params.getParameterByKey(KEY.SP_PRIMER_DELAY)) != null)) { // No need to "warm up" the SpatialPooler if we're deserializing an SP // that has been running... However "skipCount - recordNum" is there so // we make sure the Network has run at least long enough to satisfy the // original requested "primer delay". params.setParameterByKey(KEY.SP_PRIMER_DELAY, Math.max(0, skipCount - recordNum)); } } sequenceStart = sequenceStart.filter(m -> { if(!checkPointOpObservers.isEmpty() && parentNetwork != null) { // Execute check point logic doCheckPoint(); } return true; }); return sequenceStart; } /** * Executes the check point logic, handles the return of the serialized byte array * by delegating the call to {@link rx.Observer#onNext(byte[])} of all the currently queued * Observers; then clears the list of Observers. */ private void doCheckPoint() { byte[] bytes = parentNetwork.internalCheckPointOp(); if(bytes != null) { LOGGER.debug("Layer [" + getName() + "] checkPointed file: " + Persistence.get().getLastCheckPointFileName()); }else{ LOGGER.debug("Layer [" + getName() + "] checkPoint F A I L E D at: " + (new DateTime())); } for(Observer<byte[]> o : checkPointOpObservers) { o.onNext(bytes); o.onCompleted(); } checkPointOpObservers.clear(); } /** * Stores a {@link NamedTuple} which contains the input values and bucket * information - keyed to the encoded field name so that a classifier can * retrieve it later on in the processing sequence. * * @param inference * @param encoderInputMap */ private void doEncoderBucketMapping(Inference inference, Map<String, Object> encoderInputMap) { if(encoderTuples == null) { encoderTuples = encoder.getEncoders(encoder); } // Store the encoding int[] encoding = inference.getEncoding(); for(EncoderTuple t : encoderTuples) { String name = t.getName(); Encoder<?> e = t.getEncoder(); int bucketIdx = -1; Object o = encoderInputMap.get(name); if(DateTime.class.isAssignableFrom(o.getClass())) { bucketIdx = ((DateEncoder)e).getBucketIndices((DateTime)o)[0]; } else if(Number.class.isAssignableFrom(o.getClass())) { bucketIdx = e.getBucketIndices((double)o)[0]; } else { bucketIdx = e.getBucketIndices((String)o)[0]; } int offset = t.getOffset(); int[] tempArray = new int[e.getWidth()]; System.arraycopy(encoding, offset, tempArray, 0, tempArray.length); inference.getClassifierInput().put(name, new NamedTuple(new String[] { "name", "inputValue", "bucketIdx", "encoding" }, name, o, bucketIdx, tempArray)); } } /** * Connects the {@link Transformer} to the rest of the {@link Observable} * sequence. * * @param o the Transformer part of the sequence. * @return the completed {@link Observable} sequence. */ private Observable<ManualInput> fillInSequence(Observable<ManualInput> o) { // Route to ordered dispatching if required. if(hasGenericProcess) { return fillInOrderedSequence(o); } // Spatial Pooler config if(spatialPooler != null) { Integer skipCount = 0; if((skipCount = ((Integer)params.getParameterByKey(KEY.SP_PRIMER_DELAY))) != null) { o = o.map(factory.createSpatialFunc(spatialPooler)).skip(skipCount.intValue()); } else { o = o.map(factory.createSpatialFunc(spatialPooler)); } } // Temporal Memory config if(temporalMemory != null) { o = o.map(factory.createTemporalFunc(temporalMemory)); } // Classifier config if(autoCreateClassifiers != null && autoCreateClassifiers.booleanValue()) { o = o.map(factory.createClassifierFunc()); } // Anomaly config if(anomalyComputer != null) { o = o.map(factory.createAnomalyFunc(anomalyComputer)); } return o; } /** * Connects {@link Observable} or {@link Transformer} emissions in the order * they are declared. * * @param o first {@link Observable} in sequence. * @return */ @SuppressWarnings("unchecked") private Observable<ManualInput> fillInOrderedSequence(Observable<ManualInput> o) { Collections.reverse(addedItems); for(Object node : addedItems) { if(node instanceof Func1<?, ?>) { o = o.map((Func1<ManualInput, ManualInput>)node); } else if(node instanceof SpatialPooler) { Integer skipCount = 0; if((skipCount = ((Integer)params.getParameterByKey(KEY.SP_PRIMER_DELAY))) != null) { o = o.map(factory.createSpatialFunc(spatialPooler)).skip(skipCount.intValue()); } else { o = o.map(factory.createSpatialFunc(spatialPooler)); } } else if(node instanceof TemporalMemory) { o = o.map(factory.createTemporalFunc(temporalMemory)); } } // Classifier config if(autoCreateClassifiers != null && autoCreateClassifiers.booleanValue()) { o = o.map(factory.createClassifierFunc()); } // Anomaly config if(anomalyComputer != null) { o = o.map(factory.createAnomalyFunc(anomalyComputer)); } return o; } /** * Called internally to create a subscription on behalf of the specified * {@link LayerObserver} * * @param sub the LayerObserver (subscriber). * @return */ private Subscription createSubscription(final Observer<Inference> sub) { return new Subscription() { private Observer<Inference> observer = sub; @Override public void unsubscribe() { subscribers.remove(observer); if(subscribers.isEmpty()) { subscription.unsubscribe(); } } @Override public boolean isUnsubscribed() { return subscribers.contains(observer); } }; } /** * Returns the {@link PublishSubject}'s subscriber which delegates to all * the {@link Layer}'s subscribers. * * @return */ private Observer<Inference> getDelegateSubscriber() { return new Observer<Inference>() { @Override public void onCompleted() { for(Observer<Inference> o : subscribers) { o.onCompleted(); } } @Override public void onError(Throwable e) { for(Observer<Inference> o : subscribers) { o.onError(e); } } @Override public void onNext(Inference i) { currentInference = i; for(Observer<Inference> o : subscribers) { o.onNext(i); } } }; } /** * Returns the {@link PublishSubject}'s subscriber which delegates to all * the {@link Layer}'s subscribers. * * @return */ private Observer<Inference> getDelegateObserver() { return new Observer<Inference>() { @Override public void onCompleted() { for(Observer<Inference> o : observers) { o.onCompleted(); } } @Override public void onError(Throwable e) { for(Observer<Inference> o : observers) { o.onError(e); e.printStackTrace(); } } @Override public void onNext(Inference i) { currentInference = i; for(Observer<Inference> o : observers) { o.onNext(i); } } }; } /** * Clears the subscriber and observer lists so they can be rebuilt * during restart or deserialization. */ private void clearSubscriberObserverLists() { if(observers == null) observers = new ArrayList<Observer<Inference>>(); if(subscribers == null) subscribers = new ConcurrentLinkedQueue<Observer<Inference>>(); subscribers.clear(); userObservable = null; } /** * Creates the {@link NamedTuple} of names to encoders used in the * observable sequence. * * @param encoder * @return */ NamedTuple makeClassifiers(MultiEncoder encoder) { String[] names = new String[encoder.getEncoders(encoder).size()]; CLAClassifier[] ca = new CLAClassifier[names.length]; int i = 0; for(EncoderTuple et : encoder.getEncoders(encoder)) { names[i] = et.getName(); ca[i] = new CLAClassifier(); i++; } return new NamedTuple(names, (Object[])ca); } /** * Called internally to invoke the {@link SpatialPooler} * * @param input * @return */ protected int[] spatialInput(int[] input) { if(input == null) { LOGGER.info("Layer ".concat(getName()).concat(" received null input")); } else if(input.length < 1) { LOGGER.info("Layer ".concat(getName()).concat(" received zero length bit vector")); return input; } int[] activeColumns = new int[feedForwardActiveColumns.length]; spatialPooler.compute(connections, input, activeColumns, sensor == null || sensor.getMetaInfo().isLearn(), isLearn); return feedForwardActiveColumns = activeColumns; } /** * Called internally to invoke the {@link TemporalMemory} * * @param input the current input vector * @param mi the current input inference container * @return */ protected int[] temporalInput(int[] input, ManualInput mi) { ComputeCycle cc = null; if(sensor != null) { if(sensor.getMetaInfo().isReset()) { temporalMemory.reset(connections); } cc = temporalMemory.compute(connections, input, sensor.getMetaInfo().isLearn()); } else { cc = temporalMemory.compute(connections, input, isLearn); } previousPredictiveCells = predictiveCells; // Store the predictive columns mi.predictiveCells(predictiveCells = cc.predictiveCells); // Store activeCells mi.activeCells(activeCells = cc.activeCells()); // Store the Compute Cycle mi.computeCycle = cc; return SDR.asCellIndices(cc.activeCells); } /** * Starts this {@code Layer}'s thread */ protected void startLayerThread() { (LAYER_THREAD = new Thread("Sensor Layer [" + getName() + "] Thread") { @SuppressWarnings("unchecked") public void run() { LOGGER.debug("Layer [" + getName() + "] started Sensor output stream processing."); // Applies "terminal" function, at this point the input stream // is "sealed". sensor.getOutputStream().filter(i -> { if(isHalted) { notifyComplete(); if(next != null) { next.halt(); } return false; } if(Thread.currentThread().isInterrupted()) { notifyError(new RuntimeException("Unknown Exception while filtering input")); } return true; }).forEach(intArray -> { ((ManualInput)Layer.this.factory.inference).encoding(intArray); Layer.this.compute((T)intArray); // Notify all downstream observers that the stream is closed if(!sensor.hasNext()) { notifyComplete(); } }); } }).start(); } /** * Returns an {@link rx.Observable} operator that when subscribed to, invokes an operation * that stores the state of this {@code Network} while keeping the Network up and running. * The Network will be stored at the pre-configured location (in binary form only, not JSON). * * @param network the {@link Network} to check point. * @return the {@link CheckPointOp} operator */ @SuppressWarnings("unchecked") CheckPointOp<byte[]> getCheckPointOperator() { if(checkPointOp == null) { checkPointOp = new CheckPointOperator<byte[]>(Layer.this); } return (CheckPointOp<byte[]>)checkPointOp; } // Inner Class Definition for CheckPointer (Observable) // /** * <p> * Implementation of the CheckPointOp interface which serves to checkpoint * and register a listener at the same time. The {@link rx.Observer} will be * notified with the byte array of the {@link Network} being serialized. * </p><p> * The layer thread automatically tests for the list of observers to * contain > 0 elements, which indicates a check point operation should * be executed. * </p> * * @param <T> {@link rx.Observer}'s return type */ static class CheckPointOperator<T> extends Observable<T> implements CheckPointOp<T> { private CheckPointOperator(Layer<?> l) { this(new Observable.OnSubscribe<T>() { @SuppressWarnings({ "unchecked" }) @Override public void call(Subscriber<? super T> r) { if(l.LAYER_THREAD != null) { // The layer thread automatically tests for the list of observers to // contain > 0 elements, which indicates a check point operation should // be executed. l.checkPointOpObservers.add((Observer<byte[]>)r); }else{ l.doCheckPoint(); } } }); } /** * Constructs this {@code CheckPointOperator} * @param f a subscriber function */ protected CheckPointOperator(rx.Observable.OnSubscribe<T> f) { super(f); } /** * Queues the specified {@link rx.Observer} for notification upon * completion of a check point operation. */ public Subscription checkPoint(Observer<? super T> t) { return super.subscribe(t); } } // Inner Class Definition Transformer Example // /** * Factory which returns an {@link Observable} capable of transforming known * input formats to the universal format object passed between all * Observables in the Observable chains making up the processing steps * involving HTM algorithms. * * The {@link Transformer} implementations are used to transform various * inputs into a {@link ManualInput}, and thus are used at the beginning of * any Observable chain; each succeding Observable in a given chain would * then communicate via passed ManualInputs or {@link Inference}s (which are * the same thing). * * @author David Ray * @see Layer#completeDispatch(Object) * @see Layer#resolveObservableSequence(Object) * @see Layer#fillInSequence(Observable) */ class FunctionFactory implements Persistable { private static final long serialVersionUID = 1L; ManualInput inference = new ManualInput(); // TRANSFORMERS // /** * WARNING: UNIMPLEMENTED * * <p> * Emits an {@link Observable} which is transformed from a String[] of * csv input to one that emits {@link Inference}s. * </p> * <p> * This class currently lacks the implementation of csv parsing into * distinct Object types - which is necessary to compose a "multi-map" * necessary to input data into the {@link MultiEncoder} necessary to * encode multiple field inputs. * </p> * <p> * TODO: Implement later * </p> */ class String2Inference implements Transformer<String[], ManualInput> { @Override public Observable<ManualInput> call(Observable<String[]> t1) { return t1.map(new Func1<String[], ManualInput>() { @Override public ManualInput call(String[] t1) { // Do transformative work here // // In "real life", this will send data through the MultiEncoder // // Below is simply a faked out place holder... // int[] sdr = new int[t1.length]; for(int i = 0;i < sdr.length;i++) { sdr[i] = Integer.parseInt(t1[i]); } return inference.recordNum(getRecordNum()).sdr(sdr).layerInput(sdr); } }); } } /** * <p> * Emits an {@link Observable} which is transformed from a Map input * type to one that emits {@link Inference}s. * </p> * <p> * This {@link Transformer} is used when the input to a given * {@link Layer} is a map of fields to input Objects. It is typically * used when a Layer is configured with a {@link MultiEncoder} (which is * the only encoder type that may be contained within a Layer, because * it can be used to hold any combination of encoders required.). * </p> * */ @SuppressWarnings("rawtypes") class Map2Inference implements Transformer<Map, ManualInput> { @Override public Observable<ManualInput> call(Observable<Map> t1) { return t1.map(new Func1<Map, ManualInput>() { @SuppressWarnings("unchecked") @Override public ManualInput call(Map t1) { if(encoderTuples == null) { encoderTuples = encoder.getEncoders(encoder); } // Store the encoding int[] encoding = encoder.encode(t1); inference.sdr(encoding).encoding(encoding); doEncoderBucketMapping(inference, t1); return inference.recordNum(getRecordNum()).layerInput(t1); } }); } } /** * <p> * Emits an {@link Observable} which is transformed from a binary vector * input type to one that emits {@link Inference}s. * </p> * <p> * This type is used when bypassing an encoder and possibly any other * algorithm usually connected in a sequence of algorithms within a * {@link Layer} * </p> */ class Vector2Inference implements Transformer<int[], ManualInput> { @Override public Observable<ManualInput> call(Observable<int[]> t1) { return t1.map(new Func1<int[], ManualInput>() { @Override public ManualInput call(int[] t1) { // Indicates a value that skips the encoding step return inference.recordNum(getRecordNum()).sdr(t1).layerInput(t1); } }); } } /** * Emits an {@link Observable} which copies an Inference input to the * output, storing relevant information in this layer's inference object * along the way. */ class Copy2Inference implements Transformer<ManualInput, ManualInput> { @Override public Observable<ManualInput> call(Observable<ManualInput> t1) { return t1.map(new Func1<ManualInput, ManualInput>() { NamedTuple swap; boolean swapped; @Override public ManualInput call(ManualInput t1) { // Inference is shared along entire network if(!swapped) { swap = inference.getClassifiers(); inference = t1; inference.classifiers(swap); swapped = true; } // Indicates a value that skips the encoding step return inference.recordNum(getRecordNum()).sdr(t1.getSDR()).recordNum(t1.getRecordNum()).layerInput(t1); } }); } } // INPUT TRANSFORMATION FUNCTIONS // public Observable<ManualInput> createEncoderFunc(Observable<T> in) { return in.ofType(String[].class).compose(new String2Inference()); } public Observable<ManualInput> createMultiMapFunc(Observable<T> in) { return in.ofType(Map.class).compose(new Map2Inference()); } public Observable<ManualInput> createVectorFunc(Observable<T> in) { return in.ofType(int[].class).compose(new Vector2Inference()); } public Observable<ManualInput> createManualInputFunc(Observable<T> in) { return in.ofType(ManualInput.class).compose(new Copy2Inference()); } // OBSERVABLE COMPONENT CREATION METHODS // public Func1<ManualInput, ManualInput> createSpatialFunc(final SpatialPooler sp) { return new Func1<ManualInput, ManualInput>() { int inputWidth = -1; @Override public ManualInput call(ManualInput t1) { if(t1.getSDR().length > 0 && ArrayUtils.isSparse(t1.getSDR())) { if(inputWidth == -1) { inputWidth = calculateInputWidth(); } t1.sdr(ArrayUtils.asDense(t1.getSDR(), inputWidth)); } return t1.sdr(spatialInput(t1.getSDR())).feedForwardActiveColumns(t1.getSDR()); } }; } public Func1<ManualInput, ManualInput> createTemporalFunc(final TemporalMemory tm) { return new Func1<ManualInput, ManualInput>() { @Override public ManualInput call(ManualInput t1) { if(!ArrayUtils.isSparse(t1.getSDR())) { // Set on Layer, then set sparse actives as the sdr, // then set on Manual Input (t1) t1 = t1.sdr(feedForwardSparseActives(ArrayUtils.where(t1.getSDR(), ArrayUtils.WHERE_1))).feedForwardSparseActives(t1.getSDR()); } return t1.sdr(temporalInput(t1.getSDR(), t1)); } }; } public Func1<ManualInput, ManualInput> createClassifierFunc() { return new Func1<ManualInput, ManualInput>() { private Object bucketIdx; private Object actValue; Map<String, Object> inputMap = new HashMap<String, Object>() { private static final long serialVersionUID = 1L; @Override public Object get(Object o) { return o.equals("bucketIdx") ? bucketIdx : actValue; } }; @Override public ManualInput call(ManualInput t1) { Map<String, NamedTuple> ci = t1.getClassifierInput(); int recordNum = getRecordNum(); for(String key : ci.keySet()) { NamedTuple inputs = ci.get(key); bucketIdx = inputs.get("bucketIdx"); actValue = inputs.get("inputValue"); CLAClassifier c = (CLAClassifier)t1.getClassifiers().get(key); Classification<Object> result = c.compute(recordNum, inputMap, t1.getSDR(), isLearn, true); t1.recordNum(recordNum).storeClassification((String)inputs.get("name"), result); } return t1; } }; } public Func1<ManualInput, ManualInput> createAnomalyFunc(final Anomaly an) { return new Func1<ManualInput, ManualInput>() { int cellsPerColumn = connections.getCellsPerColumn(); @Override public ManualInput call(ManualInput t1) { if(t1.getFeedForwardSparseActives() == null || t1.getPreviousPredictiveCells() == null) { return t1.anomalyScore(1.0); } return t1.anomalyScore(anomalyComputer.compute(t1.getFeedForwardSparseActives(), SDR.cellsAsColumnIndices(t1.getPreviousPredictiveCells(), cellsPerColumn), 0, 0)); } }; } } /** * Re-initializes the {@link HTMSensor} following deserialization or restart * after halt. */ private void recreateSensors() { if(sensor != null) { // Recreate the Sensor and its underlying Stream Class<?> sensorKlass = sensor.getSensorClass(); if(sensorKlass.toString().indexOf("File") != -1) { Object path = sensor.getSensorParams().get("PATH"); sensor = (HTMSensor<?>)Sensor.create( FileSensor::create, SensorParams.create(Keys::path, "", path)); }else if(sensorKlass.toString().indexOf("Observ") != -1) { Object supplierOfObservable = sensor.getSensorParams().get("ONSUB"); sensor = (HTMSensor<?>)Sensor.create( ObservableSensor::create, SensorParams.create(Keys::obs, "", supplierOfObservable)); }else if(sensorKlass.toString().indexOf("URI") != -1) { Object url = sensor.getSensorParams().get("URI"); sensor = (HTMSensor<?>)Sensor.create( URISensor::create, SensorParams.create(Keys::uri, "", url)); } } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + recordNum; result = prime * result + algo_content_mask; result = prime * result + ((currentInference == null) ? 0 : currentInference.hashCode()); result = prime * result + (hasGenericProcess ? 1231 : 1237); result = prime * result + (isClosed ? 1231 : 1237); result = prime * result + (isHalted ? 1231 : 1237); result = prime * result + (isLearn ? 1231 : 1237); result = prime * result + ((parentRegion == null) ? 0 : parentRegion.hashCode()); result = prime * result + ((sensorParams == null) ? 0 : sensorParams.hashCode()); return result; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; Layer<?> other = (Layer<?>)obj; if(name == null) { if(other.name != null) return false; } else if(!name.equals(other.name)) return false; if(algo_content_mask != other.algo_content_mask) return false; if(currentInference == null) { if(other.currentInference != null) return false; } else if(!currentInference.equals(other.currentInference)) return false; if(recordNum != other.recordNum) return false; if(hasGenericProcess != other.hasGenericProcess) return false; if(isClosed != other.isClosed) return false; if(isHalted != other.isHalted) return false; if(isLearn != other.isLearn) return false; if(parentRegion == null) { if(other.parentRegion != null) return false; } else if(other.parentRegion == null || !parentRegion.getName().equals(other.parentRegion.getName())) return false; if(sensorParams == null) { if(other.sensorParams != null) return false; } else if(!sensorParams.equals(other.sensorParams)) return false; return true; } }
package org.smoothbuild.lang.base; import java.util.Objects; import java.util.Optional; import org.smoothbuild.lang.base.type.Type; import org.smoothbuild.lang.expr.Expression; import org.smoothbuild.lang.expr.ValueReferenceExpression; /** * This class is immutable. */ public class Value extends Evaluable { private final Optional<Expression> body; public Value(Type type, String name, Optional<Expression> body, Location location) { super(type, name, location); this.body = body; } @Override public Type type() { return super.type(); } public Optional<Expression> body() { return body; } public Expression createReferenceExpression(Location location) { return new ValueReferenceExpression(name(), location); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof Value that) { return this.type().equals(that.type()) && this.name().equals(that.name()) && this.body().equals(that.body()) && this.location().equals(that.location()); } return false; } @Override public int hashCode() { return Objects.hash(type(), name(), body(), location()); } @Override public String toString() { return "Value(`" + type().name() + " " + name() + " = " + body + "`)"; } }
package org.spongepowered.api.data; import io.leangen.geantyref.TypeToken; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.block.entity.Banner; import org.spongepowered.api.block.entity.BlockEntity; import org.spongepowered.api.block.entity.CommandBlock; import org.spongepowered.api.block.entity.EndGateway; import org.spongepowered.api.block.entity.Jukebox; import org.spongepowered.api.block.entity.Lectern; import org.spongepowered.api.block.entity.MobSpawner; import org.spongepowered.api.block.entity.Piston; import org.spongepowered.api.block.entity.Sign; import org.spongepowered.api.block.entity.StructureBlock; import org.spongepowered.api.block.entity.carrier.Beacon; import org.spongepowered.api.block.entity.carrier.BrewingStand; import org.spongepowered.api.block.entity.carrier.CarrierBlockEntity; import org.spongepowered.api.block.entity.carrier.Hopper; import org.spongepowered.api.block.entity.carrier.furnace.FurnaceBlockEntity; import org.spongepowered.api.data.meta.BannerPatternLayer; import org.spongepowered.api.data.type.ArmorMaterial; import org.spongepowered.api.data.type.ArtType; import org.spongepowered.api.data.type.AttachmentSurface; import org.spongepowered.api.data.type.BoatType; import org.spongepowered.api.data.type.BodyPart; import org.spongepowered.api.data.type.BodyParts; import org.spongepowered.api.data.type.CatType; import org.spongepowered.api.data.type.ChestAttachmentType; import org.spongepowered.api.data.type.ComparatorMode; import org.spongepowered.api.data.type.DoorHinge; import org.spongepowered.api.data.type.DyeColor; import org.spongepowered.api.data.type.FoxType; import org.spongepowered.api.data.type.HandPreference; import org.spongepowered.api.data.type.HorseColor; import org.spongepowered.api.data.type.HorseStyle; import org.spongepowered.api.data.type.InstrumentType; import org.spongepowered.api.data.type.ItemTier; import org.spongepowered.api.data.type.LlamaType; import org.spongepowered.api.data.type.MatterType; import org.spongepowered.api.data.type.MooshroomType; import org.spongepowered.api.data.type.NotePitch; import org.spongepowered.api.data.type.PandaGene; import org.spongepowered.api.data.type.PandaGenes; import org.spongepowered.api.data.type.ParrotType; import org.spongepowered.api.data.type.PhantomPhase; import org.spongepowered.api.data.type.PickupRule; import org.spongepowered.api.data.type.PistonType; import org.spongepowered.api.data.type.PortionType; import org.spongepowered.api.data.type.ProfessionType; import org.spongepowered.api.data.type.RabbitType; import org.spongepowered.api.data.type.RailDirection; import org.spongepowered.api.data.type.SkinPart; import org.spongepowered.api.data.type.SlabPortion; import org.spongepowered.api.data.type.SpellType; import org.spongepowered.api.data.type.SpellTypes; import org.spongepowered.api.data.type.StairShape; import org.spongepowered.api.data.type.StructureMode; import org.spongepowered.api.data.type.TropicalFishShape; import org.spongepowered.api.data.type.VillagerType; import org.spongepowered.api.data.type.WireAttachmentType; import org.spongepowered.api.data.value.ListValue; import org.spongepowered.api.data.value.MapValue; import org.spongepowered.api.data.value.SetValue; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.data.value.WeightedCollectionValue; import org.spongepowered.api.effect.VanishState; import org.spongepowered.api.effect.particle.ParticleEffect; import org.spongepowered.api.effect.particle.ParticleOption; import org.spongepowered.api.effect.particle.ParticleType; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.api.effect.potion.PotionEffectType; import org.spongepowered.api.effect.potion.PotionEffectTypes; import org.spongepowered.api.effect.sound.music.MusicDisc; import org.spongepowered.api.entity.AreaEffectCloud; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityArchetype; import org.spongepowered.api.entity.EntityType; import org.spongepowered.api.entity.ExperienceOrb; import org.spongepowered.api.entity.FallingBlock; import org.spongepowered.api.entity.Item; import org.spongepowered.api.entity.ai.goal.GoalExecutorTypes; import org.spongepowered.api.entity.explosive.EndCrystal; import org.spongepowered.api.entity.explosive.Explosive; import org.spongepowered.api.entity.explosive.fused.FusedExplosive; import org.spongepowered.api.entity.explosive.fused.PrimedTNT; import org.spongepowered.api.entity.hanging.Hanging; import org.spongepowered.api.entity.hanging.ItemFrame; import org.spongepowered.api.entity.hanging.LeashKnot; import org.spongepowered.api.entity.hanging.Painting; import org.spongepowered.api.entity.living.Ageable; import org.spongepowered.api.entity.living.Agent; import org.spongepowered.api.entity.living.ArmorStand; import org.spongepowered.api.entity.living.Bat; import org.spongepowered.api.entity.living.Humanoid; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.living.animal.Animal; import org.spongepowered.api.entity.living.animal.Cat; import org.spongepowered.api.entity.living.animal.Chicken; import org.spongepowered.api.entity.living.animal.Fox; import org.spongepowered.api.entity.living.animal.Ocelot; import org.spongepowered.api.entity.living.animal.Panda; import org.spongepowered.api.entity.living.animal.Parrot; import org.spongepowered.api.entity.living.animal.Pig; import org.spongepowered.api.entity.living.animal.PolarBear; import org.spongepowered.api.entity.living.animal.Rabbit; import org.spongepowered.api.entity.living.animal.Sheep; import org.spongepowered.api.entity.living.animal.TameableAnimal; import org.spongepowered.api.entity.living.animal.Turtle; import org.spongepowered.api.entity.living.animal.Wolf; import org.spongepowered.api.entity.living.animal.cow.Mooshroom; import org.spongepowered.api.entity.living.animal.horse.Horse; import org.spongepowered.api.entity.living.animal.horse.HorseLike; import org.spongepowered.api.entity.living.animal.horse.PackHorse; import org.spongepowered.api.entity.living.animal.horse.llama.Llama; import org.spongepowered.api.entity.living.animal.horse.llama.TraderLlama; import org.spongepowered.api.entity.living.aquatic.Dolphin; import org.spongepowered.api.entity.living.aquatic.fish.school.TropicalFish; import org.spongepowered.api.entity.living.golem.IronGolem; import org.spongepowered.api.entity.living.golem.Shulker; import org.spongepowered.api.entity.living.monster.Blaze; import org.spongepowered.api.entity.living.monster.Creeper; import org.spongepowered.api.entity.living.monster.Enderman; import org.spongepowered.api.entity.living.monster.Endermite; import org.spongepowered.api.entity.living.monster.Patroller; import org.spongepowered.api.entity.living.monster.Phantom; import org.spongepowered.api.entity.living.monster.Vex; import org.spongepowered.api.entity.living.monster.boss.Boss; import org.spongepowered.api.entity.living.monster.boss.Wither; import org.spongepowered.api.entity.living.monster.boss.dragon.EnderDragon; import org.spongepowered.api.entity.living.monster.guardian.Guardian; import org.spongepowered.api.entity.living.monster.raider.Raider; import org.spongepowered.api.entity.living.monster.raider.Ravager; import org.spongepowered.api.entity.living.monster.raider.illager.Pillager; import org.spongepowered.api.entity.living.monster.raider.illager.Vindicator; import org.spongepowered.api.entity.living.monster.raider.illager.spellcaster.Evoker; import org.spongepowered.api.entity.living.monster.raider.illager.spellcaster.Spellcaster; import org.spongepowered.api.entity.living.monster.slime.Slime; import org.spongepowered.api.entity.living.monster.spider.Spider; import org.spongepowered.api.entity.living.monster.zombie.ZombieVillager; import org.spongepowered.api.entity.living.monster.zombie.ZombifiedPiglin; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.entity.living.player.chat.ChatVisibility; import org.spongepowered.api.entity.living.player.gamemode.GameMode; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.entity.living.trader.Trader; import org.spongepowered.api.entity.living.trader.Villager; import org.spongepowered.api.entity.projectile.DamagingProjectile; import org.spongepowered.api.entity.projectile.EyeOfEnder; import org.spongepowered.api.entity.projectile.FishingBobber; import org.spongepowered.api.entity.projectile.Potion; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.entity.projectile.ShulkerBullet; import org.spongepowered.api.entity.projectile.arrow.Arrow; import org.spongepowered.api.entity.projectile.arrow.ArrowEntity; import org.spongepowered.api.entity.projectile.explosive.FireworkRocket; import org.spongepowered.api.entity.projectile.explosive.WitherSkull; import org.spongepowered.api.entity.projectile.explosive.fireball.FireballEntity; import org.spongepowered.api.entity.vehicle.Boat; import org.spongepowered.api.entity.vehicle.minecart.BlockOccupiedMinecart; import org.spongepowered.api.entity.vehicle.minecart.CommandBlockMinecart; import org.spongepowered.api.entity.vehicle.minecart.FurnaceMinecart; import org.spongepowered.api.entity.vehicle.minecart.Minecart; import org.spongepowered.api.entity.vehicle.minecart.MinecartLike; import org.spongepowered.api.entity.weather.LightningBolt; import org.spongepowered.api.entity.weather.WeatherEffect; import org.spongepowered.api.event.cause.entity.damage.source.DamageSources; import org.spongepowered.api.fluid.FluidStackSnapshot; import org.spongepowered.api.item.FireworkEffect; import org.spongepowered.api.item.FireworkShape; import org.spongepowered.api.item.ItemRarity; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.enchantment.Enchantment; import org.spongepowered.api.item.enchantment.EnchantmentTypes; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.item.inventory.equipment.EquipmentType; import org.spongepowered.api.item.inventory.slot.EquipmentSlot; import org.spongepowered.api.item.inventory.type.GridInventory; import org.spongepowered.api.item.merchant.TradeOffer; import org.spongepowered.api.item.potion.PotionType; import org.spongepowered.api.map.MapCanvas; import org.spongepowered.api.map.MapInfo; import org.spongepowered.api.map.decoration.MapDecoration; import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.profile.property.ProfileProperty; import org.spongepowered.api.projectile.source.ProjectileSource; import org.spongepowered.api.raid.RaidWave; import org.spongepowered.api.statistic.Statistic; import org.spongepowered.api.util.Axis; import org.spongepowered.api.util.Color; import org.spongepowered.api.util.Direction; import org.spongepowered.api.util.RespawnLocation; import org.spongepowered.api.util.Ticks; import org.spongepowered.api.util.orientation.Orientation; import org.spongepowered.api.util.weighted.WeightedSerializableObject; import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.api.world.weather.WeatherType; import org.spongepowered.api.world.weather.WeatherTypes; import org.spongepowered.math.vector.Vector2i; import org.spongepowered.math.vector.Vector3d; import org.spongepowered.math.vector.Vector3i; import org.spongepowered.plugin.PluginContainer; import java.time.Instant; import java.util.List; import java.util.Locale; import java.util.UUID; /** * An enumeration of known {@link Key}s used throughout the API. */ @SuppressWarnings({"unused", "WeakerAccess"}) public final class Keys { // @formatter:off // SORTFIELDS:ON /** * The {@link PotionEffectTypes#ABSORPTION} amount of a {@link Living} entity. */ public static final Key<Value<Double>> ABSORPTION = Keys.key(ResourceKey.sponge("absorption"), Double.class); /** * The acceleration of a {@link DamagingProjectile}. */ public static final Key<Value<Vector3d>> ACCELERATION = Keys.key(ResourceKey.sponge("acceleration"), Vector3d.class); /** * The item a {@link Living} entity is currently using. * For example a player eating a food or blocking with a shield. * * <p>If there is no item, the snapshot will be empty. You can check this * with {@link ItemStackSnapshot#isEmpty()}.</p> */ public static final Key<Value<ItemStackSnapshot>> ACTIVE_ITEM = Keys.key(ResourceKey.sponge("active_item"), ItemStackSnapshot.class); /** * Whether a {@link Player}s affects spawning. * * <p>A {@link Player} who does not affect spawning will be treated as a * spectator in regards to spawning. A {@link MobSpawner} will not be * activated by his presence and mobs around him may naturally despawn * if there is no other Player around who affects spawning.</p> */ public static final Key<Value<Boolean>> AFFECTS_SPAWNING = Keys.key(ResourceKey.sponge("affects_spawning"), Boolean.class); /** * The age (in ticks) of an entity. * e.g. The age of an {@link AreaEffectCloud}. * <p>Note that in vanilla this value is not persisted for most entities.</p> */ public static final Key<Value<Integer>> AGE = Keys.key(ResourceKey.sponge("age"), Integer.class); /** * The modifier to {@link Keys#VELOCITY} of a {@link Minecart} while airborne. */ public static final Key<Value<Vector3d>> AIRBORNE_VELOCITY_MODIFIER = Keys.key(ResourceKey.sponge("airborne_velocity_modifier"), Vector3d.class); /** * The anger level of a {@link ZombifiedPiglin}. * * <p>Unlike {@link Keys#IS_ANGRY}, the aggressiveness represented by this key may * fade over time and the entity will become peaceful again once its anger * reaches its minimum.</p> */ public static final Key<Value<Integer>> ANGER_LEVEL = Keys.key(ResourceKey.sponge("anger_level"), Integer.class); /** * The set of {@link PotionEffect}s applied on use of an {@link ItemStack}. * Readonly */ public static final Key<WeightedCollectionValue<PotionEffect>> APPLICABLE_POTION_EFFECTS = Keys.weightedKey(ResourceKey.sponge("applicable_potion_effects"), PotionEffect.class); /** * The enchantments applied to an {@link ItemStack}. * * <p>This data is usually applicable to all types of armor, weapons and * tools. Enchantments that are only stored on an item stack in order to * be transferred to another item (like on * {@link ItemTypes#ENCHANTED_BOOK}s) use the {@link #STORED_ENCHANTMENTS} * key instead.)</p> */ public static final Key<ListValue<Enchantment>> APPLIED_ENCHANTMENTS = Keys.listKey(ResourceKey.sponge("applied_enchantments"), Enchantment.class); /** * The {@link ArmorMaterial} of an armor {@link ItemStack}. * Readonly */ public static final Key<Value<ArmorMaterial>> ARMOR_MATERIAL = Keys.key(ResourceKey.sponge("armor_material"), ArmorMaterial.class); /** * The type of {@link ArtType} shown by {@link Painting}s. */ public static final Key<Value<ArtType>> ART_TYPE = Keys.key(ResourceKey.sponge("art_type"), ArtType.class); /** * The attachment {@link AttachmentSurface} of a button or lever {@link BlockState} */ public static final Key<Value<AttachmentSurface>> ATTACHMENT_SURFACE = Keys.key(ResourceKey.sponge("attachment_surface"), AttachmentSurface.class); /** * The damage dealt by an {@link ArrowEntity} on impact. */ public static final Key<Value<Double>> ATTACK_DAMAGE = Keys.key(ResourceKey.sponge("attack_damage"), Double.class); /** * The time of a {@link Ravager} is considered attacking. */ public static final Key<Value<Ticks>> ATTACK_TIME = Keys.key(ResourceKey.sponge("attack_time"), Ticks.class); /** * Remaining ticks of the auto spin attack a {@link Living} is doing. * @see #IS_AUTO_SPIN_ATTACK */ public static final Key<Value<Ticks>> AUTO_SPIN_ATTACK_TICKS = Keys.key(ResourceKey.sponge("auto_spin_attack_ticks"), Ticks.class); /** * The author of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}. */ public static final Key<Value<Component>> AUTHOR = Keys.key(ResourceKey.sponge("author"), Component.class); /** * The {@link Axis} direction of a {@link BlockState}. */ public static final Key<Value<Axis>> AXIS = Keys.key(ResourceKey.sponge("axis"), Axis.class); /** * The ticks until a {@link Ageable} turns into an adult. */ public static final Key<Value<Ticks>> BABY_TICKS = Keys.key(ResourceKey.sponge("baby_ticks"), Ticks.class); /** * The {@link BannerPatternLayer}s of a {@link Banner}. */ public static final Key<ListValue<BannerPatternLayer>> BANNER_PATTERN_LAYERS = Keys.listKey(ResourceKey.sponge("banner_pattern_layers"), BannerPatternLayer.class); /** * The width of the physical form of an {@link Entity}. * * <p>Together with {@link #HEIGHT} and {@link #SCALE} this defines * the size of an {@link Entity}.</p> * Readonly */ public static final Key<Value<Double>> BASE_SIZE = Keys.key(ResourceKey.sponge("base_size"), Double.class); /** * The base vehicle a passenger is riding at the moment. * This may be different from {@link Keys#VEHICLE} as the * vehicle an {@link Entity} is riding may itself be the passenger of * another vehicle. * Readonly */ public static final Key<Value<Entity>> BASE_VEHICLE = Keys.key(ResourceKey.sponge("base_vehicle"), Entity.class); /** * The target entity of a {@link Guardian} beam. */ public static final Key<Value<Living>> BEAM_TARGET_ENTITY = Keys.key(ResourceKey.sponge("beam_target_entity"), Living.class); /** * The default temperature of a biome at a specific {@link ServerLocation}. * For the exact block temperature see {@link #BLOCK_TEMPERATURE}. * Readonly */ public static final Key<Value<Double>> BIOME_TEMPERATURE = Keys.key(ResourceKey.sponge("biome_temperature"), Double.class); /** * The blast resistance of a {@link BlockState}. * Readonly */ public static final Key<Value<Double>> BLAST_RESISTANCE = Keys.key(ResourceKey.sponge("blast_resistance"), Double.class); /** * The amount of light that is emitted by the surrounding blocks at a block {@link ServerLocation}. * The value scales normally from 0 to 1. * <p>In vanilla minecraft is this value in steps of 1/15 from 0 to 1.</p> * <p>For the skylight see {@link #SKY_LIGHT}.</p> * Readonly */ public static final Key<Value<Integer>> BLOCK_LIGHT = Keys.key(ResourceKey.sponge("block_light"), Integer.class); /** * The {@link BlockState} of a {@link BlockOccupiedMinecart} or {@link FallingBlock}. */ public static final Key<Value<BlockState>> BLOCK_STATE = Keys.key(ResourceKey.sponge("block_state"), BlockState.class); /** * The temperature at a specific {@link ServerLocation}. * For the default biome temperature see {@link #BIOME_TEMPERATURE}. * Readonly */ public static final Key<Value<Double>> BLOCK_TEMPERATURE = Keys.key(ResourceKey.sponge("block_temperature"), Double.class); /** * The type of the boat. */ public static final Key<Value<BoatType>> BOAT_TYPE = Keys.key(ResourceKey.sponge("boat_type"), BoatType.class); /** * The rotation of specific body parts of a {@link ArmorStand} or {@link Living}. * * <p>This value provides a mapping, effectively combining the data * referenced by {@link #HEAD_ROTATION}, {@link #CHEST_ROTATION}, * {@link #RIGHT_ARM_ROTATION}, {@link #LEFT_ARM_ROTATION}, * {@link #RIGHT_LEG_ROTATION}, and {@link #LEFT_LEG_ROTATION}.</p> */ public static final Key<MapValue<BodyPart, Vector3d>> BODY_ROTATIONS = Keys.mapKey(ResourceKey.sponge("body_rotations"), BodyPart.class, Vector3d.class); /** * The {@link BossBar} displayed to the client by a {@link Boss}. * TODO Readonly but mutable? */ public static final Key<Value<BossBar>> BOSS_BAR = Keys.key(ResourceKey.sponge("boss_bar"), BossBar.class); /** * The {@link BlockType}s able to be broken by an {@link ItemStack}. */ public static final Key<SetValue<BlockType>> BREAKABLE_BLOCK_TYPES = Keys.setKey(ResourceKey.sponge("breakable_block_types"), BlockType.class); /** * The current breeder of an {@link Animal}, usually a {@link Player}s UUID. */ public static final Key<Value<UUID>> BREEDER = Keys.key(ResourceKey.sponge("breeder"), UUID.class); /** * The ticks until an {@link Animal} can breed again. Also see {@link #CAN_BREED}. */ public static final Key<Value<Ticks>> BREEDING_COOLDOWN = Keys.key(ResourceKey.sponge("breeding_cooldown"), Ticks.class); /** * The burntime of an {@link ItemStack} fuel in a furnace. * See {@link #FUEL} for the time * Readonly */ public static final Key<Value<Integer>> BURN_TIME = Keys.key(ResourceKey.sponge("burn_time"), Integer.class); /** * Whether an {@link Animal} can breed. * In Vanilla, animals can breed if their {@link Keys#BREEDING_COOLDOWN} is equal to 0. */ public static final Key<Value<Boolean>> CAN_BREED = Keys.key(ResourceKey.sponge("can_breed"), Boolean.class); /** * Whether a {@link FallingBlock} can drop as an item. */ public static final Key<Value<Boolean>> CAN_DROP_AS_ITEM = Keys.key(ResourceKey.sponge("can_drop_as_item"), Boolean.class); /** * Whether a {@link Humanoid} can fly. * * <p>For a {@link Player} this means they are able to toggle flight mode * by double-tapping the jump button.</p> */ public static final Key<Value<Boolean>> CAN_FLY = Keys.key(ResourceKey.sponge("can_fly"), Boolean.class); /** * Whether a {@link Living} entity may change blocks. * This mostly applies to {@link Enderman} or * {@link Creeper}s, but also to some projectiles like {@link FireballEntity}s or {@link WitherSkull}. */ public static final Key<Value<Boolean>> CAN_GRIEF = Keys.key(ResourceKey.sponge("can_grief"), Boolean.class); /** * The set of harvestable {@link BlockType}s with an {@link ItemStack}. {@link #EFFICIENCY} * Readonly */ public static final Key<SetValue<BlockType>> CAN_HARVEST = Keys.setKey(ResourceKey.sponge("can_harvest"), BlockType.class); /** * Whether a {@link FallingBlock} will damage an {@link Entity} it lands on. */ public static final Key<Value<Boolean>> CAN_HURT_ENTITIES = Keys.key(ResourceKey.sponge("can_hurt_entities"), Boolean.class); /** * Whether a {@link Raider} can join a raid. */ public static final Key<Value<Boolean>> CAN_JOIN_RAID = Keys.key(ResourceKey.sponge("can_join_raid"), Boolean.class); /** * Whether a {@link Boat} can move on land. */ public static final Key<Value<Boolean>> CAN_MOVE_ON_LAND = Keys.key(ResourceKey.sponge("can_move_on_land"), Boolean.class); /** * Whether a {@link FallingBlock} will place itself upon landing. */ public static final Key<Value<Boolean>> CAN_PLACE_AS_BLOCK = Keys.key(ResourceKey.sponge("can_place_as_block"), Boolean.class); /** * The current casting time of a {@link Spellcaster}. */ public static final Key<Value<Integer>> CASTING_TIME = Keys.key(ResourceKey.sponge("casting_time"), Integer.class); /** * The type of a {@link Cat}. */ public static final Key<Value<CatType>> CAT_TYPE = Keys.key(ResourceKey.sponge("cat_type"), CatType.class); /** * Whether a {@link ServerPlayer} can will see colours sent in messages. */ public static final Key<Value<Boolean>> CHAT_COLORS_ENABLED = Keys.key(ResourceKey.sponge("chat_colors_enabled"), Boolean.class); /** * The types of chat a {@link ServerPlayer} can see. */ public static final Key<Value<ChatVisibility>> CHAT_VISIBILITY = Keys.key(ResourceKey.sponge("chat_visibility"), ChatVisibility.class); /** * The attachment of a {@link BlockTypes#CHEST} or {@link BlockTypes#TRAPPED_CHEST} {@link BlockState}. */ public static final Key<Value<ChestAttachmentType>> CHEST_ATTACHMENT_TYPE = Keys.key(ResourceKey.sponge("chest_attachment_type"), ChestAttachmentType.class); /** * The rotation of the {@link BodyParts#CHEST}. */ public static final Key<Value<Vector3d>> CHEST_ROTATION = Keys.key(ResourceKey.sponge("chest_rotation"), Vector3d.class); /** * The {@link Color} of an {@link ItemStack} * <p> * e.g. {@link ItemTypes#LEATHER_CHESTPLATE} or {@link ItemTypes#POTION} custom color * </p> * or an {@link AreaEffectCloud}. */ public static final Key<Value<Color>> COLOR = Keys.key(ResourceKey.sponge("color"), Color.class); /** * A command stored in a {@link CommandBlock} or {@link CommandBlockMinecart}. */ public static final Key<Value<String>> COMMAND = Keys.key(ResourceKey.sponge("command"), String.class); /** * The {@link ComparatorMode} of a {@link BlockTypes#COMPARATOR} {@link BlockState}. */ public static final Key<Value<ComparatorMode>> COMPARATOR_MODE = Keys.key(ResourceKey.sponge("comparator_mode"), ComparatorMode.class); /** * The connected directions of a {@link BlockState}. * <p> * e.g. {@link BlockTypes#GLASS_PANE}, {@link BlockTypes#IRON_BARS}, {@link BlockTypes#CHEST}, * </p> */ public static final Key<SetValue<Direction>> CONNECTED_DIRECTIONS = Keys.setKey(ResourceKey.sponge("connected_directions"), Direction.class); /** * The container {@link ItemType} of an {@link ItemStack}. * e.g. {@link ItemTypes#BUCKET} for a {@link ItemTypes#WATER_BUCKET} stack. * Readonly */ public static final Key<Value<ItemType>> CONTAINER_ITEM = Keys.key(ResourceKey.sponge("container_item"), ItemType.class); /** * The amount of ticks a {@link Hopper} has to wait before transferring the next item. (in Vanilla this is 8 ticks) * or * The amount of ticks a {@link EndGateway} has to wait for the next teleportation. */ public static final Key<Value<Ticks>> COOLDOWN = Keys.key(ResourceKey.sponge("cooldown"), Ticks.class); /** * The creator, usually of an {@link Entity}. It is up to the implementation to define. */ public static final Key<Value<UUID>> CREATOR = Keys.key(ResourceKey.sponge("creator"), UUID.class); /** * The current {@link SpellType} a {@link Spellcaster} is casting. */ public static final Key<Value<SpellType>> CURRENT_SPELL = Keys.key(ResourceKey.sponge("current_spell"), SpellType.class); /** * The damage dealt towards entities of a specific {@link EntityType} by a {@link ArrowEntity}. * * <p>Note that in events, the damage defined for the provided * {@link EntityType} will take priority over the "default" damage as * defined from {@link ArrowEntity#attackDamage()}.</p> * * <p>Types not present in this mapping will be * dealt damage to according to {@link #ATTACK_DAMAGE}.</p> */ public static final Key<MapValue<EntityType<?>, Double>> CUSTOM_ATTACK_DAMAGE = Keys.mapKey(ResourceKey.sponge("custom_attack_damage"), new TypeToken<EntityType<?>>() {}, TypeToken.get(Double.class)); /** * The resource pack model index of an {@link ItemStack}. * * <p>Resource packs can use the same index in their files to replace the * item model of an ItemStack.</p> */ public static final Key<Value<Integer>> CUSTOM_MODEL_DATA = Keys.key(ResourceKey.sponge("custom_model_data"), Integer.class); /** * The custom name of an {@link Entity}, {@link ItemStack} or {@link BlockEntity}. * <p>If no custom name is set the dataholder may still have a {@link Keys#DISPLAY_NAME}</p> */ public static final Key<Value<Component>> CUSTOM_NAME = Keys.key(ResourceKey.sponge("custom_name"), Component.class); /** * The damage absorbed by an armor {@link ItemStack}. * Readonly */ public static final Key<Value<Double>> DAMAGE_ABSORPTION = Keys.key(ResourceKey.sponge("damage_absorption"), Double.class); /** * How much damage a {@link FallingBlock} deals to {@link Living} entities * it hits per block fallen. * * <p>This damage is capped by {@link #MAX_FALL_DAMAGE}.</p> */ public static final Key<Value<Double>> DAMAGE_PER_BLOCK = Keys.key(ResourceKey.sponge("damage_per_block"), Double.class); /** * The distance at which a {@link BlockState} will decay. * This usually applies to leaves, for example {@link BlockTypes#OAK_LEAVES}. */ public static final Key<Value<Integer>> DECAY_DISTANCE = Keys.key(ResourceKey.sponge("decay_distance"), Integer.class); /** * The modifier to {@link Keys#VELOCITY} of a {@link Minecart} while derailed. */ public static final Key<Value<Vector3d>> DERAILED_VELOCITY_MODIFIER = Keys.key(ResourceKey.sponge("derailed_velocity_modifier"), Vector3d.class); /** * The despawn delay (in ticks) of a {@link Item}, {@link Endermite}, {@link WeatherType} {@link TraderLlama} or {@link EyeOfEnder}. */ public static final Key<Value<Ticks>> DESPAWN_DELAY = Keys.key(ResourceKey.sponge("despawn_delay"), Ticks.class); /** * The destroy speed of a {@link BlockState}s {@link BlockType}. * * <p>This value is read-only.</p> */ public static final Key<Value<Double>> DESTROY_SPEED = Keys.key(ResourceKey.sponge("destroy_speed"), Double.class); /** * The detonator of a {@link PrimedTNT}. */ public static final Key<Value<Living>> DETONATOR = Keys.key(ResourceKey.sponge("detonator"), Living.class); /** * The {@link Direction} a {@link BlockState}, {@link Hanging}, or {@link Shulker} is facing or the * heading of a {@link ShulkerBullet}. */ public static final Key<Value<Direction>> DIRECTION = Keys.key(ResourceKey.sponge("direction"), Direction.class); /** * The display name of an {@link Entity}, {@link ItemStack} or {@link BlockEntity}. * * <p>To change a display name set a {@link Keys#CUSTOM_NAME} instead.</p> * <p>On an {@link Entity}, this represents a combination of {@link Keys#CUSTOM_NAME} (if set), scoreboard info, and any click data.</p> * <p>On an {@link ItemStack}, this represents the {@link Keys#CUSTOM_NAME} or if not set the {@link ItemType}s translation. * <p>On a {@link BlockEntity}, this usually represents the name displayed in its {@link org.spongepowered.api.item.inventory.Container} */ public static final Key<Value<Component>> DISPLAY_NAME = Keys.key(ResourceKey.sponge("display_name"), Component.class); /** * The dominant {@link HandPreference} of an {@link Agent} entity. * * <p><em>NOTE:</em> For {@link Player}s is this key read-only, the * {@link HandPreference} of a player can not be changed server-side.</p> */ public static final Key<Value<HandPreference>> DOMINANT_HAND = Keys.key(ResourceKey.sponge("dominant_hand"), HandPreference.class); /** * The {@link DoorHinge} of a door {@link BlockState}. */ public static final Key<Value<DoorHinge>> DOOR_HINGE = Keys.key(ResourceKey.sponge("door_hinge"), DoorHinge.class); /** * Whether exact teleport location should be used with a {@link EndGateway}. */ public static final Key<Value<Boolean>> DO_EXACT_TELEPORT = Keys.key(ResourceKey.sponge("do_exact_teleport"), Boolean.class); /** * The remaining duration (in ticks) of an {@link AreaEffectCloud}. */ public static final Key<Value<Ticks>> DURATION = Keys.key(ResourceKey.sponge("duration"), Ticks.class); /** * The amount of ticks the duration of an {@link AreaEffectCloud} * is increased or reduced when it applies its effect. */ public static final Key<Value<Ticks>> DURATION_ON_USE = Keys.key(ResourceKey.sponge("duration_on_use"), Ticks.class); /** * The color of a dyeable {@link BlockState}, {@link ItemStack} or entity like {@link Cat}s. * or * The base {@link DyeColor} of a {@link Banner} or {@link TropicalFish}. */ public static final Key<Value<DyeColor>> DYE_COLOR = Keys.key(ResourceKey.sponge("dye_color"), DyeColor.class); /** * The time a {@link Panda} has been eating (in ticks) */ public static final Key<Value<Ticks>> EATING_TIME = Keys.key(ResourceKey.sponge("eating_time"), Ticks.class); /** * The efficiency of an {@link ItemStack} tool. Affects mining speed of supported materials. {@link #CAN_HARVEST} * Readonly */ public static final Key<Value<Double>> EFFICIENCY = Keys.key(ResourceKey.sponge("efficiency"), Double.class); /** * The time (in ticks) until a {@link Chicken} lays an {@link ItemTypes#EGG}. * * <p> * Vanilla will calculate the egg timer by taking a random value between * 0 (inclusive) and 6000 (exclusive) and then add that by another 6000. * This unit ends up being in ticks. Once the chicken lays the egg, this * calculation is ran again. * </p> */ public static final Key<Value<Ticks>> EGG_TIME = Keys.key(ResourceKey.sponge("egg_time"), Ticks.class); /** * The age (in ticks) of an {@link EndGateway} */ public static final Key<Value<Ticks>> END_GATEWAY_AGE = Keys.key(ResourceKey.sponge("end_gateway_age"), Ticks.class); /** * The {@link EntityType entity type} of a spawn egg, which may be one of * several based on {@link ItemTypes#ZOMBIE_SPAWN_EGG}, etc. It is not * guaranteed that the type of entity is the same as the one that will be * spawned when used. It is likely unable to change the type of entity on * an {@link ItemStack}, but it is possible to change the * {@link EntityArchetype archetype} by using {@link #ENTITY_TO_SPAWN}. * * @see #ENTITY_TO_SPAWN */ @SuppressWarnings("unchecked") public static final Key<Value<EntityType<?>>> ENTITY_TYPE = Keys.key(ResourceKey.sponge("entity_type"), (Class) EntityType.class); /** * The {@link EntityArchetype} to spawn from any spawn egg, such as a * {@link ItemTypes#ZOMBIE_SPAWN_EGG} or {@link ItemTypes#CREEPER_SPAWN_EGG}. * <p>The {@link #ENTITY_TYPE} is not guaranteed to be the same as the * {@link EntityArchetype#type()} returned, but the spawned entity will be * based on the {@link EntityArchetype} returned here. */ public static final Key<Value<EntityArchetype>> ENTITY_TO_SPAWN = Keys.key(ResourceKey.sponge("entity_to_spawn"), EntityArchetype.class); /** * The {@link EquipmentType} that the target inventory supports. This usually applies to {@link EquipmentSlot}s. * or * The {@link EquipmentType} of an {@link ItemStack} * Readonly */ public static final Key<Value<EquipmentType>> EQUIPMENT_TYPE = Keys.key(ResourceKey.sponge("equipment_type"), EquipmentType.class); public static final Key<Value<Double>> EXHAUSTION = Keys.key(ResourceKey.sponge("exhaustion"), Double.class); /** * The amount of experience a {@link Player} has or an {@link ExperienceOrb} contains. */ public static final Key<Value<Integer>> EXPERIENCE = Keys.key(ResourceKey.sponge("experience"), Integer.class); /** * The total experience a {@link Player} requires to advance from his current level to the next one. * Readonly */ public static final Key<Value<Integer>> EXPERIENCE_FROM_START_OF_LEVEL = Keys.key(ResourceKey.sponge("experience_from_start_of_level"), Integer.class); /** * The current level a {@link Player} has. */ public static final Key<Value<Integer>> EXPERIENCE_LEVEL = Keys.key(ResourceKey.sponge("experience_level"), Integer.class); /** * The amount of experience a {@link Player} has collected towards the next level. */ public static final Key<Value<Integer>> EXPERIENCE_SINCE_LEVEL = Keys.key(ResourceKey.sponge("experience_since_level"), Integer.class); public static final Key<Value<Integer>> EXPLOSION_RADIUS = Keys.key(ResourceKey.sponge("explosion_radius"), Integer.class); /** * The eye height of an {@link Entity}. * Readonly */ public static final Key<Value<Double>> EYE_HEIGHT = Keys.key(ResourceKey.sponge("eye_height"), Double.class); /** * The eye position of an {@link Entity}. * Readonly */ public static final Key<Value<Vector3d>> EYE_POSITION = Keys.key(ResourceKey.sponge("eye_position"), Vector3d.class); /** * The distance an {@link Entity} has fallen. */ public static final Key<Value<Double>> FALL_DISTANCE = Keys.key(ResourceKey.sponge("fall_distance"), Double.class); /** * The amount of ticks a {@link FallingBlock} has been falling for. */ public static final Key<Value<Ticks>> FALL_TIME = Keys.key(ResourceKey.sponge("fall_time"), Ticks.class); /** * The {@link FireworkEffect}s of a * {@link ItemTypes#FIREWORK_STAR}, {@link ItemTypes#FIREWORK_ROCKET} {@link ItemStack} or a * {@link FireworkRocket}. */ public static final Key<ListValue<FireworkEffect>> FIREWORK_EFFECTS = Keys.listKey(ResourceKey.sponge("firework_effects"), FireworkEffect.class); /** * The flight duration of a {@link FireworkRocket} * * <p>The duration is tiered and will stay partially random. A rocket will * fly for roughly {@code modifier * 10 + (random number from 0 to 13)} * ticks in Vanilla Minecraft.</p> */ public static final Key<Value<Ticks>> FIREWORK_FLIGHT_MODIFIER = Keys.key(ResourceKey.sponge("firework_flight_modifier"), Ticks.class); public static final Key<Value<FireworkShape>> FIREWORK_SHAPE = Keys.key(ResourceKey.sponge("firework_shape"), FireworkShape.class); /** * The delay in ticks until the {@link Entity} will be damaged by the fire. */ public static final Key<Value<Ticks>> FIRE_DAMAGE_DELAY = Keys.key(ResourceKey.sponge("fire_damage_delay"), Ticks.class); /** * The amount of ticks an {@link Entity} is still burning. */ public static final Key<Value<Ticks>> FIRE_TICKS = Keys.key(ResourceKey.sponge("fire_ticks"), Ticks.class); /** * The time a {@link User} first joined on the Server. */ public static final Key<Value<Instant>> FIRST_DATE_JOINED = Keys.key(ResourceKey.sponge("first_date_joined"), Instant.class); /** * A {@link Fox fox's} first trusted {@link UUID}, usually a {@link Player}. */ public static final Key<Value<UUID>> FIRST_TRUSTED = Keys.key(ResourceKey.sponge("first_trusted"), UUID.class); /** * The {@link FluidStackSnapshot} contained within an item container. * Item containers may include buckets and other mod added items. * See {@link #CONTAINER_ITEM} */ public static final Key<Value<FluidStackSnapshot>> FLUID_ITEM_STACK = Keys.key(ResourceKey.sponge("fluid_item_stack"), FluidStackSnapshot.class); /** * The fluid level of a liquid {@link BlockState}. */ public static final Key<Value<Integer>> FLUID_LEVEL = Keys.key(ResourceKey.sponge("fluid_level"), Integer.class); /** * The directional tank information. * TODO dataholder? cauldron blockstate? modded? */ public static final Key<MapValue<Direction, List<FluidStackSnapshot>>> FLUID_TANK_CONTENTS = Keys.mapKey(ResourceKey.sponge("fluid_tank_contents"), TypeToken.get(Direction.class), new TypeToken<List<FluidStackSnapshot>>() {}); /** * The speed at which an {@link Player} flies. */ public static final Key<Value<Double>> FLYING_SPEED = Keys.key(ResourceKey.sponge("flying_speed"), Double.class); /** * The food level of a {@link Humanoid}. * * <p>For a {@link Humanoid}, food level has health effects, depending on game difficulty and * hunger levels. If the food level is high enough, the humanoid may heal. If the food level is at 0, * the humanoid may starve.</p> */ public static final Key<Value<Integer>> FOOD_LEVEL = Keys.key(ResourceKey.sponge("food_level"), Integer.class); /** * The type of a {@link Fox}. */ public static final Key<Value<FoxType>> FOX_TYPE = Keys.key(ResourceKey.sponge("fox_type"), FoxType.class); /** * Represents the {@link Key} for the amount of fuel left in a {@link BrewingStand} or {@link FurnaceBlockEntity} or {@link FurnaceMinecart} * * <p>One {@link ItemTypes#BLAZE_POWDER} adds 20 fuel to the brewing stand.</p> * <p>The fuel value corresponds with the number of batches of potions that can be brewed.</p> * * <p>See {@link #BURN_TIME} for the burn time added by a fuel {@link ItemStack} to a furnace</p> */ public static final Key<Value<Integer>> FUEL = Keys.key(ResourceKey.sponge("fuel"), Integer.class); /** * The time (in ticks) a {@link FusedExplosive}'s fuse will burn before the explosion. */ public static final Key<Value<Ticks>> FUSE_DURATION = Keys.key(ResourceKey.sponge("fuse_duration"), Ticks.class); /** * The {@link GameMode} a {@link ServerPlayer} has. */ public static final Key<Value<GameMode>> GAME_MODE = Keys.key(ResourceKey.sponge("game_mode"), GameMode.class); /** * The player represented by a {@link BlockTypes#PLAYER_HEAD} (and {@link BlockTypes#PLAYER_WALL_HEAD}) * {@link BlockState} or a {@link ItemTypes#PLAYER_HEAD} {@link ItemStack}. * * <p>The offered game profile will be set exactly, unlike in vanilla where the game profile will * be resolved automatically for properties (including textures). You can obtain a game profile with * properties using {@link org.spongepowered.api.profile.GameProfileManager#profile}.</p> */ public static final Key<Value<GameProfile>> GAME_PROFILE = Keys.key(ResourceKey.sponge("game_profile"), GameProfile.class); /** * The generation of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}. * Depending on the book's generation it may be impossible to copy it. */ public static final Key<Value<Integer>> GENERATION = Keys.key(ResourceKey.sponge("generation"), Integer.class); /** * The "growth stage" state of a {@link BlockState}. * e.g. {@link BlockTypes#CACTUS} or {@link BlockTypes#WHEAT} etc. */ public static final Key<Value<Integer>> GROWTH_STAGE = Keys.key(ResourceKey.sponge("growth_stage"), Integer.class); /** * Whether an {@link ArmorStand}'s arms are visible. */ public static final Key<Value<Boolean>> HAS_ARMS = Keys.key(ResourceKey.sponge("has_arms"), Boolean.class); /** * Whether an {@link ArmorStand} has a visible base plate. */ public static final Key<Value<Boolean>> HAS_BASE_PLATE = Keys.key(ResourceKey.sponge("has_base_plate"), Boolean.class); /** * Whether a {@link PackHorse} has a chest. */ public static final Key<Value<Boolean>> HAS_CHEST = Keys.key(ResourceKey.sponge("has_chest"), Boolean.class); /** *Whether a {@link Turtle} currently has an egg. */ public static final Key<Value<Boolean>> HAS_EGG = Keys.key(ResourceKey.sponge("has_egg"), Boolean.class); /** * Whether a {@link Dolphin} has a fish. * <p> * Dolphins will navigate to a treasure (if a structure that provides one is nearby) * if they have been given a fish. * </p> */ public static final Key<Value<Boolean>> HAS_FISH = Keys.key(ResourceKey.sponge("has_fish"), Boolean.class); /** * Whether an {@link ArmorStand} is a "marker" stand. * * <p>If {@code true}, the armor stand's bounding box is near * impossible to see, and the armor stand can no longer be * interacted with.</p> */ public static final Key<Value<Boolean>> HAS_MARKER = Keys.key(ResourceKey.sponge("has_marker"), Boolean.class); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#DOWN} direction. See {@link #PORES}. */ public static final Key<Value<Boolean>> HAS_PORES_DOWN = Keys.key(ResourceKey.sponge("has_pores_down"), Boolean.class); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#EAST} direction. See {@link #PORES}. */ public static final Key<Value<Boolean>> HAS_PORES_EAST = Keys.key(ResourceKey.sponge("has_pores_east"), Boolean.class); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#NORTH} direction. See {@link #PORES}. */ public static final Key<Value<Boolean>> HAS_PORES_NORTH = Keys.key(ResourceKey.sponge("has_pores_north"), Boolean.class); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#SOUTH} direction. See {@link #PORES}. */ public static final Key<Value<Boolean>> HAS_PORES_SOUTH = Keys.key(ResourceKey.sponge("has_pores_south"), Boolean.class); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#UP} direction. See {@link #PORES}. */ public static final Key<Value<Boolean>> HAS_PORES_UP = Keys.key(ResourceKey.sponge("has_pores_up"), Boolean.class); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#WEST} direction. See {@link #PORES}. */ public static final Key<Value<Boolean>> HAS_PORES_WEST = Keys.key(ResourceKey.sponge("has_pores_west"), Boolean.class); /** * Whether a server player has viewed the credits. * * <p>The credits are displayed the first time a player returns to the overworld safely using an end portal.</p> */ public static final Key<Value<Boolean>> HAS_VIEWED_CREDITS = Keys.key(ResourceKey.sponge("has_viewed_credits"), Boolean.class); /** * The rotation of a {@link Living}'s or {@link ArmorStand}'s head. * * <p>The format of the rotation is represented by:</p> * * <ul> * <li>{@code x -> pitch}</li> * <li> {@code y -> yaw}</li> * <li>{@code z -> roll}</li> * </ul> * * <p>Note that the pitch will be the same x value returned by * {@link Entity#rotation()} and Minecraft does not currently support * head roll so the z value will always be zero.</p> */ public static final Key<Value<Vector3d>> HEAD_ROTATION = Keys.key(ResourceKey.sponge("head_rotation"), Vector3d.class); /** * The {@link EndCrystal} currently healing an {@link EnderDragon}. */ public static final Key<Value<EndCrystal>> HEALING_CRYSTAL = Keys.key(ResourceKey.sponge("healing_crystal"), EndCrystal.class); /** * A {@link Living}'s or {@link EndCrystal}'s current health. * * <p>The range of the health depends on the object on which this * method is defined. For {@link Player Players} in Minecraft, the nominal range is * between 0 and 20, inclusive, but the range can be adjusted.</p> * * <p>Convention dictates that health does not fall below 0 but this * convention may be broken.</p> */ public static final Key<Value<Double>> HEALTH = Keys.key(ResourceKey.sponge("health"), Double.class); /** * The value a {@link ServerPlayer}s max-health (excluding absorption) in the GUI will scale to. * <p>Two health is equal to one heart displayed.</p> * <p>With scaling is disabled health automatically scales to {@link #MAX_HEALTH}</p> */ public static final Key<Value<Double>> HEALTH_SCALE = Keys.key(ResourceKey.sponge("health_scale"), Double.class); /** * The height of the physical form of an {@link Entity}. * * <p>Together with {@link #BASE_SIZE} and {@link #SCALE} this defines the size of an * {@link Entity}.</p> * Readonly */ public static final Key<Value<Double>> HEIGHT = Keys.key(ResourceKey.sponge("height"), Double.class); /** * The {@link ItemType} a {@link BlockState} represents. * Readonly */ public static final Key<Value<ItemType>> HELD_ITEM = Keys.key(ResourceKey.sponge("held_item"), ItemType.class); /** * The hidden {@link PandaGene gene} of a {@link Panda}. */ public static final Key<Value<PandaGene>> HIDDEN_GENE = Keys.key(ResourceKey.sponge("hidden_gene"), PandaGene.class); /** * Whether the attributes of an {@link ItemStack} are hidden. */ public static final Key<Value<Boolean>> HIDE_ATTRIBUTES = Keys.key(ResourceKey.sponge("hide_attributes"), Boolean.class); /** * Whether the {@link #BREAKABLE_BLOCK_TYPES} of an {@link ItemStack} are hidden. */ public static final Key<Value<Boolean>> HIDE_CAN_DESTROY = Keys.key(ResourceKey.sponge("hide_can_destroy"), Boolean.class); /** * Whether the {@link #PLACEABLE_BLOCK_TYPES} of an {@link ItemStack} are hidden. */ public static final Key<Value<Boolean>> HIDE_CAN_PLACE = Keys.key(ResourceKey.sponge("hide_can_place"), Boolean.class); /** * Whether the {@link #APPLIED_ENCHANTMENTS} of an {@link ItemStack} are hidden. */ public static final Key<Value<Boolean>> HIDE_ENCHANTMENTS = Keys.key(ResourceKey.sponge("hide_enchantments"), Boolean.class); /** * Whether miscellaneous values of an {@link ItemStack} are hidden. * e.g. potion effects or shield pattern info */ public static final Key<Value<Boolean>> HIDE_MISCELLANEOUS = Keys.key(ResourceKey.sponge("hide_miscellaneous"), Boolean.class); /** * Whether {@link #IS_UNBREAKABLE} state of an {@link ItemStack} is hidden. */ public static final Key<Value<Boolean>> HIDE_UNBREAKABLE = Keys.key(ResourceKey.sponge("hide_unbreakable"), Boolean.class); /** * The {@link Vector3i position} where a {@link Turtle} lays {@link BlockTypes#TURTLE_EGG eggs}. */ public static final Key<Value<Vector3i>> HOME_POSITION = Keys.key(ResourceKey.sponge("home_position"), Vector3i.class); /** * The {@link HorseColor} of a {@link Horse}. */ public static final Key<Value<HorseColor>> HORSE_COLOR = Keys.key(ResourceKey.sponge("horse_color"), HorseColor.class); /** * The {@link HorseStyle} of a {@link Horse}. */ public static final Key<Value<HorseStyle>> HORSE_STYLE = Keys.key(ResourceKey.sponge("horse_style"), HorseStyle.class); /** * The inaccuracy of an {@link ItemStack} that launches {@link Projectile}s. * * <p>An inaccuracy of 0 means perfect accuracy. Inaccuracy of 1 is the default for most vanilla items.</p> */ public static final Key<Value<Double>> INACCURACY = Keys.key(ResourceKey.sponge("inaccuracy"), Double.class); /** * Whether an {@link Item} will not despawn for an infinite time. */ public static final Key<Value<Boolean>> INFINITE_DESPAWN_DELAY = Keys.key(ResourceKey.sponge("infinite_despawn_delay"), Boolean.class); /** * Whether an {@link Item} has an infinite pickup delay. */ public static final Key<Value<Boolean>> INFINITE_PICKUP_DELAY = Keys.key(ResourceKey.sponge("infinite_pickup_delay"), Boolean.class); /** * The {@link InstrumentType} of a {@link BlockTypes#NOTE_BLOCK} {@link BlockState}. */ public static final Key<Value<InstrumentType>> INSTRUMENT_TYPE = Keys.key(ResourceKey.sponge("instrument_type"), InstrumentType.class); /** * Whether a {@link BlockTypes#DAYLIGHT_DETECTOR} {@link BlockState} is inverted. */ public static final Key<Value<Boolean>> INVERTED = Keys.key(ResourceKey.sponge("inverted"), Boolean.class); /** * The amount of ticks an {@link Entity} will remain invulnerable for. */ public static final Key<Value<Ticks>> INVULNERABILITY_TICKS = Keys.key(ResourceKey.sponge("invulnerability_ticks"), Ticks.class); /** * Whether an {@link Entity} is invulnerable. * * <p>This does not protect from the void, players in creative mode, * and manual killing like the /kill command.</p> */ public static final Key<Value<Boolean>> INVULNERABLE = Keys.key(ResourceKey.sponge("invulnerable"), Boolean.class); /** * Whether a fence gate {@link BlockState} is in a wall. */ public static final Key<Value<Boolean>> IN_WALL = Keys.key(ResourceKey.sponge("in_wall"), Boolean.class); /** * Whether an {@link Ageable} is considered an adult. */ public static final Key<Value<Boolean>> IS_ADULT = Keys.key(ResourceKey.sponge("is_adult"), Boolean.class); /** * Whether a {@link Blaze} is currently burning. * * <p>Unlike {@link Keys#FIRE_TICKS}, the burning effect will not damage * the burning entity.</p> */ public static final Key<Value<Boolean>> IS_AFLAME = Keys.key(ResourceKey.sponge("is_aflame"), Boolean.class); /** * Whether an {@link Agent}s AI is enabled. */ public static final Key<Value<Boolean>> IS_AI_ENABLED = Keys.key(ResourceKey.sponge("is_ai_enabled"), Boolean.class); /** * Whether an entity is currently aggressive. * e.g. {@link Wolf wolves} or {@link ZombifiedPiglin} */ public static final Key<Value<Boolean>> IS_ANGRY = Keys.key(ResourceKey.sponge("is_angry"), Boolean.class); /** * Whether a {@link BlockState} is "attached" to another block. */ public static final Key<Value<Boolean>> IS_ATTACHED = Keys.key(ResourceKey.sponge("is_attached"), Boolean.class); /** * Whether a {@link Living} is doing an auto spin attack (doable with the {@link EnchantmentTypes#RIPTIDE} enchantment.) * @see #AUTO_SPIN_ATTACK_TICKS */ public static final Key<Value<Boolean>> IS_AUTO_SPIN_ATTACK = Keys.key(ResourceKey.sponge("is_auto_spin_attack"), Boolean.class); /** * Whether an entity is begging for food. * e.g. {@link Cat cats} or tamed {@link Wolf wolves} */ public static final Key<Value<Boolean>> IS_BEGGING_FOR_FOOD = Keys.key(ResourceKey.sponge("is_begging_for_food"), Boolean.class); /** * Whether {@link Raider}s are currently celebrating. */ public static final Key<Value<Boolean>> IS_CELEBRATING = Keys.key(ResourceKey.sponge("is_celebrating"), Boolean.class); /** * Whether a {@link Creeper} is charged. */ public static final Key<Value<Boolean>> IS_CHARGED = Keys.key(ResourceKey.sponge("is_charged"), Boolean.class); /** * Whether a {@link Pillager} is charging it's crossbow. */ public static final Key<Value<Boolean>> IS_CHARGING_CROSSBOW = Keys.key(ResourceKey.sponge("is_charging_crossbow"), Boolean.class); /** * Whether a {@link Spider} is currently climbing. */ public static final Key<Value<Boolean>> IS_CLIMBING = Keys.key(ResourceKey.sponge("is_climbing"), Boolean.class); /** * Whether a {@link BlockState} is connected to the {@link Direction#EAST}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Key<Value<Boolean>> IS_CONNECTED_EAST = Keys.key(ResourceKey.sponge("is_connected_east"), Boolean.class); /** * Whether a {@link BlockState} is connected to the {@link Direction#NORTH}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Key<Value<Boolean>> IS_CONNECTED_NORTH = Keys.key(ResourceKey.sponge("is_connected_north"), Boolean.class); /** * Whether a {@link BlockState} is connected to the {@link Direction#SOUTH}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Key<Value<Boolean>> IS_CONNECTED_SOUTH = Keys.key(ResourceKey.sponge("is_connected_south"), Boolean.class); /** * Whether a {@link BlockState} is connected to the {@link Direction#UP}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Key<Value<Boolean>> IS_CONNECTED_UP = Keys.key(ResourceKey.sponge("is_connected_up"), Boolean.class); /** * Whether a {@link BlockState} is connected to the {@link Direction#WEST}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Key<Value<Boolean>> IS_CONNECTED_WEST = Keys.key(ResourceKey.sponge("is_connected_west"), Boolean.class); /** * Whether an {@link Arrow} will cause a critical hit. */ public static final Key<Value<Boolean>> IS_CRITICAL_HIT = Keys.key(ResourceKey.sponge("is_critical_hit"), Boolean.class); /** * Whether a {@link Fox} is currently crouching. */ public static final Key<Value<Boolean>> IS_CROUCHING = Keys.key(ResourceKey.sponge("is_crouching"), Boolean.class); /** * Whether a custom name is visible on an {@link Entity}. */ public static final Key<Value<Boolean>> IS_CUSTOM_NAME_VISIBLE = Keys.key(ResourceKey.sponge("is_custom_name_visible"), Boolean.class); /** * Whether a {@link Fox} is currently defending. */ public static final Key<Value<Boolean>> IS_DEFENDING = Keys.key(ResourceKey.sponge("is_defending"), Boolean.class); /** * Whether a {@link BlockState} is disarmed. * e.g. {@link BlockTypes#TRIPWIRE}s and {@link BlockTypes#TRIPWIRE_HOOK}s. */ public static final Key<Value<Boolean>> IS_DISARMED = Keys.key(ResourceKey.sponge("is_disarmed"), Boolean.class); /** * Whether an entity is eating. * e.g. {@link Panda} */ public static final Key<Value<Boolean>> IS_EATING = Keys.key(ResourceKey.sponge("is_eating"), Boolean.class); /** * Whether a {@link WeatherEffect} like {@link LightningBolt} is harmful to other {@link Entity entities}. * Readonly */ public static final Key<Value<Boolean>> IS_EFFECT_ONLY = Keys.key(ResourceKey.sponge("is_effect_only"), Boolean.class); /** * Whether a {@link Player} is flying with an {@link ItemTypes#ELYTRA}. */ public static final Key<Value<Boolean>> IS_ELYTRA_FLYING = Keys.key(ResourceKey.sponge("is_elytra_flying"), Boolean.class); /** * Whether a piston {@link BlockState} is currently extended. * TODO {@link Piston}? */ public static final Key<Value<Boolean>> IS_EXTENDED = Keys.key(ResourceKey.sponge("is_extended"), Boolean.class); /** * Whether a {@link Fox} is currently faceplanted. */ public static final Key<Value<Boolean>> IS_FACEPLANTED = Keys.key(ResourceKey.sponge("is_faceplanted"), Boolean.class); /** * Whether a {@link BlockState} is filled. * <p>e.g. {@link BlockTypes#END_PORTAL_FRAME}s.</p> */ public static final Key<Value<Boolean>> IS_FILLED = Keys.key(ResourceKey.sponge("is_filled"), Boolean.class); /** * Whether a {@link BlockState} is flammable. * Readonly */ public static final Key<Value<Boolean>> IS_FLAMMABLE = Keys.key(ResourceKey.sponge("is_flammable"), Boolean.class); /** * Whether an {@link Entity} is flying. TODO only player? * * <p>This key only tells whether an entity is flying at the moment. On a * {@link Player} it does not necessarily mean that the player may toggle * freely between flying and walking. To check whether a player may switch * his flying state, check {@link #CAN_FLY}.</p> */ public static final Key<Value<Boolean>> IS_FLYING = Keys.key(ResourceKey.sponge("is_flying"), Boolean.class); /** * Whether an entity is frightened. * * <p>In vanilla, {@link Panda}s that have a {@link Panda#knownGene()} * of {@link PandaGenes#WORRIED} and are in a {@link ServerWorld world} whose {@link WeatherType} is currently a * {@link WeatherTypes#THUNDER} are considered "frightened".</p> */ public static final Key<Value<Boolean>> IS_FRIGHTENED = Keys.key(ResourceKey.sponge("is_frightened"), Boolean.class); /** * Whether the block at the {@link ServerLocation} is a full block. */ public static final Key<Value<Boolean>> IS_FULL_BLOCK = Keys.key(ResourceKey.sponge("is_full_block"), Boolean.class); /** * Whether an {@link Entity} has a glowing outline. */ public static final Key<Value<Boolean>> IS_GLOWING = Keys.key(ResourceKey.sponge("is_glowing"), Boolean.class); /** * Whether {@link Turtle} is proceeding to it's {@link Vector3i home position}. */ public static final Key<Value<Boolean>> IS_GOING_HOME = Keys.key(ResourceKey.sponge("is_going_home"), Boolean.class); /** * Whether something is affected by gravity. * e.g. {@link Entity}s and {@link BlockState}s * Readonly(BlockState.class) */ public static final Key<Value<Boolean>> IS_GRAVITY_AFFECTED = Keys.key(ResourceKey.sponge("is_gravity_affected"), Boolean.class); /** * Whether a lantern block is hanging. */ public static final Key<Value<Boolean>> IS_HANGING = Keys.key(ResourceKey.sponge("is_hanging"), Boolean.class); /** * Whether a {@link Cat} is hissing. */ public static final Key<Value<Boolean>> IS_HISSING = Keys.key(ResourceKey.sponge("is_hissing"), Boolean.class); /** * Whether a {@link Ravager} is immobilized. * Readonly */ public static final Key<Value<Boolean>> IS_IMMOBILIZED = Keys.key(ResourceKey.sponge("is_immobilized"), Boolean.class); /** * Whether a {@link ServerLocation} is indirectly powered. * Readonly */ public static final Key<Value<Boolean>> IS_INDIRECTLY_POWERED = Keys.key(ResourceKey.sponge("is_indirectly_powered"), Boolean.class); /** * Whether a {@link Fox} is currently interested in something. */ public static final Key<Value<Boolean>> IS_INTERESTED = Keys.key(ResourceKey.sponge("is_interested"), Boolean.class); /** * Whether an {@link Entity} is currently invisible. * This will only simply render the entity as vanished, * but not prevent any entity updates being sent to clients. * To fully "vanish" an {@link Entity}, use {@link #VANISH_STATE}. */ public static final Key<Value<Boolean>> IS_INVISIBLE = Keys.key(ResourceKey.sponge("is_invisible"), Boolean.class); /** * Whether a {@link Boat} is currently in {@link BlockTypes#WATER}. * Readonly */ public static final Key<Value<Boolean>> IS_IN_WATER = Keys.key(ResourceKey.sponge("is_in_water"), Boolean.class); public static final Key<Value<Boolean>> IS_JOHNNY = Keys.key(ResourceKey.sponge("is_johnny"), Boolean.class); /** * Whether a {@link Turtle} is currently digging to lay an egg. */ public static final Key<Value<Boolean>> IS_LAYING_EGG = Keys.key(ResourceKey.sponge("is_laying_egg"), Boolean.class); /** * Whether a {@link Patroller} is the leader. */ public static final Key<Value<Boolean>> IS_LEADER = Keys.key(ResourceKey.sponge("is_leader"), Boolean.class); /** * Whether a {@link BlockState} is lit. * e.g. {@link BlockTypes#FURNACE}, {@link BlockTypes#CAMPFIRE} * or {@link BlockTypes#REDSTONE_TORCH}. */ public static final Key<Value<Boolean>> IS_LIT = Keys.key(ResourceKey.sponge("is_lit"), Boolean.class); /** * Whether a {@link Cat} is lying down. * * <p>In vanilla, a cat lies down near its owner when the owner goes to * sleep.</p> */ public static final Key<Value<Boolean>> IS_LYING_DOWN = Keys.key(ResourceKey.sponge("is_lying_down"), Boolean.class); /** * Whether a {@link Panda} is lying on it's back. */ public static final Key<Value<Boolean>> IS_LYING_ON_BACK = Keys.key(ResourceKey.sponge("is_lying_on_back"), Boolean.class); /** * Whether a bed {@link BlockState} is occupied. * e.g. {@link BlockTypes#WHITE_BED}. */ public static final Key<Value<Boolean>> IS_OCCUPIED = Keys.key(ResourceKey.sponge("is_occupied"), Boolean.class); /** * Whether a {@link Minecart} is on it's rail * Readonly */ public static final Key<Value<Boolean>> IS_ON_RAIL = Keys.key(ResourceKey.sponge("is_on_rail"), Boolean.class); /** * Whether a door/fencegate/trapdoor {@link BlockState} is open. */ public static final Key<Value<Boolean>> IS_OPEN = Keys.key(ResourceKey.sponge("is_open"), Boolean.class); /** * Whether a {@link BlockState} is passable (can be walked through). * Readonly */ public static final Key<Value<Boolean>> IS_PASSABLE = Keys.key(ResourceKey.sponge("is_passable"), Boolean.class); /** * Whether a {@link Patroller} is currently patrolling. */ public static final Key<Value<Boolean>> IS_PATROLLING = Keys.key(ResourceKey.sponge("is_patrolling"), Boolean.class); /** * Whether an {@link Entity} or leaves {@link BlockState} will * be prevented from despawning/decaying. * * <p>In Vanilla, entities may despawn if the player moves too far from * them. A persisting entity will not be removed due to no players being * near it.</p> */ public static final Key<Value<Boolean>> IS_PERSISTENT = Keys.key(ResourceKey.sponge("is_persistent"), Boolean.class); /** * Whether players are prevented from placing * items from an equipment slot on an {@link ArmorStand} */ public static final Key<MapValue<EquipmentType, Boolean>> IS_PLACING_DISABLED = Keys.mapKey(ResourceKey.sponge("is_placing_disabled"), EquipmentType.class, Boolean.class); public static final Key<Value<Boolean>> IS_PLAYER_CREATED = Keys.key(ResourceKey.sponge("is_player_created"), Boolean.class); /** * Whether a {@link Fox} is currently pouncing. */ public static final Key<Value<Boolean>> IS_POUNCING = Keys.key(ResourceKey.sponge("is_pouncing"), Boolean.class); /** * Whether a {@link BlockState} is powered. * * <p>Applies to blocks that may be powered in order to emit a * Redstone signal of consistently maximum strength, such as * {@link BlockTypes#LEVER}, {@link BlockTypes#OAK_BUTTON}, * {@link BlockTypes#OAK_PRESSURE_PLATE}, and their stone * counterparts.</p> */ public static final Key<Value<Boolean>> IS_POWERED = Keys.key(ResourceKey.sponge("is_powered"), Boolean.class); /** * Whether a {@link FusedExplosive} is currently primed. * Readonly */ public static final Key<Value<Boolean>> IS_PRIMED = Keys.key(ResourceKey.sponge("is_primed"), Boolean.class); /** * Whether a {@link Cat} is purring. */ public static final Key<Value<Boolean>> IS_PURRING = Keys.key(ResourceKey.sponge("is_purring"), Boolean.class); /** * Whether a {@link Cat} is relaxed. * * <p>In vanilla, a cat relaxes before lying down.</p> */ public static final Key<Value<Boolean>> IS_RELAXED = Keys.key(ResourceKey.sponge("is_relaxed"), Boolean.class); /** * Whether a {@link BlockState} can be replaced by a player without breaking it first. * e.g. {@link BlockTypes#WATER} * Readonly */ public static final Key<Value<Boolean>> IS_REPLACEABLE = Keys.key(ResourceKey.sponge("is_replaceable"), Boolean.class); /** * Whether a {@link Ravager} is roaring. * Readonly */ public static final Key<Value<Boolean>> IS_ROARING = Keys.key(ResourceKey.sponge("is_roaring"), Boolean.class); /** * Whether a {@link Panda} is rolling around. */ public static final Key<Value<Boolean>> IS_ROLLING_AROUND = Keys.key(ResourceKey.sponge("is_rolling_around"), Boolean.class); /** * Whether an entity is saddled. * e.g. {@link Horse}s and {@link Pig}s */ public static final Key<Value<Boolean>> IS_SADDLED = Keys.key(ResourceKey.sponge("is_saddled"), Boolean.class); /** * Whether an {@link Enderman} is screaming. */ public static final Key<Value<Boolean>> IS_SCREAMING = Keys.key(ResourceKey.sponge("is_screaming"), Boolean.class); /** * Whether a {@link Sheep} is sheared. */ public static final Key<Value<Boolean>> IS_SHEARED = Keys.key(ResourceKey.sponge("is_sheared"), Boolean.class); /** * Whether an {@link Entity} is silent. * * <p>A silent entity will not emit sounds or make noises.</p> */ public static final Key<Value<Boolean>> IS_SILENT = Keys.key(ResourceKey.sponge("is_silent"), Boolean.class); /** * Whether a {@link Wolf}, {@link Cat}, {@link Panda}, or {@link Fox} is sitting. */ public static final Key<Value<Boolean>> IS_SITTING = Keys.key(ResourceKey.sponge("is_sitting"), Boolean.class); /** * Whether a {@link Bat}, {@link Fox} or {@link Player} is sleeping. * * <p>If a player is considered sleeping as per this data value, the player does * not need to be in bed in order for the other players to be able to * advance through the night by going to bed.</p> * Readonly(Player.class) */ public static final Key<Value<Boolean>> IS_SLEEPING = Keys.key(ResourceKey.sponge("is_sleeping"), Boolean.class); /** * Whether a {@link Player Player's} sleeping status is ignored when checking whether to * skip the night due to players sleeping. The time in a world will be * advanced to day if all players in it either are sleeping or are set to ignore. */ public static final Key<Value<Boolean>> IS_SLEEPING_IGNORED = Keys.key(ResourceKey.sponge("is_sleeping_ignored"), Boolean.class); /** * Whether an {@link ArmorStand} is small. */ public static final Key<Value<Boolean>> IS_SMALL = Keys.key(ResourceKey.sponge("is_small"), Boolean.class); /** * Whether an {@link Entity} is sneaking. * * <p>Sneaking entities generally move slower and do not make walking * sounds.</p> */ public static final Key<Value<Boolean>> IS_SNEAKING = Keys.key(ResourceKey.sponge("is_sneaking"), Boolean.class); /** * Whether a {@link Panda} is sneezing. */ public static final Key<Value<Boolean>> IS_SNEEZING = Keys.key(ResourceKey.sponge("is_sneezing"), Boolean.class); /** * Whether a {@link BlockTypes#DIRT} {@link BlockState} is snowy. */ public static final Key<Value<Boolean>> IS_SNOWY = Keys.key(ResourceKey.sponge("is_snowy"), Boolean.class); /** * Whether a {@link BlockState} is solid. * Readonly */ public static final Key<Value<Boolean>> IS_SOLID = Keys.key(ResourceKey.sponge("is_solid"), Boolean.class); /** * Whether an {@link Entity} is sprinting. */ public static final Key<Value<Boolean>> IS_SPRINTING = Keys.key(ResourceKey.sponge("is_sprinting"), Boolean.class); /** * Whether a {@link PolarBear} is currently standing. */ public static final Key<Value<Boolean>> IS_STANDING = Keys.key(ResourceKey.sponge("is_standing"), Boolean.class); /** * Whether a {@link Ravager} is stunned. * Readonly */ public static final Key<Value<Boolean>> IS_STUNNED = Keys.key(ResourceKey.sponge("is_stunned"), Boolean.class); /** * Whether a {@link BlockState} is a surrogate block for a block that was provided in an environment * (almost always modded), that the block type provider no longer exists. * If true this may indicate that the surrogate block functions differently than the original block. * Readonly */ public static final Key<Value<Boolean>> IS_SURROGATE_BLOCK = Keys.key(ResourceKey.sponge("is_surrogate_block"), Boolean.class); /** * Whether players are prevented from taking * items from an equipment slot on an {@link ArmorStand} */ public static final Key<MapValue<EquipmentType, Boolean>> IS_TAKING_DISABLED = Keys.mapKey(ResourceKey.sponge("is_taking_disabled"), EquipmentType.class, Boolean.class); /** * Whether a {@link TameableAnimal} is currently tamed */ public static final Key<Value<Boolean>> IS_TAMED = Keys.key(ResourceKey.sponge("is_tamed"), Boolean.class); /** * Whether a {@link Trader} is currently trading with a {@link Player}. * Readonly */ public static final Key<Value<Boolean>> IS_TRADING = Keys.key(ResourceKey.sponge("is_trading"), Boolean.class); /** * Whether a {@link Turtle} is currently traveling. */ public static final Key<Value<Boolean>> IS_TRAVELING = Keys.key(ResourceKey.sponge("is_traveling"), Boolean.class); /** * Whether an {@link Ocelot} is currently trusting of {@link Player}s. */ public static final Key<Value<Boolean>> IS_TRUSTING = Keys.key(ResourceKey.sponge("is_trusting"), Boolean.class); /** * Whether an {@link ItemStack} or {@link BlockState} is unbreakable. * * <p>Setting this to {@code true} will prevent the item stack's * {@link #ITEM_DURABILITY} from changing.</p> * Readonly(BlockState.class) */ public static final Key<Value<Boolean>> IS_UNBREAKABLE = Keys.key(ResourceKey.sponge("is_unbreakable"), Boolean.class); /** * Whether a {@link Panda} is unhappy. */ public static final Key<Value<Boolean>> IS_UNHAPPY = Keys.key(ResourceKey.sponge("is_unhappy"), Boolean.class); /** * Whehter a {@link BlockState} is waterlogged. */ public static final Key<Value<Boolean>> IS_WATERLOGGED = Keys.key(ResourceKey.sponge("is_waterlogged"), Boolean.class); /** * Whether an {@link Entity} like {@link Wolf} is wet. * Readonly(Entity.class) except Wolf */ public static final Key<Value<Boolean>> IS_WET = Keys.key(ResourceKey.sponge("is_wet"), Boolean.class); /** * The durability of an {@link ItemStack}. {@link #MAX_DURABILITY} */ public static final Key<Value<Integer>> ITEM_DURABILITY = Keys.key(ResourceKey.sponge("item_durability"), Integer.class); /** * The rarity of an item. */ public static final Key<Value<ItemRarity>> ITEM_RARITY = Keys.key(ResourceKey.sponge("item_rarity"), ItemRarity.class); /** * The {@link ItemStackSnapshot item} in an * {@link Item}, {@link ItemFrame}, {@link Jukebox}, {@link Lectern} or * {@link Potion}. */ public static final Key<Value<ItemStackSnapshot>> ITEM_STACK_SNAPSHOT = Keys.key(ResourceKey.sponge("item_stack_snapshot"), ItemStackSnapshot.class); /** * The knockback strength applied by an {@link ArrowEntity}. * * <p>For the knockback provided by hits with a weapon according to the * enchantment of the same name, see {@link #APPLIED_ENCHANTMENTS}.</p> */ public static final Key<Value<Double>> KNOCKBACK_STRENGTH = Keys.key(ResourceKey.sponge("knockback_strength"), Double.class); /** * The known {@link PandaGene gene} of a {@link Panda}. */ public static final Key<Value<PandaGene>> KNOWN_GENE = Keys.key(ResourceKey.sponge("known_gene"), PandaGene.class); /** * The last attacking {@link Entity} of a {@link Living}. */ public static final Key<Value<Entity>> LAST_ATTACKER = Keys.key(ResourceKey.sponge("last_attacker"), Entity.class); /** * The output yielded by the last command of a {@link CommandBlock} or {@link CommandBlockMinecart}. */ public static final Key<Value<Component>> LAST_COMMAND_OUTPUT = Keys.key(ResourceKey.sponge("last_command_output"), Component.class); /** * The last damage a {@link Living} received. */ public static final Key<Value<Double>> LAST_DAMAGE_RECEIVED = Keys.key(ResourceKey.sponge("last_damage_received"), Double.class); /** * The last time a {@link User} joined on the server. */ public static final Key<Value<Instant>> LAST_DATE_JOINED = Keys.key(ResourceKey.sponge("last_date_joined"), Instant.class); /** * The last time a {@link User} has been playing on the server. */ public static final Key<Value<Instant>> LAST_DATE_PLAYED = Keys.key(ResourceKey.sponge("last_date_played"), Instant.class); /** * The amount of layers a {@link BlockState} has. * e.g. {@link BlockTypes#SNOW}, {@link BlockTypes#CAKE} */ public static final Key<Value<Integer>> LAYER = Keys.key(ResourceKey.sponge("layer"), Integer.class); /** * The holder of a leashed {@link Agent} * e.g. a {@link Player} or {@link LeashKnot}. * <p>Usually, a {@link LeashKnot} will always exist so long as there is * a leashed {@link Entity} attached. If the leash is broken, the leash * hitch is removed.</p> */ public static final Key<Value<Entity>> LEASH_HOLDER = Keys.key(ResourceKey.sponge("leash_holder"), Entity.class); /** * The rotation of an {@link ArmorStand}'s left arm. */ public static final Key<Value<Vector3d>> LEFT_ARM_ROTATION = Keys.key(ResourceKey.sponge("left_arm_rotation"), Vector3d.class); /** * The rotation of an {@link ArmorStand}'s left leg. */ public static final Key<Value<Vector3d>> LEFT_LEG_ROTATION = Keys.key(ResourceKey.sponge("left_leg_rotation"), Vector3d.class); /** * The amount of ticks till a {@link Vex} starts * taking damage due to living too long. * * <p>When this value hits 0 or lower, the Vex will receive damage and * then the value will set back to 20 until the Vex dies.</p> * * <p>If the Vex was summoned by a player, this value will be pegged at 0 * and the Vex will not take any damage.</p> */ public static final Key<Value<Ticks>> LIFE_TICKS = Keys.key(ResourceKey.sponge("life_ticks"), Ticks.class); /** * The amount of light that emitted by a {@link BlockState}. * Readonly */ public static final Key<Value<Integer>> LIGHT_EMISSION = Keys.key(ResourceKey.sponge("light_emission"), Integer.class); /** * A {@link Llama}'s {@link LlamaType}. */ public static final Key<Value<LlamaType>> LLAMA_TYPE = Keys.key(ResourceKey.sponge("llama_type"), LlamaType.class); /** * A {@link ServerPlayer}'s client language. */ public static final Key<Value<Locale>> LOCALE = Keys.key(ResourceKey.sponge("locale"), Locale.class); /** * The token used to lock a {@link CarrierBlockEntity}. Or the token on an {@link ItemStack} to unlock it. */ public static final Key<Value<String>> LOCK_TOKEN = Keys.key(ResourceKey.sponge("lock_token"), String.class); /** * A lodestone location, used with {@link ItemTypes#COMPASS}. */ public static final Key<Value<ServerLocation>> LODESTONE = Keys.key(ResourceKey.sponge("lodestone"), ServerLocation.class); /** * The displayed description ("lore") text of an {@link ItemStack}. * * <p>The lore text is usually displayed when the player hovers his cursor * over the stack. For the contents of a book see {@link #PAGES} * instead.</p> */ public static final Key<ListValue<Component>> LORE = Keys.listKey(ResourceKey.sponge("lore"), Component.class); /** * Represents the {@link Key} for the {@link MapCanvas} of a map * for a {@link MapInfo}. * This contains the colors displayed on a map. * */ public static final Key<Value<MapCanvas>> MAP_CANVAS = Keys.key(ResourceKey.sponge("map_canvas"), MapCanvas.class); /** * Represents the {@link Key} for the Set of {@link MapDecoration}s * for a {@link MapInfo}. * */ public static final Key<SetValue<MapDecoration>> MAP_DECORATIONS = Keys.setKey(ResourceKey.sponge("map_decorations"), MapDecoration.class); /** * Represents the {@link Key} for the {@link MapInfo} * of an {@link ItemStack} of type {@link ItemTypes#FILLED_MAP}. * * <b>Can be null if the ItemStack was made by a plugin and hasn't been offered a MapInfo yet.</b> */ public static final Key<Value<MapInfo>> MAP_INFO = Keys.key(ResourceKey.sponge("map_info"), MapInfo.class); /** * Represents the {@link Key} for the centre x and z of where a * {@link MapInfo} represents. * This will be automatically centralised correctly. */ public static final Key<Value<Vector2i>> MAP_LOCATION = Keys.key(ResourceKey.sponge("map_location"), Vector2i.class); public static final Key<Value<Boolean>> MAP_LOCKED = Keys.key(ResourceKey.sponge("map_locked"), Boolean.class); public static final Key<Value<Integer>> MAP_SCALE = Keys.key(ResourceKey.sponge("map_scale"), Integer.class); /** * Represents the {@link Key} for whether a {@link MapInfo} * tracks player positions. */ public static final Key<Value<Boolean>> MAP_TRACKS_PLAYERS = Keys.key(ResourceKey.sponge("map_tracks_players"), Boolean.class); /** * Represents the {@link Key} for whether a {@link MapInfo} can track * a player from anywhere in the world. */ public static final Key<Value<Boolean>> MAP_UNLIMITED_TRACKING = Keys.key(ResourceKey.sponge("map_unlimited_tracking"), Boolean.class); /** * Represents the {@link Key} for the {@link ResourceKey} of a {@link ServerWorld}. * {@link MapInfo} */ public static final Key<Value<ResourceKey>> MAP_WORLD = Keys.key(ResourceKey.sponge("map_world"), ResourceKey.class); /** * The matter state of a {@link BlockState} * Readonly */ public static final Key<Value<MatterType>> MATTER_TYPE = Keys.key(ResourceKey.sponge("matter_type"), MatterType.class); /** * The maximum air supply a {@link Living} may have. * * <p>For the current amount of air, check {@link #REMAINING_AIR}.</p> */ public static final Key<Value<Integer>> MAX_AIR = Keys.key(ResourceKey.sponge("max_air"), Integer.class); /** * The maximum amount of ticks a {@link FurnaceBlockEntity} * can burn with the currently used fuel item. */ public static final Key<Value<Ticks>> MAX_BURN_TIME = Keys.key(ResourceKey.sponge("max_burn_time"), Ticks.class); /** * The total time the current {@link ItemStack} in a * {@link FurnaceBlockEntity} has to be cooked. */ public static final Key<Value<Ticks>> MAX_COOK_TIME = Keys.key(ResourceKey.sponge("max_cook_time"), Ticks.class); /** * The maximum durability of an {@link ItemStack}. {@link #ITEM_DURABILITY} * Readonly */ public static final Key<Value<Integer>> MAX_DURABILITY = Keys.key(ResourceKey.sponge("max_durability"), Integer.class); /** * The maximum exhuastion of a {@link Humanoid}. Readonly. * * @see Keys#EXHAUSTION */ public static final Key<Value<Double>> MAX_EXHAUSTION = Keys.key(ResourceKey.sponge("max_exhaustion"), Double.class); /** * The maximum damage a {@link FallingBlock} can deal. */ public static final Key<Value<Double>> MAX_FALL_DAMAGE = Keys.key(ResourceKey.sponge("max_fall_damage"), Double.class); /** * The maximum food level of a {@link Humanoid}. Readonly. * * @see Keys#FOOD_LEVEL */ public static final Key<Value<Integer>> MAX_FOOD_LEVEL = Keys.key(ResourceKey.sponge("max_food_level"), Integer.class); /** * The maximum health of a {@link Living}. * * <p>The maximum health set here may affect the attribute increasing * health points. The base health should be minded that it may be lower * than the total maximum health of the entity.</p> */ public static final Key<Value<Double>> MAX_HEALTH = Keys.key(ResourceKey.sponge("max_health"), Double.class); /** * The maximum number of entities around a {@link MobSpawner}. * A spawner will not spawn entities if there are more * entities around than this value permits. */ public static final Key<Value<Integer>> MAX_NEARBY_ENTITIES = Keys.key(ResourceKey.sponge("max_nearby_entities"), Integer.class); /** * The maximum saturation of a {@link Humanoid}. Readonly. * * @see Keys#SATURATION */ public static final Key<Value<Double>> MAX_SATURATION = Keys.key(ResourceKey.sponge("max_saturation"), Double.class); /** * The maximum amount of ticks between two * batches of entities spawned by a {@link MobSpawner}. */ public static final Key<Value<Ticks>> MAX_SPAWN_DELAY = Keys.key(ResourceKey.sponge("max_spawn_delay"), Ticks.class); /** * The max speed of a {@link Boat}. In vanilla, this is 0.4 */ public static final Key<Value<Double>> MAX_SPEED = Keys.key(ResourceKey.sponge("max_speed"), Double.class); /** * The maximum stack size of slots in an inventory. For most vanilla inventories this is 64. * Readonly */ public static final Key<Value<Integer>> MAX_STACK_SIZE = Keys.key(ResourceKey.sponge("max_stack_size"), Integer.class); /** * The represented block's offset of a {@link MinecartLike}. */ public static final Key<Value<Integer>> MINECART_BLOCK_OFFSET = Keys.key(ResourceKey.sponge("minecart_block_offset"), Integer.class); /** * The minimum amount of ticks between two * batches of entities spawned by a {@link MobSpawner}. */ public static final Key<Value<Ticks>> MIN_SPAWN_DELAY = Keys.key(ResourceKey.sponge("min_spawn_delay"), Ticks.class); /** * The moisture value of a {@link BlockTypes#FARMLAND} {@link BlockState}. */ public static final Key<Value<Integer>> MOISTURE = Keys.key(ResourceKey.sponge("moisture"), Integer.class); /** * The type of a {@link Mooshroom}. */ public static final Key<Value<MooshroomType>> MOOSHROOM_TYPE = Keys.key(ResourceKey.sponge("mooshroom_type"), MooshroomType.class); /** * The type of {@link MusicDisc} an {@link ItemStack} holds. */ public static final Key<Value<MusicDisc>> MUSIC_DISC = Keys.key(ResourceKey.sponge("music_disc"), MusicDisc.class); /** * The next entity that will be spawned by a {@link MobSpawner}. * * <p>Normally the entities to be spawned are determined by a random value * applied to the {@link #SPAWNABLE_ENTITIES} weighted collection. If this * value exists, it will override the random spawn with a definite one.</p> */ public static final Key<Value<WeightedSerializableObject<EntityArchetype>>> NEXT_ENTITY_TO_SPAWN = Keys.key(ResourceKey.sponge("next_entity_to_spawn"), new TypeToken<WeightedSerializableObject<EntityArchetype>>() {}); /** * The pitch of a {@link BlockTypes#NOTE_BLOCK} {@link BlockState}. */ public static final Key<Value<NotePitch>> NOTE_PITCH = Keys.key(ResourceKey.sponge("note_pitch"), NotePitch.class); /** * The notifier, usually of an {@link Entity}. It is up to the implementation to define. */ public static final Key<Value<UUID>> NOTIFIER = Keys.key(ResourceKey.sponge("notifier"), UUID.class); /** * The deceleration a {@link Boat} while it has {@link Keys#PASSENGERS}. */ public static final Key<Value<Double>> OCCUPIED_DECELERATION = Keys.key(ResourceKey.sponge("occupied_deceleration"), Double.class); /** * Whether an {@link Entity} is currently considered to be on the ground. * Readonly */ public static final Key<Value<Boolean>> ON_GROUND = Keys.key(ResourceKey.sponge("on_ground"), Boolean.class); /** * The {@link Orientation} of an {@link ItemFrame}. */ public static final Key<Value<Orientation>> ORIENTATION = Keys.key(ResourceKey.sponge("orientation"), Orientation.class); /** * The content of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}. * * <p>Use {@link Keys#PLAIN_PAGES} if you wish to inspect the contents * of a {@link ItemTypes#WRITABLE_BOOK}.</p> */ public static final Key<ListValue<Component>> PAGES = Keys.listKey(ResourceKey.sponge("pages"), Component.class); /** * The {@link ParrotType type} of a {@link Parrot}. */ public static final Key<Value<ParrotType>> PARROT_TYPE = Keys.key(ResourceKey.sponge("parrot_type"), ParrotType.class); /** * The particle type of an {@link AreaEffectCloud}. * * <p>Only a few {@link ParticleOption}s will be usable for this * effect for specific {@link ParticleType}s and not every * {@link ParticleType} will be applicable.</p> */ public static final Key<Value<ParticleEffect>> PARTICLE_EFFECT = Keys.key(ResourceKey.sponge("particle_effect"), ParticleEffect.class); /** * The amount of ticks a {@link FurnaceBlockEntity} has * been cooking the current item for. * * <p>Once this value reaches the {@link #MAX_COOK_TIME}, the * item will be finished cooking.</p> */ public static final Key<Value<Ticks>> PASSED_COOK_TIME = Keys.key(ResourceKey.sponge("passed_cook_time"), Ticks.class); /** * The entities that act as passengers for an {@link Entity}. * * <p>For example, a {@link Player} riding on a {@link Horse} or a * {@link Pig} would be considered its passenger.</p> */ public static final Key<ListValue<Entity>> PASSENGERS = Keys.listKey(ResourceKey.sponge("passengers"), Entity.class); /** * A {@link TropicalFish}'s pattern color. */ public static final Key<Value<DyeColor>> PATTERN_COLOR = Keys.key(ResourceKey.sponge("pattern_color"), DyeColor.class); /** * The {@link PhantomPhase phase} of a {@link Phantom}. */ public static final Key<Value<PhantomPhase>> PHANTOM_PHASE = Keys.key(ResourceKey.sponge("phantom_phase"), PhantomPhase.class); /** * The pickup delay (in ticks) of an {@link Item}. */ public static final Key<Value<Ticks>> PICKUP_DELAY = Keys.key(ResourceKey.sponge("pickup_delay"), Ticks.class); /** * The {@link PickupRule} of an {@link ArrowEntity}. */ public static final Key<Value<PickupRule>> PICKUP_RULE = Keys.key(ResourceKey.sponge("pickup_rule"), PickupRule.class); /** * The piston type of a piston {@link BlockState} TODO dataholder {@link Piston}. */ public static final Key<Value<PistonType>> PISTON_TYPE = Keys.key(ResourceKey.sponge("piston_type"), PistonType.class); /** * The block types an {@link ItemStack} may be placed on. */ public static final Key<SetValue<BlockType>> PLACEABLE_BLOCK_TYPES = Keys.setKey(ResourceKey.sponge("placeable_block_types"), BlockType.class); /** * The content of a {@link ItemTypes#WRITABLE_BOOK} {@link ItemStack}. * * <p>Use {@link Keys#PAGES} if you wish to get the contents of a * {@link ItemTypes#WRITTEN_BOOK}</p> */ public static final Key<ListValue<String>> PLAIN_PAGES = Keys.listKey(ResourceKey.sponge("plain_pages"), String.class); /** * The plugin that created an {@link Inventory} */ public static final Key<Value<PluginContainer>> PLUGIN_CONTAINER = Keys.key(ResourceKey.sponge("plugin_container"), PluginContainer.class); /** * The pore sides of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. * See {@link #HAS_PORES_UP}, {@link #HAS_PORES_DOWN}, {@link #HAS_PORES_NORTH}, {@link #HAS_PORES_EAST}, {@link #HAS_PORES_SOUTH}, {@link #HAS_PORES_WEST}. */ public static final Key<SetValue<Direction>> PORES = Keys.setKey(ResourceKey.sponge("pores"), Direction.class); /** * The {@link PortionType} of a {@link BlockState}. * e.g. {@link BlockTypes#OAK_DOOR}, {@link BlockTypes#ROSE_BUSH} or {@link BlockTypes#WHITE_BED} * For slabs use {@link #SLAB_PORTION} instead */ public static final Key<Value<PortionType>> PORTION_TYPE = Keys.key(ResourceKey.sponge("portion_type"), PortionType.class); /** * The potential max speed of a {@link Minecart}. */ public static final Key<Value<Double>> POTENTIAL_MAX_SPEED = Keys.key(ResourceKey.sponge("potential_max_speed"), Double.class); /** * The potion effects that are present on an {@link Entity} * <p>or applied by an {@link AreaEffectCloud} or {@link ArrowEntity}</p> * <p>or stored on an {@link ItemStack}.</p> */ public static final Key<ListValue<PotionEffect>> POTION_EFFECTS = Keys.listKey(ResourceKey.sponge("potion_effects"), PotionEffect.class); /** * The potion type of an {@link ItemStack}. */ public static final Key<Value<PotionType>> POTION_TYPE = Keys.key(ResourceKey.sponge("potion_type"), PotionType.class); /** * The signal power of a {@link BlockState}. * * <p>Applies to blocks that may emit a Redstone signal of variable * strength, such as {@link BlockTypes#REDSTONE_WIRE}, * {@link BlockTypes#DAYLIGHT_DETECTOR}, * {@link BlockTypes#LIGHT_WEIGHTED_PRESSURE_PLATE} etc.</p> */ public static final Key<Value<Integer>> POWER = Keys.key(ResourceKey.sponge("power"), Integer.class); /** * The previous {@link GameMode} of a {@link ServerPlayer}. */ public static final Key<Value<GameMode>> PREVIOUS_GAME_MODE = Keys.key(ResourceKey.sponge("previous_game_mode"), GameMode.class); /** * A {@link Beacon}'s primary effect. */ public static final Key<Value<PotionEffectType>> PRIMARY_POTION_EFFECT_TYPE = Keys.key(ResourceKey.sponge("primary_potion_effect_type"), PotionEffectType.class); /** * The {@link Villager} or {@link ZombieVillager}'s {@link ProfessionType}. */ public static final Key<Value<ProfessionType>> PROFESSION_TYPE = Keys.key(ResourceKey.sponge("profession_type"), ProfessionType.class); /** * The {@link Villager} or {@link ZombieVillager}'s {@link ProfessionType} level. */ public static final Key<Value<Integer>> PROFESSION_LEVEL = Keys.key(ResourceKey.sponge("profession_level"), Integer.class); /** * The type of a {@link Rabbit}. */ public static final Key<Value<RabbitType>> RABBIT_TYPE = Keys.key(ResourceKey.sponge("rabbit_type"), RabbitType.class); /** * The radius of an {@link AreaEffectCloud}. */ public static final Key<Value<Double>> RADIUS = Keys.key(ResourceKey.sponge("radius"), Double.class); /** * The amount the radius of an * {@link AreaEffectCloud} grows or shrinks each time it applies its * effect. */ public static final Key<Value<Double>> RADIUS_ON_USE = Keys.key(ResourceKey.sponge("radius_on_use"), Double.class); /** * The amount the radius of an * {@link AreaEffectCloud} grows or shrinks per tick. */ public static final Key<Value<Double>> RADIUS_PER_TICK = Keys.key(ResourceKey.sponge("radius_per_tick"), Double.class); /** * The wave number of a raid a {@link Raider} is in. * Readonly but mutable */ public static final Key<Value<RaidWave>> RAID_WAVE = Keys.key(ResourceKey.sponge("raid_wave"), RaidWave.class); /** * The {@link RailDirection} of a {@link BlockState}. */ public static final Key<Value<RailDirection>> RAIL_DIRECTION = Keys.key(ResourceKey.sponge("rail_direction"), RailDirection.class); /** * The delay (in ticks) after which an * {@link AreaEffectCloud} will reapply its effect on a previously * affected {@link Entity}. */ public static final Key<Value<Ticks>> REAPPLICATION_DELAY = Keys.key(ResourceKey.sponge("reapplication_delay"), Ticks.class); /** * The redstone delay on a {@link BlockTypes#REPEATER} {@link BlockState}. */ public static final Key<Value<Integer>> REDSTONE_DELAY = Keys.key(ResourceKey.sponge("redstone_delay"), Integer.class); /** * The amount of air a {@link Living} has left. */ public static final Key<Value<Integer>> REMAINING_AIR = Keys.key(ResourceKey.sponge("remaining_air"), Integer.class); /** * The remaining amount of ticks the current brewing * process of a {@link BrewingStand} will take. * * <p>If nothing is being brewed, the remaining brew time will be 0.</p> */ public static final Key<Value<Ticks>> REMAINING_BREW_TIME = Keys.key(ResourceKey.sponge("remaining_brew_time"), Ticks.class); /** * Represents the {@link Key} for the remaining number of ticks to pass * before another attempt to spawn entities is made by a {@link MobSpawner}. */ public static final Key<Value<Ticks>> REMAINING_SPAWN_DELAY = Keys.key(ResourceKey.sponge("remaining_spawn_delay"), Ticks.class); /** * The amount of food a food {@link ItemStack} restores when eaten. * Readonly */ public static final Key<Value<Integer>> REPLENISHED_FOOD = Keys.key(ResourceKey.sponge("replenished_food"), Integer.class); /** * The amount of saturation a food {@link ItemStack} provides when eaten. * Readonly */ public static final Key<Value<Double>> REPLENISHED_SATURATION = Keys.key(ResourceKey.sponge("replenished_saturation"), Double.class); /** * The {@link InstrumentType} of a {@link BlockState} when placed under a {@link BlockTypes#NOTE_BLOCK}. * Readonly */ public static final Key<Value<InstrumentType>> REPRESENTED_INSTRUMENT = Keys.key(ResourceKey.sponge("represented_instrument"), InstrumentType.class); /** * How close a {@link Player} has to be around the {@link MobSpawner} * in order for it to attempt to spawn entities. */ public static final Key<Value<Double>> REQUIRED_PLAYER_RANGE = Keys.key(ResourceKey.sponge("required_player_range"), Double.class); /** * The spawn locations a {@link Player} * may have for various worlds based on {@link UUID} of the world. */ public static final Key<MapValue<ResourceKey, RespawnLocation>> RESPAWN_LOCATIONS = Keys.mapKey(ResourceKey.sponge("respawn_locations"), ResourceKey.class, RespawnLocation.class); /** * The rotation of an {@link ArmorStand}'s right arm. */ public static final Key<Value<Vector3d>> RIGHT_ARM_ROTATION = Keys.key(ResourceKey.sponge("right_arm_rotation"), Vector3d.class); /** * The rotation of an {@link ArmorStand}'s right leg. */ public static final Key<Value<Vector3d>> RIGHT_LEG_ROTATION = Keys.key(ResourceKey.sponge("right_leg_rotation"), Vector3d.class); /** * The time a {@link Ravager} is roaring. */ public static final Key<Value<Ticks>> ROARING_TIME = Keys.key(ResourceKey.sponge("roaring_time"), Ticks.class); public static final Key<Value<Double>> SATURATION = Keys.key(ResourceKey.sponge("saturation"), Double.class); /** * The "scale" for the size of an {@link Entity}. * * <p>Together with {@link #BASE_SIZE} and {@link #HEIGHT} this defines the size of an {@link Entity}.</p> */ public static final Key<Value<Double>> SCALE = Keys.key(ResourceKey.sponge("scale"), Double.class); public static final Key<SetValue<String>> SCOREBOARD_TAGS = Keys.setKey(ResourceKey.sponge("scoreboard_tags"), String.class); /** * A {@link Beacon}'s secondary effect. */ public static final Key<Value<PotionEffectType>> SECONDARY_POTION_EFFECT_TYPE = Keys.key(ResourceKey.sponge("secondary_potion_effect_type"), PotionEffectType.class); /** * A {@link Fox fox's} second trusted {@link UUID}, usually a {@link Player}. */ public static final Key<Value<UUID>> SECOND_TRUSTED = Keys.key(ResourceKey.sponge("second_trusted"), UUID.class); /** * The shooter of a {@link Projectile}. */ public static final Key<Value<ProjectileSource>> SHOOTER = Keys.key(ResourceKey.sponge("shooter"), ProjectileSource.class); /** * Whether a {@link EndCrystal} should show it's bottom bedrock platform. */ public static final Key<Value<Boolean>> SHOW_BOTTOM = Keys.key(ResourceKey.sponge("show_bottom"), Boolean.class); /** * The lines displayed on a {@link Sign}. */ public static final Key<ListValue<Component>> SIGN_LINES = Keys.listKey(ResourceKey.sponge("sign_lines"), Component.class); /** * The size of a {@link Slime}. * or * The size of a {@link Phantom}. In vanilla, this ranges between 0 and 64. */ public static final Key<Value<Integer>> SIZE = Keys.key(ResourceKey.sponge("size"), Integer.class); /** * The parts of a {@link ServerPlayer} skin that should be displayed. * * <p>This is a read-only value, set by the client.</p> */ public static final Key<SetValue<SkinPart>> SKIN_PARTS = Keys.setKey(ResourceKey.sponge("skin_parts"), SkinPart.class); /** * The skin of a {@link Humanoid}. * * <p>Skins can only be manipulated by supplying the UUID of a player * having that skin. The binary skin data is signed by Mojang so fully * customized skins are not possible.</p> * Readonly (Player) */ public static final Key<Value<ProfileProperty>> SKIN_PROFILE_PROPERTY = Keys.key(ResourceKey.sponge("skin_profile_property"), ProfileProperty.class); /** * The "moisture" state of a {@link Dolphin}. * * <p> * Vanilla sets the dolphin's skin moisture to 2400 so long as the entity * is in water, being rained on, or in a bubble column. If not, the dolphin * will loose 1 moisture per tick. Once this value is 0 or below, the dolphin * will be damaged via {@link DamageSources#DRYOUT} with a value of 1 per tick * until death. * </p> */ public static final Key<Value<Integer>> SKIN_MOISTURE = Keys.key(ResourceKey.sponge("skin_moisture"), Integer.class); /** * The skylight value at a {@link ServerLocation}. * For the blocklight see {@link #BLOCK_LIGHT}. * Readonly */ public static final Key<Value<Integer>> SKY_LIGHT = Keys.key(ResourceKey.sponge("sky_light"), Integer.class); /** * The {@link SlabPortion} of a {@link BlockState}. */ public static final Key<Value<SlabPortion>> SLAB_PORTION = Keys.key(ResourceKey.sponge("slab_portion"), SlabPortion.class); /** * The sleep timer of a {@link Player}. */ public static final Key<Value<Integer>> SLEEP_TIMER = Keys.key(ResourceKey.sponge("sleep_timer"), Integer.class); /** * The index of a {@link Slot} in an {@link Inventory} * Readonly */ public static final Key<Value<Integer>> SLOT_INDEX = Keys.key(ResourceKey.sponge("slot_index"), Integer.class); /** * The position of a {@link Slot} within a {@link GridInventory}. * Readonly */ public static final Key<Value<Vector2i>> SLOT_POSITION = Keys.key(ResourceKey.sponge("slot_position"), Vector2i.class); /** * The side of a particular {@link Slot}, for use in querying "sided inventories". * Readonly */ public static final Key<Value<Direction>> SLOT_SIDE = Keys.key(ResourceKey.sponge("slot_side"), Direction.class); /** * Whether a {@link Minecart} slows down when it has no {@link Keys#PASSENGERS}. */ public static final Key<Value<Boolean>> SLOWS_UNOCCUPIED = Keys.key(ResourceKey.sponge("slows_unoccupied"), Boolean.class); /** * The time a {@link Panda} has been sneezing (in ticks) */ public static final Key<Value<Ticks>> SNEEZING_TIME = Keys.key(ResourceKey.sponge("sneezing_time"), Ticks.class); /** * The list of {@link EntityArchetype}s able to be spawned by a {@link MobSpawner}. */ public static final Key<WeightedCollectionValue<EntityArchetype>> SPAWNABLE_ENTITIES = Keys.weightedKey(ResourceKey.sponge("spawnable_entities"), EntityArchetype.class); /** * How many entities a {@link MobSpawner} has spawned so far. */ public static final Key<Value<Integer>> SPAWN_COUNT = Keys.key(ResourceKey.sponge("spawn_count"), Integer.class); /** * How far away from the {@link MobSpawner} the entities spawned by it may appear. */ public static final Key<Value<Double>> SPAWN_RANGE = Keys.key(ResourceKey.sponge("spawn_range"), Double.class); /** * The {@link Entity target} of the spectator camera of a {@link Player}. */ public static final Key<Value<Entity>> SPECTATOR_TARGET = Keys.key(ResourceKey.sponge("spectator_target"), Entity.class); /** * The {@link StairShape} of a {@link BlockState}. */ public static final Key<Value<StairShape>> STAIR_SHAPE = Keys.key(ResourceKey.sponge("stair_shape"), StairShape.class); /** * The {@link Statistic}s of a {@link Player}. */ public static final Key<MapValue<Statistic, Long>> STATISTICS = Keys.mapKey(ResourceKey.sponge("statistics"), Statistic.class, Long.class); /** * The enchantments stored on an {@link ItemStack}. * * <p>Stored enchantments are meant to be transferred. Usually this key * applies to {@link ItemTypes#ENCHANTED_BOOK} {@link ItemStack}s. Enchantments * affecting the item stack are retrieved via {@link #APPLIED_ENCHANTMENTS} * instead.</p> */ public static final Key<ListValue<Enchantment>> STORED_ENCHANTMENTS = Keys.listKey(ResourceKey.sponge("stored_enchantments"), Enchantment.class); /** * A {@link Llama}s carrying strength. The higher the strength, * the more items it can carry (effectively the size of inventory). */ public static final Key<Value<Integer>> STRENGTH = Keys.key(ResourceKey.sponge("strength"), Integer.class); /** * The author of a structure from a {@link StructureBlock}. */ public static final Key<Value<String>> STRUCTURE_AUTHOR = Keys.key(ResourceKey.sponge("structure_author"), String.class); /** * Whether a {@link StructureBlock} should * ignore entities when saving a structure. */ public static final Key<Value<Boolean>> STRUCTURE_IGNORE_ENTITIES = Keys.key(ResourceKey.sponge("structure_ignore_entities"), Boolean.class); /** * The integrity of a {@link StructureBlock}. */ public static final Key<Value<Double>> STRUCTURE_INTEGRITY = Keys.key(ResourceKey.sponge("structure_integrity"), Double.class); /** * The mode of a {@link StructureBlock}. */ public static final Key<Value<StructureMode>> STRUCTURE_MODE = Keys.key(ResourceKey.sponge("structure_mode"), StructureMode.class); /** * The position of a {@link StructureBlock}. */ public static final Key<Value<Vector3i>> STRUCTURE_POSITION = Keys.key(ResourceKey.sponge("structure_position"), Vector3i.class); /** * Whether a {@link StructureBlock} is powered. */ public static final Key<Value<Boolean>> STRUCTURE_POWERED = Keys.key(ResourceKey.sponge("structure_powered"), Boolean.class); /** * The seed of a {@link StructureBlock} */ public static final Key<Value<Long>> STRUCTURE_SEED = Keys.key(ResourceKey.sponge("structure_seed"), Long.class); /** * Whether a * {@link StructureBlock} should make all {@link BlockTypes#AIR}, * {@link BlockTypes#CAVE_AIR}, {@link BlockTypes#STRUCTURE_VOID} visible. */ public static final Key<Value<Boolean>> STRUCTURE_SHOW_AIR = Keys.key(ResourceKey.sponge("structure_show_air"), Boolean.class); /** * Whether a {@link StructureBlock} shows the bounding box. */ public static final Key<Value<Boolean>> STRUCTURE_SHOW_BOUNDING_BOX = Keys.key(ResourceKey.sponge("structure_show_bounding_box"), Boolean.class); /** * The size of a {@link StructureBlock}s structure. */ public static final Key<Value<Vector3i>> STRUCTURE_SIZE = Keys.key(ResourceKey.sponge("structure_size"), Vector3i.class); /** * The amount of "stuck arrows" in a {@link Living}. */ public static final Key<Value<Integer>> STUCK_ARROWS = Keys.key(ResourceKey.sponge("stuck_arrows"), Integer.class); /** * The time (in ticks) a {@link Ravager} is stunned. */ public static final Key<Value<Ticks>> STUNNED_TIME = Keys.key(ResourceKey.sponge("stunned_time"), Ticks.class); /** * The amount of successful executions of a command * stored in a {@link CommandBlock} or {@link CommandBlockMinecart}. */ public static final Key<Value<Integer>> SUCCESS_COUNT = Keys.key(ResourceKey.sponge("success_count"), Integer.class); /** * Whether a {@link BlockState} is suspended. */ public static final Key<Value<Boolean>> SUSPENDED = Keys.key(ResourceKey.sponge("suspended"), Boolean.class); /** * The swiftness of an {@link Entity} e.g. {@link Minecart}s. * <p>This is equivalent to the magnitude of the {@link #VELOCITY} vector</p> */ public static final Key<Value<Double>> SWIFTNESS = Keys.key(ResourceKey.sponge("swiftness"), Double.class); /** * The tamer of a {@link TameableAnimal} or {@link HorseLike}. */ public static final Key<Value<UUID>> TAMER = Keys.key(ResourceKey.sponge("tamer"), UUID.class); /** * The targeted entity either by an {@link Agent} and it's * {@link GoalExecutorTypes#TARGET} selector or by a {@link FishingBobber} or {@link ShulkerBullet}. */ public static final Key<Value<Entity>> TARGET_ENTITY = Keys.key(ResourceKey.sponge("target_entity"), Entity.class); /** * A target location. * e.g. An {@link EyeOfEnder} target or a {@link Player}'s compass. */ public static final Key<Value<Vector3d>> TARGET_LOCATION = Keys.key(ResourceKey.sponge("target_location"), Vector3d.class); /** * A target block position. * e.g. A {@link Patroller}'s patrol target, * the travel position of a {@link Turtle}, * the exit portal position of a {@link EndGateway} or * an {@link EndCrystal}'s beam target. */ public static final Key<Value<Vector3i>> TARGET_POSITION = Keys.key(ResourceKey.sponge("target_position"), Vector3i.class); /** * The remaining fuse time in ticks of a {@link FusedExplosive}. * This value may be set to an arbitrary value * if the explosive is not primed. */ public static final Key<Value<Ticks>> TICKS_REMAINING = Keys.key(ResourceKey.sponge("ticks_remaining"), Ticks.class); /** * The {@link ItemTier} of an {@link ItemStack} tool. * Readonly */ public static final Key<Value<ItemTier>> TOOL_TYPE = Keys.key(ResourceKey.sponge("tool_type"), ItemTier.class); /** * Whether a {@link CommandBlock} does track its output. * * <p>If this is set, the output of the most recent execution can be * retrieved using {@link #LAST_COMMAND_OUTPUT}.</p> */ public static final Key<Value<Boolean>> TRACKS_OUTPUT = Keys.key(ResourceKey.sponge("tracks_output"), Boolean.class); /** * The {@link TradeOffer}s offered by a {@link Trader}. */ public static final Key<ListValue<TradeOffer>> TRADE_OFFERS = Keys.listKey(ResourceKey.sponge("trade_offers"), TradeOffer.class); /** * Whether an {@link Entity} is transient. * This prevents the entity from being saved to disk. * The rules for this are as follows... * If the entity type says that it isn't transient then this key is readonly. * If the entity type says that it is transient, then this key dictates the current state. */ public static final Key<Value<Boolean>> TRANSIENT = Keys.key(ResourceKey.sponge("transient"), Boolean.class); /** * A {@link TropicalFish}'s shape. */ public static final Key<Value<TropicalFishShape>> TROPICAL_FISH_SHAPE = Keys.key(ResourceKey.sponge("tropical_fish_shape"), TropicalFishShape.class); /** * The time a {@link Panda} has been unhappy (in ticks) */ public static final Key<Value<Ticks>> UNHAPPY_TIME = Keys.key(ResourceKey.sponge("unhappy_time"), Ticks.class); /** * The {@link UUID} of a custom inventory. */ public static final Key<Value<UUID>> UNIQUE_ID = Keys.key(ResourceKey.sponge("unique_id"), UUID.class); /** * The deceleration a {@link Boat} while it does not have {@link Keys#PASSENGERS}. */ public static final Key<Value<Double>> UNOCCUPIED_DECELERATION = Keys.key(ResourceKey.sponge("unoccupied_deceleration"), Double.class); /** * Whether a {@link BlockTypes#TNT} {@link BlockState} is unstable. */ public static final Key<Value<Boolean>> UNSTABLE = Keys.key(ResourceKey.sponge("unstable"), Boolean.class); /** * Whether changes to {@link Keys#SKIN_PROFILE_PROPERTY} should * be reflected in an entitie's {@link GameProfile}. */ public static final Key<Value<Boolean>> UPDATE_GAME_PROFILE = Keys.key(ResourceKey.sponge("update_game_profile"), Boolean.class); /** * The {@link VanishState} of an {@link Entity}. * * <p>The presence of a vanished entity will not be made known to a client; * no packets pertaining to this entity are sent. Client-side, this entity * will cease to exist. Server-side it may still be targeted by hostile * entities or collide with other entities.</p> * * <p>Vanishing an {@link Entity} ridden by other entities (see * {@link #PASSENGERS} will cause problems.</p> */ public static final Key<Value<VanishState>> VANISH_STATE = Keys.key(ResourceKey.sponge("vanish"), VanishState.class); /** * Whether an {@link Entity} is vanished. * * <p>The presence of a vanished entity will not be made known to a client; * no packets pertaining to this entity are sent. Client-side, this entity * will cease to exist. Server-side it may still be targeted by hostile * entities or collide with other entities.</p> * * <p>Vanishing an {@link Entity} ridden by other entities (see * {@link #PASSENGERS} will cause problems.</p> * @deprecated use {@link #VANISH_STATE} */ @Deprecated public static final Key<Value<Boolean>> VANISH = Keys.key(ResourceKey.sponge("vanish"), Boolean.class); /** * Whether an {@link Entity} ignores collision with other entities. * * <p>This state will be ignored if the {@link Entity} is not also * vanished as per {@link #VANISH}.</p> * @deprecated use {@link #VANISH_STATE} */ @Deprecated public static final Key<Value<Boolean>> VANISH_IGNORES_COLLISION = Keys.key(ResourceKey.sponge("vanish_ignores_collision"), Boolean.class); /** * Whether an {@link Entity} can be targeted for attack by another entity. * This prevents neither {@link Player}s from attacking the entity nor * will it be protected from untargeted damage like fire or explosions. * * <p>This state will be ignored if the {@link Entity} is not also * vanished as per {@link #VANISH}.}.</p> * @deprecated use {@link #VANISH_STATE} */ @Deprecated public static final Key<Value<Boolean>> VANISH_PREVENTS_TARGETING = Keys.key(ResourceKey.sponge("vanish_prevents_targeting"), Boolean.class); /** * The vehicle an {@link Entity} is riding. * * <p>Vehicles may be nested as a vehicle might itself ride another entity. * To get the vehicle on bottom, use {@link Keys#BASE_VEHICLE}.</p> */ public static final Key<Value<Entity>> VEHICLE = Keys.key(ResourceKey.sponge("vehicle"), Entity.class); /** * The velocity of an {@link Entity}. */ public static final Key<Value<Vector3d>> VELOCITY = Keys.key(ResourceKey.sponge("velocity"), Vector3d.class); /** * The client view distance of a {@link ServerPlayer}. Read-only. * * <p>This value represents the radius (around the player) in * unit chunks.</p> */ public static final Key<Value<Integer>> VIEW_DISTANCE = Keys.key(ResourceKey.sponge("view_distance"), Integer.class); /** * The type of a {@link Villager} or {@link ZombieVillager}. */ public static final Key<Value<VillagerType>> VILLAGER_TYPE = Keys.key(ResourceKey.sponge("villager_type"), VillagerType.class); /** * The duration in ticks after which an * {@link AreaEffectCloud} will begin to apply its effect to entities. */ public static final Key<Value<Ticks>> WAIT_TIME = Keys.key(ResourceKey.sponge("wait_time"), Ticks.class); /** * The base speed at which a {@link Player} or {@link Living} walks. */ public static final Key<Value<Double>> WALKING_SPEED = Keys.key(ResourceKey.sponge("walking_speed"), Double.class); /** * Whether a thrown {@link EyeOfEnder} will shatter. */ public static final Key<Value<Boolean>> WILL_SHATTER = Keys.key(ResourceKey.sponge("will_shatter"), Boolean.class); /** * The {@link WireAttachmentType}s of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} for its neighboring blocks. */ public static final Key<MapValue<Direction, WireAttachmentType>> WIRE_ATTACHMENTS = Keys.mapKey(ResourceKey.sponge("wire_attachments"), Direction.class, WireAttachmentType.class); /** * The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} * for its neighboring block to the {@link Direction#EAST}. */ public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_EAST = Keys.key(ResourceKey.sponge("wire_attachment_east"), WireAttachmentType.class); /** * The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} * for its neighboring block to the {@link Direction#NORTH}. */ public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_NORTH = Keys.key(ResourceKey.sponge("wire_attachment_north"), WireAttachmentType.class); /** * The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} * for its neighboring block to the {@link Direction#SOUTH}. */ public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_SOUTH = Keys.key(ResourceKey.sponge("wire_attachment_south"), WireAttachmentType.class); /** * The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} * for its neighboring block to the {@link Direction#WEST}. */ public static final Key<Value<WireAttachmentType>> WIRE_ATTACHMENT_WEST = Keys.key(ResourceKey.sponge("wire_attachment_west"), WireAttachmentType.class); /** * The entities targeted by the three {@link Wither} heads. In vanilla the wither only targets {@link Living}. {@code null} for no target entity. */ public static final Key<ListValue<Entity>> WITHER_TARGETS = Keys.listKey(ResourceKey.sponge("wither_targets"), Entity.class); /** * The {@link Sheep} who is being targeted by the {@link SpellTypes#WOLOLO} * spell being casted by an {@link Evoker} */ public static final Key<Value<Sheep>> WOLOLO_TARGET = Keys.key(ResourceKey.sponge("wololo_target"), Sheep.class); // SORTFIELDS:OFF // @formatter:on private static <T> Key<Value<T>> key(final ResourceKey resourceKey, final TypeToken<T> token) { return Key.builder().key(resourceKey).elementType(token).build(); } private static <T> Key<Value<T>> key(final ResourceKey resourceKey, final Class<T> type) { return Key.builder().key(resourceKey).elementType(type).build(); } private static <T> Key<ListValue<T>> listKey(final ResourceKey resourceKey, final Class<T> elementType) { return Key.builder().key(resourceKey).listElementType(elementType).build(); } private static <T> Key<ListValue<T>> listKey(final ResourceKey resourceKey, final TypeToken<T> elementType) { return Key.builder().key(resourceKey).listElementType(elementType).build(); } private static <T> Key<SetValue<T>> setKey(final ResourceKey resourceKey, final Class<T> elementType) { return Key.builder().key(resourceKey).setElementType(elementType).build(); } private static <T> Key<SetValue<T>> setKey(final ResourceKey resourceKey, final TypeToken<T> elementType) { return Key.builder().key(resourceKey).setElementType(elementType).build(); } private static <K, V> Key<MapValue<K, V>> mapKey(final ResourceKey resourceKey, final Class<K> keyType, final Class<V> valueType) { return Key.builder().key(resourceKey).mapElementType(keyType, valueType).build(); } private static <K, V> Key<MapValue<K, V>> mapKey(final ResourceKey resourceKey, final TypeToken<K> keyType, final TypeToken<V> valueType) { return Key.builder().key(resourceKey).mapElementType(keyType, valueType).build(); } private static <T> Key<WeightedCollectionValue<T>> weightedKey(final ResourceKey resourceKey, final Class<T> elementType) { return Key.builder().key(resourceKey).weightedCollectionElementType(elementType).build(); } private static <T> Key<WeightedCollectionValue<T>> weightedKey(final ResourceKey resourceKey, final TypeToken<T> elementType) { return Key.builder().key(resourceKey).weightedCollectionElementType(elementType).build(); } private Keys() { } }
package org.voovan.network; import org.voovan.network.Event.EventName; import org.voovan.network.Event.EventState; import org.voovan.network.exception.IoFilterException; import org.voovan.network.exception.SendMessageException; import org.voovan.network.exception.SocketDisconnectByRemote; import org.voovan.tools.Chain; import org.voovan.tools.TObject; import org.voovan.tools.log.Logger; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; public class EventProcess { private EventProcess(){ } /** * Accept * * @param event * * @throws Exception * @throws IOException */ public static void onAccepted(Event event) throws IOException { SocketContext socketContext = event.getSession().sockContext(); if (socketContext != null) { socketContext.start(); } } /** * * * @param event * * @throws SendMessageException * @throws IOException * @throws IoFilterException */ public static void onConnect(Event event) throws SendMessageException, IOException, IoFilterException { IoSession session = event.getSession(); // SSL if (session!=null && session.getSSLParser() != null && !session.getSSLParser().isHandShakeDone()) { try { session.getSSLParser().doHandShake(); } catch (IOException e) { Logger.error("SSL hand shake failed",e); } } SocketContext socketContext = event.getSession().sockContext(); if (socketContext != null && session != null) { Object result = socketContext.handler().onConnect(session); if (result != null) { socketContext.filterChain().rewind(); while (socketContext.filterChain().hasNext()) { IoFilter fitler = socketContext.filterChain().next(); result = fitler.encode(session, result); } sendMessage(session, result); } } } /** * * * @param event * */ public static void onDisconnect(Event event) { SocketContext socketContext = event.getSession().sockContext(); if (socketContext != null) { IoSession session = event.getSession(); socketContext.handler().onDisconnect(session); } } /** * * * @param event * * @throws IOException * @throws SendMessageException * @throws IoFilterException * @throws Exception */ public static void onRead(Event event) throws IOException, SendMessageException, IoFilterException { SocketContext socketContext = event.getSession().sockContext(); IoSession session = event.getSession(); if (socketContext != null && session != null) { ByteBuffer byteBuffer = ByteBuffer.allocate(1); // onRecive while (byteBuffer.limit() != 0) { byteBuffer = session.getMessageLoader().read(); // null if (byteBuffer == null) { session.close(); return; } if (byteBuffer.limit() == 0) { return; } Object result = byteBuffer; Chain<IoFilter> filterChain = socketContext.filterChain().clone(); result = filterDecoder(filterChain,session,result); if (result != null) { IoHandler handler = socketContext.handler(); result = handler.onReceive(session, result); } if (result != null) { result = filterEncoder(filterChain,session,result); sendMessage(session, result); } filterChain.clear(); } } } /** * * @param filterChain * @param session * @param result * @return * @throws IoFilterException */ private static Object filterDecoder(Chain<IoFilter> filterChain,IoSession session,Object result) throws IoFilterException{ while (filterChain.hasNext()) { IoFilter fitler = filterChain.next(); result = fitler.decode(session, result); } return result; } /** * * @param filterChain * @param session * @param result * @return * @throws IoFilterException */ private static Object filterEncoder(Chain<IoFilter> filterChain,IoSession session,Object result) throws IoFilterException{ filterChain.rewind(); while (filterChain.hasPrevious()) { IoFilter fitler = filterChain.previous(); result = fitler.encode(session, result); } return result; } /** * * * @param event * * @param obj * * @throws IOException */ public static void onSent(Event event, Object obj) throws IOException { SocketContext socketContext = event.getSession().sockContext(); if (socketContext != null) { IoSession session = event.getSession(); socketContext.handler().onSent(session, obj); } } /** * * * @param event * * @param e */ public static void onException(Event event, Exception e) { if (event != null && event.getSession() != null && event.getSession().sockContext() != null) { SocketContext socketContext = event.getSession().sockContext(); IoSession session = event.getSession(); //SocketDisconnectByRemote,session if(e instanceof SocketDisconnectByRemote || e instanceof ClosedChannelException){ event.getSession().close(); return; } if (socketContext.handler() != null) { socketContext.handler().onException(session, e); } } } /** * * * @param session * @param sendObj * @throws SendMessageException * @throws IOException */ public static void sendMessage(IoSession session, Object sendObj) throws SendMessageException, IOException{ ByteBuffer resultBuf = null; if (sendObj != null) { if (sendObj instanceof ByteBuffer) { resultBuf = TObject.cast(sendObj); resultBuf.rewind(); } else if (sendObj instanceof String) { String sendString = TObject.cast(sendObj); resultBuf = ByteBuffer.wrap(sendString.getBytes()); } else { throw new SendMessageException("Expect Object type is 'java.nio.ByteBuffer' or 'java.lang.String',reality got type is '" + sendObj.getClass() + "'"); } } if (sendObj != null && session.isConnect()) { if (session.getSSLParser() != null && session.getSSLParser().handShakeDone) { session.sendSSLData(resultBuf); } else { session.send(resultBuf); } Event event = new Event(session, EventName.ON_SENT, resultBuf); EventProcess.process(event); } } public static void process(Event event) { if (event == null) { return; } event.setState(EventState.DISPOSEING); EventName eventName = event.getName(); try { if (eventName == EventName.ON_ACCEPTED) { SocketContext socketContext = TObject.cast(event.getSession().sockContext()); socketContext.start(); } else if (eventName == EventName.ON_CONNECT) { EventProcess.onConnect(event); } else if (eventName == EventName.ON_DISCONNECT) { EventProcess.onDisconnect(event); } else if (eventName == EventName.ON_RECEIVE) { EventProcess.onRead(event); } else if (eventName == EventName.ON_SENT) { EventProcess.onSent(event, event.getOther()); } else if (eventName == EventName.ON_EXCEPTION) { EventProcess.onException(event, (Exception)event.getOther()); } } catch (IOException | SendMessageException | IoFilterException e) { EventProcess.onException(event, e); } finally { event.setState(EventState.FINISHED); } } }
package pitt.search.semanticvectors; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.logging.Logger; import org.apache.lucene.document.Document; import org.apache.lucene.index.*; import org.apache.lucene.util.BytesRef; import pitt.search.semanticvectors.LuceneUtils.TermWeight; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; /** * Generates predication vectors incrementally.Requires as input an index containing * documents with the fields "subject", "predicate" and "object" * * Produces as output the files: elementalvectors.bin, predicatevectors.bin and semanticvectors.bin * * @author Trevor Cohen, Dominic Widdows */ public class PSI { private static final Logger logger = Logger.getLogger(PSI.class.getCanonicalName()); private FlagConfig flagConfig; private ElementalVectorStore elementalItemVectors, predicateVectors; private VectorStoreRAM semanticItemVectors; private static final String SUBJECT_FIELD = "subject"; private static final String PREDICATE_FIELD = "predicate"; private static final String OBJECT_FIELD = "object"; private static final String PREDICATION_FIELD = "predication"; private String[] itemFields = {SUBJECT_FIELD, OBJECT_FIELD}; private LuceneUtils luceneUtils; private PSI() {}; /** * Creates PSI vectors incrementally, using the fields "subject" and "object" from a Lucene index. */ public static void createIncrementalPSIVectors(FlagConfig flagConfig) throws IOException { PSI incrementalPSIVectors = new PSI(); incrementalPSIVectors.flagConfig = flagConfig; if (incrementalPSIVectors.luceneUtils == null) { incrementalPSIVectors.luceneUtils = new LuceneUtils(flagConfig); } incrementalPSIVectors.trainIncrementalPSIVectors(); } private void trainIncrementalPSIVectors() throws IOException { // Create elemental and semantic vectors for each concept, and elemental vectors for predicates elementalItemVectors = new ElementalVectorStore(flagConfig); semanticItemVectors = new VectorStoreRAM(flagConfig); predicateVectors = new ElementalVectorStore(flagConfig); flagConfig.setContentsfields(itemFields); HashSet<String> addedConcepts = new HashSet<String>(); for (String fieldName : itemFields) { Terms terms = luceneUtils.getTermsForField(fieldName); if (terms == null) { throw new NullPointerException(String.format( "No terms for field '%s'. Please check that index at '%s' was built correctly for use with PSI.", fieldName, flagConfig.luceneindexpath())); } TermsEnum termsEnum = terms.iterator(null); BytesRef bytes; while((bytes = termsEnum.next()) != null) { Term term = new Term(fieldName, bytes); if (!luceneUtils.termFilter(term)) { VerbatimLogger.fine("Filtering out term: " + term + "\n"); continue; } if (!addedConcepts.contains(term.text())) { addedConcepts.add(term.text()); elementalItemVectors.getVector(term.text()); // Causes vector to be created. semanticItemVectors.putVector(term.text(), VectorFactory.createZeroVector( flagConfig.vectortype(), flagConfig.dimension())); } } } // Now elemental vectors for the predicate field. Terms predicateTerms = luceneUtils.getTermsForField(PREDICATE_FIELD); String[] dummyArray = new String[] { PREDICATE_FIELD }; // To satisfy LuceneUtils.termFilter interface. TermsEnum termsEnum = predicateTerms.iterator(null); BytesRef bytes; while((bytes = termsEnum.next()) != null) { Term term = new Term(PREDICATE_FIELD, bytes); // frequency thresholds do not apply to predicates... but the stopword list does if (!luceneUtils.termFilter(term, dummyArray, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, 1)) { continue; } predicateVectors.getVector(term.text().trim()); // Add an inverse vector for the predicates. predicateVectors.getVector(term.text().trim()+"-INV"); } String fieldName = PREDICATION_FIELD; // Iterate through documents (each document = one predication). Terms allTerms = luceneUtils.getTermsForField(fieldName); termsEnum = allTerms.iterator(null); while((bytes = termsEnum.next()) != null) { int pc = 0; Term term = new Term(fieldName, bytes); pc++; // Output progress counter. if ((pc > 0) && ((pc % 10000 == 0) || ( pc < 10000 && pc % 1000 == 0 ))) { VerbatimLogger.info("Processed " + pc + " unique predications ... "); } DocsEnum termDocs = luceneUtils.getDocsForTerm(term); termDocs.nextDoc(); Document document = luceneUtils.getDoc(termDocs.docID()); String subject = document.get(SUBJECT_FIELD); String predicate = document.get(PREDICATE_FIELD); String object = document.get(OBJECT_FIELD); if (!(elementalItemVectors.containsVector(object) && elementalItemVectors.containsVector(subject) && predicateVectors.containsVector(predicate))) { logger.info("skipping predication " + subject + " " + predicate + " " + object); continue; } float sWeight = 1; float oWeight = 1; float pWeight = 1; sWeight = luceneUtils.getGlobalTermWeight(new Term(SUBJECT_FIELD, subject)); oWeight = luceneUtils.getGlobalTermWeight(new Term(OBJECT_FIELD, object)); // TODO: Explain different weighting for predicates, log(occurrences of predication) pWeight = luceneUtils.getLocalTermWeight(luceneUtils.getGlobalTermFreq(term)); Vector subjectSemanticvector = semanticItemVectors.getVector(subject); Vector objectSemanticvector = semanticItemVectors.getVector(object); Vector subjectElementalvector = elementalItemVectors.getVector(subject); Vector objectElementalvector = elementalItemVectors.getVector(object); Vector predicateVector = predicateVectors.getVector(predicate); Vector predicateVectorInv = predicateVectors.getVector(predicate+"-INV"); Vector objToAdd = objectElementalvector.copy(); objToAdd.bind(predicateVector); subjectSemanticvector.superpose(objToAdd, pWeight*oWeight, null); Vector subjToAdd = subjectElementalvector.copy(); subjToAdd.bind(predicateVectorInv); objectSemanticvector.superpose(subjToAdd, pWeight*sWeight, null); } // Finish iterating through predications. //Normalize semantic vectors Enumeration<ObjectVector> e = semanticItemVectors.getAllVectors(); while (e.hasMoreElements()) { e.nextElement().getVector().normalize(); } VectorStoreWriter.writeVectors(flagConfig.elementalvectorfile(), flagConfig, elementalItemVectors); VectorStoreWriter.writeVectors(flagConfig.semanticvectorfile(), flagConfig, semanticItemVectors); VectorStoreWriter.writeVectors(flagConfig.predicatevectorfile(), flagConfig, predicateVectors); VerbatimLogger.info("Finished writing vectors.\n"); } public static void main(String[] args) throws IllegalArgumentException, IOException { FlagConfig flagConfig = FlagConfig.getFlagConfig(args); args = flagConfig.remainingArgs; if (flagConfig.luceneindexpath().isEmpty()) { throw (new IllegalArgumentException("-luceneindexpath argument must be provided.")); } VerbatimLogger.info("Building PSI model from index in: " + flagConfig.luceneindexpath() + "\n"); VerbatimLogger.info("Minimum frequency = " + flagConfig.minfrequency() + "\n"); VerbatimLogger.info("Maximum frequency = " + flagConfig.maxfrequency() + "\n"); VerbatimLogger.info("Number non-alphabet characters = " + flagConfig.maxnonalphabetchars() + "\n"); createIncrementalPSIVectors(flagConfig); } }
package scrum.server.admin; import ilarkesto.auth.AuthenticationFailedException; import ilarkesto.auth.OpenId; import ilarkesto.base.Str; import ilarkesto.base.Utl; import ilarkesto.base.time.DateAndTime; import ilarkesto.core.logging.Log; import ilarkesto.integration.ldap.Ldap; import ilarkesto.io.IO; import ilarkesto.ui.web.HtmlRenderer; import ilarkesto.webapp.Servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.openid4java.consumer.VerificationResult; import scrum.client.ScrumGwtApplication; import scrum.server.WebSession; import scrum.server.common.AHttpServlet; public class LoginServlet extends AHttpServlet { private static final long serialVersionUID = 1; private static Log log = Log.get(LoginServlet.class); @Override protected void onRequest(HttpServletRequest req, HttpServletResponse resp, WebSession session) throws IOException { String historyToken = req.getParameter("historyToken"); if (session.getUser() != null) { resp.sendRedirect(getStartPage(historyToken)); return; } if (tokenLogin(req, resp, session)) { resp.sendRedirect(getStartPage(historyToken)); return; } if (OpenId.isOpenIdCallback(req)) { loginOpenId(resp, session, req); return; } if (req.getParameter("createAccount") != null) { createAccount(req.getParameter("username"), req.getParameter("email"), req.getParameter("password"), historyToken, req, resp, session); return; } if (req.getParameter("passwordRequest") != null) { passwordRequest(req.getParameter("email"), historyToken, resp, session); return; } String openId = req.getParameter("openid"); if (openId != null) { redirectOpenId(openId, req.getParameter("keepmeloggedin") != null, historyToken, resp, session, req); return; } String username = req.getParameter("username"); if (username != null) { login(username, req.getParameter("password"), req.getParameter("keepmeloggedin") != null, historyToken, req, resp, session); return; } renderLoginPage(resp, null, null, historyToken, null, req.getParameter("showPasswordRequest") != null, req.getParameter("showCreateAccount") != null); } private void passwordRequest(String login, String historyToken, HttpServletResponse resp, WebSession session) throws UnsupportedEncodingException, IOException { if (login == null || Str.isBlank(login)) { renderLoginPage(resp, login, null, historyToken, "E-Mail required.", true, false); return; } User user = null; if (login.contains("@")) { user = userDao.getUserByEmail(login.toLowerCase()); } if (user == null) { user = userDao.getUserByName(login); } if (user == null) { renderLoginPage(resp, login, login, historyToken, "User '" + login + "' does not exist.", true, false); return; } if (user.isAdmin()) { renderLoginPage(resp, login, login, historyToken, "Admins can not request new passwords.", true, false); return; } if (!user.isEmailVerified()) { renderLoginPage(resp, login, login, historyToken, "User '" + login + "' has no verified email. Please contact the admin: " + systemConfig.getAdminEmail(), true, false); return; } user.triggerNewPasswordRequest(); renderLoginPage(resp, login, login, historyToken, "New password has been sent to " + login, false, false); } private void createAccount(String username, String email, String password, String historyToken, HttpServletRequest req, HttpServletResponse resp, WebSession session) throws UnsupportedEncodingException, IOException { if (webApplication.getSystemConfig().isRegistrationDisabled()) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Feature is disabled.", false, false); return; } if (Str.isBlank(username)) username = null; if (Str.isBlank(email)) email = null; if (Str.isBlank(password)) password = null; if (username == null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Username required.", false, true); return; } if (systemConfig.isUserEmailMandatory() && email == null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. E-Mail required.", false, true); return; } if (password == null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Password required.", false, true); return; } if (Str.containsNonLetterOrDigit(username)) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Name '" + username + "' contains an illegal character. Only letters and digits allowed.", false, true); return; } if (email != null && !Str.isEmail(email)) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Illegal email address.", false, true); return; } if (userDao.getUserByName(username) != null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Name '" + username + "' is already used.", false, true); log.warn("Registration failed. User name already exists:", username); return; } if (email != null && userDao.getUserByEmail(email) != null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Email '" + email + "' is already used.", false, true); log.warn("Registration failed. User email already exists:", email); return; } User user = userDao.postUser(email, username, password); user.setLastLoginDateAndTime(DateAndTime.now()); user.triggerEmailVerification(); webApplication.getTransactionService().commit(); webApplication.triggerRegisterNotification(user, req.getRemoteHost()); webApplication.sendToClients(user); session.setUser(user); resp.sendRedirect(getStartPage(historyToken)); } private String getStartPage(String historyToken) { String url = getDefaultStartPage(); if (historyToken != null) url += "#" + historyToken; url = webApplication.createUrl(url); return url; } private void loginOpenId(HttpServletResponse resp, WebSession session, HttpServletRequest request) throws UnsupportedEncodingException, IOException { HttpSession httpSession = request.getSession(); String historyToken = (String) httpSession.getAttribute("openidHistoryToken"); boolean keepmeloggedin = httpSession.getAttribute("openidKeepmeloggedin") != null; VerificationResult openIdResult; try { openIdResult = OpenId.getVerificationFromCallback(request); } catch (RuntimeException ex) { log.error("OpenID authentication failed.", ex); renderLoginPage(resp, null, null, historyToken, "OpenID authentication failed: " + Str.format(Utl.getRootCause(ex)), false, false); return; } String openId = OpenId.getOpenId(openIdResult); if (openId == null) { renderLoginPage(resp, null, null, historyToken, "OpenID authentication failed.", false, false); return; } String email = OpenId.getEmail(openIdResult); String nickname = OpenId.getNickname(openIdResult); String fullName = OpenId.getFullname(openIdResult); User user = userDao.getUserByOpenId(openId); if (user == null) { if (webApplication.getSystemConfig().isRegistrationDisabled()) { renderLoginPage(resp, null, null, historyToken, "There is no user with the OpenID " + openId + " and creating new users is disabled.", false, false); return; } if (!webApplication.getSystemConfig().isOpenIdDomainAllowed(openId)) { renderLoginPage(resp, null, null, historyToken, "Registration failed. OpenID domains are limited to: " + webApplication.getSystemConfig().getOpenIdDomains(), false, false); log.warn("Registration failed. OpenID domains are limited to:", webApplication.getSystemConfig() .getOpenIdDomains()); return; } if (email != null) { if (userDao.getUserByEmail(email) != null) { renderLoginPage(resp, null, null, historyToken, "Creating account failed. Email '" + email + "' is already used.", false, false); log.warn("Registration failed. Email already exists:", email); return; } } if (email == null && webApplication.getSystemConfig().isUserEmailMandatory()) { renderLoginPage(resp, null, null, historyToken, "Creating account failed. Required email address was not included in OpenID response.", false, false); return; } user = userDao.postUserWithOpenId(openId, nickname, fullName, email); webApplication.getTransactionService().commit(); webApplication.triggerRegisterNotification(user, request.getRemoteHost()); } log.info("User authenticated by OpenID:", openId, "->", user); if (user.isDisabled()) { renderLoginPage(resp, null, null, historyToken, "User is disabled.", false, false); return; } user.setLastLoginDateAndTime(DateAndTime.now()); if (!user.isEmailSet()) user.setEmail(email); session.setUser(user); if (keepmeloggedin) Servlet.setCookie(resp, ScrumGwtApplication.LOGIN_TOKEN_COOKIE, user.getLoginToken(), LOGIN_TOKEN_COOKIE_MAXAGE); resp.sendRedirect(getStartPage(historyToken)); } private void redirectOpenId(String openId, boolean keepmeloggedin, String historyToken, HttpServletResponse resp, WebSession session, HttpServletRequest request) throws UnsupportedEncodingException, IOException { HttpSession httpSession = request.getSession(); if (Str.isBlank(openId)) openId = null; if (openId == null) { renderLoginPage(resp, null, null, historyToken, "Login failed. OpenID required.", false, true); return; } String returnUrl = webApplication.createUrl("login.html"); if (!returnUrl.startsWith("http")) { returnUrl = request.getRequestURL().toString(); } String openIdUrl; try { openIdUrl = OpenId.createAuthenticationRequestUrl(openId, returnUrl, httpSession, true, false, false, false, true, webApplication.getSystemConfig().isUserEmailMandatory()); } catch (RuntimeException ex) { log.error("OpenID authentication failed.", ex); renderLoginPage(resp, null, null, historyToken, "OpenID authentication failed: " + Str.format(Utl.getRootCause(ex)), false, false); return; } httpSession.setAttribute("openidHistoryToken", historyToken); httpSession.setAttribute("openidKeepmeloggedin", keepmeloggedin ? "true" : null); resp.sendRedirect(openIdUrl); } private void login(String username, String password, boolean keepmeloggedin, String historyToken, HttpServletRequest request, HttpServletResponse resp, WebSession session) throws UnsupportedEncodingException, IOException { User user = null; if (username.contains("@")) user = userDao.getUserByEmail(username.toLowerCase()); if (user == null) user = userDao.getUserByName(username); boolean admin = user != null && user.isAdmin(); boolean authenticated; String email = null; if (systemConfig.isLdapEnabled(true) && !admin) { // LDAP authentication try { email = Ldap.authenticateUserGetEmail(systemConfig.getLdapUrl(), systemConfig.getLdapUser(), systemConfig.getLdapPassword(), systemConfig.getLdapBaseDn(), systemConfig.getLdapUserFilterRegex(), username, password); authenticated = true; } catch (AuthenticationFailedException ex) { authenticated = false; } catch (Exception ex) { log.error("LDAP authentication failed.", ex); renderLoginPage(resp, username, null, historyToken, "LDAP authentication failed: " + Str.getRootCauseMessage(ex), false, false); return; } if (authenticated && user == null) { if (webApplication.getSystemConfig().isRegistrationDisabled()) { renderLoginPage(resp, null, null, historyToken, "There is no user " + username + " and creating new users is disabled.", false, false); return; } if (userDao.getUserByEmail(email) != null) { renderLoginPage(resp, null, null, historyToken, "User with email " + email + " already exists: " + email, false, false); return; } user = userDao.postUser(email, username, Str.generatePassword(23)); if (Str.isEmail(email)) user.setEmail(email); webApplication.triggerRegisterNotification(user, request.getRemoteHost()); } } else { // default password authentication authenticated = user != null && user.matchesPassword(password); } if (!authenticated || user == null) { renderLoginPage(resp, username, null, historyToken, "Login failed.", false, false); return; } if (user.isDisabled()) { renderLoginPage(resp, username, null, historyToken, "User is disabled.", false, false); return; } user.setLastLoginDateAndTime(DateAndTime.now()); session.setUser(user); if (keepmeloggedin) Servlet.setCookie(resp, ScrumGwtApplication.LOGIN_TOKEN_COOKIE, user.getLoginToken(), LOGIN_TOKEN_COOKIE_MAXAGE); resp.sendRedirect(getStartPage(historyToken)); } private void renderLoginPage(HttpServletResponse resp, String username, String email, String historyToken, String message, boolean passwordRequest, boolean createAccount) throws UnsupportedEncodingException, IOException { if (webApplication.getSystemConfig().isRegistrationDisabled()) createAccount = false; String charset = IO.UTF_8; resp.setContentType("text/html"); HtmlRenderer html = new HtmlRenderer(resp.getOutputStream(), charset); html.startHTMLstandard(); String title = "Kunagi Login"; if (webApplication.getConfig().isShowRelease()) title += " " + applicationInfo.getRelease(); if (systemConfig.isInstanceNameSet()) title += " @ " + systemConfig.getInstanceName(); html.startHEAD(title, "EN"); html.META("X-UA-Compatible", "chrome=1"); html.LINKfavicon(); html.LINKcss("scrum.ScrumGwtApplication/screen.css"); html.endHEAD(); html.startBODY(); html.startDIV("loginPage"); html.startDIV("panel"); String logoUrl = webApplication.getSystemConfig().getLoginPageLogoUrl(); if (Str.isBlank(logoUrl)) logoUrl = "kunagi.png"; html.IMG(logoUrl, "Kunagi", null, null, null, null); html.DIV("separator", null); if (message != null) renderMessage(html, message); if (!createAccount && !passwordRequest) renderLogin(html, username, historyToken); if (passwordRequest) renderPasswordRequest(html, username, historyToken); if (createAccount) renderCreateAccount(html, username, email, historyToken); html.DIV("separator", null); html.startDIV("kunagiLink"); html.text("Kunagi " + webApplication.getReleaseLabel() + " | "); html.A("http://kunagi.org", "kunagi.org"); html.endDIV(); html.endDIV(); html.endDIV(); html.comment(applicationInfo.toString()); html.SCRIPTjavascript(null, "document.getElementById('username').focus();"); String analyticsId = systemConfig.getGoogleAnalyticsId(); if (analyticsId != null) html.googleAnalytics(analyticsId); html.endBODY(); html.endHTML(); html.flush(); } private void renderLogin(HtmlRenderer html, String username, String historyToken) { if (!webApplication.getSystemConfig().isOpenIdDisabled()) { html.H2("Login with OpenID"); renderOpenIdLoginForm(html, historyToken); html.DIV("separator", null); html.H2("Login with Password"); } renderRetroLoginForm(html, username, historyToken); html.BR(); html.A("login.html?showPasswordRequest=true", "Forgot your password?"); if (!systemConfig.isRegistrationDisabled()) { html.nbsp(); html.nbsp(); html.A("login.html?showCreateAccount=true", "Create new account"); } if (webApplication.isAdminPasswordDefault()) { html.DIV("separator", null); html.startDIV("configMessage"); html.html("<h2>Warning!</h2>The administrator user <code>admin</code> has the default password <code>" + systemConfig.getDefaultUserPassword() + "</code>. Please change it."); html.endDIV(); } if (systemConfig.isLoginPageMessageSet()) { html.DIV("separator", null); html.startDIV("configMessage"); html.html(systemConfig.getLoginPageMessage()); html.endDIV(); } } public void renderRetroLoginForm(HtmlRenderer html, String username, String historyToken) { html.startFORM(null, "loginForm", false); html.INPUThidden("historyToken", historyToken); html.startTABLE().setAlignCenter(); html.startTR(); html.startTD(); html.LABEL("username", "Username / E-Mail"); html.endTD(); html.startTD(); html.LABEL("password", "Password"); html.endTD(); html.endTR(); html.startTR(); html.startTD(); html.INPUTtext("username", "username", username, 80); html.endTD(); html.startTD(); html.INPUTpassword("password", "password", 80, ""); html.endTD(); html.endTR(); html.startTR(); html.startTD(); html.INPUTcheckbox("keepmeloggedin", "keepmeloggedin", true); html.LABEL("keepmeloggedin", "Keep me logged in"); html.endTD(); html.startTD().setAlignRight(); html.INPUTsubmit("login", "Login", null, 's'); html.endTD(); html.endTR(); html.endTABLE(); html.endFORM(); } public void renderOpenIdLoginForm(HtmlRenderer html, String historyToken) { renderOpenIdLink(OpenId.MYOPENID, "MyOpenID", historyToken, html); renderOpenIdLink(OpenId.GOOGLE, "Google", historyToken, html); renderOpenIdLink(OpenId.YAHOO, "Yahoo!", historyToken, html); renderOpenIdLink(OpenId.LAUNCHPAD, "Launchpad", historyToken, html); renderOpenIdLink(OpenId.AOL, "AOL", historyToken, html); renderOpenIdLink(OpenId.VERISIGN, "Verisign", historyToken, html); renderOpenIdLink(OpenId.WORDPRESS, "WordPress", historyToken, html); renderOpenIdLink(OpenId.FLICKR, "Flickr", historyToken, html); // renderOpenIdLink(OpenId.BLOGSPOT, "Blogger", historyToken, html); renderOpenIdLink(OpenId.MYVIDOOP, "Vidoop", historyToken, html); html.DIVclear(); html.BR(); html.startFORM(null, "openIdForm", false); html.INPUThidden("historyToken", historyToken); html.startTABLE().setAlignCenter(); html.startTR(); html.startTD(); html.LABEL("openid", "Custom OpenID"); html.endTD(); html.TD(""); html.endTR(); html.startTR(); html.startTD(null, 2); html.INPUTtext("openid", "openid", null, 80); html.endTD(); html.endTR(); html.startTR(); html.startTD(); html.INPUTcheckbox("keepmeloggedinOpenId", "keepmeloggedin", true); html.LABEL("keepmeloggedinOpenId", "Keep me logged in"); html.endTD(); html.startTD().setAlignRight(); html.INPUTsubmit("login", "Login", null, 's'); html.endTD(); html.endTR(); html.endTABLE(); html.BR(); html.A("http://openid.net/get-an-openid/", "Don't have an OpenID?", true); html.endFORM(); } private void renderOpenIdLink(String openId, String label, String historyToken, HtmlRenderer html) { StringBuilder sb = new StringBuilder(); sb.append("login.html?openid=").append(Str.encodeUrlParameter(openId)); sb.append("&login=Login"); if (historyToken != null) sb.append("&historyToken=").append(Str.encodeUrlParameter(historyToken)); html.startA("openid", sb.toString()); html.startDIV("button"); html.text(label); html.endDIV(); html.endA(); } private void renderPasswordRequest(HtmlRenderer html, String username, String historyToken) { html.H2("Request new password"); html.startFORM(null, "passwordRequestForm", false); html.INPUThidden("historyToken", historyToken); html.startTABLE().setAlignCenter(); html.startTR(); html.startTD(); html.LABEL("email", "E-Mail"); html.endTD(); html.TD(" "); html.endTR(); html.startTR(); html.startTD(); html.INPUTtext("email", "email", username, 80); html.endTD(); html.startTD(); html.INPUTsubmit("passwordRequest", "Request password", null, 's'); html.endTD(); html.endTR(); html.endTABLE(); html.endFORM(); html.BR(); html.A("login.html", "Back to Login"); } private void renderCreateAccount(HtmlRenderer html, String username, String email, String historyToken) { html.H2("Create account"); html.startDIV("createAccount"); html.startFORM(null, "loginForm", false); html.INPUThidden("historyToken", historyToken); html.startTABLE().setAlignCenter(); html.startTR(); html.startTD(); html.LABEL("username", "Username"); html.endTD(); html.startTD(); html.INPUTtext("username", "username", username, 80); html.endTD(); html.endTR(); html.startTR(); html.startTD(); if (!webApplication.getSystemConfig().isUserEmailMandatory()) html.startDIV("optionalLabel"); html.LABEL("email", "E-Mail"); if (!webApplication.getSystemConfig().isUserEmailMandatory()) html.endDIV(); html.endTD(); html.startTD(); html.INPUTtext("email", "email", email, 80); html.endTD(); html.endTR(); html.startTR(); html.startTD(); html.LABEL("password", "Password"); html.endTD(); html.startTD(); html.INPUTpassword("password", "password", 80, ""); html.endTD(); html.endTR(); html.startTR(); html.TD(""); html.startTD(); html.INPUTsubmit("createAccount", "Create account", null, 's'); html.endTD(); html.endTR(); html.endTABLE(); html.endFORM(); html.endDIV(); html.BR(); html.A("login.html", "Back to Login"); if (systemConfig.isRegisterPageMessageSet()) { html.DIV("separator", null); html.startDIV("configMessage"); html.html(systemConfig.getRegisterPageMessage()); html.endDIV(); } } private void renderMessage(HtmlRenderer html, String message) { html.startDIV("message"); html.text(message); html.endDIV(); html.DIV("separator", null); } }
package sds.assemble.controlflow; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import sds.assemble.LineInstructions; import sds.classfile.bytecode.BranchOpcode; import sds.classfile.bytecode.OpcodeInfo; import sds.classfile.bytecode.Opcodes; import sds.classfile.bytecode.LookupSwitch; import sds.classfile.bytecode.TableSwitch; import static sds.assemble.controlflow.NodeTypeChecker.check; import static sds.assemble.controlflow.CFNodeType.Entry; import static sds.assemble.controlflow.CFNodeType.OneLineEntry; import static sds.assemble.controlflow.CFNodeType.OneLineEntryBreak; import static sds.assemble.controlflow.CFNodeType.Exit; import static sds.assemble.controlflow.CFNodeType.LoopExit; import static sds.assemble.controlflow.CFNodeType.StringSwitch; import static sds.assemble.controlflow.CFNodeType.SynchronizedExit; import static sds.assemble.controlflow.CFNodeType.Switch; import static sds.classfile.bytecode.MnemonicTable._goto; import static sds.classfile.bytecode.MnemonicTable.goto_w; /** * This class is for node of control flow graph. * @author inagaki */ public class CFNode { private Set<CFEdge> parents; private Set<CFEdge> children; private CFNode dominator; private CFNode immediateDominator; private OpcodeInfo start; private OpcodeInfo end; private Opcodes opcodes; private int[] jumpPoints = new int[0]; // private int jumpPoint = -1; private int gotoPoint = -1; private int[] switchJump = new int[0]; private int hash; private String instStr; // package-private fields. CFNodeType nodeType; boolean inTry = false; boolean isCatch = false; boolean isFinally = false; int synchIndent = 0; /** * constructor. * @param inst instructions of a line. */ public CFNode(LineInstructions inst) { this.opcodes = inst.getOpcodes(); int size = opcodes.size(); this.start = opcodes.getAll()[0]; if(size == 1) { this.end = start; } else { this.end = opcodes.getAll()[size-1]; } StringBuilder sb = new StringBuilder(); for(OpcodeInfo info : opcodes.getAll()) { sb.append(info.getOpcodeType()).append(" "); } this.instStr = sb.toString(); this.nodeType = CFNodeType.getType(opcodes, end); if(check(this, Entry, OneLineEntry, OneLineEntryBreak)) { // if_xx int[] points = new int[opcodes.size()]; int ifCount = 0; for(OpcodeInfo op : opcodes.getAll()) { if(op instanceof BranchOpcode) { int branch = ((BranchOpcode)op).getBranch() + op.getPc(); if(op.getOpcodeType() == _goto || op.getOpcodeType() == goto_w) { this.gotoPoint = branch; continue; } points[ifCount] = branch; ifCount++; } } jumpPoints = Arrays.copyOf(points, ifCount); } else if(check(this, Exit, LoopExit)) { // goto this.gotoPoint = ((BranchOpcode)end).getBranch() + end.getPc(); } else if(check(this, Switch)) { // switch for(OpcodeInfo op : opcodes.getAll()) { if(op instanceof LookupSwitch) { LookupSwitch look = (LookupSwitch)op; this.switchJump = new int[look.getMatch().length + 1]; int[] offsets = look.getOffset(); for(int i = 0; i < switchJump.length-1; i++) { switchJump[i] = offsets[i] + look.getPc(); } switchJump[switchJump.length - 1] = look.getDefault() + look.getPc(); break; } else if(op instanceof TableSwitch) { TableSwitch table = (TableSwitch)op; this.switchJump = new int[table.getJumpOffsets().length + 1]; int[] offsets = table.getJumpOffsets(); for(int i = 0; i < switchJump.length-1; i++) { switchJump[i] = offsets[i] + table.getPc(); } switchJump[switchJump.length - 1] = table.getDefault() + table.getPc(); break; } } } else if(check(this, StringSwitch)) { // switch statement with string if(end instanceof LookupSwitch) { LookupSwitch look = (LookupSwitch)end; this.switchJump = new int[look.getMatch().length + 1]; int[] offsets = look.getOffset(); for(int i = 0; i < switchJump.length-1; i++) { switchJump[i] = offsets[i] + look.getPc(); } switchJump[switchJump.length - 1] = look.getDefault() + look.getPc(); } else if(end instanceof TableSwitch) { TableSwitch table = (TableSwitch)end; this.switchJump = new int[table.getJumpOffsets().length + 1]; int[] offsets = table.getJumpOffsets(); for(int i = 0; i < switchJump.length-1; i++) { switchJump[i] = offsets[i] + table.getPc(); } switchJump[switchJump.length - 1] = table.getDefault() + table.getPc(); } } else if(check(this, SynchronizedExit)) { // end of synchronized for(OpcodeInfo info : opcodes.getAll()) { if(info instanceof BranchOpcode) { this.gotoPoint = ((BranchOpcode)info).getBranch() + info.getPc(); break; } } } // calc hash char[] val1 = String.valueOf(start.getPc()).toCharArray(); char[] val2 = String.valueOf(end.getPc()).toCharArray(); char[] val3 = start.getOpcodeType().toString().toCharArray(); char[] val4 = end.getOpcodeType().toString().toCharArray(); for(int i = 0; i < val1.length; i++) { hash = 31 * hash + val1[i]; } for(int i = 0; i < val2.length; i++) { hash = 31 * hash + val2[i]; } for(int i = 0; i < val3.length; i++) { hash = 31 * hash + val3[i]; } for(int i = 0; i < val4.length; i++) { hash = 31 * hash + val4[i]; } this.parents = new LinkedHashSet<>(); this.children = new LinkedHashSet<>(); } /** * returns opcodes which this node has. * @return opcodes */ public Opcodes getOpcodes() { return opcodes; } /** * returns indexes into code array of jump point. * @return jump point indexes */ public int[] getJumpPoints() { return jumpPoints; } /** * returns index into code array of jump point. * @return jump point index */ public int getGotoPoint() { return gotoPoint; } /** * returns indexes into code array of jump point. * @return jump point indexes */ public int[] getSwitchJump() { return switchJump; } /** * returns node type. * @return node type */ public CFNodeType getType() { return nodeType; } /** * returns parent nodes. * @return parent nodes */ public Set<CFEdge> getParents() { return parents; } /** * returns child nodes. * @return child nodes */ public Set<CFEdge> getChildren() { return children; } /** * returns immediate dominator node. * @return immediate dominator node */ public CFNode getImmediateDominator() { return immediateDominator; } /** * returns dominator node. * @return dominator node */ public CFNode getDominator() { return dominator; } /** * sets immediate dominator node. * @param node immediate dominator node */ public void setImmediateDominator(CFNode node) { this.immediateDominator = node; } /** * sets dominator node. * @param node dominator node */ public void setDominator(CFNode node) { this.dominator = node; } /** * adds parent node of this. * @param parent parent node */ public void addParent(CFNode parent) { addParent(parent, CFEdgeType.Normal); } /** * adds parent node of this. * @param parent parent node * @param type edge type */ public void addParent(CFNode parent, CFEdgeType type) { if(equals(parent)) { return; } if(!isRoot()) { CFEdge edge = new CFEdge(this, parent, type); if(parents.isEmpty()) { this.immediateDominator = parent; this.parents.add(edge); } else { if(!parents.contains(edge)) { parents.add(edge); } } } } /** * adds child node of this. * @param child child node */ public void addChild(CFNode child) { addChild(child, CFEdgeType.Normal); } /** * adds child node of this. * @param child child node * @param type edge type */ public void addChild(CFNode child, CFEdgeType type) { if(equals(child)) { return; } CFEdge edge = new CFEdge(this, child, type); if(!children.contains(edge)) { children.add(edge); } } /** * returns whether specified pc is in range of opcode pc of this opcodes. * @param pc index into code array * @return if specified pc is in range of opcode pc, this method returns true.<br> * Otherwise, this method returns false. */ public boolean isInPcRange(int pc) { return start.getPc() <= pc && pc <= end.getPc(); } /** * returns whether this node is root. * @return if this node is root, this method returns true.<br> * Otherwise, this method returns false. */ public boolean isRoot() { return start.getPc() == 0; } /** * returns start opcode of instructions of this node. * @return start opcode */ public OpcodeInfo getStart() { return start; } /** * returns end opcode of instructions of this node. * @return end opcode */ public OpcodeInfo getEnd() { return end; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if(!(obj instanceof CFNode)) { return false; } CFNode node = (CFNode)obj; return start.getPc() == node.getStart().getPc() && end.getPc() == node.getEnd().getPc(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("#").append(start.getPc()).append("-").append(end.getPc()) .append(" [").append(nodeType).append("]").append("\n"); if(inTry) sb.append(" in try\n"); if(isCatch) sb.append(" in catch\n"); if(isFinally) sb.append(" in finally\n"); if(synchIndent > 0) sb.append(" in synchronized ").append(synchIndent).append("\n"); sb.append(" opcodes: ").append(instStr).append("\n"); if(parents.size() == 1) { sb.append(" immediate dominator: ").append(parents.iterator().next()); } else if(parents.size() > 1) { sb.append(" dominator: ") .append(dominator.getStart().getPc()).append("-") .append(dominator.getEnd().getPc()) .append("\n parents: "); for(CFEdge edge : parents) { sb.append(edge.toString()).append(" "); } } else { sb.append(" parents: not exist"); } sb.append("\n children: "); for(CFEdge edge : children) { sb.append(edge.toString()).append(" "); } return sb.toString(); } }
package seedu.address.model.person; public class Time { private int hour; private int minute; private String hourStr; private String minuteStr; public final String value; public final String TIME_DELIMITER = ":"; public final int MINUTE_ARRAY_INDEX = 0; public final int HOUR_ARRAY_INDEX = 1; public Time(String time) { time = time.trim(); value = time; int[] timeArray = timeFormatConverter(time); setMinute(timeArray[MINUTE_ARRAY_INDEX]); setHour(timeArray[HOUR_ARRAY_INDEX]); } public String toString() { return hourStr + TIME_DELIMITER + minuteStr; } public void setHour(int hour) { if (0 <= hour && hour <= 23) { this.hour = hour; } else { throw new IllegalArgumentException("Invalid hour"); } } public void setMinute(int minute) { if (0 <= minute && minute <= 59) { this.minute = minute; } else { throw new IllegalArgumentException("Invalid minute"); } } public int[] timeFormatConverter(String time) { if (time.length() < 3 || time.length() > 5) { throw new IllegalArgumentException("Invalid time format"); } else if (time.length() == 3) { this.minuteStr = time.substring(1,3); this.hourStr = time.substring(0,1); } else if (time.length() == 4) { if (time.substring(1,2).equals(":")) { this.minuteStr = time.substring(2,4); this.hourStr = "0" + time.substring(0,1); } else { this.minuteStr = time.substring(2,4); this.hourStr = time.substring(0,2); } } else { this.minuteStr = time.substring(3,5); this.hourStr = time.substring(0,2); } int minute = Integer.parseInt(minuteStr); int hour = Integer.parseInt(hourStr); int[] timeArray = {minute, hour}; return timeArray; } public static void main(String[] args) { Time t = new Time("0204"); System.out.println(t); t = new Time("305"); System.out.println(t); t = new Time("4:10"); System.out.println(t); t = new Time("12:30"); System.out.println(t); t = new Time("0:01"); System.out.println(t); } }
package seedu.doist.logic.parser; import static seedu.doist.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.doist.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.doist.logic.commands.AddCommand; import seedu.doist.logic.commands.ClearCommand; import seedu.doist.logic.commands.Command; import seedu.doist.logic.commands.DeleteCommand; import seedu.doist.logic.commands.EditCommand; import seedu.doist.logic.commands.ExitCommand; import seedu.doist.logic.commands.FindCommand; import seedu.doist.logic.commands.HelpCommand; import seedu.doist.logic.commands.IncorrectCommand; import seedu.doist.logic.commands.ListCommand; import seedu.doist.logic.commands.SelectCommand; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); if (AddCommand.commandWords.contains(commandWord) || AddCommand.DEFAULT_COMMAND_WORD == commandWord) { return new AddCommandParser().parse(arguments); } else if (EditCommand.commandWords.contains(commandWord) || EditCommand.DEFAULT_COMMAND_WORD == commandWord) { return new EditCommandParser().parse(arguments); } else if (SelectCommand.commandWords.contains(commandWord) || SelectCommand.DEFAULT_COMMAND_WORD == commandWord) { return new SelectCommandParser().parse(arguments); } else if (DeleteCommand.commandWords.contains(commandWord) || DeleteCommand.DEFAULT_COMMAND_WORD == commandWord) { return new DeleteCommandParser().parse(arguments); } else if (ClearCommand.commandWords.contains(commandWord) || ClearCommand.DEFAULT_COMMAND_WORD == commandWord) { return new ClearCommand(); } else if (FindCommand.commandWords.contains(commandWord) || FindCommand.DEFAULT_COMMAND_WORD == commandWord) { return new FindCommandParser().parse(arguments); } else if (ListCommand.commandWords.contains(commandWord) || ListCommand.DEFAULT_COMMAND_WORD == commandWord) { return new ListCommand(); } else if (ExitCommand.commandWords.contains(commandWord) || ExitCommand.DEFAULT_COMMAND_WORD == commandWord) { return new ExitCommand(); } else if (HelpCommand.commandWords.contains(commandWord) || HelpCommand.DEFAULT_COMMAND_WORD == commandWord) { return new HelpCommand(); } else { return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } // switch (commandWord) { // case AddCommand.COMMAND_WORD: // return new AddCommandParser().parse(arguments); // case EditCommand.COMMAND_WORD: // return new EditCommandParser().parse(arguments); // case SelectCommand.COMMAND_WORD: // return new SelectCommandParser().parse(arguments); // case DeleteCommand.COMMAND_WORD: // return new DeleteCommandParser().parse(arguments); // case ClearCommand.COMMAND_WORD: // return new ClearCommand(); // case FindCommand.COMMAND_WORD: // return new FindCommandParser().parse(arguments); // case ListCommand.COMMAND_WORD: // return new ListCommand(); // case ExitCommand.COMMAND_WORD: // return new ExitCommand(); // case HelpCommand.COMMAND_WORD: // return new HelpCommand(); // default: // return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } }
package ui.components; import javafx.scene.input.KeyCode; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Optional; import java.util.function.IntConsumer; /** * A very specialized ListView subclass that: * * - can be navigated with the arrow keys and Enter * - supports an event for item selection * - provides methods for retaining selection after its contents are changed * * It depends on the functionality of ScrollableListView to ensure that * navigation scrolls the list properly. The Up, Down, and Enter key events * should not be separately bound on it. * * An item is considered selected when: * * - it is highlighted with the arrow keys, but only when the Shift key is not down * - Enter is pressed when it is highlighted * - it is clicked */ public class NavigableListView<T> extends ScrollableListView<T> { private static final Logger logger = LogManager.getLogger(NavigableListView.class.getName()); // Tracks the index of the list which should be currently selected private Optional<Integer> selectedIndex = Optional.empty(); // Used for saving and restoring selection. // selectedIndex should be used to get the currently-selected item, through the provided getter. private Optional<T> lastSelectedItem = Optional.empty(); // Indicates that saveSelection was called, in the event that saveSelection itself fails // (when nothing is selected, both should be no-ops) private boolean saveSelectionCalled = false; private IntConsumer onItemSelected = i -> {}; public NavigableListView() { setupKeyEvents(); setupMouseEvents(); } /** * Should be called before making changes to the item list of this list view if * it's important that selection is retained after. */ public void saveSelection() { if (getSelectionModel().getSelectedItem() != null) { lastSelectedItem = Optional.of(getSelectionModel().getSelectedItem()); } saveSelectionCalled = true; } public void restoreSelection() { if (!lastSelectedItem.isPresent()) { if (!saveSelectionCalled) { throw new IllegalStateException("saveSelection must be called before restoreSelection"); } else { saveSelectionCalled = false; return; // No-op } } saveSelectionCalled = false; // Find index of previously-selected item int index = -1; int i = 0; for (T item : getItems()) { if (item.equals(lastSelectedItem.get())) { index = i; break; } i++; } boolean itemFound = index > -1; if (itemFound) { // Select that item getSelectionModel().clearAndSelect(index); selectedIndex = Optional.of(index); // Do not trigger event; selection did not conceptually change } else { // The item disappeared if (getItems().size() == 0) { // No more items in the list selectedIndex = Optional.empty(); } else { // The list is non-empty, so we can be sure that we're selecting something // The current index is the same as the next, due to the item disappearing int lastIndex = getItems().size() - 1; int nextIndex = Math.min(selectedIndex.get(), lastIndex); getSelectionModel().clearAndSelect(nextIndex); selectedIndex = Optional.of(nextIndex); // The next item will be considered selected onItemSelected.accept(nextIndex); } } } private void setupMouseEvents() { setOnMouseClicked(e -> { int currentlySelected = getSelectionModel().getSelectedIndex(); // The currently-selected index is sometimes -1 when an issue is clicked. // When this happens we ignore this event. if (currentlySelected != -1) { selectedIndex = Optional.of(currentlySelected); logger.info("Mouse click on issue " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } }); } private void setupKeyEvents() { setOnKeyPressed(e -> { if (e.isControlDown()){ return; } switch (e.getCode()) { case UP: case T: case DOWN: case V: e.consume(); handleUpDownKeys(e.getCode() == KeyCode.DOWN || e.getCode() == KeyCode.V); assert selectedIndex.isPresent() : "handleUpDownKeys doesn't set selectedIndex!"; if (!e.isShiftDown()) { logger.info("Arrow key navigation to issue " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } break; case ENTER: e.consume(); if (selectedIndex.isPresent()) { logger.info("Enter key selection on issue " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } break; default: break; } }); } private void handleUpDownKeys(boolean isDownKey) { // Nothing is selected or the list is empty; do nothing if (!selectedIndex.isPresent()) return; if (getItems().size() == 0) return; // Compute new index and clamp it within range int newIndex = selectedIndex.get() + (isDownKey ? 1 : -1); newIndex = Math.min(Math.max(0, newIndex), getItems().size()-1); // Update selection state and our selection model getSelectionModel().clearAndSelect(newIndex); selectedIndex = Optional.of(newIndex); // Ensure that the newly-selected item is in view scrollAndShow(newIndex); } public void setOnItemSelected(IntConsumer callback) { onItemSelected = callback; } public void selectFirstItem(){ requestFocus(); if (getItems().size() == 0) return; getSelectionModel().clearAndSelect(0); scrollAndShow(0); selectedIndex = Optional.of(0); onItemSelected.accept(selectedIndex.get()); } public Optional<T> getSelectedItem() { return selectedIndex.map(getItems()::get); } }
package uk.ac.ebi.pride.px; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.pride.data.exception.SubmissionFileException; import uk.ac.ebi.pride.data.io.SubmissionFileParser; import uk.ac.ebi.pride.data.model.*; import uk.ac.ebi.pride.data.util.MassSpecFileType; import uk.ac.ebi.pride.px.Reader.DBController; import uk.ac.ebi.pride.px.model.*; import uk.ac.ebi.pride.px.model.Contact; import uk.ac.ebi.pride.px.model.CvParam; import uk.ac.ebi.pride.px.xml.PxMarshaller; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; public class WriteMessage { private static DBController dbac; private static PxMarshaller marshaller; private static final String FORMAT_VERSION = "1.0.0"; //name of the file containing the summary of the submission private static final String SUBMISSION_SUMMARY_FILE = "submission.px"; private static final Logger logger = LoggerFactory.getLogger(WriteMessage.class); //this list will store the contact emails present in the file, so we don't add them again from DB private static Set<String> contactEmails = new HashSet<String>(); //main method to write a message to ProteomeXChange public WriteMessage(DBController dbController) { dbac = dbController; } //the pxSummaryLocation will indicate where in the filesystem is stored the summary file //to extract some of the information public File createXMLMessage(String pxAccession, File directory, File submissionFile) throws Exception { //first, extract submission file object // File submissionFile = new File(pxSummaryLocation + File.separator + SUBMISSION_SUMMARY_FILE); if (!submissionFile.isFile() || !submissionFile.exists()) { throw new Exception("No submission file in " + submissionFile.getAbsolutePath()); } Submission submissionSummary = SubmissionFileParser.parse(submissionFile); //will return if submission contains only supported files //to extract info from database or not supported files //and extract info from the metadata file boolean submissionSupported = submissionSummary.getMetaData().isSupported(); File file = new File(directory.getAbsolutePath() + File.separator + pxAccession + ".xml"); try { FileWriter fw = new FileWriter(file); marshaller = new PxMarshaller(); ProteomeXchangeDataset proteomeXchangeDataset = new ProteomeXchangeDataset(); //extract DatasetSummary: this information will always come from Summary object DatasetSummary datasetSummary = getDatasetSummary(submissionSummary); proteomeXchangeDataset.setDatasetSummary(datasetSummary); //extract ContactList: this information comes from summary file ContactList contactList = getContactList(submissionSummary); proteomeXchangeDataset.setContactList(contactList); //extract Keyword List from file KeywordList keywordList = getKeywordList(submissionSummary); proteomeXchangeDataset.setKeywordList(keywordList); if (!submissionSupported) { populatePxSubmissionFromFile(proteomeXchangeDataset, submissionSummary, pxAccession); } else { populatePxSubmissionFromDB(proteomeXchangeDataset, pxAccession); } //and add the attributes proteomeXchangeDataset.setId(pxAccession); //TODO: format version will always be hardcoded ?? proteomeXchangeDataset.setFormatVersion(FORMAT_VERSION); //and marshal it marshaller.marshall(proteomeXchangeDataset, fw); } catch (IOException e) { logger.error(e.getMessage(), e); //To change body of catch statement use File | Settings | File Templates. } return file; } //method to retrieve keyword list from the summary file private static KeywordList getKeywordList(Submission submissionSummary) { KeywordList keywordList = new KeywordList(); keywordList.getCvParam().add(createCvParam("MS:1001925", submissionSummary.getMetaData().getKeywords(), "submitter keyword", "MS")); return keywordList; } //method to populate all information in the proteomeXchange dataset from the //summary file private static void populatePxSubmissionFromFile(ProteomeXchangeDataset proteomeXchangeDataset, Submission submissionSummary, String pxAccession) { DatasetIdentifierList datasetIdentifierList = new DatasetIdentifierList(); datasetIdentifierList.getDatasetIdentifier().add(getDatasetIdentifier(submissionSummary, pxAccession)); proteomeXchangeDataset.setDatasetIdentifierList(datasetIdentifierList); //add DataSet info, it is constant right now DatasetOriginList datasetOriginList = new DatasetOriginList(); datasetOriginList.setDatasetOrigin(getDatasetOrigin()); proteomeXchangeDataset.setDatasetOriginList(datasetOriginList); //add species from file SpeciesList speciesList = new SpeciesList(); speciesList.setSpecies(getSpecies(submissionSummary)); proteomeXchangeDataset.setSpeciesList(speciesList); //add instrument from file InstrumentList instrumentList = new InstrumentList(); instrumentList.getInstrument().addAll(getInstrument(submissionSummary)); proteomeXchangeDataset.setInstrumentList(instrumentList); //add modification ModificationList modificationList = new ModificationList(); modificationList.getCvParam().addAll(getModificationCvParams(submissionSummary)); proteomeXchangeDataset.setModificationList(modificationList); //add pubmed information, if present if (submissionSummary.getMetaData().hasPubmedIds()) { PublicationList publicationList = new PublicationList(); publicationList.getPublication().addAll(getPublicationParams(submissionSummary)); proteomeXchangeDataset.setPublicationList(publicationList); } //add dataset link list, data will be in FTP only, so link will refer to files in FTP FullDatasetLinkList fullDatasetLinkList = createFullDatasetLinkList(submissionSummary); proteomeXchangeDataset.setFullDatasetLinkList(fullDatasetLinkList); } //method to extract Publication information from file private static List<Publication> getPublicationParams(Submission submissionSummary) { List<Publication> publications = new ArrayList<Publication>(); for (String pubmedID : submissionSummary.getMetaData().getPubmedIds()) { Publication publication = new Publication(); publication.setId("PMID" + pubmedID); publication.getCvParam().add(createCvParam("MS:1000879", pubmedID, "PubMed identifier", "MS")); publications.add(publication); } return publications; } //method to extract modifications from summary file private static List<CvParam> getModificationCvParams(Submission submissionSummary) { List<CvParam> cvParams = new ArrayList<CvParam>(); for (uk.ac.ebi.pride.data.model.CvParam cvParam : submissionSummary.getMetaData().getModifications()) { cvParams.add(createCvParam(cvParam.getAccession(), cvParam.getValue(), cvParam.getName(), cvParam.getCvLabel())); } return cvParams; } //method to extract instrument information from summary file private static List<Instrument> getInstrument(Submission submissionSummary) { List<Instrument> instruments = new ArrayList<Instrument>(); int instrumentNum = 1; //convert CvParam into px CvParam for (List<uk.ac.ebi.pride.data.model.CvParam> cvParams : submissionSummary.getMetaData().getInstruments()) { Instrument instrument = new Instrument(); instrument.setId("Instrument_" + instrumentNum); instrumentNum++; for (uk.ac.ebi.pride.data.model.CvParam cvParam : cvParams) { instrument.getCvParam().add(createCvParam(cvParam.getAccession(), cvParam.getValue(), cvParam.getName(), cvParam.getCvLabel())); } instruments.add(instrument); } return instruments; } //method to get Species information from summary file private static Species getSpecies(Submission submissionSummary) { Species species = new Species(); //need to create 2 cvParam: one with the NEWT code and one with the name for (uk.ac.ebi.pride.data.model.CvParam cvParam : submissionSummary.getMetaData().getSpecies()) { species.getCvParam().add(createCvParam("MS:1001469", cvParam.getName(), "taxonomy: scientific name", "PSI-MS")); species.getCvParam().add(createCvParam("MS:1001467", cvParam.getAccession(), "taxonomy: NCBI TaxID", "PSI-MS")); } return species; } //method to add Dataset identifier information from file //at the moment, let's not worry about PxAccessions, they refer to previous submissions private static DatasetIdentifier getDatasetIdentifier(Submission submissionSummary, String pxAccession) { //add px number as CvParam DatasetIdentifier px = new DatasetIdentifier(); px.getCvParam().add(createCvParam("MS:1001919", pxAccession, "ProteomeXchange accession number", "MS")); // //add DOI from file if present // if (submissionSummary.getMetaData().hasPxAccessions()){ // for (String accession : submissionSummary.getMetaData().getPxAccessions()) { // px.getCvParam().add(createCvParam("MS:1001922", accession, "Digital Object Identifier (DOI)", "MS")); return px; } private static CvParam createCvParam(String accession, String value, String name, String cvRef) { CvParam cvParam = new CvParam(); cvParam.setAccession(accession); cvParam.setValue(value); cvParam.setName(name); cvParam.setCvRef(cvRef); return cvParam; } //method will get all information for a specific submission from the database and populate //the ProteomeXchangeDataset object with it private static void populatePxSubmissionFromDB(ProteomeXchangeDataset proteomeXchangeDataset, String pxAccession) { //get all experiments in the project List<Long> experimentIDs = dbac.getExperimentIds(pxAccession); if (experimentIDs.isEmpty()) { logger.error("Project contains no experiments"); System.exit(0); } DatasetIdentifierList datasetIdentifierList = dbac.getDatasetIdentifierList(experimentIDs); proteomeXchangeDataset.setDatasetIdentifierList(datasetIdentifierList); DatasetOriginList datasetOriginList = new DatasetOriginList(); datasetOriginList.setDatasetOrigin(getDatasetOrigin()); proteomeXchangeDataset.setDatasetOriginList(datasetOriginList); //extract Species information for all experiments SpeciesList speciesList = dbac.getSpecies(experimentIDs); proteomeXchangeDataset.setSpeciesList(speciesList); //extract instrument information InstrumentList instrumentList = dbac.getInstrumentList(experimentIDs); proteomeXchangeDataset.setInstrumentList(instrumentList); //extract modification list ModificationList modificationList = dbac.getModificationList(experimentIDs); proteomeXchangeDataset.setModificationList(modificationList); //extract contact list that are not present already in the file ContactList newContactList = dbac.getContactList(experimentIDs, contactEmails); ContactList contactList = proteomeXchangeDataset.getContactList(); //add contacts from DB contactList.getContact().addAll(newContactList.getContact()); proteomeXchangeDataset.setContactList(contactList); //extract publicationList PublicationList publicationList = dbac.getPublicationList(experimentIDs); proteomeXchangeDataset.setPublicationList(publicationList); // KeywordList keywordList = dbac.getKeywordList(experimentIDs); // proteomeXchangeDataset.setKeywordList(keywordList); FullDatasetLinkList datasetLinkList = dbac.getFullDataSetLinkList(experimentIDs); if (!datasetLinkList.getFullDatasetLink().isEmpty()) { proteomeXchangeDataset.setFullDatasetLinkList(datasetLinkList); } //TODO: no DatasetFileList, where are the raw files stored? // create RepositoryRecordList with all experiments in project RepositoryRecordList repositoryRecordList = new RepositoryRecordList(); for (long experimentID : experimentIDs) { //get new record RepositoryRecord repositoryRecord = dbac.getRepositoryRecord(experimentID); //we now need to add the additional elements to the record: source, publication, instrument, sample, modification //TODO; need to deal with source file, where are they ?? //TODO: an experiment can have more than 1 publication or more than 1 instrument ?? Ref publicationRef = dbac.getRef("publication", experimentID); repositoryRecord.getPublicationRef().add(publicationRef); Ref instrumentRef = dbac.getRef("instrument", experimentID); repositoryRecord.getInstrumentRef().add(instrumentRef); SampleList sampleList = dbac.getSampleList(experimentID); repositoryRecord.getSampleList().add(sampleList); //and the modificationList List<Long> expId = new ArrayList<Long>(); //need to create a list with 1 element for the method expId.add(experimentID); modificationList = dbac.getModificationList(expId); repositoryRecord.setModificationList(modificationList); repositoryRecordList.getRepositoryRecord().add(repositoryRecord); } proteomeXchangeDataset.setRepositoryRecordList(repositoryRecordList); } //TODO: DatasetOriginList, at the moment, it is hardcoded, all are new submissions //might change in future private static DatasetOrigin getDatasetOrigin() { DatasetOrigin datasetOrigin = new DatasetOrigin(); CvParam cvParam = new CvParam(); cvParam.setAccession("PRIDE:0000402"); cvParam.setName("Original data"); cvParam.setCvRef("PRIDE"); datasetOrigin.getCvParam().add(cvParam); return datasetOrigin; } //helper method to return DatasetLink private static FullDatasetLinkList createFullDatasetLinkList(Submission submissionSummary) { FullDatasetLinkList fullDatasetLinkList = new FullDatasetLinkList(); //for each of the result files, add it to the DatasetLinkList for (DataFile dataFile : submissionSummary.getDataFiles()) { if (dataFile.getFileType().equals(MassSpecFileType.RESULT)) { FullDatasetLink fullDatasetLink = new FullDatasetLink(); CvParam datasetLinkParam = createCvParam("PRIDE:0000411", dataFile.getFile().getAbsolutePath(), "Dataset FTP location", "PRIDE"); fullDatasetLink.setCvParam(datasetLinkParam); fullDatasetLinkList.getFullDatasetLink().add(fullDatasetLink); } } return fullDatasetLinkList; } //this information will come from the summary file private static DatasetSummary getDatasetSummary(Submission submissionSummary) { DatasetSummary datasetSummary = new DatasetSummary(); datasetSummary.setTitle(submissionSummary.getMetaData().getTitle()); datasetSummary.setDescription(submissionSummary.getMetaData().getDescription()); datasetSummary.setAnnounceDate(Calendar.getInstance()); datasetSummary.setHostingRepository(HostingRepositoryType.PRIDE); //add Review level, depending wether has a pubmed or not ReviewLevelType reviewLevelType = addReviewLevel(submissionSummary); datasetSummary.setReviewLevel(reviewLevelType); //add Repository Support level, depending if files are supported or not RepositorySupportType repositorySupportType = addRepositorySupport(submissionSummary); datasetSummary.setRepositorySupport(repositorySupportType); return datasetSummary; } //helper method to retrieve Repository support, either submission is supported or non supported at the moment private static RepositorySupportType addRepositorySupport(Submission submissionSummary) { RepositorySupportType repositorySupportType = new RepositorySupportType(); CvParam repositorySupport; if (submissionSummary.getMetaData().isSupported()) { repositorySupport = createCvParam("PRIDE:0000416", null, "Supported dataset by repository", "PRIDE"); } else { repositorySupport = createCvParam("PRIDE:0000417", null, "Unsupported dataset by repository", "PRIDE"); } repositorySupportType.setCvParam(repositorySupport); return repositorySupportType; } //helper method to retrieve reviewLeveltype, either peered or non-peered at the moment private static ReviewLevelType addReviewLevel(Submission submissionSummary) { ReviewLevelType reviewLevelType = new ReviewLevelType(); CvParam reviewLevel; if (submissionSummary.getMetaData().hasPubmedIds()) { reviewLevel = createCvParam("PRIDE:0000414", null, "Peer-reviewed dataset", "PRIDE"); } else { reviewLevel = createCvParam("PRIDE:0000415", null, "Non peer-reviewed dataset", "PRIDE"); } reviewLevelType.setCvParam(reviewLevel); return reviewLevelType; } //private method to extract the contact list from the summary file private static ContactList getContactList(Submission submissionSummary) { ContactList contactList = new ContactList(); Contact contact = new Contact(); contact.setId(submissionSummary.getContact().getName().replace(' ', '_')); contact.getCvParam().add(createCvParam("MS:1000586", submissionSummary.getContact().getName(), "contact name", "MS")); contact.getCvParam().add(createCvParam("MS:1000589", submissionSummary.getContact().getEmail(), "contact email", "MS")); contactEmails.add(submissionSummary.getContact().getEmail()); contact.getCvParam().add(createCvParam("MS:1000590", submissionSummary.getContact().getAffiliation(), "contact affiliation", "MS")); contactList.getContact().add(contact); return contactList; } }
package mondrian.olap4j; import mondrian.olap.Hierarchy; import mondrian.olap.OlapElement; import mondrian.olap.Role; import org.olap4j.OlapException; import org.olap4j.impl.*; import org.olap4j.metadata.*; import java.util.*; /** * Implementation of {@link org.olap4j.metadata.Schema} * for the Mondrian OLAP engine. * * @author jhyde * @since May 24, 2007 */ class MondrianOlap4jSchema extends MondrianOlap4jMetadataElement implements Schema, Named { final MondrianOlap4jCatalog olap4jCatalog; final String schemaName; final mondrian.olap.Schema schema; /** * Creates a MondrianOlap4jSchema. * * <p>The name of the schema is not necessarily the same as * schema.getName(). If schema was loaded in a datasources.xml file, the * name it was given there (in the &lt;Catalog&gt; element) trumps the name * in the catalog.xml file. * * @param olap4jCatalog Catalog containing schema * @param schemaName Name of schema * @param schema Mondrian schema */ MondrianOlap4jSchema( MondrianOlap4jCatalog olap4jCatalog, String schemaName, mondrian.olap.Schema schema) { this.olap4jCatalog = olap4jCatalog; this.schemaName = schemaName; this.schema = schema; } public Catalog getCatalog() { return olap4jCatalog; } public NamedList<Cube> getCubes() throws OlapException { NamedList<MondrianOlap4jCube> list = new NamedListImpl<MondrianOlap4jCube>(); final MondrianOlap4jConnection olap4jConnection = olap4jCatalog.olap4jDatabaseMetaData.olap4jConnection; for (mondrian.olap.Cube cube : olap4jConnection.getMondrianConnection() .getSchemaReader().getCubes()) { if(cube.isVisible()) { list.add(olap4jConnection.toOlap4j(cube)); } } return Olap4jUtil.cast(list); } public NamedList<Dimension> getSharedDimensions() throws OlapException { final MondrianOlap4jConnection olap4jConnection = olap4jCatalog.olap4jDatabaseMetaData.olap4jConnection; final SortedSet<MondrianOlap4jDimension> dimensions = new TreeSet<MondrianOlap4jDimension>( new Comparator<MondrianOlap4jDimension>() { public int compare( MondrianOlap4jDimension o1, MondrianOlap4jDimension o2) { return o1.getName().compareTo(o2.getName()); } } ); final Role role = olap4jConnection.getMondrianConnection().getRole(); for (Hierarchy hierarchy : schema.getSharedHierarchies()) { if (role.canAccess(hierarchy)) { dimensions.add( olap4jConnection.toOlap4j(hierarchy.getDimension())); } } NamedList<MondrianOlap4jDimension> list = new NamedListImpl<MondrianOlap4jDimension>(); list.addAll(dimensions); return Olap4jUtil.cast(list); } public Collection<Locale> getSupportedLocales() throws OlapException { return Collections.emptyList(); } public String getName() { return schemaName; } /** * Shorthand for catalog.database.connection.getLocale(). * Not part of the olap4j api; do not make public. * * @return Locale of current connection */ final Locale getLocale() { return olap4jCatalog.olap4jDatabase.getOlapConnection().getLocale(); } protected OlapElement getOlapElement() { return null; } } // End MondrianOlap4jSchema.java
package mondrian.rolap.agg; import mondrian.rolap.RolapStar; import mondrian.rolap.StarColumnPredicate; import mondrian.rolap.StarPredicate; import mondrian.rolap.sql.SqlQuery; import java.util.List; /** * Definition of a query which retrieves a single cell with a complex * combination of predicates. * * <p>It is typically used to retrieve the value of a cell whose measure is * distinct-count (or another aggregate which cannot be rolled up) * and whose context contains one or more compound measures. * * <p>For example, given an eval context with a compound member: * * <blockquote><pre> * [Measures].[Customer Count] * [Time].[1997].[Q1] * [Store Type].[All Store Types] * Aggregate({[Store].[USA].[CA], [Store].[USA].[OR].[Portland]}) * ... everything else 'all' * </pre></blockquote> * * we want to generate the SQL * * <blockquote><pre> * SELECT COUNT(DISTINCT cust_id) * FROM sales_fact_1997 AS sales, store, time * WHERE store.store_id = sales.store_id * AND time.time_id = sales.time_id * AND time.year = 1997 * AND time.quarter = 'Q1' * AND (store.store_state ='USA' * AND ( store.store_state = 'CA' * OR ( store.store_state = 'OR' * AND store.store_City = 'Portland'))) * </pre></blockquote> * * <p>Note that because the members in the Store hierarchy were at * different levels, the WHERE clause contains an AND of an OR of an AND. * * @author jhyde * @version $Id$ */ public class CompoundQuerySpec extends AbstractQuerySpec { private final RolapStar.Measure measure; private final RolapStar.Column[] columns; private final List<StarColumnPredicate> columnPredicateList; private final List<StarPredicate> predicateList; CompoundQuerySpec( RolapStar.Measure measure, RolapStar.Column[] columns, List<StarColumnPredicate> columnPredicateList, List<StarPredicate> predicateList) { // It's a bit of a stretch to extend SegmentArrayQuerySpec. We inherit // a few of the methods, but we don't use the data members. super(measure.getStar(), true); this.measure = measure; this.columns = columns; this.columnPredicateList = columnPredicateList; this.predicateList = predicateList; } public int getMeasureCount() { return 1; } protected boolean isAggregate() { return true; } public RolapStar.Measure getMeasure(final int i) { assert i == 0; return measure; } public String getMeasureAlias(final int i) { return "c"; } public String getColumnAlias(int i) { throw new UnsupportedOperationException(); } public RolapStar.Column[] getColumns() { return columns; } public StarColumnPredicate getColumnPredicate(final int i) { return columnPredicateList.get(i); } protected List<StarPredicate> getPredicateList() { return predicateList; } protected void nonDistinctGenerateSql(SqlQuery sqlQuery) { // add constraining dimensions int arity = columns.length; addMeasure(0, sqlQuery); for (int i = 0; i < arity; i++) { RolapStar.Column column = columns[i]; RolapStar.Table table = column.getTable(); if (table.isFunky()) { // this is a funky dimension -- ignore for now continue; } table.addToFrom(sqlQuery, false, true); String expr = column.generateExprString(sqlQuery); final StarColumnPredicate predicate = columnPredicateList.get(i); final String where = RolapStar.Column.createInExpr( expr, predicate, column.getDatatype(), sqlQuery); if (!where.equals("true")) { sqlQuery.addWhere(where); } } extraPredicates(sqlQuery); } public static String compoundGenerateSql( RolapStar.Measure measure, RolapStar.Column[] columns, List<StarColumnPredicate> columnPredicateList, List<StarPredicate> predicateList) { final CompoundQuerySpec querySpec = new CompoundQuerySpec( measure, columns, columnPredicateList, predicateList); return querySpec.generateSqlQuery(); } } // End CompoundQuerySpec.java
package org.codehaus.groovy.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Properties; /** * Exposes the Groovy release information * * @author Roshan Dawrani */ public class ReleaseInfo { private static Properties releaseInfo = new Properties(); private static String RELEASE_INFO_FILE = "META-INF/groovy-release-info.properties"; private static String KEY_IMPLEMENTATION_VERSION = "ImplementationVersion"; private static String KEY_BUNDLE_VERSION = "BundleVersion"; private static String KEY_BUILD_DATE = "BuildDate"; private static String KEY_BUILD_TIME = "BuildTime"; private static boolean loaded = false; public static String getVersion() { return get(KEY_IMPLEMENTATION_VERSION); } public static Properties getAllProperties() { loadInfo(); return releaseInfo; } private static String get(String propName) { loadInfo(); String propValue = releaseInfo.getProperty(propName); return (propValue == null ? "" : propValue); } private static void loadInfo() { if(!loaded) { URL url = null; ClassLoader cl = ReleaseInfo.class.getClassLoader(); // we need no security check for getting the system class // loader since if we do the invoker has a null loader, // in which case no security check will be done if (cl==null) cl = ClassLoader.getSystemClassLoader(); if (cl instanceof URLClassLoader) { // this avoids going through the parent classloaders/bootstarp url = ((URLClassLoader) cl).findResource(RELEASE_INFO_FILE); } else { // fallback option as ClassLoader#findResource() is protected url = cl.getResource(RELEASE_INFO_FILE); } if (url!=null) { try { InputStream is = url.openStream(); if(is != null) { releaseInfo.load(is); } } catch(IOException ioex) { // ignore. In case of some exception, release info is not available } } loaded = true; } } }
package au.csiro.ontology; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * Represents a node in the taxonomy generated after classifying an ontology. * * @author Alejandro Metke * */ public class Node<T extends Comparable<T>> implements Serializable { private static final long serialVersionUID = 1L; /** * Set of equivalent concepts in this node. */ protected final Set<T> equivalentConcepts = new HashSet<>(); /** * Set of parents nodes. */ protected final Set<Node<T>> parents = new HashSet<>(); /** * Set of child nodes. */ protected final Set<Node<T>> children = new HashSet<>(); /** * @return the equivalentConcepts */ public Set<T> getEquivalentConcepts() { return equivalentConcepts; } /** * @return the parents */ public Set<Node<T>> getParents() { return parents; } /** * @return the children */ public Set<Node<T>> getChildren() { return children; } @Override public String toString() { StringBuilder sb = new StringBuilder(); int size = equivalentConcepts.size(); int i = 0; sb.append("{"); for (T equiv : equivalentConcepts) { sb.append(equiv); if (++i < size) sb.append(", "); } sb.append("}"); return sb.toString(); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((equivalentConcepts == null) ? 0 : equivalentConcepts .hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @SuppressWarnings("rawtypes") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Node other = (Node) obj; if (equivalentConcepts == null) { if (other.equivalentConcepts != null) return false; } else if (!equivalentConcepts.equals(other.equivalentConcepts)) return false; return true; } }
// RMG - Reaction Mechanism Generator // RMG Team (rmg_dev@mit.edu) // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. package jing.chem; import java.io.*; import java.util.*; import jing.chemUtil.*; import jing.chemParser.*; import jing.chemUtil.HierarchyTree; import jing.rxnSys.Logger; //## package jing::chem // jing\chem\ThermoGAGroupLibrary.java /** There are six libraries: (1) group (2) radical (3) ring correction (4) other correction (5) gauche correction (6) 1,5 correction In each library, the key should be functional group (name + adjList), and the value should be ThermoGAValue. for (2), (3), (4), we scan the library to find match between chemgraph and functional group each time. search time O(n), where n is the library size. for (1), we first match chemgraph with a tree structure to find out the proper functional group, and then access the library by the key functional group, so the search tiem is O(1) + O(logN), where N is the tree size. */ //## class ThermoGAGroupLibrary public class ThermoGAGroupLibrary { protected static ThermoGAGroupLibrary INSTANCE = new ThermoGAGroupLibrary(); //## attribute INSTANCE protected HashMap groupDictionary; //## attribute groupDictionary protected HashMap groupLibrary; //## attribute groupLibrary /** Note: this kind of tree is different with the kinetics tree. In kinetics tree, tree nodes are FunctionalGroup or FunctionalGroupCollection. In thermo tree, tree nodes are Nodes with connectivity, */ protected HierarchyTree groupTree; //## attribute groupTree protected HashMap otherDictionary; //## attribute otherDictionary protected HashMap otherLibrary; //## attribute otherLibrary protected HierarchyTree otherTree; //## attribute otherTree protected HashMap radicalDictionary; //## attribute radicalDictionary protected HashMap radicalLibrary; //## attribute radicalLibrary protected HierarchyTree radicalTree; //## attribute radicalTree protected HierarchyTree ringTree; protected HashMap ringDictionary; protected HashMap ringLibrary; //## attribute ringLibrary protected HashMap gaucheDictionary; protected HashMap gaucheLibrary; protected HierarchyTree gaucheTree; protected HashMap oneFiveDictionary; protected HashMap oneFiveLibrary; protected HierarchyTree oneFiveTree; protected HashMap abramDictionary; protected HashMap abramLibrary; protected HierarchyTree abramTree; protected HashMap abramradDictionary; protected HashMap abramradLibrary; protected HierarchyTree abramradTree; protected HashMap unifacDictionary; protected HashMap unifacLibrary; protected HierarchyTree unifacTree; private HierarchyTree polycylicTree; private HashMap polycyclicDictionary; private HashMap polycyclicLibrary; //protected HashMap solventDictionary; //protected HashMap solventLibrary; // Constructors //## operation ThermoGAGroupLibrary() private ThermoGAGroupLibrary() { groupTree = new HierarchyTree(); groupDictionary = new HashMap(); groupLibrary = new HashMap(); radicalTree = new HierarchyTree(); radicalDictionary = new HashMap(); radicalLibrary = new HashMap(); ringLibrary = new HashMap(); ringDictionary = new HashMap(); ringTree = new HierarchyTree(); otherLibrary = new HashMap(); otherDictionary = new HashMap(); otherTree = new HierarchyTree(); gaucheLibrary = new HashMap(); gaucheDictionary = new HashMap(); gaucheTree = new HierarchyTree(); oneFiveLibrary = new HashMap(); oneFiveDictionary = new HashMap(); oneFiveTree = new HierarchyTree(); abramLibrary= new HashMap(); abramDictionary=new HashMap(); abramTree=new HierarchyTree(); abramradLibrary= new HashMap(); abramradDictionary=new HashMap(); abramradTree=new HierarchyTree(); unifacLibrary= new HashMap(); unifacDictionary=new HashMap(); unifacTree=new HierarchyTree(); polycyclicLibrary = new HashMap(); polycyclicDictionary = new HashMap(); polycylicTree = new HierarchyTree(); // solventDictionary=new HashMap(); // solventLibrary=new HashMap(); String directory = System.getProperty("jing.chem.ThermoGAGroupLibrary.pathName"); if (directory == null) { Logger.critical("undefined system property: jing.chem.ThermoGAGroupLibrary.pathName, exit!"); System.exit(0); } String separator = System.getProperty("file.separator"); if (!directory.endsWith(separator)) directory = directory + separator; Logger.info("\nReading thermo database from "+directory); String gDictionary = directory + "Group_Dictionary.txt"; String gTree = directory + "Group_Tree.txt"; String gLibrary = directory + "Group_Library.txt"; String rDictionary = directory + "Radical_Dictionary.txt"; String rTree = directory + "Radical_Tree.txt"; String rLibrary = directory + "Radical_Library.txt"; String ringDictionary = directory + "Ring_Dictionary.txt"; String ringTree = directory + "Ring_Tree.txt"; String ringLibrary = directory + "Ring_Library.txt"; String otherLibrary = directory + "Other_Library.txt"; String otherDictionary = directory + "Other_Dictionary.txt"; String otherTree = directory + "Other_Tree.txt"; String gauDictionary = directory + "Gauche_Dictionary.txt"; String gauTree = directory + "Gauche_Tree.txt"; String gauLibrary = directory + "Gauche_Library.txt"; String one5Dictionary = directory + "15_Dictionary.txt"; String one5Tree = directory + "15_Tree.txt"; String one5Library = directory + "15_Library.txt"; String AbDictionary=directory+"Abraham_Dictionary.txt"; String AbTree=directory+"Abraham_Tree.txt"; String AbLibrary=directory+"Abraham_Library.txt"; //Added by Amrit Jalan on December 13, 2010 String AbradDictionary=directory+"Abraham_Radical_Dictionary.txt"; String AbradTree=directory+"Abraham_Radical_Tree.txt"; String AbradLibrary=directory+"Abraham_Radical_Library.txt"; String UnDictionary=directory+"Unifac_Dictionary.txt"; String UnTree=directory+"Unifac_Tree.txt"; String UnLibrary=directory+"Unifac_Library.txt"; String PolycyclicDictionary=directory+"Polycyclic_Dictionary.txt"; String PolycyclicTree=directory+"Polycyclic_Tree.txt"; String PolycyclicLibrary=directory+"Polycyclic_Library.txt"; //String solventdict=directory+"Solvent_Dictionary.txt"; //String solventlib=directory+"Solvent_Library.txt"; read(gDictionary,gTree,gLibrary,rDictionary,rTree,rLibrary,ringDictionary,ringTree,ringLibrary,otherDictionary,otherLibrary,otherTree,gauDictionary,gauTree,gauLibrary,one5Dictionary,one5Tree,one5Library,AbDictionary,AbTree,AbLibrary,UnDictionary,UnTree,UnLibrary,AbradDictionary,AbradTree,AbradLibrary, PolycyclicDictionary,PolycyclicTree,PolycyclicLibrary); } //## operation findCorrectionInLibrary(ChemGraph,HashMap) private ThermoData findCorrectionInLibrary(ChemGraph p_chemGraph, HashMap p_library) { //#[ operation findCorrectionInLibrary(ChemGraph,HashMap) p_chemGraph.clearCentralNode(); ThermoData result=new ThermoData(); int redundance; Iterator iter = p_library.keySet().iterator(); while (iter.hasNext()) { redundance = 0; FunctionalGroup f = (FunctionalGroup)iter.next(); HashSet gv = p_chemGraph.identifyThermoMatchedSite(f); if (gv != null) { redundance = gv.size(); if (redundance > 0) { ThermoGAValue ga = (ThermoGAValue)p_library.get(f); if (ga != null) { ThermoData temp = new ThermoData(ga); temp.multiply(redundance); result.plus(temp); temp = null; } } } } p_chemGraph.getGraph().resetMatchedGC(); return result; // } /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ //## operation findGAGroup(ChemGraph) public ThermoGAValue findGAGroup(ChemGraph p_chemGraph) throws GroupNotFoundException, MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = groupTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC();//2/13/09 gmagoon: resetting the matched GC value...for some reason, thermoLibrary.findGAGroup (within getGAGroup in GATP.java) ended up modifiying the central node so that it was matched; this ended up wreaking havoc with subsequent symmetry number calculations; ideally, I would probably want to fix the code so that it didn't end up modifying the matchedGC from the null value after it is done with it, but I do not immediately see how to due so, and debugging proved extremely difficult; I have also tried to put this elsewhere in this class where it might be appropriate if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)groupLibrary.get(fg); p_chemGraph.appendThermoComments("Group:" + fg.getName()); if (ga != null) //System.out.println("Group found: " + fg.getName()); return ga; } return null; // } //## operation findOtherCorrection(ChemGraph) public ThermoGAValue findOtherCorrection(ChemGraph p_chemGraph) { //#[ operation findOtherCorrection(ChemGraph) if (p_chemGraph == null) return null; Stack stack = otherTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); FunctionalGroup fg = (FunctionalGroup)node.getElement(); ThermoGAValue ga = (ThermoGAValue)otherLibrary.get(fg); p_chemGraph.appendThermoComments("Other:" + fg.getName()); if (ga != null) return ga; } return null; // } //## operation findRadicalGroup(ChemGraph) public ThermoGAValue findRadicalGroup(ChemGraph p_chemGraph) throws InvalidThermoCenterException { //#[ operation findRadicalGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = radicalTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)radicalLibrary.get(fg); p_chemGraph.appendThermoComments("Radical:" + fg.getName()); if (ga != null) return ga; } return null; // } //## operation findRingCorrection(ChemGraph) public Map<ThermoGAValue, Integer> findRingCorrections(ChemGraph p_chemGraph) { if (p_chemGraph == null) return null; Set<Node> fusedRingAtoms = p_chemGraph.getGraph().getFusedRingAtoms(); if(fusedRingAtoms != null){ p_chemGraph.appendThermoComments("!Fused Ring System!\n"); p_chemGraph.appendThermoComments("!Additive ring strain corrections might not be accurate!\n"); } List<Set<Node>> ringNodes = p_chemGraph.getGraph().getCycleNodes(); if(ringNodes == null){ Logger.error("Could not find ring nodes in graph."); return null; } else{ Map<Stack, Integer> deepestStackMap = null; deepestStackMap = new HashMap<Stack, Integer>(); for(Set<Node> set : ringNodes){ int deepest = -1; Stack dummy = null; Iterator iterNodes = set.iterator(); while(iterNodes.hasNext()){ //take first atom in this ring: Node node = (Node)iterNodes.next(); Atom atom = (Atom)node.getElement(); // make the current node the central atom p_chemGraph.resetThermoSite(node); // find the match in the thermo tree Stack stack = ringTree.findMatchedPath(p_chemGraph); // check if it's the deepest match if (!stack.empty()) { HierarchyTreeNode htn = (HierarchyTreeNode) stack.peek(); if (htn.getDepth() > deepest) { //we have found a Stack that is deeper than the previous ones, re-initialize Set: dummy = stack; deepest = htn.getDepth(); } } } if(deepestStackMap.containsKey(dummy)){ deepestStackMap.put(dummy, deepestStackMap.get(dummy)+1); } else{ deepestStackMap.put(dummy,1); } } if (deepestStackMap.keySet().isEmpty()) return null; //determine ThermoGAValues: Map<ThermoGAValue, Integer> GAMap = new HashMap<ThermoGAValue, Integer>(); for(Stack element : deepestStackMap.keySet()){ HierarchyTreeNode node = (HierarchyTreeNode)element.pop(); FunctionalGroup fg = (FunctionalGroup)node.getElement(); ThermoGAValue ga = (ThermoGAValue)ringLibrary.get(fg); p_chemGraph.appendThermoComments("!Ring:" + fg.getName()); if (ga != null) { if(GAMap.containsKey(ga)){ GAMap.put(ga, GAMap.get(ga)+1); } else{ GAMap.put(ga,1); } } } p_chemGraph.getGraph().resetMatchedGC(); if(GAMap.isEmpty()){ return null; } else{ return GAMap; } } } //2/5/09 gmagoon: new functions for gauche and 1,5-interactions /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ public ThermoGAValue findGaucheGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = gaucheTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)gaucheLibrary.get(fg); p_chemGraph.appendThermoComments("Gauche:" + fg.getName()); if (ga != null) return ga; } return null; } /** Requires: the central node of p_chemGraph has been set to the thermo center atom. Effects: find a matched thermo functional group in the group tree for the pass-in p_chemGraph, return this functional group's thermo value. If no leaf is found, throw GroupNotFoundException Modifies: */ public ThermoGAValue find15Group(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = oneFiveTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)oneFiveLibrary.get(fg); p_chemGraph.appendThermoComments("1,5:" + fg.getName()); if (ga != null) return ga; } return null; } public AbrahamGAValue findAbrahamGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = abramTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); AbrahamGAValue ga = (AbrahamGAValue)abramLibrary.get(fg); if (ga != null) { //System.out.println("Platts Group found: " + fg.getName()); return ga; } } return null; } //Added by Amrit Jalan on December 13, 2010 public AbrahamGAValue findAbrahamradGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findRadicalGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = abramradTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); AbrahamGAValue ga = (AbrahamGAValue)abramradLibrary.get(fg); if (ga != null) return ga; } return null; } public UnifacGAValue findUnifacGroup(ChemGraph p_chemGraph) throws MultipleGroupFoundException, InvalidCenterTypeException { //#[ operation findGAGroup(ChemGraph) if (p_chemGraph == null) return null; Stack stack = unifacTree.findMatchedPath(p_chemGraph); p_chemGraph.getGraph().resetMatchedGC(); if (stack == null) return null; while (!stack.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)stack.pop(); Matchable fg = (Matchable)node.getElement(); UnifacGAValue ga = (UnifacGAValue)unifacLibrary.get(fg); if (ga != null) { //System.out.println("Unifac Group found: " + fg.getName()); return ga; } } return null; } //## operation read(String,String,String,String,String,String,String,String,String) public void read(String p_groupDictionary, String p_groupTree, String p_groupLibrary, String p_radicalDictionary, String p_radicalTree, String p_radicalLibrary, String p_ringDictionary, String p_ringTree, String p_ringLibrary, String p_otherDictionary, String p_otherLibrary, String p_otherTree, String p_gaucheDictionary, String p_gaucheTree, String p_gaucheLibrary, String p_15Dictionary, String p_15Tree, String p_15Library,String p_abramDictionary,String p_abramTree,String p_abramLibrary,String p_unifacDictionary,String p_unifacTree,String p_unifacLibrary,String p_abramradDictionary,String p_abramradTree,String p_abramradLibrary, String polycyclicDictionary,String polycyclicTree,String polycyclicLibrary) { //,String p_solventDictionary,String p_solventLibrary) { // step 1: read in GA Groups Logger.info("Reading thermochemistry groups"); // read thermo functional Group dictionary readGroupDictionary(p_groupDictionary); // read thermo functional Group tree structure readGroupTree(p_groupTree); // read group values readGroupLibrary(p_groupLibrary); // step 2: read in Radical Corrections Logger.info("Reading radical correction groups"); // read radical dictionary readRadicalDictionary(p_radicalDictionary); // read radical tree readRadicalTree(p_radicalTree); // read radical value readRadicalLibrary(p_radicalLibrary); // step 3: read in Ring Correction Logger.info("Reading ring correction groups"); readRingDictionary(p_ringDictionary); readRingTree(p_ringTree); readRingLibrary(p_ringLibrary); // step 4: read in Other Correction Logger.info("Reading other correction groups"); readOtherDictionary(p_otherDictionary); readOtherLibrary(p_otherLibrary); readOtherTree(p_otherTree); // step 5: read in Gauche and 15 Correction libraries Logger.info("Reading gauche and 1/5 correction groups"); readGaucheDictionary(p_gaucheDictionary); readGaucheTree(p_gaucheTree); readGaucheLibrary(p_gaucheLibrary); read15Dictionary(p_15Dictionary); read15Tree(p_15Tree); read15Library(p_15Library); if (Species.useSolvation) { // Definitions of Platts dictionary, library and tree for Abraham Model Implementation Logger.info("Reading Abraham solvation groups"); readAbrahamDictionary(p_abramDictionary); readAbrahamTree(p_abramTree); readAbrahamLibrary(p_abramLibrary); Logger.info("Reading Abraham radical solvation groups"); readAbrahamradDictionary(p_abramradDictionary); readAbrahamradTree(p_abramradTree); readAbrahamradLibrary(p_abramradLibrary); /* We no longer need UNIFAC groups, and loading them reports some errors, so let's not bother. Logger.info("Reading UNIFAC solvation groups"); readUnifacDictionary(p_unifacDictionary); readUnifacTree(p_unifacTree); readUnifacLibrary(p_unifacLibrary); */ } // step 6: read in Polyclic ring libraries Logger.info("Reading polycyclic groups"); readPolycyclicDictionary(polycyclicDictionary); readPolycyclicTree(polycyclicTree); readPolycyclicLibrary(polycyclicLibrary); } private void readPolycyclicTree(String polycyclicTree2) { try { polycylicTree = readStandardTree(polycyclicTree2,polycyclicDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read polycylic tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } private void readPolycyclicLibrary(String polycyclicLibrary2) { try { polycyclicLibrary = readStandardLibrary(polycyclicLibrary2, polycyclicDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read polycylic library!"); System.exit(0); } } private void readPolycyclicDictionary(String polycyclicDictionary2) { try { polycyclicDictionary = readStandardDictionary(polycyclicDictionary2); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read polyclic dictionary!"); System.exit(0); } } //## operation readGroupDictionary(String) public void readGroupDictionary(String p_fileName) { //#[ operation readGroupDictionary(String) try { groupDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read group dictionary!"); System.exit(0); } // } //## operation readGroupLibrary(String) public void readGroupLibrary(String p_fileName) { try { groupLibrary = readStandardLibrary(p_fileName, groupDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Group Library!"); System.exit(0); } } //## operation readGroupTree(String) public void readGroupTree(String p_fileName) { try { groupTree = readStandardTree(p_fileName,groupDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo group tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readOtherDictionary(String) public void readOtherDictionary(String p_fileName) { try { otherDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read other dictionary!"); System.exit(0); } } //## operation readOtherLibrary(String) public void readOtherLibrary(String p_fileName) { try { otherLibrary = readStandardLibrary(p_fileName, otherDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Other Library!"); System.exit(0); } } //## operation readOtherTree(String) public void readOtherTree(String p_fileName) { try { otherTree = readStandardTree(p_fileName,otherDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo Other tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //2/5/09 gmagoon: new functions for gauche and 1,5 correction reading (based on analogs for regular values, e.g. readGroupDictionary) public void readGaucheDictionary(String p_fileName) { try { gaucheDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read gauche dictionary!"); System.exit(0); } } public void readGaucheLibrary(String p_fileName) { try { gaucheLibrary = readStandardLibrary(p_fileName, gaucheDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read gauche library!"); System.exit(0); } } public void readGaucheTree(String p_fileName) { try { gaucheTree = readStandardTree(p_fileName,gaucheDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read gauche tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } public void readAbrahamDictionary(String p_fileName) { try { abramDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Abraham dictionary!"); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradDictionary(String p_fileName) { try { abramradDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Abraham Radical dictionary!"); System.exit(0); } } public void readUnifacDictionary(String p_fileName) { try { unifacDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read Unifac dictionary!"); System.exit(0); } } public void readAbrahamLibrary(String p_fileName) { try { abramLibrary = readAbramLibrary(p_fileName, abramDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham library!"); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradLibrary(String p_fileName) { try { abramradLibrary = readAbramLibrary(p_fileName, abramradDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham library!"); System.exit(0); } } public void readUnifacLibrary(String p_fileName) { try { unifacLibrary = readUNIFACLibrary(p_fileName, unifacDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Unifac library!"); System.exit(0); } } public void readAbrahamTree(String p_fileName) { try { abramTree = readStandardTree(p_fileName,abramDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //Added by Amrit Jalan on December 13, 2010 public void readAbrahamradTree(String p_fileName) { try { abramradTree = readStandardTree(p_fileName,abramradDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Abraham Radical tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } public void readUnifacTree(String p_fileName) { try { unifacTree = readStandardTree(p_fileName,unifacDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Unifac tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //public void readSolventDictionary(String p_fileName) { //try { // solventDictionary = readStandard/Dictionary(p_fileName); // return; //catch (Exception e) { // Logger.logStackTrace(e); // Logger.critical("Error in read Solvent dictionary!"); // System.exit(0); // // public void readSolventLibrary(String p_fileName) { // try { // solventLibrary = readStandardLibrary(p_fileName, solventDictionary); // return; // catch (Exception e) { // Logger.logStackTrace(e); // Logger.critical("Can't read solvent library!"); // System.exit(0); // public void read15Dictionary(String p_fileName) { try { oneFiveDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read 1,5 dictionary!"); System.exit(0); } } public void read15Library(String p_fileName) { try { oneFiveLibrary = readStandardLibrary(p_fileName, oneFiveDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read 1,5 library!"); System.exit(0); } } public void read15Tree(String p_fileName) { try { oneFiveTree = readStandardTree(p_fileName,oneFiveDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read 1,5 tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readRadicalDictionary(String) public void readRadicalDictionary(String p_fileName) { try { radicalDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read radical dictionary!\n" + e.getMessage()); System.exit(0); } } //## operation readRadicalLibrary(String) public void readRadicalLibrary(String p_fileName) { try { radicalLibrary = readStandardLibrary(p_fileName, radicalDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read radical Library!"); System.exit(0); } } //## operation readRadicalTree(String) public void readRadicalTree(String p_fileName) { try { radicalTree = readStandardTree(p_fileName,radicalDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read thermo group tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } //## operation readRingLibrary(String) public void readRingDictionary(String p_fileName) { try { ringDictionary = readStandardDictionary(p_fileName); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Error in read ring dictionary!\n" + e.getMessage()); System.exit(0); } } //## operation readRingTree(String) public void readRingTree(String p_fileName) { try { ringTree = readStandardTree(p_fileName,ringDictionary,0); } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read ring tree file!"); Logger.critical("Error: " + e.getMessage()); System.exit(0); } } // end pey //## operation readRingLibrary(String) public void readRingLibrary(String p_fileName) { try { ringLibrary = readStandardLibrary(p_fileName, ringDictionary); return; } catch (Exception e) { Logger.logStackTrace(e); Logger.critical("Can't read Ring Correction Library!"); Logger.critical("Error: " + e); System.exit(0); } } //## operation readStandardCorrectionLibrary(String,HashMap) protected void readStandardCorrectionLibrary(String p_fileName, HashMap p_library) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); int index = Integer.parseInt(token.nextToken()); String name = token.nextToken(); if (p_library == ringLibrary) { String fomula = token.nextToken(); String sigma = token.nextToken(); } // setp 2: read in thermoGAValue String thermo=""; for (int i=0;i<12;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } ThermoGAValue gaValue = ChemParser.parseThermoGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } ThermoGAValue newGaValue = new ThermoGAValue(name,gaValue,comments); // step3: read in graph of the functional group Graph g = ChemParser.readFGGraph(data); if (g == null) throw new NullGraphException(); FunctionalGroup fg = FunctionalGroup.make(name, g); // step4: put in library Object previous = p_library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } line = ChemParser.readMeaningfulLine(data, true); } in.close(); return; } catch (IOException e) { throw new IOException(); } } //## operation readStandardDictionary(String) public HashMap readStandardDictionary(String p_fileName) throws FileNotFoundException, IOException { //#[ operation readStandardDictionary(String) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap dictionary = new HashMap(); HashMap unRead = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); read: while (line != null) { StringTokenizer st = new StringTokenizer(line); String fgname = st.nextToken(); data.mark(10000); line = ChemParser.readMeaningfulLine(data, true); if (line == null) break read; line = line.trim(); String prefix = line.substring(0,5); if (prefix.compareToIgnoreCase("union") == 0) { HashSet union = ChemParser.readUnion(line); unRead.put(fgname,union); } else { data.reset(); Graph fgGraph = null; try { fgGraph = ChemParser.readFGGraph(data); } catch (Exception e) { Logger.logStackTrace(e); throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage()); } if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname); FunctionalGroup fg = FunctionalGroup.make(fgname, fgGraph); Object old = dictionary.get(fgname); if (old == null) { dictionary.put(fgname,fg); } else { FunctionalGroup oldFG = (FunctionalGroup)old; if (!oldFG.equals(fg)) throw new ReplaceFunctionalGroupException(fgname); } } //System.out.println(line); line = ChemParser.readMeaningfulLine(data, true); } while (!unRead.isEmpty()) { String fgname = (String)(unRead.keySet().iterator().next()); ChemParser.findUnion(fgname,unRead,dictionary); } in.close(); return dictionary; } catch (FileNotFoundException e) { throw new FileNotFoundException(p_fileName); } catch (IOException e) { throw new IOException(p_fileName + ": " + e.getMessage()); } } //## operation readStandardLibrary(String,HashMap) protected HashMap readStandardLibrary(String p_fileName, HashMap p_dictionary) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { //System.out.println(line);// // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in thermoGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<11;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } ThermoGAValue gaValue = ChemParser.parseThermoGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } ThermoGAValue newGaValue=new ThermoGAValue(name,gaValue,comments); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof ThermoGAValue)) { throw new InvalidReferenceThermoGAValueException(); } ThermoGAValue newGaValue = new ThermoGAValue(fg.getName(),(ThermoGAValue)gaValue, "Use the value of " + path); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readAbramLibrary(String,HashMap) protected HashMap readAbramLibrary(String p_fileName, HashMap p_dictionary) throws IOException { //#[ operation readStandardLibrary(String,HashMap) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in AbrahamGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<4;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } AbrahamGAValue gaValue = ChemParser.parseAbrahamGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } AbrahamGAValue newGaValue=new AbrahamGAValue(gaValue); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof AbrahamGAValue)) { throw new InvalidReferenceThermoGAValueException(); } AbrahamGAValue newGaValue = new AbrahamGAValue((AbrahamGAValue)gaValue); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readAbramLibrary(String,HashMap) protected HashMap readUNIFACLibrary(String p_fileName, HashMap p_dictionary) throws IOException { try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HashMap library = new HashMap(); String line = ChemParser.readMeaningfulLine(data, true); while (line != null) { // step 1: read in index and name StringTokenizer token = new StringTokenizer(line); String index = token.nextToken(); //1/6/09 gmagoon changed index from integer to string, so that if/when ChemGreen/RMGVE adds a decimal after the entry number (after editing thermo library), RMG will still be able to read it String name = token.nextToken(); // step 2: find this functional group in dictionary by name Matchable fg = (Matchable)p_dictionary.get(name); if (fg == null) { throw new FunctionalGroupNotFoundException(); //System.out.println(name); } // step 3: read in AbrahamGAValue String thermo = token.nextToken(); // if there is a set of real thermo numbers, read them in and put the thermo data into library try { double H = Double.parseDouble(thermo); thermo = thermo.concat(" "); for (int i=0;i<1;i++) { thermo = thermo.concat(token.nextToken()); thermo = thermo.concat(" "); } UnifacGAValue gaValue = ChemParser.parseUnifacGAValue(thermo); String comments = ""; while (token.hasMoreTokens()) { comments = comments + " " + token.nextToken(); } UnifacGAValue newGaValue=new UnifacGAValue(gaValue); // step4: put in library Object previous = library.put(fg, newGaValue); if (previous != null) { throw new ReplaceThermoGAValueException(); } } // if there is a referenced name, put the name into library catch (NumberFormatException e) { Object o = p_dictionary.get(thermo); if (o == null) { //throw new FunctionalGroupNotFoundException(thermo); System.out.print(index); System.out.println(": " + thermo); } Object previous = library.put(fg, thermo); if (previous != null) { throw new ReplaceThermoGAValueException(); } } line = ChemParser.readMeaningfulLine(data, true); } // scan the library to give the ones having referenced name the real thermo data Iterator iter = library.keySet().iterator(); while (iter.hasNext()) { Matchable fg = (Matchable)iter.next(); Object gaValue = library.get(fg); String path = ""; if (gaValue instanceof String) { do { String name = (String)gaValue; path = path + "->" + name; gaValue = library.get((Matchable)p_dictionary.get(name)); } while (gaValue instanceof String); if (gaValue == null || !(gaValue instanceof UnifacGAValue)) { throw new InvalidReferenceThermoGAValueException(); } UnifacGAValue newGaValue = new UnifacGAValue((UnifacGAValue)gaValue); library.put(fg,newGaValue); } } in.close(); return library; } catch (IOException e) { throw new IOException(); } } //## operation readStandardTree(String,HashMap,int) public HierarchyTree readStandardTree(String p_fileName, HashMap p_dictionary, int p_level) throws IOException { //#[ operation readStandardTree(String,HashMap,int) try { FileReader in = new FileReader(p_fileName); BufferedReader data = new BufferedReader(in); HierarchyTree tree = ChemParser.readHierarchyTree(data,p_dictionary,p_level); in.close(); return tree; } catch (IOException e) { throw new IOException(p_fileName); } } protected static ThermoGAGroupLibrary getINSTANCE() { return INSTANCE; } public HashMap getGroupDictionary() { return groupDictionary; } public HashMap getGroupLibrary() { return groupLibrary; } public void setGroupLibrary(HashMap p_groupLibrary) { groupLibrary = p_groupLibrary; } protected HierarchyTree getGroupTree() { return groupTree; } public HashMap getOtherDictionary() { return otherDictionary; } public void setOtherDictionary(HashMap p_otherDictionary) { otherDictionary = p_otherDictionary; } public HashMap getOtherLibrary() { return otherLibrary; } public HierarchyTree getOtherTree() { return otherTree; } public void setOtherTree(HierarchyTree p_otherTree) { otherTree = p_otherTree; } public HashMap getRadicalDictionary() { return radicalDictionary; } public void setRadicalDictionary(HashMap p_radicalDictionary) { radicalDictionary = p_radicalDictionary; } protected HashMap getRadicalLibrary() { return radicalLibrary; } public HierarchyTree getRadicalTree() { return radicalTree; } public void setRadicalTree(HierarchyTree p_radicalTree) { radicalTree = p_radicalTree; } protected HashMap getRingLibrary() { return ringLibrary; } public ThermoGAValue findPolyCyclicRingCorrections( ChemGraph molecule) { int deepest = -1; Stack dummy = null; Iterator iterNodes = molecule.getGraph().getNodeList(); while(iterNodes.hasNext()){ //take first atom in this ring: Node node = (Node)iterNodes.next(); Atom atom = (Atom)node.getElement(); // make the current node the central atom molecule.resetThermoSite(node); // find the match in the thermo tree Stack stack = polycylicTree.findMatchedPath(molecule); // check if it's the deepest match if (!stack.empty()) { HierarchyTreeNode htn = (HierarchyTreeNode) stack.peek(); if (htn.getDepth() > deepest) { //we have found a Stack that is deeper than the previous ones, re-initialize Set: dummy = stack; deepest = htn.getDepth(); } } } if (dummy == null) return null; /* * If deepest node is L0, then none of the L1 nodes could be matched. * We should return null then. */ if(deepest == 0) return null; while (!dummy.empty()) { HierarchyTreeNode node = (HierarchyTreeNode)dummy.pop(); Matchable fg = (Matchable)node.getElement(); ThermoGAValue ga = (ThermoGAValue)polycyclicLibrary.get(fg); molecule.appendThermoComments("Polyclic ring system:" + fg.getName()); if (ga != null) return ga; } molecule.getGraph().resetMatchedGC(); return null; } }
package org.jasig.portal; import java.util.Map; import org.jasig.portal.security.IPerson; import org.jasig.portal.security.ISecurityContext; import org.jasig.portal.security.PermissionManager; import javax.naming.InitialContext; import javax.naming.Context; import java.util.Hashtable; /** * Used to store channel configuration items and parameters. * @author Ken Weiner, Peter Kharchenko * @version $Revision$ * @author Peter Kharchenko */ public class ChannelStaticData extends Hashtable { private long m_timeout = java.lang.Long.MAX_VALUE; // Cache a reference to the portal's JNDI context private InitialContext m_portalContext = null; // This is the ID that globally identifies the channel private String m_channelGlobalID = null; // This is the ID that locally identifies the channel in the user's layout private String m_channelInstanceID = null; // Cache the IPerson private IPerson m_person = null; // Cache the security context private ISecurityContext m_securityContext = null; private PermissionManager m_permissionManager = null; /** * Set information contained in a channel <param> element * Parameters are strings! * @param key param name * @param value param value */ public synchronized String setParameter (String key, String value) { return (String)super.put(key, value); } /** * Get information contained in a particular <param> element * @param key param name * @return param value */ public synchronized String getParameter (String key) { return (String)super.get(key); } /** * If you need to pass Objects, use this * Similar to the {@link #setParameter(String,String)}, but can be used to pass things other then strings. * @param key * @param value * @return */ public synchronized Object put (Object key, Object value) { return super.put(key, value); } /** * Similar to the {@link #getParameter(String)}, but can be used to pass things other then strings. * @param key * @return */ public synchronized Object get (Object key) { return super.get(key); } /** * Copy parameter list from a Map * @param params a map of params */ public void setParameters (Map params) { // Copy the map putAll(params); } /** * Sets the channel instance ID * @param sChannelID the unique channelID */ public void setChannelID (String sChID) { m_channelInstanceID = sChID; } /** * Gets the channel ID * @return the channel's ID */ public String getChannelID () { return (m_channelInstanceID); } /** * put your documentation comment here * @param String channelGlobalID */ public void setChannelGlobalID (String channelGlobalID) { m_channelGlobalID = channelGlobalID; } /** * put your documentation comment here */ public String getChannelGlobalID () { return (m_channelGlobalID); } /** * put your documentation comment here * @param value */ public void setTimeout (long value) { m_timeout = value; } /** * put your documentation comment here * @return */ public long getTimeout () { return (m_timeout); } /** * put your documentation comment here * @return */ public IPerson getPerson () { return (m_person); } /** * put your documentation comment here * @param per */ public void setPerson (IPerson person) { m_person = person; } /** * put your documentation comment here * @return */ public ISecurityContext getSecurityContext () { return (m_securityContext); } /** * put your documentation comment here * @param sc */ public void setSecurityContext (ISecurityContext securitContext) { m_securityContext = securitContext; } /** * put your documentation comment here * @return */ public InitialContext getPortalContext () { if (m_portalContext != null) { return (m_portalContext); } else { Hashtable environment = new Hashtable(1); // Set up the path environment.put(Context.INITIAL_CONTEXT_FACTORY, "org.jasig.portal.jndi.PortalInitialContextFactory"); try { InitialContext ctx = new InitialContext(environment); return (ctx); } catch (Exception e) { e.printStackTrace(System.err); return (null); } } } public PermissionManager getPermissionManager () { return (m_permissionManager); } public void setPermissionManager (PermissionManager permissionManager) { m_permissionManager = permissionManager; } }
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.List; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.entity.CategoryItemEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.CategoryToolTipGenerator; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.urls.CategoryURLGenerator; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintList; import org.jfree.util.PaintUtilities; import org.jfree.util.Rotation; import org.jfree.util.ShapeUtilities; import org.jfree.util.StrokeList; import org.jfree.util.TableOrder; /** * A plot that displays data from a {@link CategoryDataset} in the form of a * "spider web". Multiple series can be plotted on the same axis to allow * easy comparison. This plot doesn't support negative values at present. */ public class SpiderWebPlot extends Plot implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -5376340422031599463L; /** The default head radius percent (currently 1%). */ public static final double DEFAULT_HEAD = 0.01; /** The default axis label gap (currently 10%). */ public static final double DEFAULT_AXIS_LABEL_GAP = 0.10; /** The default interior gap. */ public static final double DEFAULT_INTERIOR_GAP = 0.25; /** The maximum interior gap (currently 40%). */ public static final double MAX_INTERIOR_GAP = 0.40; /** The default starting angle for the radar chart axes. */ public static final double DEFAULT_START_ANGLE = 90.0; /** The default series label font. */ public static final Font DEFAULT_LABEL_FONT = new Font("SansSerif", Font.PLAIN, 10); /** The default series label paint. */ public static final Paint DEFAULT_LABEL_PAINT = Color.black; /** The default series label background paint. */ public static final Paint DEFAULT_LABEL_BACKGROUND_PAINT = new Color(255, 255, 192); /** The default series label outline paint. */ public static final Paint DEFAULT_LABEL_OUTLINE_PAINT = Color.black; /** The default series label outline stroke. */ public static final Stroke DEFAULT_LABEL_OUTLINE_STROKE = new BasicStroke(0.5f); /** The default series label shadow paint. */ public static final Paint DEFAULT_LABEL_SHADOW_PAINT = Color.lightGray; /** * The default maximum value plotted - forces the plot to evaluate * the maximum from the data passed in */ public static final double DEFAULT_MAX_VALUE = -1.0; /** The head radius as a percentage of the available drawing area. */ protected double headPercent; /** The space left around the outside of the plot as a percentage. */ private double interiorGap; /** The gap between the labels and the axes as a %age of the radius. */ private double axisLabelGap; /** * The paint used to draw the axis lines. * * @since 1.0.4 */ private transient Paint axisLinePaint; /** * The stroke used to draw the axis lines. * * @since 1.0.4 */ private transient Stroke axisLineStroke; /** The dataset. */ private CategoryDataset dataset; /** The maximum value we are plotting against on each category axis */ private double maxValue; /** * The data extract order (BY_ROW or BY_COLUMN). This denotes whether * the data series are stored in rows (in which case the category names are * derived from the column keys) or in columns (in which case the category * names are derived from the row keys). */ private TableOrder dataExtractOrder; /** The starting angle. */ private double startAngle; /** The direction for drawing the radar axis & plots. */ private Rotation direction; /** The legend item shape. */ private transient Shape legendItemShape; /** The paint for ALL series (overrides list). */ private transient Paint seriesPaint; /** The series paint list. */ private PaintList seriesPaintList; /** The base series paint (fallback). */ private transient Paint baseSeriesPaint; /** The outline paint for ALL series (overrides list). */ private transient Paint seriesOutlinePaint; /** The series outline paint list. */ private PaintList seriesOutlinePaintList; /** The base series outline paint (fallback). */ private transient Paint baseSeriesOutlinePaint; /** The outline stroke for ALL series (overrides list). */ private transient Stroke seriesOutlineStroke; /** The series outline stroke list. */ private StrokeList seriesOutlineStrokeList; /** The base series outline stroke (fallback). */ private transient Stroke baseSeriesOutlineStroke; /** The font used to display the category labels. */ private Font labelFont; /** The color used to draw the category labels. */ private transient Paint labelPaint; /** The label generator. */ private CategoryItemLabelGenerator labelGenerator; /** controls if the web polygons are filled or not */ private boolean webFilled = true; /** A tooltip generator for the plot (<code>null</code> permitted). */ private CategoryToolTipGenerator toolTipGenerator; /** A URL generator for the plot (<code>null</code> permitted). */ private CategoryURLGenerator urlGenerator; /** * Creates a default plot with no dataset. */ public SpiderWebPlot() { this(null); } /** * Creates a new spider web plot with the given dataset, with each row * representing a series. * * @param dataset the dataset (<code>null</code> permitted). */ public SpiderWebPlot(CategoryDataset dataset) { this(dataset, TableOrder.BY_ROW); } /** * Creates a new spider web plot with the given dataset. * * @param dataset the dataset. * @param extract controls how data is extracted ({@link TableOrder#BY_ROW} * or {@link TableOrder#BY_COLUMN}). */ public SpiderWebPlot(CategoryDataset dataset, TableOrder extract) { super(); if (extract == null) { throw new IllegalArgumentException("Null 'extract' argument."); } this.dataset = dataset; if (dataset != null) { dataset.addChangeListener(this); } this.dataExtractOrder = extract; this.headPercent = DEFAULT_HEAD; this.axisLabelGap = DEFAULT_AXIS_LABEL_GAP; this.axisLinePaint = Color.black; this.axisLineStroke = new BasicStroke(1.0f); this.interiorGap = DEFAULT_INTERIOR_GAP; this.startAngle = DEFAULT_START_ANGLE; this.direction = Rotation.CLOCKWISE; this.maxValue = DEFAULT_MAX_VALUE; this.seriesPaint = null; this.seriesPaintList = new PaintList(); this.baseSeriesPaint = null; this.seriesOutlinePaint = null; this.seriesOutlinePaintList = new PaintList(); this.baseSeriesOutlinePaint = DEFAULT_OUTLINE_PAINT; this.seriesOutlineStroke = null; this.seriesOutlineStrokeList = new StrokeList(); this.baseSeriesOutlineStroke = DEFAULT_OUTLINE_STROKE; this.labelFont = DEFAULT_LABEL_FONT; this.labelPaint = DEFAULT_LABEL_PAINT; this.labelGenerator = new StandardCategoryItemLabelGenerator(); this.legendItemShape = DEFAULT_LEGEND_ITEM_CIRCLE; } /** * Returns a short string describing the type of plot. * * @return The plot type. */ public String getPlotType() { // return localizationResources.getString("Radar_Plot"); return ("Spider Web Plot"); } /** * Returns the dataset. * * @return The dataset (possibly <code>null</code>). * * @see #setDataset(CategoryDataset) */ public CategoryDataset getDataset() { return this.dataset; } /** * Sets the dataset used by the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param dataset the dataset (<code>null</code> permitted). * * @see #getDataset() */ public void setDataset(CategoryDataset dataset) { // if there is an existing dataset, remove the plot from the list of // change listeners... if (this.dataset != null) { this.dataset.removeChangeListener(this); } // set the new dataset, and register the chart as a change listener... this.dataset = dataset; if (dataset != null) { setDatasetGroup(dataset.getGroup()); dataset.addChangeListener(this); } // send a dataset change event to self to trigger plot change event datasetChanged(new DatasetChangeEvent(this, dataset)); } /** * Method to determine if the web chart is to be filled. * * @return A boolean. * * @see #setWebFilled(boolean) */ public boolean isWebFilled() { return this.webFilled; } /** * Sets the webFilled flag and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param flag the flag. * * @see #isWebFilled() */ public void setWebFilled(boolean flag) { this.webFilled = flag; fireChangeEvent(); } /** * Returns the data extract order (by row or by column). * * @return The data extract order (never <code>null</code>). * * @see #setDataExtractOrder(TableOrder) */ public TableOrder getDataExtractOrder() { return this.dataExtractOrder; } public void setDataExtractOrder(TableOrder order) { if (order == null) { throw new IllegalArgumentException("Null 'order' argument"); } this.dataExtractOrder = order; fireChangeEvent(); } /** * Returns the head percent. * * @return The head percent. * * @see #setHeadPercent(double) */ public double getHeadPercent() { return this.headPercent; } /** * Sets the head percent and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param percent the percent. * * @see #getHeadPercent() */ public void setHeadPercent(double percent) { this.headPercent = percent; fireChangeEvent(); } /** * Returns the start angle for the first radar axis. * <BR> * This is measured in degrees starting from 3 o'clock (Java Arc2D default) * and measuring anti-clockwise. * * @return The start angle. * * @see #setStartAngle(double) */ public double getStartAngle() { return this.startAngle; } /** * Sets the starting angle and sends a {@link PlotChangeEvent} to all * registered listeners. * <P> * The initial default value is 90 degrees, which corresponds to 12 o'clock. * A value of zero corresponds to 3 o'clock... this is the encoding used by * Java's Arc2D class. * * @param angle the angle (in degrees). * * @see #getStartAngle() */ public void setStartAngle(double angle) { this.startAngle = angle; fireChangeEvent(); } /** * Returns the maximum value any category axis can take. * * @return The maximum value. * * @see #setMaxValue(double) */ public double getMaxValue() { return this.maxValue; } /** * Sets the maximum value any category axis can take and sends * a {@link PlotChangeEvent} to all registered listeners. * * @param value the maximum value. * * @see #getMaxValue() */ public void setMaxValue(double value) { this.maxValue = value; fireChangeEvent(); } /** * Returns the direction in which the radar axes are drawn * (clockwise or anti-clockwise). * * @return The direction (never <code>null</code>). * * @see #setDirection(Rotation) */ public Rotation getDirection() { return this.direction; } /** * Sets the direction in which the radar axes are drawn and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param direction the direction (<code>null</code> not permitted). * * @see #getDirection() */ public void setDirection(Rotation direction) { if (direction == null) { throw new IllegalArgumentException("Null 'direction' argument."); } this.direction = direction; fireChangeEvent(); } /** * Returns the interior gap, measured as a percentage of the available * drawing space. * * @return The gap (as a percentage of the available drawing space). * * @see #setInteriorGap(double) */ public double getInteriorGap() { return this.interiorGap; } /** * Sets the interior gap and sends a {@link PlotChangeEvent} to all * registered listeners. This controls the space between the edges of the * plot and the plot area itself (the region where the axis labels appear). * * @param percent the gap (as a percentage of the available drawing space). * * @see #getInteriorGap() */ public void setInteriorGap(double percent) { if ((percent < 0.0) || (percent > MAX_INTERIOR_GAP)) { throw new IllegalArgumentException( "Percentage outside valid range."); } if (this.interiorGap != percent) { this.interiorGap = percent; fireChangeEvent(); } } /** * Returns the axis label gap. * * @return The axis label gap. * * @see #setAxisLabelGap(double) */ public double getAxisLabelGap() { return this.axisLabelGap; } /** * Sets the axis label gap and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param gap the gap. * * @see #getAxisLabelGap() */ public void setAxisLabelGap(double gap) { this.axisLabelGap = gap; fireChangeEvent(); } /** * Returns the paint used to draw the axis lines. * * @return The paint used to draw the axis lines (never <code>null</code>). * * @see #setAxisLinePaint(Paint) * @see #getAxisLineStroke() * @since 1.0.4 */ public Paint getAxisLinePaint() { return this.axisLinePaint; } /** * Sets the paint used to draw the axis lines and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getAxisLinePaint() * @since 1.0.4 */ public void setAxisLinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.axisLinePaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the axis lines. * * @return The stroke used to draw the axis lines (never <code>null</code>). * * @see #setAxisLineStroke(Stroke) * @see #getAxisLinePaint() * @since 1.0.4 */ public Stroke getAxisLineStroke() { return this.axisLineStroke; } /** * Sets the stroke used to draw the axis lines and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getAxisLineStroke() * @since 1.0.4 */ public void setAxisLineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.axisLineStroke = stroke; fireChangeEvent(); } //// SERIES PAINT ///////////////////////// /** * Returns the paint for ALL series in the plot. * * @return The paint (possibly <code>null</code>). * * @see #setSeriesPaint(Paint) */ public Paint getSeriesPaint() { return this.seriesPaint; } /** * Sets the paint for ALL series in the plot. If this is set to</code> null * </code>, then a list of paints is used instead (to allow different colors * to be used for each series of the radar group). * * @param paint the paint (<code>null</code> permitted). * * @see #getSeriesPaint() */ public void setSeriesPaint(Paint paint) { this.seriesPaint = paint; fireChangeEvent(); } /** * Returns the paint for the specified series. * * @param series the series index (zero-based). * * @return The paint (never <code>null</code>). * * @see #setSeriesPaint(int, Paint) */ public Paint getSeriesPaint(int series) { // return the override, if there is one... if (this.seriesPaint != null) { return this.seriesPaint; } // otherwise look up the paint list Paint result = this.seriesPaintList.getPaint(series); if (result == null) { DrawingSupplier supplier = getDrawingSupplier(); if (supplier != null) { Paint p = supplier.getNextPaint(); this.seriesPaintList.setPaint(series, p); result = p; } else { result = this.baseSeriesPaint; } } return result; } /** * Sets the paint used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint (<code>null</code> permitted). * * @see #getSeriesPaint(int) */ public void setSeriesPaint(int series, Paint paint) { this.seriesPaintList.setPaint(series, paint); fireChangeEvent(); } /** * Returns the base series paint. This is used when no other paint is * available. * * @return The paint (never <code>null</code>). * * @see #setBaseSeriesPaint(Paint) */ public Paint getBaseSeriesPaint() { return this.baseSeriesPaint; } /** * Sets the base series paint. * * @param paint the paint (<code>null</code> not permitted). * * @see #getBaseSeriesPaint() */ public void setBaseSeriesPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.baseSeriesPaint = paint; fireChangeEvent(); } //// SERIES OUTLINE PAINT //////////////////////////// /** * Returns the outline paint for ALL series in the plot. * * @return The paint (possibly <code>null</code>). */ public Paint getSeriesOutlinePaint() { return this.seriesOutlinePaint; } /** * Sets the outline paint for ALL series in the plot. If this is set to * </code> null</code>, then a list of paints is used instead (to allow * different colors to be used for each series). * * @param paint the paint (<code>null</code> permitted). */ public void setSeriesOutlinePaint(Paint paint) { this.seriesOutlinePaint = paint; fireChangeEvent(); } /** * Returns the paint for the specified series. * * @param series the series index (zero-based). * * @return The paint (never <code>null</code>). */ public Paint getSeriesOutlinePaint(int series) { // return the override, if there is one... if (this.seriesOutlinePaint != null) { return this.seriesOutlinePaint; } // otherwise look up the paint list Paint result = this.seriesOutlinePaintList.getPaint(series); if (result == null) { result = this.baseSeriesOutlinePaint; } return result; } /** * Sets the paint used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint (<code>null</code> permitted). */ public void setSeriesOutlinePaint(int series, Paint paint) { this.seriesOutlinePaintList.setPaint(series, paint); fireChangeEvent(); } /** * Returns the base series paint. This is used when no other paint is * available. * * @return The paint (never <code>null</code>). */ public Paint getBaseSeriesOutlinePaint() { return this.baseSeriesOutlinePaint; } /** * Sets the base series paint. * * @param paint the paint (<code>null</code> not permitted). */ public void setBaseSeriesOutlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.baseSeriesOutlinePaint = paint; fireChangeEvent(); } //// SERIES OUTLINE STROKE ///////////////////// /** * Returns the outline stroke for ALL series in the plot. * * @return The stroke (possibly <code>null</code>). */ public Stroke getSeriesOutlineStroke() { return this.seriesOutlineStroke; } /** * Sets the outline stroke for ALL series in the plot. If this is set to * </code> null</code>, then a list of paints is used instead (to allow * different colors to be used for each series). * * @param stroke the stroke (<code>null</code> permitted). */ public void setSeriesOutlineStroke(Stroke stroke) { this.seriesOutlineStroke = stroke; fireChangeEvent(); } /** * Returns the stroke for the specified series. * * @param series the series index (zero-based). * * @return The stroke (never <code>null</code>). */ public Stroke getSeriesOutlineStroke(int series) { // return the override, if there is one... if (this.seriesOutlineStroke != null) { return this.seriesOutlineStroke; } // otherwise look up the paint list Stroke result = this.seriesOutlineStrokeList.getStroke(series); if (result == null) { result = this.baseSeriesOutlineStroke; } return result; } /** * Sets the stroke used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param stroke the stroke (<code>null</code> permitted). */ public void setSeriesOutlineStroke(int series, Stroke stroke) { this.seriesOutlineStrokeList.setStroke(series, stroke); fireChangeEvent(); } /** * Returns the base series stroke. This is used when no other stroke is * available. * * @return The stroke (never <code>null</code>). */ public Stroke getBaseSeriesOutlineStroke() { return this.baseSeriesOutlineStroke; } /** * Sets the base series stroke. * * @param stroke the stroke (<code>null</code> not permitted). */ public void setBaseSeriesOutlineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.baseSeriesOutlineStroke = stroke; fireChangeEvent(); } /** * Returns the shape used for legend items. * * @return The shape (never <code>null</code>). * * @see #setLegendItemShape(Shape) */ public Shape getLegendItemShape() { return this.legendItemShape; } /** * Sets the shape used for legend items and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param shape the shape (<code>null</code> not permitted). * * @see #getLegendItemShape() */ public void setLegendItemShape(Shape shape) { if (shape == null) { throw new IllegalArgumentException("Null 'shape' argument."); } this.legendItemShape = shape; fireChangeEvent(); } /** * Returns the series label font. * * @return The font (never <code>null</code>). * * @see #setLabelFont(Font) */ public Font getLabelFont() { return this.labelFont; } /** * Sets the series label font and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param font the font (<code>null</code> not permitted). * * @see #getLabelFont() */ public void setLabelFont(Font font) { if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } this.labelFont = font; fireChangeEvent(); } /** * Returns the series label paint. * * @return The paint (never <code>null</code>). * * @see #setLabelPaint(Paint) */ public Paint getLabelPaint() { return this.labelPaint; } /** * Sets the series label paint and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getLabelPaint() */ public void setLabelPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.labelPaint = paint; fireChangeEvent(); } /** * Returns the label generator. * * @return The label generator (never <code>null</code>). * * @see #setLabelGenerator(CategoryItemLabelGenerator) */ public CategoryItemLabelGenerator getLabelGenerator() { return this.labelGenerator; } /** * Sets the label generator and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param generator the generator (<code>null</code> not permitted). * * @see #getLabelGenerator() */ public void setLabelGenerator(CategoryItemLabelGenerator generator) { if (generator == null) { throw new IllegalArgumentException("Null 'generator' argument."); } this.labelGenerator = generator; } /** * Returns the tool tip generator for the plot. * * @return The tool tip generator (possibly <code>null</code>). * * @see #setToolTipGenerator(CategoryToolTipGenerator) * * @since 1.0.2 */ public CategoryToolTipGenerator getToolTipGenerator() { return this.toolTipGenerator; } /** * Sets the tool tip generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getToolTipGenerator() * * @since 1.0.2 */ public void setToolTipGenerator(CategoryToolTipGenerator generator) { this.toolTipGenerator = generator; fireChangeEvent(); } /** * Returns the URL generator for the plot. * * @return The URL generator (possibly <code>null</code>). * * @see #setURLGenerator(CategoryURLGenerator) * * @since 1.0.2 */ public CategoryURLGenerator getURLGenerator() { return this.urlGenerator; } /** * Sets the URL generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getURLGenerator() * * @since 1.0.2 */ public void setURLGenerator(CategoryURLGenerator generator) { this.urlGenerator = generator; fireChangeEvent(); } /** * Returns a collection of legend items for the radar chart. * * @return The legend items. */ public LegendItemCollection getLegendItems() { LegendItemCollection result = new LegendItemCollection(); List keys = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { keys = this.dataset.getRowKeys(); } else if (this.dataExtractOrder == TableOrder.BY_COLUMN) { keys = this.dataset.getColumnKeys(); } if (keys != null) { int series = 0; Iterator iterator = keys.iterator(); Shape shape = getLegendItemShape(); while (iterator.hasNext()) { String label = iterator.next().toString(); String description = label; Paint paint = getSeriesPaint(series); Paint outlinePaint = getSeriesOutlinePaint(series); Stroke stroke = getSeriesOutlineStroke(series); LegendItem item = new LegendItem(label, description, null, null, shape, paint, stroke, outlinePaint); item.setDataset(getDataset()); result.add(item); series++; } } return result; } /** * Returns a cartesian point from a polar angle, length and bounding box * * @param bounds the area inside which the point needs to be. * @param angle the polar angle, in degrees. * @param length the relative length. Given in percent of maximum extend. * * @return The cartesian point. */ protected Point2D getWebPoint(Rectangle2D bounds, double angle, double length) { double angrad = Math.toRadians(angle); double x = Math.cos(angrad) * length * bounds.getWidth() / 2; double y = -Math.sin(angrad) * length * bounds.getHeight() / 2; return new Point2D.Double(bounds.getX() + x + bounds.getWidth() / 2, bounds.getY() + y + bounds.getHeight() / 2); } /** * Draws the plot on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area within which the plot should be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param info collects info about the drawing. */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // adjust for insets... RectangleInsets insets = getInsets(); insets.trim(area); if (info != null) { info.setPlotArea(area); info.setDataArea(area); } drawBackground(g2, area); drawOutline(g2, area); Shape savedClip = g2.getClip(); g2.clip(area); Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); if (!DatasetUtilities.isEmptyOrNull(this.dataset)) { int seriesCount = 0, catCount = 0; if (this.dataExtractOrder == TableOrder.BY_ROW) { seriesCount = this.dataset.getRowCount(); catCount = this.dataset.getColumnCount(); } else { seriesCount = this.dataset.getColumnCount(); catCount = this.dataset.getRowCount(); } // ensure we have a maximum value to use on the axes if (this.maxValue == DEFAULT_MAX_VALUE) calculateMaxValue(seriesCount, catCount); // Next, setup the plot area // adjust the plot area by the interior spacing value double gapHorizontal = area.getWidth() * getInteriorGap(); double gapVertical = area.getHeight() * getInteriorGap(); double X = area.getX() + gapHorizontal / 2; double Y = area.getY() + gapVertical / 2; double W = area.getWidth() - gapHorizontal; double H = area.getHeight() - gapVertical; double headW = area.getWidth() * this.headPercent; double headH = area.getHeight() * this.headPercent; // make the chart area a square double min = Math.min(W, H) / 2; X = (X + X + W) / 2 - min; Y = (Y + Y + H) / 2 - min; W = 2 * min; H = 2 * min; Point2D centre = new Point2D.Double(X + W / 2, Y + H / 2); Rectangle2D radarArea = new Rectangle2D.Double(X, Y, W, H); // draw the axis and category label for (int cat = 0; cat < catCount; cat++) { double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount); Point2D endPoint = getWebPoint(radarArea, angle, 1); // 1 = end of axis Line2D line = new Line2D.Double(centre, endPoint); g2.setPaint(this.axisLinePaint); g2.setStroke(this.axisLineStroke); g2.draw(line); drawLabel(g2, radarArea, 0.0, cat, angle, 360.0 / catCount); } // Now actually plot each of the series polygons.. for (int series = 0; series < seriesCount; series++) { drawRadarPoly(g2, radarArea, centre, info, series, catCount, headH, headW); } } else { drawNoDataMessage(g2, area); } g2.setClip(savedClip); g2.setComposite(originalComposite); drawOutline(g2, area); } /** * loop through each of the series to get the maximum value * on each category axis * * @param seriesCount the number of series * @param catCount the number of categories */ private void calculateMaxValue(int seriesCount, int catCount) { double v = 0; Number nV = null; for (int seriesIndex = 0; seriesIndex < seriesCount; seriesIndex++) { for (int catIndex = 0; catIndex < catCount; catIndex++) { nV = getPlotValue(seriesIndex, catIndex); if (nV != null) { v = nV.doubleValue(); if (v > this.maxValue) { this.maxValue = v; } } } } } /** * Draws a radar plot polygon. * * @param g2 the graphics device. * @param plotArea the area we are plotting in (already adjusted). * @param centre the centre point of the radar axes * @param info chart rendering info. * @param series the series within the dataset we are plotting * @param catCount the number of categories per radar plot * @param headH the data point height * @param headW the data point width */ protected void drawRadarPoly(Graphics2D g2, Rectangle2D plotArea, Point2D centre, PlotRenderingInfo info, int series, int catCount, double headH, double headW) { Polygon polygon = new Polygon(); EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } // plot the data... for (int cat = 0; cat < catCount; cat++) { Number dataValue = getPlotValue(series, cat); if (dataValue != null) { double value = dataValue.doubleValue(); if (value >= 0) { // draw the polygon series... // Finds our starting angle from the centre for this axis double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount); // The following angle calc will ensure there isn't a top // vertical axis - this may be useful if you don't want any // given criteria to 'appear' move important than the // others.. // + (getDirection().getFactor() // * (cat + 0.5) * 360 / catCount); // find the point at the appropriate distance end point // along the axis/angle identified above and add it to the // polygon Point2D point = getWebPoint(plotArea, angle, value / this.maxValue); polygon.addPoint((int) point.getX(), (int) point.getY()); // put an elipse at the point being plotted.. Paint paint = getSeriesPaint(series); Paint outlinePaint = getSeriesOutlinePaint(series); Stroke outlineStroke = getSeriesOutlineStroke(series); Ellipse2D head = new Ellipse2D.Double(point.getX() - headW / 2, point.getY() - headH / 2, headW, headH); g2.setPaint(paint); g2.fill(head); g2.setStroke(outlineStroke); g2.setPaint(outlinePaint); g2.draw(head); if (entities != null) { String tip = null; if (this.toolTipGenerator != null) { tip = this.toolTipGenerator.generateToolTip( this.dataset, series, cat); } String url = null; if (this.urlGenerator != null) { url = this.urlGenerator.generateURL(this.dataset, series, cat); } Shape area = new Rectangle( (int) (point.getX() - headW), (int) (point.getY() - headH), (int) (headW * 2), (int) (headH * 2)); CategoryItemEntity entity = new CategoryItemEntity( area, tip, url, this.dataset, this.dataset.getRowKey(series), this.dataset.getColumnKey(cat)); entities.add(entity); } } } } // Plot the polygon Paint paint = getSeriesPaint(series); g2.setPaint(paint); g2.setStroke(getSeriesOutlineStroke(series)); g2.draw(polygon); // Lastly, fill the web polygon if this is required if (this.webFilled) { g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f)); g2.fill(polygon); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); } } /** * Returns the value to be plotted at the interseries of the * series and the category. This allows us to plot * <code>BY_ROW</code> or <code>BY_COLUMN</code> which basically is just * reversing the definition of the categories and data series being * plotted. * * @param series the series to be plotted. * @param cat the category within the series to be plotted. * * @return The value to be plotted (possibly <code>null</code>). * * @see #getDataExtractOrder() */ protected Number getPlotValue(int series, int cat) { Number value = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { value = this.dataset.getValue(series, cat); } else if (this.dataExtractOrder == TableOrder.BY_COLUMN) { value = this.dataset.getValue(cat, series); } return value; } /** * Draws the label for one axis. * * @param g2 the graphics device. * @param plotArea the plot area * @param value the value of the label (ignored). * @param cat the category (zero-based index). * @param startAngle the starting angle. * @param extent the extent of the arc. */ protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value, int cat, double startAngle, double extent) { FontRenderContext frc = g2.getFontRenderContext(); String label = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { // if series are in rows, then the categories are the column keys label = this.labelGenerator.generateColumnLabel(this.dataset, cat); } else { // if series are in columns, then the categories are the row keys label = this.labelGenerator.generateRowLabel(this.dataset, cat); } Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc); LineMetrics lm = getLabelFont().getLineMetrics(label, frc); double ascent = lm.getAscent(); Point2D labelLocation = calculateLabelLocation(labelBounds, ascent, plotArea, startAngle); Composite saveComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g2.setPaint(getLabelPaint()); g2.setFont(getLabelFont()); g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY()); g2.setComposite(saveComposite); } /** * Returns the location for a label * * @param labelBounds the label bounds. * @param ascent the ascent (height of font). * @param plotArea the plot area * @param startAngle the start angle for the pie series. * * @return The location for a label. */ protected Point2D calculateLabelLocation(Rectangle2D labelBounds, double ascent, Rectangle2D plotArea, double startAngle) { Arc2D arc1 = new Arc2D.Double(plotArea, startAngle, 0, Arc2D.OPEN); Point2D point1 = arc1.getEndPoint(); double deltaX = -(point1.getX() - plotArea.getCenterX()) * this.axisLabelGap; double deltaY = -(point1.getY() - plotArea.getCenterY()) * this.axisLabelGap; double labelX = point1.getX() - deltaX; double labelY = point1.getY() - deltaY; if (labelX < plotArea.getCenterX()) { labelX -= labelBounds.getWidth(); } if (labelX == plotArea.getCenterX()) { labelX -= labelBounds.getWidth() / 2; } if (labelY > plotArea.getCenterY()) { labelY += ascent; } return new Point2D.Double(labelX, labelY); } /** * Tests this plot for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof SpiderWebPlot)) { return false; } if (!super.equals(obj)) { return false; } SpiderWebPlot that = (SpiderWebPlot) obj; if (!this.dataExtractOrder.equals(that.dataExtractOrder)) { return false; } if (this.headPercent != that.headPercent) { return false; } if (this.interiorGap != that.interiorGap) { return false; } if (this.startAngle != that.startAngle) { return false; } if (!this.direction.equals(that.direction)) { return false; } if (this.maxValue != that.maxValue) { return false; } if (this.webFilled != that.webFilled) { return false; } if (this.axisLabelGap != that.axisLabelGap) { return false; } if (!PaintUtilities.equal(this.axisLinePaint, that.axisLinePaint)) { return false; } if (!this.axisLineStroke.equals(that.axisLineStroke)) { return false; } if (!ShapeUtilities.equal(this.legendItemShape, that.legendItemShape)) { return false; } if (!PaintUtilities.equal(this.seriesPaint, that.seriesPaint)) { return false; } if (!this.seriesPaintList.equals(that.seriesPaintList)) { return false; } if (!PaintUtilities.equal(this.baseSeriesPaint, that.baseSeriesPaint)) { return false; } if (!PaintUtilities.equal(this.seriesOutlinePaint, that.seriesOutlinePaint)) { return false; } if (!this.seriesOutlinePaintList.equals(that.seriesOutlinePaintList)) { return false; } if (!PaintUtilities.equal(this.baseSeriesOutlinePaint, that.baseSeriesOutlinePaint)) { return false; } if (!ObjectUtilities.equal(this.seriesOutlineStroke, that.seriesOutlineStroke)) { return false; } if (!this.seriesOutlineStrokeList.equals( that.seriesOutlineStrokeList)) { return false; } if (!this.baseSeriesOutlineStroke.equals( that.baseSeriesOutlineStroke)) { return false; } if (!this.labelFont.equals(that.labelFont)) { return false; } if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) { return false; } if (!this.labelGenerator.equals(that.labelGenerator)) { return false; } if (!ObjectUtilities.equal(this.toolTipGenerator, that.toolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.urlGenerator, that.urlGenerator)) { return false; } return true; } /** * Returns a clone of this plot. * * @return A clone of this plot. * * @throws CloneNotSupportedException if the plot cannot be cloned for * any reason. */ public Object clone() throws CloneNotSupportedException { SpiderWebPlot clone = (SpiderWebPlot) super.clone(); clone.legendItemShape = ShapeUtilities.clone(this.legendItemShape); clone.seriesPaintList = (PaintList) this.seriesPaintList.clone(); clone.seriesOutlinePaintList = (PaintList) this.seriesOutlinePaintList.clone(); clone.seriesOutlineStrokeList = (StrokeList) this.seriesOutlineStrokeList.clone(); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendItemShape, stream); SerialUtilities.writePaint(this.seriesPaint, stream); SerialUtilities.writePaint(this.baseSeriesPaint, stream); SerialUtilities.writePaint(this.seriesOutlinePaint, stream); SerialUtilities.writePaint(this.baseSeriesOutlinePaint, stream); SerialUtilities.writeStroke(this.seriesOutlineStroke, stream); SerialUtilities.writeStroke(this.baseSeriesOutlineStroke, stream); SerialUtilities.writePaint(this.labelPaint, stream); SerialUtilities.writePaint(this.axisLinePaint, stream); SerialUtilities.writeStroke(this.axisLineStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendItemShape = SerialUtilities.readShape(stream); this.seriesPaint = SerialUtilities.readPaint(stream); this.baseSeriesPaint = SerialUtilities.readPaint(stream); this.seriesOutlinePaint = SerialUtilities.readPaint(stream); this.baseSeriesOutlinePaint = SerialUtilities.readPaint(stream); this.seriesOutlineStroke = SerialUtilities.readStroke(stream); this.baseSeriesOutlineStroke = SerialUtilities.readStroke(stream); this.labelPaint = SerialUtilities.readPaint(stream); this.axisLinePaint = SerialUtilities.readPaint(stream); this.axisLineStroke = SerialUtilities.readStroke(stream); if (this.dataset != null) { this.dataset.addChangeListener(this); } } }
package org.pitest.maven; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; /** * Goal which runs a coverage mutation report */ @Mojo(name = "mutationCoverage", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.TEST) public class PitMojo extends AbstractPitMojo { protected final Predicate<Artifact> filter; // Concrete List types declared for all fields to work around maven 2 bug /** * List of places where to add to classpath for mutating * * @parameter expression="${mutationClasspaths}" * */ protected ArrayList<String> mutationClasspaths; /** * Classes to include in mutation test * * @parameter expression="${targetClasses}" * */ protected ArrayList<String> targetClasses; /** * Tests to run * * @parameter expression="${targetTests}" * */ protected ArrayList<String> targetTests; /** * Methods not to mutate * * @parameter expression="${excludedMethods}" * */ private ArrayList<String> excludedMethods; /** * Classes not to mutate or run tests from * * @parameter expression="${excludedClasses}" * */ private ArrayList<String> excludedClasses; /** * * @parameter expression="${avoidCallsTo}" * */ private ArrayList<String> avoidCallsTo; /** * Base directory where all reports are written to. * * @parameter default-value="${project.build.directory}/pit-reports" * expression="${reportsDirectory}" */ private File reportsDirectory; /** * File to write history information to for incremental analysis * * @parameter expression="${historyOutputFile}" */ private File historyOutputFile; /** * File to read history from for incremental analysis (can be same as output * file) * * @parameter expression="${historyInputFile}" */ private File historyInputFile; /** * Maximum distance to look from test to class. Relevant when mutating static * initializers * * @parameter default-value="-1" expression="${maxDependencyDistance}" */ private int maxDependencyDistance; /** * Number of threads to use * * @parameter default-value="1" expression="${threads}" */ private int threads; /** * Mutate static initializers * * @parameter default-value="false" expression="${mutateStaticInitializers}" */ private boolean mutateStaticInitializers; /** * Detect inlined code * * @parameter default-value="true" expression="${detectInlinedCode}" */ private boolean detectInlinedCode; /** * Mutation operators to apply * * @parameter expression="${mutators}" */ private ArrayList<String> mutators; /** * Weighting to allow for timeouts * * @parameter default-value="1.25" expression="${timeoutFactor}" */ private float timeoutFactor; /** * Constant factor to allow for timeouts * * @parameter default-value="3000" expression="${timeoutConstant}" */ private long timeoutConstant; /** * Maximum number of mutations to allow per class * * @parameter default-value="-1" expression="${maxMutationsPerClass}" */ private int maxMutationsPerClass; /** * Arguments to pass to child processes * * @parameter */ private ArrayList<String> jvmArgs; /** * Formats to output during analysis phase * * @parameter expression="${outputFormats}" */ private ArrayList<String> outputFormats; /** * Output verbose logging * * @parameter default-value="false" expression="${verbose}" */ private boolean verbose; /** * Throw error if no mutations found * * @parameter default-value="true" expression="${failWhenNoMutations}" */ private boolean failWhenNoMutations; /** * Create timestamped subdirectory for report * * @parameter default-value="true" expression="${timestampedReports}" */ private boolean timestampedReports; /** * TestNG Groups/JUnit Categories to exclude * * @parameter expression="${excludedGroups}" */ private ArrayList<String> excludedGroups; /** * TestNG Groups/JUnit Categories to include * * @parameter expression="${includedGroups}" */ private ArrayList<String> includedGroups; /** * Maximum number of mutations to include in a single analysis unit. * * @parameter expression="${mutationUnitSize}" */ private int mutationUnitSize; /** * Export line coverage data * * @parameter default-value="false" expression="${exportLineCoverage}" */ private boolean exportLineCoverage; /** * Mutation score threshold at which to fail build * * @parameter default-value="0" expression="${mutationThreshold}" */ private int mutationThreshold; /** * Line coverage threshold at which to fail build * * @parameter default-value="0" expression="${coverageThreshold}" */ private int coverageThreshold; /** * Path to java executable to use when running tests. Will default * to executable in JAVA_HOME if none set. * * @parameter */ private String jvm; /** * Engine to use when generating mutations. * * @parameter default-value="gregor" expression="${mutationEngine}" */ private String mutationEngine; /** * Parameter to set if to run mutations * * @parameter default-value="true" expression="${runMutations}" */ private boolean runMutations; /** * <i>Internal</i>: Project to interact with. * * @parameter expression="${project}" * @required * @readonly */ protected MavenProject project; /** * <i>Internal</i>: Map of plugin artifacts. * * @parameter expression="${plugin.artifactMap}" * @required * @readonly */ private Map<String, Artifact> pluginArtifactMap; protected final GoalStrategy goalStrategy; public PitMojo() { this(new RunPitStrategy(), new DependencyFilter()); } public PitMojo(final GoalStrategy strategy, Predicate<Artifact> filter) { this.goalStrategy = strategy; this.filter = filter; } public final void execute() throws MojoExecutionException, MojoFailureException { if (shouldRun()) { for ( ToolClasspathPlugin each : PluginServices.findToolClasspathPlugins() ) { this.getLog().info("Found plugin : " + each.description()); } for ( ClientClasspathPlugin each : PluginServices.findClientClasspathPlugins() ) { this.getLog().info("Found shared classpath plugin : " + each.description()); } final Option<CombinedStatistics> result = analyse(); if (result.hasSome()) { throwErrorIfScoreBelowThreshold(result.value().getMutationStatistics()); throwErrorIfCoverageBelowThreshold(result.value().getCoverageSummary()); } } else { this.getLog().info("Skipping project"); } } private void throwErrorIfCoverageBelowThreshold( CoverageSummary coverageSummary) throws MojoFailureException { if ((this.coverageThreshold != 0) && (coverageSummary.getCoverage() < this.coverageThreshold)) { throw new MojoFailureException("Line coverage of " + coverageSummary.getCoverage() + " is below threshold of " + this.coverageThreshold); } } private void throwErrorIfScoreBelowThreshold(final MutationStatistics result) throws MojoFailureException { if ((this.mutationThreshold != 0) && (result.getPercentageDetected() < this.mutationThreshold)) { throw new MojoFailureException("Mutation score of " + result.getPercentageDetected() + " is below threshold of " + this.mutationThreshold); } } protected Option<CombinedStatistics> analyse() throws MojoExecutionException { final ReportOptions data = new MojoToReportOptionsConverter(this, filter).convert(); return Option.some(this.goalStrategy.execute(detectBaseDir(), data)); } protected File detectBaseDir() { // execution project doesn't seem to always be available. // possibily a maven 2 vs maven 3 issue? final MavenProject executionProject = this.project.getExecutionProject(); if (executionProject == null) { return null; } return executionProject.getBasedir(); } public List<String> getMutationClasspaths() { return this.mutationClasspaths; } public List<String> getTargetClasses() { return this.targetClasses; } public List<String> getTargetTests() { return this.targetTests; } public List<String> getExcludedMethods() { return this.excludedMethods; } public List<String> getExcludedClasses() { return this.excludedClasses; } public List<String> getAvoidCallsTo() { return this.avoidCallsTo; } public File getReportsDirectory() { return this.reportsDirectory; } public int getMaxDependencyDistance() { return this.maxDependencyDistance; } public int getThreads() { return this.threads; } public boolean isMutateStaticInitializers() { return this.mutateStaticInitializers; } public List<String> getMutators() { return this.mutators; } public float getTimeoutFactor() { return this.timeoutFactor; } public long getTimeoutConstant() { return this.timeoutConstant; } public int getMaxMutationsPerClass() { return this.maxMutationsPerClass; } public List<String> getJvmArgs() { return this.jvmArgs; } public List<String> getOutputFormats() { return this.outputFormats; } public boolean isVerbose() { return this.verbose; } public MavenProject getProject() { return this.project; } public Map<String, Artifact> getPluginArtifactMap() { return this.pluginArtifactMap; } public boolean isFailWhenNoMutations() { return this.failWhenNoMutations; } public List<String> getExcludedGroups() { return this.excludedGroups; } public List<String> getIncludedGroups() { return this.includedGroups; } public int getMutationUnitSize() { return this.mutationUnitSize; } public boolean isTimestampedReports() { return this.timestampedReports; } public boolean isDetectInlinedCode() { return this.detectInlinedCode; } public void setTimestampedReports(final boolean timestampedReports) { this.timestampedReports = timestampedReports; } public File getHistoryOutputFile() { return this.historyOutputFile; } public File getHistoryInputFile() { return this.historyInputFile; } public boolean isExportLineCoverage() { return this.exportLineCoverage; } protected boolean shouldRun() { return !this.project.getPackaging().equalsIgnoreCase("pom"); } public String getMutationEngine() { return this.mutationEngine; } public String getJavaExecutable() { return jvm; } public void setJavaExecutable(String javaExecutable) { this.jvm = javaExecutable; } public boolean isRunMutations() { return this.runMutations; } }
public class Doublecheck { static private Object o; static private volatile Object v; static private String s; static private int i; static private long j; static private Object lock = new Object(); static public Object standardDoubleCheck() { if (o == null) { synchronized (lock) { if (o == null) o = new Object(); } } return o; } static public Object volatileDoubleCheck() { if (v == null) { synchronized (lock) { if (v == null) v = new Object(); } } return o; } static public String stringDoubleCheck() { if (s == null) { synchronized (lock) { if (s == null) s = Thread.currentThread().toString(); } } return s; } static public int intDoubleCheck() { if (i == 0) { synchronized (lock) { if (i == 0) i = Thread.currentThread().hashCode(); } } return i; } static public long longDoubleCheck() { if (j == 0) { synchronized (lock) { if (j == 0) j = System.currentTimeMillis(); } } return j; } }
package butterknife; import android.app.Activity; import android.view.View; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Method; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.lang.ClassNotFoundException; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.JavaFileObject; import static javax.lang.model.element.ElementKind.CLASS; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import static javax.tools.Diagnostic.Kind.ERROR; /** View injection utilities. */ public class Views { private Views() { // No instances. } public enum Finder { VIEW { @SuppressWarnings("unchecked") @Override public <T extends View> T findById(Object source, int id) { return (T) ((View) source).findViewById(id); } }, ACTIVITY { @SuppressWarnings("unchecked") @Override public <T extends View> T findById(Object source, int id) { return (T) ((Activity) source).findViewById(id); } }; public abstract <T extends View> T findById(Object source, int id); } private static final Map<Class<?>, Method> INJECTORS = new LinkedHashMap<Class<?>, Method>(); /** * Inject fields annotated with {@link InjectView} in the specified {@link Activity}. The current * content view is used as the view root. * * @param target Target activity for field injection. * @throws UnableToInjectException if injection could not be performed. */ public static void inject(Activity target) { inject(target, target, Finder.ACTIVITY); } /** * Inject fields annotated with {@link InjectView} in the specified {@link View}. The view and * its children are used as the view root. * * @param target Target view for field injection. * @throws UnableToInjectException if injection could not be performed. */ public static void inject(View target) { inject(target, target, Finder.VIEW); } /** * Inject fields annotated with {@link InjectView} in the specified {@code source} using the * {@code target} {@link Activity} as the view root. * * @param target Target class for field injection. * @param source Activity on which IDs will be looked up. * @throws UnableToInjectException if injection could not be performed. */ public static void inject(Object target, Activity source) { inject(target, source, Finder.ACTIVITY); } /** * Inject fields annotated with {@link InjectView} in the specified {@code source} using the * {@code target} {@link View} as the view root. * * @param target Target class for field injection. * @param source View root on which IDs will be looked up. * @throws UnableToInjectException if injection could not be performed. */ public static void inject(Object target, View source) { inject(target, source, Finder.VIEW); } private static void inject(Object target, Object source, Finder finder) { if (target == null) throw new UnableToInjectException("target of injection cannot be null"); Class<?> targetClass = target.getClass(); try { Method inject = INJECTORS.get(targetClass); if (inject == null) { Class<?> injector = Class.forName(targetClass.getName() + InjectViewProcessor.SUFFIX); inject = injector.getMethod("inject", Finder.class, targetClass, Object.class); INJECTORS.put(targetClass, inject); } inject.invoke(null, finder, target, source); } catch (ClassNotFoundException e) { // Allows inject to be called on targets without injected Views INJECTORS.put(targetClass, NO_OP); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new UnableToInjectException("Unable to inject views for " + target, e); } } /** No-op method for use for Classes that don't have any {@link View}s to inject. */ public static void noOp(Object finder, Object target, Object source) { } /** No-op method reference */ private static final Method NO_OP = Views.class.getMethod("noOp", Object.class, Object.class, Object.class); /** Simpler version of {@link View#findViewById(int)} which infers the target type. */ @SuppressWarnings({ "unchecked", "UnusedDeclaration" }) // Checked by runtime cast, helper method. public static <T extends View> T findById(View view, int id) { return (T) view.findViewById(id); } /** Simpler version of {@link Activity#findViewById(int)} which infers the target type. */ @SuppressWarnings({ "unchecked", "UnusedDeclaration" }) // Checked by runtime cast, helper method. public static <T extends View> T findById(Activity activity, int id) { return (T) activity.findViewById(id); } public static class UnableToInjectException extends RuntimeException { UnableToInjectException(String message, Throwable cause) { super(message, cause); } } @SupportedAnnotationTypes("butterknife.InjectView") public static class InjectViewProcessor extends AbstractProcessor { static final String SUFFIX = "$$ViewInjector"; @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } private void error(Element element, String message, Object... args) { processingEnv.getMessager().printMessage(ERROR, String.format(message, args), element); } @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) { Elements elementUtils = processingEnv.getElementUtils(); Types typeUtils = processingEnv.getTypeUtils(); Filer filer = processingEnv.getFiler(); TypeMirror viewType = elementUtils.getTypeElement("android.view.View").asType(); Map<TypeElement, Set<InjectionPoint>> injectionsByClass = new LinkedHashMap<TypeElement, Set<InjectionPoint>>(); Set<TypeMirror> injectionTargets = new HashSet<TypeMirror>(); for (Element element : env.getElementsAnnotatedWith(InjectView.class)) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type extends from View. if (!typeUtils.isSubtype(element.asType(), viewType)) { error(element, "@InjectView fields must extend from View (%s.%s).", enclosingElement.getQualifiedName(), element); continue; } // Verify field properties. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) { error(element, "@InjectView fields must not be private or static (%s.%s).", enclosingElement.getQualifiedName(), element); continue; } // Verify containing type. if (enclosingElement.getKind() != CLASS) { error(element, "@InjectView field annotations may only be specified in classes (%s).", enclosingElement); continue; } // Verify containing class visibility is not private. if (enclosingElement.getModifiers().contains(PRIVATE)) { error(element, "@InjectView fields may not be on private classes (%s).", enclosingElement); continue; } // Get and optionally create a set of all injection points for a type. Set<InjectionPoint> injections = injectionsByClass.get(enclosingElement); if (injections == null) { injections = new HashSet<InjectionPoint>(); injectionsByClass.put(enclosingElement, injections); } // Assemble information on the injection point. String variableName = element.getSimpleName().toString(); int value = element.getAnnotation(InjectView.class).value(); injections.add(new InjectionPoint(variableName, value)); // Add to the valid injection targets set. injectionTargets.add(enclosingElement.asType()); } for (Map.Entry<TypeElement, Set<InjectionPoint>> injection : injectionsByClass.entrySet()) { TypeElement type = injection.getKey(); Set<InjectionPoint> injectionPoints = injection.getValue(); String targetType = type.getQualifiedName().toString(); String packageName = elementUtils.getPackageOf(type).getQualifiedName().toString(); String className = type.getQualifiedName().toString().substring(packageName.length() + 1).replace('.', '$') + SUFFIX; String parentClass = resolveParentType(type, injectionTargets); StringBuilder injections = new StringBuilder(); if (parentClass != null) { injections.append(String.format(PARENT, parentClass)).append('\n'); } for (InjectionPoint injectionPoint : injectionPoints) { injections.append(injectionPoint).append('\n'); } // Write the view injector class. try { JavaFileObject jfo = filer.createSourceFile(packageName + "." + className, type); Writer writer = jfo.openWriter(); writer.write( String.format(INJECTOR, packageName, className, targetType, injections.toString())); writer.flush(); writer.close(); } catch (IOException e) { error(type, "Unable to write injector for type %s: %s", type, e.getMessage()); } } return true; } /** Finds the parent injector type in the supplied set, if any. */ private String resolveParentType(TypeElement typeElement, Set<TypeMirror> parents) { TypeMirror type; while (true) { type = typeElement.getSuperclass(); if (type.getKind() == TypeKind.NONE) { return null; } if (parents.contains(type)) { return type.toString(); } typeElement = (TypeElement) ((DeclaredType) type).asElement(); } } private static class InjectionPoint { private final String variableName; private final int value; InjectionPoint(String variableName, int value) { this.variableName = variableName; this.value = value; } @Override public String toString() { return String.format(INJECTION, variableName, value); } } private static final String INJECTION = " target.%s = finder.findById(source, %s);"; private static final String PARENT = " %s.inject(finder, target, source);"; private static final String INJECTOR = "" + "// Generated code from Butter Knife. Do not modify!\n" + "package %s;\n\n" + "import butterknife.Views.Finder;\n\n" + "public class %s {\n" + " public static void inject(Finder finder, %s target, Object source) {\n" + "%s" + " }\n" + "}\n"; } }
package com.trywildcard.pair.extraction; import com.google.common.collect.ImmutableSet; import com.trywildcard.pair.exception.CardBuilderException; import com.trywildcard.pair.util.HtmlParserUtil; import com.trywildcard.pair.util.HttpAgent; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import static com.trywildcard.pair.extraction.MetaTagModel.*; public class MetaTagExtractor { private static final Set<String> EXTRACTABLE_TWITTER_META_TAG_ATTRIBUTES = ImmutableSet.of("twitter:title", "twitter:description", "twitter:image", "twitter:image:src", "twitter:app:url:iphone", "twitter:app:url:googleplay", "twitter:player", "twitter:player:width", "twitter:player:height"); private static final Set<String> EXTRACTABLE_OG_META_TAG_ATTRIBUTES = ImmutableSet.of("og:title", "og:description", "og:image", "og:image:width", "og:image:height", "og:price:amount", "product:price:amount", "og:video", "og:video:width", "og:video:height"); private static final Set<String> EXTRACTABLE_AL_META_TAG_ATTRIBUTES = ImmutableSet.of("al:android:url", "al:ios:url"); private static String getMetaTagKey(String attribute) { if (attribute == null) { return null; } switch (attribute.toLowerCase()) { case "twitter:title": return TITLE_DATA_KEY; case "twitter:description": return DESCRIPTION_DATA_KEY; case "twitter:image": return IMAGE_URL_DATA_KEY; case "twitter:image:src": return IMAGE_URL_DATA_KEY; case "og:title": return TITLE_DATA_KEY; case "og:description": return DESCRIPTION_DATA_KEY; case "og:image": return IMAGE_URL_DATA_KEY; case "og:image:height": return IMAGE_HEIGHT_DATA_KEY; case "og:image:width": return IMAGE_WIDTH_DATA_KEY; case "og:price:amount": return PRICE_DATA_KEY; case "product:price:amount": return PRICE_DATA_KEY; case "twitter:app:url:iphone": return APP_LINK_IOS; case "twitter:app:url:googleplay": return APP_LINK_ANDROID; case "al:ios:url": return APP_LINK_IOS; case "al:android:url": return APP_LINK_ANDROID; case "og:video": return VIDEO_URL_DATA_KEY; case "og:video:width": return VIDEO_WIDTH_DATA_KEY; case "og:video:height": return VIDEO_HEIGHT_DATA_KEY; case "twitter:player": return VIDEO_URL_DATA_KEY; case "twitter:player:width": return VIDEO_WIDTH_DATA_KEY; case "twitter:player:height": return VIDEO_HEIGHT_DATA_KEY; default: return null; } } protected static MetaTagModel getMetaTags(String htmlContent) throws CardBuilderException { Map<String, String> metaTagsAndValues = new HashMap<String, String>(); //lets store htmlcontent - may be used for article or review cards metaTagsAndValues.put(HTML_DATA_KEY, htmlContent); Document htmlDocumentModel = HtmlParserUtil.getHtmlDocumentModel(htmlContent); NodeList metaTags = htmlDocumentModel.getElementsByTagName("meta"); for (int i = 0; i < metaTags.getLength(); i++) { Node node = metaTags.item(i); NamedNodeMap attributes = node.getAttributes(); String key = getMetaKey(attributes); if (key == null || metaTagsAndValues.containsKey(getMetaTagKey(key))) { continue; } if (EXTRACTABLE_OG_META_TAG_ATTRIBUTES.contains(key.toLowerCase())) { String content = getMetaValue(attributes); if (content != null && !content.isEmpty()) { metaTagsAndValues.put(getMetaTagKey(key), content); } } else if (EXTRACTABLE_AL_META_TAG_ATTRIBUTES.contains(key.toLowerCase())) { String content = getMetaValue(attributes); if (content != null && !content.isEmpty()) { metaTagsAndValues.put(getMetaTagKey(key), content); } } else if (EXTRACTABLE_TWITTER_META_TAG_ATTRIBUTES.contains(key.toLowerCase())) { String content = getMetaValue(attributes); if (content != null && !content.isEmpty()) { metaTagsAndValues.put(getMetaTagKey(key), content); } } } return new MetaTagModel(metaTagsAndValues); } protected static String getHtmlTitleTag(String htmlContent) { Document htmlDocumentModel = HtmlParserUtil.getHtmlDocumentModel(htmlContent); NodeList titleTags = htmlDocumentModel.getElementsByTagName("title"); if (titleTags.getLength() == 0) { return null; } else { //get first one Node titleNode = titleTags.item(0); return titleNode.getTextContent(); } } public static String getHtmlTitle(URL webUrl) { try { HttpAgent httpAgent = new HttpAgent(); String htmlContent = httpAgent.get(webUrl.toString()); return getHtmlTitleTag(htmlContent); } catch (URISyntaxException use) { return null; } catch (IOException ioe) { return null; } catch (RuntimeException rte) { return null; } } public static MetaTagModel getMetaTags(URL webUrl) throws CardBuilderException { try { HttpAgent httpAgent = new HttpAgent(); String htmlContent = httpAgent.get(webUrl.toString()); return getMetaTags(htmlContent); } catch (URISyntaxException use) { return new MetaTagModel(Collections.EMPTY_MAP); } catch (IOException ioe) { return new MetaTagModel(Collections.EMPTY_MAP); } catch (RuntimeException rte) { return new MetaTagModel(Collections.EMPTY_MAP); } } /** * @param attributes - the node map for the meta tag * @return the value of the key */ private static String getMetaKey(NamedNodeMap attributes) { Node keyAttribute = attributes.getNamedItem("name"); if (keyAttribute == null) { keyAttribute = attributes.getNamedItem("property"); } if (keyAttribute == null) { return null; } return keyAttribute.getNodeValue(); } /** * @param attributes - the node map for the meta tag * @return the value of the value */ private static String getMetaValue(NamedNodeMap attributes) { Node contentAttribute = attributes.getNamedItem("content"); if (contentAttribute == null) { contentAttribute = attributes.getNamedItem("value"); } if (contentAttribute == null) { return null; } return contentAttribute.getNodeValue(); } }
package controller; import view.*; import java.awt.Toolkit; import java.awt.Window; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.*; import java.io.IOException; import java.util.ArrayList; import javax.swing.*; import exceptions.*; import model.dao.*; import model.entity.*; import persistence.FileWrite; public class Controller implements ActionListener, KeyListener, DropTargetListener { private MainWindow mainWindow; private OwnerManager ownerManager; private ProductManager productManager; private UserManager userManager; private User user; private Owner owner; private Nueve dialogAddOwner; private Cuatro viewCuatro; private Dos viewdos; private Diez viewDiez; private DialogLogIn dialogLogIn; private Seis seis; private User userActual; private Owner ownerActual; private Cinco cinco; private FileWrite fileWrite; private Doce doce; private DialogOptions options; private int position; private KeyListenerForLogin keyListener; private OrderManager orderManager; public Controller() { keyListener = new KeyListenerForLogin(this); options = new DialogOptions(this, mainWindow); doce = new Doce(this, mainWindow); seis = new Seis(this); fileWrite = new FileWrite(); cinco = new Cinco(this); ownerManager = new OwnerManager(); userManager = new UserManager(); dialogLogIn = new DialogLogIn(this, keyListener); productManager = new ProductManager(); mainWindow = new MainWindow(this); mainWindow.setVisible(true); viewdos = new Dos(this, mainWindow); viewCuatro = new Cuatro(this); viewDiez = new Diez(this); userActual = null; ownerActual = null; dialogAddOwner = new Nueve(this, mainWindow); orderManager = new OrderManager(); ownerManager.addOwner(OwnerManager.createOwner("Mc Donalds", "s", "src/image/mcDonalds.jpg")); ownerManager.addOwner(OwnerManager.createOwner("El Pirata", "z", "src/image/ElPirata.jpg")); ownerManager.addOwner(OwnerManager.createOwner("Al Toque", "z", "src/image/AlToque.png")); userManager.addUser(UserManager.createUser("Juan", "X", true)); productManager.addProduct(ProductManager.createProduct("Hamburguesa Dijon", "deliciosa", 3000, State.RECEIVED, "src/image/HamburguerProduct.png")); productManager.addProduct( ProductManager.createProduct("Gaseosa Manzana", "deliciosa", 3000, State.RECEIVED, "src/image/BebidaProducto.png")); productManager.addProduct( ProductManager.createProduct("Gaseosa Manzana", "deliciosa", 3000, State.RECEIVED, "src/image/BebidaProducto.png")); productManager.addProduct(ProductManager.createProduct("Hamburguesa Dijon", "deliciosa", 3000, State.RECEIVED, "src/image/HamburguerProduct.png")); try { ownerManager.addAssignProductoToOwner(ownerManager .createAssignProductoToOwner(productManager.searchProductById(0), ownerManager.searchOwner(1))); ownerManager.addAssignProductoToOwner(ownerManager .createAssignProductoToOwner(productManager.searchProductById(1), ownerManager.searchOwner(1))); ownerManager.addAssignProductoToOwner(ownerManager .createAssignProductoToOwner(productManager.searchProductById(2), ownerManager.searchOwner(1))); ownerManager.addAssignProductoToOwner(ownerManager .createAssignProductoToOwner(productManager.searchProductById(3), ownerManager.searchOwner(1))); } catch (ExceptionSearchId e) { e.printStackTrace(); } } @Override public void actionPerformed(ActionEvent event) { switch (Actions.valueOf(event.getActionCommand())) { case LETS_DO_IT: letsDoIt(); break; case SIGN_IN: signIn(); break; case USER: userLogin(); break; case BUSINESS_OWNER: businessOwnerLogin(); break; case PRODUCT_ADD_MY_CAR: addMyProductToListOrder(Integer.parseInt(((JButton) event.getSource()).getName())); break; case JOIN: join(); break; case LOGIN: login(); break; case SIGN_UP: signIn(); break; case JOIN_ACCOUNT_OWNER: joinOwner(); break; case RESTAURANT: testingButtons(Integer.parseInt(((JButton) event.getSource()).getName())); break; case CREATE_PRODUCT: createProduct(); break; case GENERATE_ORDER: break; case CREATE_PRODUCT_NEW: showDialogcreateProduct(); break; case BACK_VIEW_THREE: backViewThree(); break; case SHOW_DIALOG_OPTIONS: showDialogOptionsRestaurant(); break; case BACK_OF_OPTIONS_DIALOG: dontShowOptionsDialog(); break; case EDIT_PRODUCT_BYOWNER: showProductByOwner(Integer.parseInt(((JButton) event.getSource()).getName())); break; case SAVE_EDITED_PRODUCT: saveEditedProductByOwner(); break; case SEARCH_PRODUCT_BYWORD: searchProductsByOwner(); break; case SEARCH_OWNER_BYWORD: searchOwnersByUser(); break; case SHOW_MENU_FOR_OWNER: showMenuOwner(); break; case SHOW_ORDERS_FOR_OWNER: showOrdersOwner(); break; case BACK_SIX: backsix(); break; case EXIT: System.exit(0); break; case CHANGE_STATUS: break; case GENERATE_SHOPPING_CAR: generateShoppingCar(); break; } } private void generateShoppingCar() { seis.fillPanelCenter(orderManager.getShoppingCarList()); } private void backsix() { cinco.setVisible(false); seis.setVisible(true); } //Este metodo es para mostrar las ordenes que tiene un restaurante. Utilizar el metodo de la clase Diez, agregarpaneles private void showOrdersOwner() { } private void showMenuOwner() { try { viewDiez.addPanelsToDialogForProducts(ownerManager.searchAssignProductoToOwner(ownerActual.getId())); } catch (ExceptionSearchId e) { e.printStackTrace(); } } private void searchOwnersByUser(){ seis.addPanelsToDialogForProducts(ownerManager.searchOwnersByWord(seis.getWordOnSpace())); } private void searchProductsByOwner() { try { ArrayList<Product> products = ownerManager.searchProductByWord(viewDiez.getWordOnSpace(), ownerManager.searchAssignProductoToOwner(ownerActual.getId())); viewDiez.addPanelsToDialogForProducts(products); } catch (ExceptionSearchId e) { e.printStackTrace(); } } private void saveEditedProductByOwner() { try { Product product = productManager.searchProductById(position); product.setAttributes(doce.getNameProduct(), doce.getDescriptionProduct(), doce.getPriceProduct(), doce.getImageProduct()); viewDiez.addPanelsToDialogForProducts(ownerManager.searchAssignProductoToOwner(ownerActual.getId())); viewDiez.setVisible(true); doce.setVisible(false); doce.clear(); } catch (ExceptionSearchId e) { e.printStackTrace(); } } private void showProductByOwner(int idProduct) { try { viewDiez.setVisible(false); doce.editProduct(productManager.searchProductById(idProduct)); position = idProduct; doce.setVisible(true); } catch (ExceptionSearchId e1) { } } private void showDialogcreateProduct() { viewDiez.setVisible(false); options.setVisible(false); doce.addProduct(); doce.setVisible(true); } private void dontShowOptionsDialog() { options.setVisible(false); } private void showDialogOptionsRestaurant() { options.setVisible(true); } private void backViewThree() { seis.setVisible(false); seis.clear(); dialogLogIn.setVisible(true); viewDiez.clear(); options.setVisible(false); viewDiez.setVisible(false); } public void createProduct() { try { Product product = doce.createProduct(); productManager.addProduct(product); ownerManager.addAssignProductoToOwner(ownerManager.createAssignProductoToOwner(product, ownerActual)); viewDiez.addPanelsToDialogForProducts(ownerManager.searchAssignProductoToOwner(ownerActual.getId())); viewDiez.setVisible(true); doce.setVisible(false); doce.clear(); } catch (ExceptionSearchId e) { e.printStackTrace(); } } // Este metodo arroja por consola los ID unicos para cada resturante private void testingButtons(int idOwner) { try { Owner owner = ownerManager.searchOwner(idOwner); cinco.fillCenter(ownerManager.searchAssignProductoToOwner(idOwner), this); cinco.changeNameOwner(owner.getName()); cinco.setVisible(true); } catch (ExceptionSearchId e1) { } } private void addMyProductToListOrder(int idProdcut) { try { Product product = productManager.searchProductById(idProdcut); cinco.counttotal(product.getPrice()); orderManager.addShoppingCarList(product); } catch (ExceptionSearchId e) { } } public void joinOwner() { try { ownerManager.addOwner(dialogAddOwner.createOwner()); fileWrite.saveOwner(ownerManager.getOwnerList()); dialogAddOwner.clear(); dialogAddOwner.setVisible(false); dialogLogIn.setVisible(true); } catch (ExceptionIncorrectPassword e) { dialogAddOwner.validatePasswordField(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void join() { try { userManager.addUser(viewdos.createUser()); fileWrite.saveUser(userManager.getUserList()); viewdos.clear(); viewdos.setVisible(false); dialogLogIn.setVisible(true); } catch (ExceptionIncorrectPassword e) { viewdos.validatePasswordField(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void login() { String nameUser = dialogLogIn.dataLogIn()[0]; try { User user = userManager.searchUserByName(nameUser); userActual = user; seis.addPanelsToDialogForProducts(ownerManager.getOwnerList()); seis.setVisible(true); dialogLogIn.setVisible(false); } catch (ExceptionSearchId e) { try { Owner owner = ownerManager.searchOwnerByName(nameUser); ownerActual = owner; viewDiez.addPanelsToDialogForProducts(ownerManager.searchAssignProductoToOwner(ownerActual.getId())); viewDiez.setVisible(true); dialogLogIn.setVisible(false); } catch (ExceptionSearchId f) { // JOptionPane.showMessageDialog(mainWindow, f.getMessage()); } } } public void businessOwnerLogin() { viewCuatro.setVisible(false); dialogAddOwner.setVisible(true); } public void userLogin() { viewCuatro.setVisible(false); viewdos.setVisible(true); } public void letsDoIt() { mainWindow.setVisible(false); dialogLogIn.setVisible(true); } public void signIn() { dialogLogIn.setVisible(false); mainWindow.setVisible(false); viewCuatro.setVisible(true); } public void closeAllWindows() { mainWindow.setVisible(false); viewCuatro.setVisible(false); } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { limitCharactersForToolbar(e); } public void limitCharactersForToolbar(KeyEvent e) { int limit = 38; if (viewDiez.getWordOnSpace().length() == limit) { e.consume(); } if (seis.getWordOnSpace().length() == limit) { e.consume(); } } @Override public void dragEnter(DropTargetDragEvent arg0) { } @Override public void dragExit(DropTargetEvent arg0) { } @Override public void dragOver(DropTargetDragEvent arg0) { } @Override public void drop(DropTargetDropEvent dtde) { dtde.acceptDrop(DnDConstants.ACTION_COPY); try { if (doce.isVisible() == true) { doce.addImage(dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor).toString().replace("[", "").replace("]", "").replace("\\", "/")); Toolkit.getDefaultToolkit().beep(); }else if (dialogAddOwner.isVisible() == true) { dialogAddOwner.addImage(dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor).toString().replace("[", "").replace("]", "").replace("\\", "/")); Toolkit.getDefaultToolkit().beep(); } } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } dtde.dropComplete(true); } @Override public void dropActionChanged(DropTargetDragEvent arg0) { } }
/** * University of British Columbia ("UBC") will freely share software * registered in the JA-SIG Clearing House with institutions of * higher-education for their non-profit use. The borrowing institution * will not share or distribute the software without the consent of * UBC. By its use, the borrowing institution agrees to indemnify * and hold harmless UBC against all loss, cost, damage, liability, * injury or expense, including reasonable attorneys' fees, arising out * of their use of the software. * * Those desiring to incorporate this software into commercial products * or use for commercial purposes should contact: * * Associate Director of Info Sys, ITServices, UBC * 6356 Agricultural Road * Vancouver, B.C., CANADA * V6T 1Z2 * * Tel: 604-822-6611 * * * SOFTWARE IS PROVIDED "AS IS." TO THE MAXIMUM EXTENT PERMITTED BY LAW, * UBC DISCLAIMS ALL WARRANTIES OF ANY KIND, EITHER EXPRESS OR * IMPLIED, INCLUDING, WITHOUT LIMITATION, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. UBC DOES * NOT WARRANT THAT THE FUNCTIONS OR INFORMATION CONTAINED IN SOFTWARE * WILL MEET ANY REQUIREMENTS OR NEEDS OF THE BORROWING INSTITUTION, OR * THAT SOFTWARE WILL OPERATE ERROR FREE, OR IN AN UNINTERRUPTED FASHION, * OR THAT ANY DEFECTS OR ERRORS IN SOFTWARE WILL BE CORRECTED, OR THAT * SOFTWARE IS COMPATIBLE WITH ANY PARTICULAR PLATFORM. * IN NO EVENT WILL UBC BE LIABLE TO ANY BORROWING INSTITUTION OR * ANY THIRD PARTY FOR ANY INCIDENTAL OR CONSEQUENTIAL DAMAGES * (INCLUDING, WITHOUT LIMITATION, INDIRECT, SPECIAL, PUNITIVE, OR * EXEMPLARY DAMAGES) ARISING OUT OF THE USE OF OR INABILITY TO USE * SOFTWARE, OR FOR ANY CLAIM BY ANY OTHER PARTY, EVEN IF UBC HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. */ /** * Web IMAP email channel * * @author George Lindholm, ITServices, UBC * @author Ken Weiner, IBS * @version $Revision$ */ package org.jasig.portal.channels; import javax.servlet.*; import javax.servlet.jsp.*; import javax.servlet.http.*; import javax.mail.*; import javax.mail.internet.*; import javax.mail.event.*; import javax.mail.search.*; import java.io.*; import java.util.*; import java.net.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.activation.DataHandler; import com.oreilly.servlet.multipart.FilePart; import org.jasig.portal.*; import org.jasig.portal.utils.XSLT; import org.jasig.portal.services.LogService; import org.jasig.portal.security.IPerson; import org.xml.sax.DocumentHandler; import java.util.zip.*; import org.w3c.tidy.Tidy; public final class CIMAPMail extends GenericPortalBean implements IChannel, HttpSessionBindingListener { private static String rcsVersion = "$Revision$"; // from rcs/cvs private static String clientVersion = "2.00c"; private static boolean DEBUG = false; // Configurable parameters private static class WebmailConfig { static String sName = null; static String sIMAPHost = null; // IMAP host static int iIMAPPort = 0; // IMAP port static String sSMTPHost = null; // IMAP host private static int iSMTPPort = 0; // IMAP port private static String sCaption = null; // Application name private static String sOrganization = null; // Service Provider name private static String sTrashName = null; // "Wastebasket" private static String sSentName = null; // "Sent Items" private static int iMaxMessageSize = 0; // Largest message we will send private static String sFolderDir = null; // users folder directory private static String sDomainName = null; // Our email domain private static String sSessionUsername = null; // session atribute for authenticated username private static String sSessionPassword = null; // session atribute for password of authenticated username private static String sLoginText = null; private static String sProtocol = "imap"; private static String sMailbox = "INBOX"; } private static WebmailConfig config = new WebmailConfig(); /** Returns channel runtime properties * @return handle to runtime properties */ public ChannelRuntimeProperties getRuntimeProperties () { // Channel will always render, so the default values are ok return new ChannelRuntimeProperties (); } /** Processes layout-level events coming from the portal * @param ev a portal layout event */ public void receiveEvent (PortalEvent ev) { // no events for this channel } private class UserPrefs { // Candidates for configurable parameters int iMsgsPerPage = 15; int iFldrsPerPage = 7; String sNavBarColor = "#99ccff"; String sHeaderColor = "#dddddd"; String sControlColor = "#ffffff"; String sColumnHeadersColor = "#cccccc"; // From, Subject, etc line String sTableCellColor = "#cafcac"; String sUnseenMsgColor = "#ffffcc"; // Unseen messages String sSeenMsgColor = "#99ccff"; // Seen messages boolean showFullHeaders = false; } private UserPrefs userPrefs = new UserPrefs(); private static String sDraftsName = "Drafts"; //"Drafts" // User configuration // button messages private static String nextMessageButtonTxt = "Next message"; private static String returnToMessageButtonTxt = "Return to "; private static String checkNewMailButtonTxt = "Check for new mail"; // Used to keep state // Initialized in respondToAuthentication //private int iMsgsStartAt; private boolean authenticated; private ActiveFolder activeFolder; private ActiveFolder inbox; private Comparator msgSortOrder; private ImapFolder imapFolders; private boolean onetimeSetupDone = false; // These should be deduced from portal authentication (hard-coded for now) private String sUser = null; //ask private String sPassword = null; // ask private String sUserEmail = null; // get from session private String sFullName = ""; // get from IPerson private static String layoutUrl = null; // get from HTTP request private static String portalHost = null; // URL to non-secure host private static String securePortalHost = null; // URL to secure host private boolean redirectBack = false; // return to http after https authentication private static String[] sSpecialFolderNames = null; // Folders managed by the client private URLName urlName = null; // imap url private Properties props = System.getProperties (); private Session session = null; private Store store = null; // Compilation constants private static boolean USE_APPLET = false; // Generate HTML code to use applet to access mail channel // Not used since it causes session timeouts to not work private FetchProfile fetchProfile = null; private char folderSeparator; // IMAP folder separator private static DateFormat httpDateFormat = new SimpleDateFormat("EE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); // Metrics about our session private class Metrics { int messagesRead = 0; int messagesDeleted = 0; int messagesMoved = 0; int messagesDownloaded = 0; int attachmentsViewed = 0; int messagesSent = 0; boolean showMetrics = true; public String toString() { return "Read " + messagesRead + ", Deleted " + messagesDeleted + ", Moved " + messagesMoved + ", Downloaded " + messagesDownloaded + ", Attachments " + attachmentsViewed + ", Sent " + messagesSent; } } private Metrics metrics = new Metrics(); private class ImapFolderException extends Exception { public ImapFolderException (){} public ImapFolderException (String eMsg) { super (eMsg); } } private class CIMAPLostConnectionException extends Exception { public CIMAPLostConnectionException (){super ();} public CIMAPLostConnectionException (String eMsg) { super (eMsg); } } private StoreListener storeListener = new StoreListener () { public void notification (StoreEvent e) { String eventMsg = e.getMessage (); int eventType = e.getMessageType (); if (DEBUG) LogService.instance().log(LogService.DEBUG, "store event: " + eventMsg + ", " + eventType); } }; private ChannelRuntimeData runtimeData = null; private static String fs = File.separator; private static String portalBaseDir = UtilitiesBean.getPortalBaseDir (); private static String stylesheetDir = portalBaseDir + "webpages" + fs + "stylesheets" + fs + "org" + fs + "jasig" + fs + "portal" + fs + "channels" + fs + "CIMAPMail"; private static final String sslLocation = stylesheetDir + fs + "CIMAPMail.ssl"; public CIMAPMail () { } private FolderListener folderListener = new FolderListener () { public void folderCreated (FolderEvent e) { try { //LogService.instance().log(LogService.DEBUG, "folder created event for " + e.getFolder().getName()); imapFolders.add (e.getFolder ()); } catch (MessagingException me) { LogService.instance().log(LogService.ERROR, "folderCreated" + me); } } public void folderDeleted (FolderEvent e) { //LogService.instance().log(LogService.DEBUG, "folder deleted event for " + e.getFolder().getName()); try { imapFolders.deleted (e.getFolder ().getName ()); } catch (ImapFolderException sfe) {} } public void folderRenamed (FolderEvent e) { //LogService.instance().log(LogService.DEBUG, "folder renamed event from " + e.getFolder().getName() + " to " + e.getNewFolder()); try { imapFolders.rename (e.getFolder ().getName (), e.getNewFolder ().getName ()); } catch (ImapFolderException sfe) { } } }; /** * Passes ChannelStaticData to the channel. * This is done during channel instantiation time. * see org.jasig.portal.StaticData * @param sd channel static data * @see ChannelStaticData */ private ChannelStaticData staticData; public void setStaticData (ChannelStaticData sd) { staticData = sd; String sParameter; IPerson person = sd.getPerson(); if (person != null) { sFullName = person.getFullName(); } if (sFullName == null) { sFullName = ""; } config.sName = sd.getParameter("name"); config.sIMAPHost = sd.getParameter("host"); props.put ("mail.smtp.host", config.sIMAPHost); sParameter = sd.getParameter("port"); if (sParameter != null) { try { config.iIMAPPort = Integer.parseInt (sParameter); } catch (NumberFormatException nfe) { } } if (config.iIMAPPort == 0) { config.iIMAPPort = 143; // IMAP default } config.sSMTPHost = sd.getParameter("smtphost"); if (config.sSMTPHost != null) { props.put ("mail.smtp.host", config.sSMTPHost); } sParameter = sd.getParameter("smtpport"); if (sParameter != null) { try { config.iSMTPPort = Integer.parseInt (sParameter); } catch (NumberFormatException nfe) { } } if (config.iSMTPPort == 0) { config.iSMTPPort = 25; // SMTP default } props.put ("mail.smtp.port", config.iSMTPPort + ""); config.sCaption = sd.getParameter("caption"); config.sOrganization = sd.getParameter("organization"); config.sDomainName = sd.getParameter("domain"); config.sSentName = sd.getParameter("sentName"); config.sTrashName = sd.getParameter("trashName"); config.sFolderDir = sd.getParameter("folderDir"); config.sSessionUsername = sd.getParameter("sessionUsername"); config.sSessionPassword = sd.getParameter("sessionPassword"); config.sLoginText = sd.getParameter("loginText"); if (config.sFolderDir != null && config.sFolderDir.trim ().length () == 0) { config.sFolderDir = null; } sSpecialFolderNames = new String[] {"Inbox", sDraftsName, config.sSentName, config.sTrashName}; fetchProfile = new FetchProfile (); fetchProfile.add (FetchProfile.Item.ENVELOPE); httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } public interface IXmlMethod { public abstract boolean isThisMethod(String methodName); public abstract void doit(ChannelRuntimeData rd) throws Exception; public abstract String renderString() throws Exception; public abstract StringWriter respond(String submitValue) throws Exception; public abstract StringWriter display() throws Exception; } private abstract class XmlMethod implements IXmlMethod { protected String weAre = "unknown"; public Exception exception = null; public String getWeAre() { return weAre; } public void setException(Exception e) { exception = e; LogService.instance().log(LogService.ERROR, e); } public boolean isThisMethod(String methodName) { return methodName.equals(weAre); } public void doit(ChannelRuntimeData rd) throws Exception { if (DEBUG) System.err.println("default doit for " + weAre); } public StringWriter respond (String submitValue) throws Exception { return null; } public String renderString() throws Exception { if (DEBUG) System.err.println("generic renderString for " + weAre); String submitValue = runtimeData.getParameter("submit"); if (DEBUG) System.err.println("submit=" + submitValue); if (submitValue != null) { StringWriter result = respond(submitValue); if (result != null) { return result.toString(); } else { return null; } } else { String xml = display().toString(); return xml; } } } private XmlMethod authenticateMethod = new Authenticate(); private XmlMethod statusMethod = new MailStatus(); private XmlMethod composeMethod = new ComposeMessage(); private XmlMethod displayMethod = new DisplayMessage(); private XmlMethod listMessages = new ListMessages(); private XmlMethod listFolders = new ListFolders(); private XmlMethod[] jumpTable = new XmlMethod[] { authenticateMethod, statusMethod, listMessages, displayMethod, composeMethod, listFolders, new SetupMethod(), }; private XmlMethod findJumptableEntry(String method) { for (int i = 0; i < jumpTable.length; i++) { if (jumpTable[i].isThisMethod(method)) { return jumpTable[i]; } } return null; } private XmlMethod activeMethod = null; private class Authenticate extends XmlMethod { String username; String password; public Authenticate() { weAre = "authenticate"; } public void doit(ChannelRuntimeData rd) { if (DEBUG) System.err.println("doit for " + weAre); runtimeData = rd; /* if (false && sUser == null) { // Get password from authentication stack HttpSession httpSession = rd.getHttpRequest().getSession (false); sUser = (String) httpSession.getAttribute (config.sSessionUsername); sPassword = (String) httpSession.getAttribute (config.sSessionPassword); } */ username = runtimeData.getParameter("username"); password = runtimeData.getParameter("password"); } public StringWriter display() { return null; } public String renderString() { String loginError = ""; try { initialize(username, password); if (DEBUG) System.err.println("authorized"); if (false) { //runtimeData.redirect("action=mailstatus"); return null; } else { activeMethod = statusMethod; return statusMethod.renderString(); } } catch (Exception e) { if (DEBUG) System.err.println(e); loginError = "<error>" + e.getMessage() + "</error>\n"; } if (DEBUG) System.err.println("renderString for " + weAre); return "<" + weAre + ">\n" + loginError + (config.sLoginText == null ? "" : "<loginText>" + config.sLoginText + "</loginText>") + "<username>" + (sUser == null ? "" : sUser) + "</username>\n</" + weAre + ">\n"; } } private class ListMessages extends XmlMethod { private String xslTag = "listMessages"; int iMsgsStartAt; int iMsgsEndAt; private String searchFolderButtonTxt = "Search Folder"; private String deleteMessagesButtonTxt = "Delete"; private String searchMessagesButtonTxt = "Search"; private String clearSearchMessagesButtonTxt = "Clear Search"; private String moveMessagesButtonTxt = "Move"; public ListMessages() { weAre = xslTag; reset(); } public void reset() { iMsgsStartAt = 0; iMsgsEndAt = userPrefs.iMsgsPerPage; msgSortOrder = ORDER_BY_DATE_ASCENDING; } public StringWriter respond(String submitValue) throws Exception { StringWriter xml = new StringWriter(); xml.write("<" + weAre + ">\n"); String allMessages = runtimeData.getParameter("AllMessages"); // If the user clicked "Delete", move selected messages to wastebasket if (submitValue.equals (checkNewMailButtonTxt)) { // Does nothing. The real work will be done in printHeader() } else if (submitValue.equals (searchMessagesButtonTxt)) { // Search the current folder for specific messages printSearchMsgForm(xml); xml.write("</" + weAre + ">\n"); return xml; } else if (submitValue.equals (clearSearchMessagesButtonTxt)) { activeFolder.clearSearch(); runtimeData.setParameter("page", "last"); return display(); } else if (submitValue.equals (searchFolderButtonTxt)) { String criteriaText = runtimeData.getParameter ("criteriatext"); String criteria = runtimeData.getParameter ("criteria"); if (criteriaText.trim().length() == 0) { return displayErrorMsg("Please specify the search text", false); } else if (criteria == null) { return displayErrorMsg("Please specify the search criteria", false); } SearchTerm term; if (criteria.equals("Sender")) { term = new FromStringTerm(criteriaText); } else if (criteria.equals("Subject")) { term = new SubjectTerm(criteriaText); } else { return displayErrorMsg(criteria + " is an unrecognized search item", true); } activeFolder.search(term); runtimeData.setParameter("page", "last"); } else if (submitValue.equals (deleteMessagesButtonTxt) || submitValue.equals (moveMessagesButtonTxt)) { String destinationFolder = config.sTrashName; if (submitValue.equals (moveMessagesButtonTxt)) { if ( (destinationFolder = runtimeData.getParameter ("destinationFolder1")).trim ().equals ("") && (destinationFolder = runtimeData.getParameter ("destinationFolder2")).trim ().equals ("")) { return displayErrorMsg ("Missing destination folder", true); } } if (allMessages == null || !allMessages.equalsIgnoreCase("on")) { String sMsgs[]; if ( (sMsgs = runtimeData.getParameterValues ("msg")) == null || sMsgs.length == 0) { return displayErrorMsg ("Please select the message(s) to be " + submitValue + "d", true); } Collection cMsgs = new ArrayList (sMsgs.length); for (int i = 0; i < sMsgs.length; i++) { try { int msg = Integer.parseInt (sMsgs[i]); Message deletedMessage = activeFolder.getMessage (msg); cMsgs.add (deletedMessage); } catch (Exception e) { LogService.instance().log(LogService.ERROR, "respondToMsgControls: Unable to get message " + sMsgs[i] + "in " + activeFolder.getFolderName() + ": " + e); } } if (cMsgs.size() > 0) { Message[] msgs = (Message[]) cMsgs.toArray (new Message[0]); activeFolder.removeMsg (msgs, destinationFolder); if (submitValue.equals (moveMessagesButtonTxt)) { metrics.messagesMoved += msgs.length; } else { metrics.messagesDeleted += msgs.length; } } if (cMsgs.size() != sMsgs.length) { return displayErrorMsg("Unable to delete some or all of your messages", false); } } else { // asked for all messages activeFolder.removeMsg (destinationFolder); } } return display(); } String newFolder = null; String pageIndex = null; public void setNewFolder(String newFolder) { this.newFolder = newFolder; } public void setPageIndex(String pageIndex) { this.pageIndex = pageIndex; } public void doit(ChannelRuntimeData rd) { if (DEBUG) System.err.println("doit for " + weAre); runtimeData = rd; String value; if ((value = runtimeData.getParameter("folder")) != null){ setNewFolder(value); } if ((value = runtimeData.getParameter("page")) != null){ setPageIndex(value); } } public StringWriter display() throws Exception{ if (DEBUG) System.err.println("renderString for " + weAre); StringWriter xml = new StringWriter(); if (activeFolder == null) { activeFolder = inbox; } if (DEBUG) System.err.println("list messages in " + newFolder); if (newFolder != null && !activeFolder.getFolderName().equalsIgnoreCase(newFolder)) { try { activeFolder.finalize (); // Free resources used for current folder } catch (FolderClosedException fce) { } activeFolder = createActiveFolder (newFolder); runtimeData.setParameter("page", "last"); } String sActiveFolderName = activeFolder.getFolderName (); xml.write("<" + weAre + (activeFolder.isFiltered() ? " filtered=\"yes\"" : "") + ">\n"); // Navigation bar printNavBar (xml); // Unread message count and title printHeader (sActiveFolderName, activeFolder.getUnreadMessageCount(), xml); int totalMsgs = activeFolder.getMessageCount (); if (totalMsgs > 0) { if (pageIndex != null) { if (pageIndex.equals("last")) { iMsgsEndAt = totalMsgs; if (iMsgsEndAt - userPrefs.iMsgsPerPage < 0) { iMsgsStartAt = 0; } else { iMsgsStartAt = iMsgsEndAt - userPrefs.iMsgsPerPage; } } else { try { iMsgsStartAt = Integer.parseInt(pageIndex); } catch (Exception e) { iMsgsStartAt = totalMsgs - userPrefs.iMsgsPerPage - 1; } } } if (iMsgsStartAt > totalMsgs) { iMsgsStartAt = totalMsgs - userPrefs.iMsgsPerPage - 1; } if (iMsgsStartAt < 0) { iMsgsStartAt = 0; } iMsgsEndAt = iMsgsStartAt + userPrefs.iMsgsPerPage; if (iMsgsEndAt > totalMsgs) { iMsgsEndAt = totalMsgs; } if (iMsgsStartAt > iMsgsEndAt - userPrefs.iMsgsPerPage) { iMsgsStartAt = iMsgsEndAt - userPrefs.iMsgsPerPage; } if (iMsgsStartAt < 0) { iMsgsStartAt = 0; } xml.write("<controls>\n"); xml.write("<buttons bgcolor=\"" + userPrefs.sControlColor + "\">"); xml.write("<folders>\n"); if (DEBUG) System.err.println(">folder list"); String[] folders = (String [])imapFolders.toArray(new String[0]); for (int iFldr = 0; iFldr < folders.length; iFldr++) { if (!activeFolder.getFolderName ().equalsIgnoreCase (folders[iFldr])) { xml.write("<folder value=\"" + folders[iFldr] + "\">" + folders[iFldr] + "</folder>"); } } if (DEBUG) System.err.println("<folder list"); xml.write("</folders>\n"); xml.write("</buttons>\n"); xml.write("</controls>\n"); xml.write("<pagination action=\"" + weAre + "\" bgcolor=\"" + userPrefs.sControlColor + "\""); if (iMsgsStartAt > userPrefs.iMsgsPerPage + 1) { xml.write(" first=\"0\""); } if (iMsgsStartAt > 1) { xml.write(" prev=\"" + (iMsgsStartAt - userPrefs.iMsgsPerPage) + "\""); } xml.write(" start=\"" + (iMsgsStartAt + 1) + "\" end=\"" + iMsgsEndAt + "\" total=\"" + totalMsgs + "\""); if (iMsgsEndAt < totalMsgs) { xml.write(" next=\"" + (iMsgsStartAt + userPrefs.iMsgsPerPage) + "\""); } if (iMsgsEndAt < totalMsgs && iMsgsEndAt + userPrefs.iMsgsPerPage < totalMsgs) { xml.write(" last=\"last\""); } xml.write("/>"); xml.write("<messages bgcolor=\"" + userPrefs.sColumnHeadersColor + "\">\n"); xml.write("<headers bgcolor=\"" + userPrefs.sColumnHeadersColor + "\">\n"); xml.write("<header align=\"center\">Select</header>\n"); xml.write("<header>&#160;</header>\n"); xml.write("<header value=\"from\" align=\"left\"" + ((msgSortOrder == ORDER_BY_FROM_ASCENDING || msgSortOrder == ORDER_BY_FROM_DESCENDING) ? " active=\"yes\"" : "") + ">From</header>\n"); xml.write("<header value=\"subject\" align=\"left\"" + ((msgSortOrder == ORDER_BY_SUBJECT_ASCENDING || msgSortOrder == ORDER_BY_SUBJECT_DESCENDING) ? " active=\"yes\"" : "") + ">Subject</header>\n"); xml.write("<header value=\"date\" align=\"left\"" + ((msgSortOrder == ORDER_BY_DATE_ASCENDING || msgSortOrder == ORDER_BY_DATE_DESCENDING) ? " active=\"yes\"" : "") + ">Time/Date</header>\n"); xml.write("<header value=\"size\" align=\"right\"" + ((msgSortOrder == ORDER_BY_SIZE_ASCENDING || msgSortOrder == ORDER_BY_SIZE_DESCENDING) ? " active=\"yes\"" : "") + ">Size</header>\n"); xml.write("</headers>\n"); if (DEBUG) System.err.println(">Fetching messages"); activeFolder.fetchHeaders (iMsgsStartAt, iMsgsEndAt); // Preload headers if (DEBUG) System.err.println("<Fetched messages"); // Loop through messages for (int iMsg = iMsgsStartAt; iMsg < iMsgsEndAt; iMsg++) { Message msg = activeFolder.getMessage (iMsg); //if (DEBUG) out.println ("#" + msg.getMessageNumber () + " " + getSystemFlags (msg)); if (msg.isSet (Flags.Flag.DELETED)) { continue; // Don't show deleted messages } String bg = (msg.isSet (Flags.Flag.SEEN) ? userPrefs.sSeenMsgColor : userPrefs.sUnseenMsgColor); xml.write("<message bgcolor=\"" + bg + "\" msg=\"" + iMsg + "\""); xml.write(" size=\"" + formatSize (msg.getSize ()) + "\""); if (msg.isSet (Flags.Flag.ANSWERED)) { xml.write(" status=\"R\""); } xml.write(sActiveFolderName.equals (sDraftsName) ? " draft=\"yes\"" : ""); xml.write(">\n"); // From Address[] addresses; xml.write("<from>\n"); if ( (addresses = msg.getFrom ()) != null) { for (int iAddr = 0; iAddr < addresses.length; iAddr++) { InternetAddress ia = (InternetAddress) addresses[iAddr]; String sPersonal = ia.getPersonal (); xml.write("<address>"); if (sPersonal != null) { xml.write("<personal>" + HTMLescape(sPersonal) + "</personal>"); } xml.write("<email>" + HTMLescape(ia.getAddress()) + "</email>"); xml.write("</address>\n"); } } xml.write("</from>\n"); // Subject String sSubject = msg.getSubject (); xml.write("<subject>"); if (sSubject == null || sSubject.trim ().length () == 0) { xml.write("[none]"); } else { xml.write(HTMLescape(sSubject)); } xml.write("</subject>\n"); // Time/Date Date date = msg.getSentDate (); xml.write("<date>" + (date != null ? date.toString () : "Unknown") + "</date>\n"); xml.write("</message>\n"); } xml.write("</messages>"); } else { //printMessageListControls (true, req, res, out); //out.println ("<p align=center><strong><em>This folder is empty.</em></strong><p>"); } xml.write("</" + weAre + ">\n"); return xml; } /** * sort a folder * @param the servlet request object * @param the servlet response object * @param the JspWriter object */ public StringWriter sortList () throws Exception { String sSortBy = runtimeData.getParameter ("sortBy"); if (sSortBy != null) { if (sSortBy.equals ("from")) { if (msgSortOrder == ORDER_BY_FROM_ASCENDING) { msgSortOrder = ORDER_BY_FROM_DESCENDING; } else { msgSortOrder = ORDER_BY_FROM_ASCENDING; } } else if (sSortBy.equals ("subject")) { if (msgSortOrder == ORDER_BY_SUBJECT_ASCENDING) { msgSortOrder = ORDER_BY_SUBJECT_DESCENDING; } else { msgSortOrder = ORDER_BY_SUBJECT_ASCENDING; } } else if (sSortBy.equals ("date")) { if (msgSortOrder == ORDER_BY_DATE_ASCENDING) { msgSortOrder = ORDER_BY_DATE_DESCENDING; } else { msgSortOrder = ORDER_BY_DATE_ASCENDING; } } else if (sSortBy.equals ("size")) { if (msgSortOrder == ORDER_BY_SIZE_ASCENDING) { msgSortOrder = ORDER_BY_SIZE_DESCENDING; } else { msgSortOrder = ORDER_BY_SIZE_ASCENDING; } } activeFolder.sort (msgSortOrder); } return listMessages.display(); } /** * Print search form * @param the JspWriter object */ private void printSearchMsgForm (StringWriter xml) throws IOException { // Navigation bar printNavBar (xml); xml.write("<searchFolder/>"); } } void redirect(ChannelRuntimeData rd, String action, String args) throws Exception { // rd.redirect(runtimeData.getBaseActionURL(), "action=" + action + (!args.equals("") ? "&" + args : "")); } private class DisplayMessage extends XmlMethod { private String xslTag = "displayMessage"; private String replyMessageButtonTxt = "Reply"; private String replyAllMessageButtonTxt = "Reply All"; private String forwardMessageButtonTxt = "Forward"; private String deleteMessageButtonTxt = "Delete"; private Tidy tidy = new Tidy(); // We have to make sure the html is XML compliant public DisplayMessage() { weAre = xslTag; tidy.setXHTML (true); tidy.setDocType ("omit"); tidy.setQuiet(true); tidy.setShowWarnings(false); tidy.setNumEntities(true); tidy.setWord2000(true); try { if ( System.getProperty("os.name").indexOf("Windows") != -1 ) { tidy.setErrout( new PrintWriter ( new FileOutputStream (new File ("nul") ) ) ); } else { tidy.setErrout( new PrintWriter ( new FileOutputStream (new File ("/dev/null") ) ) ); } } catch (FileNotFoundException fnfe) { /* Ignore */} } private int msgIndex; public void doit(ChannelRuntimeData rd) throws Exception { if (DEBUG) System.err.println("doit for " + weAre); runtimeData = rd; String value ; if ((value = runtimeData.getParameter("msg")) != null) { msgIndex = Integer.parseInt(value); } if (DEBUG) System.err.println("doit for " + weAre); } public void setMsg(int msg) { msgIndex = msg; } public StringWriter respond(String submitValue) throws Exception { StringWriter xml = new StringWriter(); xml.write("<" + xslTag + ">\n"); if (submitValue.equals("download")) { downloadAttachment(); return null; // If the user clicked "Reply", goto compose screen using this message as a draft } else if (submitValue.equals (replyMessageButtonTxt)) { if (true) { activeMethod = composeMethod; ((ComposeMessage)composeMethod).setAction("reply"); ((ComposeMessage)composeMethod).setPrevMsg(msgIndex); return activeMethod.display(); } else { redirect(runtimeData, composeMethod.getWeAre(), "mode=reply&prevMsg=" + msgIndex); } return null; // If the user clicked "Reply All", goto compose screen using this message as a draft } else if (submitValue.equals (replyAllMessageButtonTxt)) { if (true) { activeMethod = composeMethod; ((ComposeMessage)composeMethod).setAction("replyAll"); ((ComposeMessage)composeMethod).setPrevMsg(msgIndex); return activeMethod.display(); } else { redirect(runtimeData, composeMethod.getWeAre(), "mode=replyAll&prevMsg=" + msgIndex); } return null; // If the user clicked "Forward", goto compose screen using this message as a draft } else if (submitValue.equals (forwardMessageButtonTxt)) { if (true) { activeMethod = composeMethod; ((ComposeMessage)composeMethod).setAction("forward"); ((ComposeMessage)composeMethod).setPrevMsg(msgIndex); return activeMethod.display(); } else { redirect(runtimeData, composeMethod.getWeAre(), "mode=forward&prevMsg=" + msgIndex); } return null; // If the user clicked "Delete", delete the message } else if (submitValue.equals (deleteMessageButtonTxt)) { Message[] deletedMsgs = new Message[1]; deletedMsgs[0] = activeFolder.getMessage (msgIndex); if (activeFolder.getFolderName ().equals (config.sTrashName)) { //if we are in the trash, then delete that one message activeFolder.deleteMessage(deletedMsgs); } else { // Copy message to trash folder activeFolder.removeMsg (deletedMsgs, config.sTrashName); } // Go to the next message in the folder if (msgIndex >= activeFolder.getMessageCount ()) { if (true) { activeMethod = listMessages; ((ListMessages)listMessages).setNewFolder(null); ((ListMessages)listMessages).setPageIndex("last"); return activeMethod.display(); } else { redirect(runtimeData, listMessages.getWeAre(), "page=last"); } } else { if (true) { activeMethod = displayMethod; ((DisplayMessage) displayMethod).setMsg(msgIndex); return activeMethod.display(); } else { redirect(runtimeData, getWeAre(), "msg=" + msgIndex); } } return null; } else if (submitValue.startsWith (returnToMessageButtonTxt)) { if (true) { activeMethod = listMessages; return activeMethod.display(); } else { redirect(runtimeData, listMessages.getWeAre(), ""); } return null; // Step to the next message in folder } else if (submitValue.equals (nextMessageButtonTxt)) { msgIndex++; if (msgIndex >= activeFolder.getMessageCount ()) { if (true) { activeMethod = listMessages; ((ListMessages)listMessages).setNewFolder(null); ((ListMessages)listMessages).setPageIndex("last"); return activeMethod.display(); } else { redirect(runtimeData, listMessages.getWeAre(), "page=last"); } } else { if (true) { activeMethod = displayMethod; ((DisplayMessage)displayMethod).setMsg(msgIndex); return activeMethod.display(); } else { redirect(runtimeData, getWeAre(), "msg=" + msgIndex); } } return null; } xml.write("</" + xslTag + ">\n"); return xml; } public StringWriter display() throws Exception { if (DEBUG) System.err.println("Display msg=" + msgIndex); if (DEBUG) System.err.println("renderString for " + xslTag); StringWriter xml = new StringWriter(); xml.write("<" + xslTag + ">\n"); Message msg = activeFolder.openMessage (msgIndex); MessageParts msgParts = new MessageParts (msg); // Navigation bar printNavBar (xml); // Header and title printHeader ("Read", xml); //printFormStart ("respondToReadMsgControls", false, null, out); xml.write ("<hidden name=\"msg\" value=\"" + msgIndex + "\"/>"); // Message Controls xml.write("<controls bgcolor=\"" + userPrefs.sControlColor + "\">\n"); xml.write("<button>" + replyMessageButtonTxt + "</button>\n"); xml.write("<button>" + replyAllMessageButtonTxt + "</button>\n"); xml.write("<button>" + forwardMessageButtonTxt + "</button>\n"); xml.write("<button>" + deleteMessageButtonTxt + "</button>\n"); xml.write("<button>" + HTMLescape(returnToMessageButtonTxt + activeFolder.getFolderName()) +"</button>\n"); xml.write("<button>" + nextMessageButtonTxt + "</button>\n"); xml.write("</controls>"); // Message headers xml.write("<headers>\n"); if (userPrefs.showFullHeaders) { Enumeration headers = msg.getAllHeaders(); while (headers.hasMoreElements ()) { Header header = (Header)headers.nextElement (); xml.write("<header name=\"" + header.getName() + "\">" + HTMLescape(header.getValue()) + "</header>\n"); } } else { xml.write("<header name=\"From\">" + msgParts.getFrom () + "</header>\n"); xml.write("<header name=\"To\">" + msgParts.getTo () + "</header>\n"); xml.write("<header name=\"Cc\">" + msgParts.getCc () + "</header>\n"); xml.write("<header name=\"Subject\">" + HTMLescape(msgParts.getSubject ()) + "</header>\n"); xml.write("<header name=\"Date\">" + msgParts.getDate () + "</header>\n"); } xml.write("</headers>\n"); // Message body Part textPart = msgParts.getBodyText (); Part[] attachments = msgParts.getAttachments (); if (attachments.length > 0) { xml.write("<attachments>"); for (int i = 0; i < attachments.length; i++) { String attachmentName = attachmentName(attachments[i], i); xml.write("<attachment msg=\"" + msgIndex + "\" attachment=\"" + i + "\">" + attachmentName + "</attachment>"); } xml.write("</attachments>"); } xml.write("<msgbody>"); if (textPart == null) { xml.write("<msgtext><strong>Message has no displayable text</strong></msgtext>\n"); } else if (textPart.isMimeType ("text/html")) { ByteArrayOutputStream out = new ByteArrayOutputStream(1024); tidy.parse(textPart.getInputStream (), out); xml.write("<msgtext>\n" + out.toString() + "\n</msgtext>"); } else { BufferedReader in = new BufferedReader (new InputStreamReader (textPart.getInputStream ())); try { String line; xml.write("<msgtext>"); while ( (line = in.readLine ()) != null) { xml.write(HTMLescape(line)+ "<br/>"); } xml.write("</msgtext>"); } finally { in.close (); } } xml.write("</msgbody>"); metrics.messagesRead++; xml.write("</" + xslTag + ">\n"); return xml; } /** * Respond to read message attachment url */ public void downloadAttachment () { try { int iMsg = Integer.parseInt (runtimeData.getParameter ("msg")); String index = runtimeData.getParameter ("attachment"); if (DEBUG) System.err.println(iMsg + ", " + index); if (index == null) { setContentType("text/html"); //displayErrorMsg ("No attachment selected", true, xml); } else { int attachmentIndex = Integer.parseInt (index); Message msg = activeFolder.openMessage (iMsg); MessageParts msgParts = new MessageParts (msg); Part attachment = msgParts.getAttachments ()[attachmentIndex]; String contentType = attachment.getContentType (); String attachmentName = attachmentName(attachment, attachmentIndex); addHeader("Accept-Ranges", "bytes"); addHeader("Content-Disposition", "inline; filename=\"" + attachmentName + "\""); addHeader("Cache-Control", "private"); // Have to override (possible) no-cache directives int colonPos = contentType.indexOf (";"); if (colonPos > 0) { setContentType (contentType.substring (0, colonPos).toLowerCase ()); } else { setContentType (contentType.toLowerCase ()); } Date sentDate = msg.getSentDate(); if (sentDate != null) { addHeader("Last-Modified", httpDateFormat.format(sentDate)); } OutputStream browser = getOutputStream(); InputStream in = attachment.getInputStream (); try { int bufferSize = 8192; byte[] buff = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read (buff, 0, bufferSize)) != -1) { browser.write(buff, 0, bytesRead); } } catch (IOException ioe) { /* Browser probably closed the connection */ } finally { in.close(); browser.close(); // We've sent everything that we want to } metrics.attachmentsViewed++; } } catch (Exception e) { LogService.instance().log(LogService.ERROR, e); /* try { out.println ("Unable to find/display attachment"); } catch (IOException ie) { LogService.instance().log(LogService.ERROR, "respondToReadAttachment:"+ie); } */ } } } private class ListFolders extends XmlMethod { private String xslTag = "listFolders"; private int iFldrsStartAt; private int iFldrsEndAt; private String newFolderButtonTxt = "New"; private String createFolderButtonTxt = "Create"; private String deleteFolderButtonTxt = "Delete"; private String renameFolderButtonTxt = "Rename"; private String renameFolderNameButtonTxt = "Rename Folder"; private String emptyFolderButtonTxt = "Empty "; // folder name appended public ListFolders() { weAre = xslTag; reset(); } void reset() { iFldrsStartAt = 1; iFldrsEndAt = userPrefs.iFldrsPerPage; } public StringWriter respond(String submitValue) throws Exception { if (submitValue.equals("download")) { downloadFolder(); return null; } StringWriter xml = new StringWriter(); xml.write("<" + xslTag + ">\n"); // If the user clicked "New", prompt the user for a new folder name if (submitValue.equals (newFolderButtonTxt)) { enterFolderName (xml); xml.write("</" + xslTag + ">\n"); return xml; } else if (submitValue.equals (renameFolderButtonTxt)) { String sFolders[]; if ( (sFolders = runtimeData.getParameterValues ("folder")) == null || sFolders.length == 0) { return displayErrorMsg ("Please select a folder to be renamed", true); } else if (sFolders.length > 1) { return displayErrorMsg ("You can only rename one folder at a time", true); } else { enterFolderName (xml, sFolders[0]); } xml.write("</" + xslTag + ">\n"); return xml; } if (activeFolder != null) { activeFolder.finalize (); // Can't manipulate folder if it is open activeFolder = null; } // If the user entered a new folder name, create the folder if (submitValue.equals (createFolderButtonTxt)) { String sNewFolderName = runtimeData.getParameter("newFolderName"); if ( sNewFolderName.length ()==0) { return displayErrorMsg ("Folder must have a name.", true); } else if ( sNewFolderName.indexOf (folderSeparator) > 0) { return displayErrorMsg (sNewFolderName + " contains an illegal character.", true); } Folder newFolder = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + sNewFolderName); newFolder.create (Folder.HOLDS_MESSAGES); imapFolders.add (newFolder); Thread.yield (); // allow listener to run } // If the user entered a new folder name, rename the folder if (submitValue.equals (renameFolderNameButtonTxt)) { String sOldFolderName = runtimeData.getParameter("oldFolderName"); String sNewFolderName = runtimeData.getParameter("newFolderName"); if (sNewFolderName == null || sNewFolderName.trim ().length () == 0) { return displayErrorMsg ("Please enter a new name for the folder", true); } Folder oldFolder = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + sOldFolderName); Folder newFolder = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + sNewFolderName); try { if (oldFolder.renameTo (newFolder)) { imapFolders.rename (sOldFolderName, sNewFolderName); } else { return displayErrorMsg ("Unable to rename folder '" + sOldFolderName + "' to '" + sNewFolderName + "'", false); } Thread.yield (); // allow listener to run } catch (ImapFolderException sfe) { return displayErrorMsg(sfe, false); } catch (MessagingException me) { return displayErrorMsg(me, false); } } // If the user clicked "Delete", delete the folder if it is empty else if (submitValue.equals (deleteFolderButtonTxt)) { String sFolders[]; if ( (sFolders = runtimeData.getParameterValues("folder")) == null || sFolders.length == 0) { return displayErrorMsg ("Please select a folder to be deleted.", true); } for (int i = 0; i < sFolders.length; i++) { Folder folder = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + sFolders[i]); if (folder.getType () == Folder.HOLDS_FOLDERS) { int subFolders = folder.list ().length; if (subFolders == 0) { folder.delete (true); imapFolders.deleted (folder.getName ()); } else { return displayErrorMsg ("Can't delete folder \"" + sFolders[i] + "\" because it still has " + subFolders + " folders in it.<br>", true); } } else { if (folder.getMessageCount () == 0) { folder.delete (true); imapFolders.deleted (folder.getName ()); Thread.yield (); // allow listener to run } else { return displayErrorMsg ("Can't delete folder \"" + sFolders[i] + "\" because it still has " + folder.getMessageCount () + " messages in it.<br>", true); } } } } // If the user clicked "Empty Trash", expunge messages in the Trash folder else if (submitValue.equals (emptyFolderButtonTxt + config.sTrashName)) { Folder trash = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + config.sTrashName); trash.open (Folder.READ_WRITE); Message[] msgs = trash.getMessages (); Flags flags = new Flags (Flags.Flag.DELETED); trash.setFlags (msgs, flags, true); trash.close (true); } // I need some logic here to determine what messages to show after a delete // Set start and end messages and then call: listMessages (req, res, out); // firstFldrPage (req, res, out); return display(); } public StringWriter display() { StringWriter xml = new StringWriter(); int iTotalFldrs = imapFolders.size(); if (DEBUG) System.err.println("renderString for " + xslTag); xml.write("<" + xslTag + ">\n"); try { // Navigation bar (top) printNavBar (xml); // Header and title printHeader ("Folders", xml); // Pagination controls xml.write("<pagination action=\"" + weAre + "\" bgcolor=\"" + userPrefs.sControlColor + "\""); if (iFldrsStartAt > userPrefs.iFldrsPerPage + 1) { xml.write(" first=\"1\""); } if (iFldrsStartAt > userPrefs.iFldrsPerPage + 2){ xml.write(" prev=\"" + (iFldrsStartAt - userPrefs.iFldrsPerPage) + "\""); } xml.write(" start=\"" + iFldrsStartAt + "\" end=\"" + iFldrsEndAt + "\" total=\"" + iTotalFldrs + "\""); if (iFldrsEndAt < iTotalFldrs){ xml.write(" next=\"" + (iFldrsStartAt + userPrefs.iFldrsPerPage) + "\""); } if (iFldrsEndAt < iTotalFldrs && iFldrsEndAt + userPrefs.iFldrsPerPage < iTotalFldrs){ xml.write(" last=\"" + (iTotalFldrs - userPrefs.iFldrsPerPage) + "\""); } xml.write("/>\n"); // Controls for this page (top) xml.write("<controls bgcolor=\"" + userPrefs.sControlColor + "\">"); xml.write("<button>" + newFolderButtonTxt + "</button>\n"); xml.write("<button>" + deleteFolderButtonTxt + "</button>\n"); xml.write("<button>" + renameFolderButtonTxt + "</button>\n"); xml.write("<button>" + emptyFolderButtonTxt + config.sTrashName + "</button>\n"); xml.write("</controls>\n"); // List folders in active store // Headers xml.write("<headers bgcolor=\"" + userPrefs.sColumnHeadersColor + "\">\n"); xml.write("<header>Select</header>\n"); xml.write("<header>Folder</header>\n"); xml.write("<header>Messages</header>\n"); xml.write("<header>Unread</header>\n"); xml.write("<header>&#160;</header>\n"); xml.write("</headers>\n"); // Loop through folders int iTotalMsgs = 0; int iTotalNewMsgs = 0; xml.write("<folders>\n"); for (int iFldr = iFldrsStartAt - 1; iFldr < iFldrsEndAt; iFldr++) { ImapFolder.FolderData folderData = null; try { folderData = imapFolders.getFolderData (iFldr); if (!folderData.exists) continue; xml.write("<folder bgcolor=\"" + userPrefs.sTableCellColor + "\""); String sFolderName = folderData.folderName; if (folderData.specialFolder) { xml.write(" special=\"yes\""); } // Folders if (folderData.folderContainer) { xml.write(" folders=\"yes\""); } else { // Messages int iMsgCount = folderData.messageCount; xml.write(" messages=\"" + iMsgCount + "\""); iTotalMsgs += iMsgCount; // New Messages int iNewMsgCount = folderData.unreadMessageCount; xml.write(" unread=\"" + iNewMsgCount + "\""); iTotalNewMsgs += iNewMsgCount; } xml.write(">" + HTMLescape(sFolderName) + "</folder>\n"); } catch (Exception e) { //out.println ("<tr>" + me + " -> " + (folderData == null ? "null" : folderData.folderName) + "</tr>"); LogService.instance().log(LogService.ERROR, e); } } xml.write("</folders>\n"); // Totals xml.write("<totals messages=\"" + iTotalMsgs + "\" unread=\"" + iTotalNewMsgs + "\"/>\n"); } catch (Exception e) { } xml.write("</" + xslTag + ">\n"); return xml; } /** * Prompt user for a folder name * @param the servlet request object * @param the servlet response object * @param the JspWriter object */ private void enterFolderName (StringWriter xml) { enterFolderName (xml, null); } private void enterFolderName (StringWriter xml, String oldName) { try { // Navigation bar printNavBar (xml); // Header and title printHeader ("Folders", xml); // Prompt for new folder name String command; xml.write("<enterFolder"); if (oldName == null) { command = createFolderButtonTxt; } else { xml.write (" oldname=\"" + oldName + "\""); command = renameFolderNameButtonTxt; } xml.write(" mode=\"" + command + "\"/>\n"); } catch (MessagingException me) { } catch (IOException ioe) { } } /** * Download the contents of a folder as a zip file * @param the servlet request object * @param the servlet response object * @param the JspWriter object */ public void downloadFolder () { String crlf = "\r\n"; // new line sequence for a zip file String folderName; if ( (folderName = runtimeData.getParameter ("downloadfolder")) != null) { try { Folder folder; if (folderName.equalsIgnoreCase (config.sMailbox)) { folder = inbox.folder; } else { folder = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + folderName); folder.open(Folder.READ_ONLY); if (folder == null) { setContentType("text/html"); //displayErrorMsg ("Lost connection to mail server", false, xml); return; } } Message messages[] = folder.getMessages(); addHeader("Accept-Ranges", "bytes"); addHeader("Content-Disposition", "inline; filename=\"" + folderName + ".zip\""); addHeader("Cache-Control", "private"); // Have to override (possible) no-cache directives setContentType("application/zip"); addHeader("Last-Modified", httpDateFormat.format(new Date())); ZipOutputStream zout = new ZipOutputStream(getOutputStream()); zout.setLevel(Deflater.BEST_COMPRESSION); zout.setMethod(zout.DEFLATED); StringBuffer pad = new StringBuffer(); int padLength = (folder.getMessageCount() + "").length(); for (int i = padLength; i > 0; i pad.append("0"); } for (int i = 1; i <= messages.length; i++) { MessageParts msgParts = new MessageParts (messages[i-1], true); int indexLength = (i + "").length(); String messageName = (pad.toString() + i).substring(indexLength) + " " + msgParts.getSubject().replace('/', '_'); Part[] attachments = msgParts.getAttachments (); Part bodyText = msgParts.getBodyText(); ZipEntry zpart = null; String fileExtension = ".txt"; String htmlBreak = ""; if (bodyText.isMimeType("text/html")) { fileExtension = ".htm"; htmlBreak = "<br/>"; } zpart = new ZipEntry(folderName + "/" + messageName + fileExtension); Date fileDate = messages[i-1].getSentDate(); if (fileDate == null) { fileDate = new Date(); } zpart.setTime(fileDate.getTime()); zout.putNextEntry(zpart); try { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); Message msg = msgParts.getMsg(); Enumeration headers = msg.getAllHeaders(); while (headers.hasMoreElements ()) { Header header = (Header)headers.nextElement (); printWriter.print(header.getName() + ": " + header.getValue() + htmlBreak + crlf); } printWriter.print(htmlBreak + crlf); printWriter.flush(); printWriter.close(); zout.write(stringWriter.getBuffer().toString().getBytes()); if (bodyText != null) { InputStream in = bodyText.getInputStream (); try { int bytes; byte buffer[] = new byte[8192]; while ( (bytes = in.read (buffer, 0, 8192)) > -1) { zout.write (buffer, 0, bytes); } } finally { in.close(); } } } catch (Exception e) { LogService.instance().log(LogService.ERROR, e); } zout.closeEntry(); for (int j = 0; j < attachments.length; j++) { String partName = attachmentName(attachments[j], j); zpart = new ZipEntry(folderName + "/" + messageName + "/" + partName); zout.putNextEntry(zpart); try { InputStream in = attachments[j].getInputStream (); try { int bytes; byte buffer[] = new byte[8192]; while ( (bytes = in.read (buffer, 0, 8192)) > -1) { zout.write (buffer, 0, bytes); } } finally { in.close(); } } catch (Exception e) { LogService.instance().log(LogService.ERROR, e); } zout.closeEntry(); } } zout.flush(); zout.finish(); zout.close(); metrics.messagesDownloaded += messages.length; if (!folderName.equalsIgnoreCase (config.sMailbox)) { folder.close(false); } } catch (FolderClosedException fce) { //displayErrorMsg(fce, false, out); return; } catch (Exception e) { //displayErrorMsg(e, false, out); LogService.instance().log(LogService.ERROR, e); return; } } } } private class Template extends XmlMethod { public Template() { weAre = "mailstatus"; } public void doit(ChannelRuntimeData rd) { if (DEBUG) System.err.println("doit for " + weAre); } public StringWriter respond(String submitValue) { StringWriter xml = new StringWriter(); return xml; } public StringWriter display() { StringWriter xml = new StringWriter(); return xml; } } private class MailStatus extends XmlMethod { public MailStatus() { weAre = "mailstatus"; } public StringWriter display() { StringWriter xml = new StringWriter(); if (DEBUG) System.err.println("renderString for " + weAre); String messageCount; try { messageCount = inbox.getUnreadMessageCount() + ""; } catch (MessagingException me) { messageCount = "unavailable"; } xml.write("<" + weAre + ">\n"); xml.write("<unread>" + messageCount + "</unread>"); xml.write("</" + weAre + ">\n"); return xml; } } private class SetupMethod extends XmlMethod { public SetupMethod() { weAre = "setup"; } public StringWriter respond(String submitValue) throws Exception { if (submitValue.equals("Configure")) { String fullHeaders = runtimeData.getParameter ("fullheaders"); if (fullHeaders != null) { userPrefs.showFullHeaders = fullHeaders.equals("on"); } else { userPrefs.showFullHeaders = false; } if (DEBUG) System.err.println("returning to " + runtimeData.getParameter("returnTo")); } if (true) { activeMethod = listMessages; return activeMethod.display(); } else { redirect(runtimeData, runtimeData.getParameter("returnTo"), ""); } return null; } public StringWriter display() { StringWriter xml = new StringWriter(); xml.write("<" + weAre + ">\n"); xml.write("<fullheaders " + (userPrefs.showFullHeaders ? " fullheaders=\"on\"" : "") + "/>"); xml.write("</" + weAre + ">\n"); return xml; } } private class ComposeMessage extends XmlMethod { private int MAX_ATTACHMENTS = 5; private Part[] includeAttachments = null; // Attachments from a Draft message needed when sending draft private Message msg = null; public ComposeMessage() { weAre = "composeMessage"; } public void finalize() { includeAttachments = null; // Attachments from a Draft message needed when sending draft msg = null; } public StringWriter respond(String submitValue) throws Exception { StringWriter xml = new StringWriter(); xml.write("<" + weAre + ">\n"); msg = constructMessage (); // If the user clicked "Return to folder" if (submitValue.equals ("Return to folder")) { if (true) { activeMethod = listMessages; return activeMethod.display(); } else { redirect(runtimeData, listMessages.getWeAre(), ""); } return null; } else if (submitValue.startsWith("Remove ")) { } else { printNavBar (xml); // If the user clicked "Send", send the message if (submitValue.equals ("Send")) { // Send the message try { Transport.send (msg); metrics.messagesSent++; // Save copy in sent folder msg.setSentDate (new Date ()); Message[] msgs = new Message[1]; msgs[0] = msg; Folder sent = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + config.sSentName); // Create Sent Items folder if it doesn't already exist if (!sent.exists ()) { sent.create (Folder.HOLDS_MESSAGES); imapFolders.add (sent); } sent.open (Folder.READ_WRITE); sent.appendMessages (msgs); sent.close (false); /** * If we are replying to a message, set the replied to flag for * that message */ String replyMsg = runtimeData.getParameter("replymsg"); if (replyMsg != null) { int iReplyMsg = Integer.parseInt(replyMsg); Message[] oldMsg = new Message[1]; oldMsg[0] = activeFolder.getMessage(iReplyMsg); Flags flags = new Flags (Flags.Flag.ANSWERED); flags.add (Flags.Flag.SEEN); activeFolder.folder.setFlags (oldMsg, flags, true); } xml.write("<sentmsg><subject>" + HTMLescape (msg.getSubject ()) + "</subject><savedFolder>" + config.sSentName + "</savedFolder></sentmsg>"); includeAttachments = null; msg = null; } catch (AddressException ae) { return displayErrorMsg (ae, false); } catch (SendFailedException sfe) { return displayErrorMsg (sfe, false); } } // If the user clicked "Save as draft", construct message and save it in drafts folder else if (submitValue.equals ("Save as draft")) { try { msg.setSentDate (new Date ()); Message[] msgs = new Message[1]; msgs[0] = msg; if (activeFolder != null && activeFolder.getFolderName ().equals (sDraftsName)) { activeFolder.folder.appendMessages (msgs); activeFolder.folder.expunge (); // Remove old copies of draft } else { Folder drafts = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + sDraftsName); // Create Drafts folder if it doesn't already exist if (!drafts.exists ()) { drafts.create (Folder.HOLDS_MESSAGES); imapFolders.add (drafts); } drafts.open (Folder.READ_WRITE); Flags flags = new Flags (Flags.Flag.DRAFT); msg.setFlags (flags, true); drafts.appendMessages (msgs); drafts.close (true); } xml.write("<savedmsg><subject>" + HTMLescape (runtimeData.getParameter("subject")) + "</subject><folder>" + sDraftsName + "</folder></savedmsg>"); includeAttachments = null; msg = null; } catch (AddressException ae) { return displayErrorMsg (ae, false); } } // If the user clicked "Cancel", else if (submitValue.equals ("Cancel")) { xml.write("<cancelled/>"); includeAttachments = null; msg = null; } else if (submitValue.equals("To:")) { return display(); } } xml.write("</" + weAre + ">\n"); return xml; } private String sAction; private int prevMsgIndex; public void doit(ChannelRuntimeData rd) { if (DEBUG) System.err.println("doit for " + weAre); runtimeData = rd; String value; if ((value = runtimeData.getParameter("mode")) != null) { setAction(value); } if ((value = runtimeData.getParameter("prevMsg")) != null) { setPrevMsg(Integer.parseInt(value)); } } public void setAction(String action) { sAction = action; } public void setPrevMsg(int prevMsgIndex) { this.prevMsgIndex = prevMsgIndex; } public StringWriter display() throws Exception { StringWriter xml = new StringWriter(); xml.write("<" + weAre + ">\n"); metrics.showMetrics = true; // Might be coming from forward or reply... Message prevMsg = null; MessageParts msgParts = null; String sTo = ""; String sCc = ""; String sBcc = ""; String sSubject = ""; String sIncludedMsgText = ""; boolean repliedTo = false; if (DEBUG) System.err.println("mode=" + sAction); if (DEBUG) System.err.println("compose msg = " + msg); if (sAction != null) { prevMsg = activeFolder.getMessage (prevMsgIndex); if (DEBUG) System.err.println("prevMsg=" + prevMsgIndex); msgParts = new MessageParts (prevMsg); includeAttachments = null; if (sAction.equals ("forward")) { sSubject = "Fwd: " + HTMLescape (msgParts.getSubject ()); sIncludedMsgText = getIncludedMessageText (msgParts); includeAttachments = msgParts.getAttachments (); } else if (sAction.equals ("reply")) { repliedTo = true; sTo = msgParts.getFrom (); sSubject = "Re: " + HTMLescape (msgParts.getSubject ()); sIncludedMsgText = getIncludedMessageText (msgParts); } else if (sAction.equals ("replyAll")) { repliedTo = true; sTo = msgParts.getFrom () + ", " + msgParts.getTo (); sCc = msgParts.getCc (); sSubject = "Re: " + HTMLescape (msgParts.getSubject ()); sIncludedMsgText = getIncludedMessageText (msgParts); } else if (sAction.equals ("draft")) { sTo = msgParts.getTo (); sCc = msgParts.getCc (); sBcc = msgParts.getBcc (); sSubject = HTMLescape (msgParts.getSubject ()); sIncludedMsgText = getIncludedMessageText (msgParts, true, userPrefs.showFullHeaders); includeAttachments = msgParts.getAttachments (); } } else if (msg != null) { if (DEBUG) System.err.println("Picking up compose message"); msgParts = new MessageParts(msg); sTo = msgParts.getTo (); sCc = msgParts.getCc (); sBcc = msgParts.getBcc (); sSubject = HTMLescape (msgParts.getSubject ()); sIncludedMsgText = getIncludedMessageText (msgParts, true, false); includeAttachments = msgParts.getAttachments (); } // Navigation bar printNavBar (xml); // Header and title printHeader ("Compose", xml); if (repliedTo) { xml.write("<hidden name=\"replymsg\" value=\"" + runtimeData.getParameter ("msg") + "\"/>\n"); } // Message Controls xml.write("<controls bgcolor=\"" + userPrefs.sControlColor + "\">"); xml.write("<button>Send</button>\n"); xml.write("<button>Save as draft</button>\n"); xml.write("<button>Cancel</button>\n"); if (sAction != null) { xml.write("<button>Return to folder</button>\n"); } xml.write("</controls>\n"); // Message headers xml.write("<recipient tag=\"To\">" + sTo + "</recipient>\n"); xml.write("<recipient tag=\"Cc\">" + sCc + "</recipient>\n"); xml.write("<recipient tag=\"Bcc\">" + sBcc + "</recipient>\n"); xml.write("<subject>" + sSubject + "</subject>\n"); xml.write("<body>" + sIncludedMsgText +"</body>\n"); // If coming from forward or reply // Attachments xml.write("<attachments>"); int attachments = MAX_ATTACHMENTS; if (includeAttachments != null) { for (int i = 0; i < MAX_ATTACHMENTS && i < includeAttachments.length; i++) { xml.write("<attachment>" + includeAttachments[i].getFileName() + "</attachment>\n"); attachments } } for (int i = 0; i < attachments; i++) { xml.write("<getattachment/>"); } xml.write("</attachments>\n"); xml.write("</" + weAre + ">\n"); return xml; } /** * Construct a message object from compose inputs * @param the HashMap of parameters * @param ArrayList of attachments as MimeBodyParts * @returns assembled Message object */ private Message constructMessage () throws IOException, MessagingException { String sTo = runtimeData.getParameter("To"); String sCc = runtimeData.getParameter("Cc"); String sBcc = runtimeData.getParameter("Bcc"); String sSubject = runtimeData.getParameter("subject"); String sBody = runtimeData.getParameter("body"); if (DEBUG) System.err.println("Body text: " + sBody); if (DEBUG) System.err.println("To text: " + sTo); Message msg = new MimeMessage (session); msg.setFrom (new InternetAddress (sUserEmail, sFullName)); if (sTo != null && sTo.length () > 0) { msg.setRecipients (Message.RecipientType.TO, cleanAddressList(sTo)); } if (sCc != null && sCc.length () > 0) { msg.setRecipients (Message.RecipientType.CC, cleanAddressList(sCc)); } if (sBcc != null && sBcc.length () > 0) { msg.setRecipients (Message.RecipientType.BCC, cleanAddressList(sBcc)); } msg.setSubject (sSubject != null ? sSubject : "[none]"); msg.addHeader ("X-Mailer", "uPortal WEB email client " + clientVersion); msg.addHeader ("Organization", config.sOrganization); ArrayList attachments = new ArrayList(MAX_ATTACHMENTS); org.jasig.portal.MultipartDataSource[] fileParts = (org.jasig.portal.MultipartDataSource[]) runtimeData.getObjectParameterValues("attachment"); for (int i = 0; i < fileParts.length; i++) { if (DEBUG) System.err.println("attachment=" + fileParts[i]); if (fileParts[i] != null) { if (DEBUG) System.err.println("found filepart " + fileParts[i].getName()); attachments.add(fileParts[i]); } } if (attachments.size () > 0 || (includeAttachments != null && includeAttachments.length > 0)) { MimeMultipart mp = new MimeMultipart (); // First add text of message if (sBody != null && sBody.trim ().length () > 0) { MimeBodyPart body = new MimeBodyPart (); body.setDisposition (Part.INLINE); body.setContent (sBody, "text/plain"); mp.addBodyPart (body); if (DEBUG) System.err.println("Added body text"); } if (includeAttachments != null) { // Attachments from draft message for (int i = 0; i < includeAttachments.length; i++) { MimeBodyPart bp = new MimeBodyPart (); bp.setDisposition (Part.ATTACHMENT); bp.setDataHandler (includeAttachments[i].getDataHandler ()); bp.setFileName (attachmentName(includeAttachments[i], i)); mp.addBodyPart (bp); } includeAttachments = null; } for (int i = 0; i < attachments.size(); i++) { org.jasig.portal.MultipartDataSource filePart = (org.jasig.portal.MultipartDataSource) attachments.get(i); MimeBodyPart bp = new MimeBodyPart (); bp.setDisposition (Part.ATTACHMENT); bp.setFileName (filePart.getName()); if (DEBUG) System.err.println("Attaching " + filePart.getName()); bp.setDataHandler(new DataHandler(filePart)); mp.addBodyPart (bp); } msg.setContent (mp); } else { msg.setContent (sBody, "text/plain"); } msg.saveChanges (); return msg; } /** * Clean up a recipient list. Basically this involves replacing ";" (Outlook people) * with "," (JavaMail). * @param receipients string * @result clean Internet Address object */ private InternetAddress[] cleanAddressList(String recipients) throws AddressException { StringBuffer list = new StringBuffer(recipients); while (true) { try { return InternetAddress.parse(list.toString()); } catch (AddressException ae) { int charPos = ae.getPos(); if (charPos > 0 && list.substring(charPos, charPos + 1).equals(";")) { list.replace(charPos, charPos + 1, ","); } else { throw ae; } } } } /** * Format message text by appending headers and '>' to each line * @param the message being forwarded or replied to * @return message text */ private String getIncludedMessageText (MessageParts msgParts) throws IOException, MessagingException{ return getIncludedMessageText(msgParts, false, userPrefs.showFullHeaders); } /** * Format message text by appending headers and '>' to each line * @param the message being forwarded or replied to * @param Whether message is a draft message * @return message text */ private String getIncludedMessageText (MessageParts msgParts, boolean bIsDraft, boolean showFullHeaders) throws IOException, MessagingException { Part bodyText = msgParts.getBodyText (); StringBuffer sbMsgText = new StringBuffer (); if (DEBUG) System.err.println("body text recovered: " + bodyText); // Return empty string if message is not of type TEXT/PLAIN /** * Passes ChannelRuntimeData to the channel. * This function is called prior to the renderXML() call. * @param rd channel runtime data * @see ChannelRuntimeData */ public void setRuntimeData(ChannelRuntimeData rd) { runtimeData = rd; if (!authenticated) { activeMethod = authenticateMethod; } else { String methodAskedFor = runtimeData.getParameter("action"); if (methodAskedFor != null) { activeMethod = findJumptableEntry(methodAskedFor); if (activeMethod == null) { if (DEBUG) System.err.println("missing method " + methodAskedFor); activeMethod = statusMethod; } } else { activeMethod = statusMethod; } } try { activeMethod.doit(rd); } catch (Exception e) { activeMethod.setException(e); } } /** * Ask channel to render its content. * @param out the SAX DocumentHandler to output content to */ public void renderXML (DocumentHandler out) { String xmlHeader = "<?xml version=\"1.0\"?>\n"; try { String weAre; String xmlString = null; try { try { if (!authenticated) { if (DEBUG) System.err.println("renderXML unauthorized"); authenticateMethod.renderString(); weAre = activeMethod.getWeAre(); // Now status method xmlString = activeMethod.renderString(); } else { if (DEBUG) System.err.println("renderXML authorized"); checkIMAPConnection(); xmlString = activeMethod.renderString(); } } catch (CIMAPLostConnectionException clce) { if (DEBUG) System.err.println("renderXML lostconnection"); activeMethod = listMessages; xmlString = listMessages.renderString(); } } catch (Exception e) { activeMethod = listMessages; xmlString = displayErrorMsg(e, true).toString(); LogService.instance().log(LogService.ERROR, e); } if (xmlString != null) { weAre = activeMethod.getWeAre(); if (DEBUG) System.err.println(weAre + ":" + xmlString); Hashtable ssParams = new Hashtable(); ssParams.put("baseActionURL", runtimeData.getBaseActionURL()); XSLT.transform(xmlString, new URL(UtilitiesBean.fixURI(sslLocation)), out, ssParams, weAre, runtimeData.getBrowserInfo()); } else { } } catch (Exception e) { LogService.instance().log(LogService.ERROR, e); } } /** * Connects to the store and retrieves the default folder object * @return the Folder object representing the default folder */ private Folder getDefaultFolder () throws MessagingException { Folder defaultFolder = null; if (!store.isConnected ()) { throw new MessagingException ("Lost connection to the mail store"); } defaultFolder = store.getDefaultFolder (); if (defaultFolder == null) { throw new MessagingException ("No default folder"); } return defaultFolder; } /** * Return an ActiveFolder for the desired folder * @param folder to access * @return opened folder */ private ActiveFolder createActiveFolder (String sFolder) throws MessagingException { if (sFolder.equalsIgnoreCase (config.sMailbox)) { if (DEBUG) System.err.println("reusing INBOX"); return inbox; } else { if (DEBUG) System.err.println("opening " + sFolder); return new ActiveFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + sFolder); } } /** * Connects to the store and retrieves a folder object * @param the name of the folder to get * @return the Folder object */ private Folder getFolder (String sFolder) throws MessagingException { Folder folder = null; Folder defaultFolder = getDefaultFolder (); if (defaultFolder == null) { throw new MessagingException ("No default folder"); } folder = defaultFolder.getFolder (sFolder); if (folder == null) { throw new MessagingException ("Invalid folder"); } return folder; } /** * Get a string representing the system flags that have been set. * This method is included for debugging. * @param a message * @return a string representing the system flags that have been set */ private String getSystemFlags (Message msg) throws MessagingException { StringBuffer sbFlags = new StringBuffer (); // Examine ALL system flags for this message Flags.Flag[] sf = msg.getFlags ().getSystemFlags (); for (int i = 0; i < sf.length; i++) { if (sf[i] == Flags.Flag.ANSWERED) sbFlags.append ("ANSWERED "); else if (sf[i] == Flags.Flag.DELETED) sbFlags.append ("DELETED "); else if (sf[i] == Flags.Flag.DRAFT) sbFlags.append ("DRAFT "); else if (sf[i] == Flags.Flag.FLAGGED) sbFlags.append ("FLAGGED "); else if (sf[i] == Flags.Flag.RECENT) sbFlags.append ("RECENT "); else if (sf[i] == Flags.Flag.SEEN) sbFlags.append ("SEEN "); else if (sf[i] == Flags.Flag.USER) sbFlags.append ("USER "); } return sbFlags.toString (); } /** * Outputs a navigation bar containing links to * Inbox, Folders, Compose, Address, Set-ups, and Help * @param the servlet request object * @param the servlet response object * @param the JspWriter object */ private void printNavBar (StringWriter xml) { xml.write("<navigationBar bgcolor=\"" + userPrefs.sNavBarColor + "\" inbox=\"" + config.sMailbox + "\" returnMethod=\"" + activeMethod.getWeAre() + "\"/>\n"); } /** is this a special folder * @param Foldername to check */ private static boolean isSpecialFolder (String folderName) { for (int i = 0; i < sSpecialFolderNames.length; i++) { if (folderName.equalsIgnoreCase (sSpecialFolderNames[i])) { return true; } } return false; } /** Returns a HTML safe version of the text * @param String to present * @return a HTML safe version */ private static final String[][] htmlCharacters= new String[][] { {"<", "&lt;"}, {">", "&gt;"}, {"&", "&amp;"}, {"'", "&#039;"}, {"\"", "&quot;"}, }; private static String replaceHTMLcharacter (String character) { for (int i = 0; i < htmlCharacters.length; i++) { if (character.equals (htmlCharacters[i][0])) { return htmlCharacters[i][1]; } } return character; } private static String HTMLescape (String text) { StringBuffer newText = new StringBuffer (text.length ()); for (int i = 0; i < text.length (); i++) { String charAt = text.substring (i, i+1); newText.append (replaceHTMLcharacter (charAt)); } return newText.toString (); } /** * Returns a formatted String representing the size of the message * @param the size of the message in bytes * @return a formatted String representing the size of the message */ private static String formatSize (int iSize) { String sSize = null; if (iSize < 1024) { sSize = iSize + ""; } else if (iSize < 1024 * 1024) { sSize = iSize/1024 + "K"; } else { sSize = iSize/ (1024*1024) + "M"; } return sSize; } /** * Deduce you say, the mime type * @param Body part to examine * @result Mime type string */ private static String mimeType(Part attachment) throws MessagingException { String mimeType = ""; String contentType; if (attachment.isMimeType("text/plain")) { mimeType = "txt"; } else if (attachment.isMimeType("text/html")) { mimeType = "htm"; } else if ((contentType = attachment.getContentType()) != null) { int pos = contentType.indexOf("/"); int endPos = contentType.indexOf(";"); if (endPos > pos) { mimeType = contentType.substring(pos+1, endPos).toLowerCase(); } else { mimeType = contentType.substring(pos+1).toLowerCase(); } } return "." + mimeType; } /** * Deduce what name we should give to an attachment * @param The attachment to inspect * @returns an attachment name */ private static String attachmentName (Part attachment, int index) { String attachmentName = null; try { attachmentName = attachment.getFileName (); String contentType = null; if (attachmentName == null) { contentType = attachment.getContentType (); if (contentType != null) { int pos = contentType.indexOf("name="); if (pos > 0) { int endPos = contentType.indexOf(";", pos + 5); if (endPos > pos) { attachmentName = contentType.substring(pos+5, endPos); } else { attachmentName = contentType.substring(pos+5); } } } } if (attachmentName == null) { String disposition = attachment.getDisposition (); if (disposition != null) { int pos = disposition.indexOf("filename="); if (pos > 0) { int endPos = disposition.indexOf(";", pos + 9); if (endPos > pos) { attachmentName = disposition.substring(pos+9, endPos); } else { attachmentName = disposition.substring(pos+9); } } } } if (attachmentName == null) { attachmentName = "attachment" + index + mimeType(attachment); } if (attachmentName != null && attachmentName.indexOf(".") < 0) { attachmentName = attachmentName + mimeType(attachment); } } catch (MessagingException me) { attachmentName = "attachment" + index ; } return attachmentName; } /** * Present error message to the user * @param Exception object * @param Whether we should print navigation bar * @param JspWriter object */ private StringWriter displayErrorMsg (Exception e, boolean navigationBar) { return displayErrorMsg (new String[] {e.getMessage ()}, navigationBar); } /** * Present error message to the user * @param Error message to display * @param Whether we should print navigation bar * @param JspWriter object */ private StringWriter displayErrorMsg (String errorMsg, boolean navigationBar) { return displayErrorMsg (new String[] {errorMsg}, navigationBar); } /** * Present error message to the user * @param Array of error messages to display * @param Whether we should print navigation bar * @param JspWriter object */ private StringWriter displayErrorMsg (String[] errorMsg, boolean navigationBar) { StringWriter xml = new StringWriter(); xml.write("<errors>"); if (navigationBar) { printNavBar (xml); } for (int i = 0; i < errorMsg.length; i++) { xml.write("<error>" + errorMsg[i] + "</error>"); } xml.write("</errors>"); return xml; } /** * Print the client header * @param the client name * @param the JspWriter object */ private void printHeader (String sTitle, StringWriter xml) throws IOException, MessagingException { printHeader(sTitle, -1, xml); } private void printHeader(String title, int unread, StringWriter xml) { xml.write("<headerBar bgcolor=\"" + userPrefs.sHeaderColor + "\"" + " version=\"" + clientVersion + "\"" + " caption=\"" + config.sCaption + "\""); try { if (inbox != null && inbox.mailCheck ()) { xml.write(" newmail=\"yes\""); } } catch (MessagingException me) { } if (unread >= 0) { xml.write(" unread=\"" + unread + "\""); } xml.write(">" + HTMLescape(title) + "</headerBar>\n"); } /** Initialize our world * @param the session object */ private void initialize() throws Exception, AuthenticationFailedException { initialize(sUser, sPassword); } private void initialize (String username, String password) throws Exception, AuthenticationFailedException { if (username == null && password == null) { throw new AuthenticationFailedException (""); } if (username == null || password == null) { throw new AuthenticationFailedException ("Invalid Username/Password"); } try { urlName = new URLName (config.sProtocol, config.sIMAPHost, config.iIMAPPort, config.sMailbox, username, password); if (DEBUG) System.err.println(urlName.toString()); sUser = username; sPassword = password; session = Session.getDefaultInstance (props, null); session.setDebug(false); store = session.getStore (urlName); store.addStoreListener (storeListener); store.connect (); sUserEmail = sUser + "@" + config.sDomainName; if (inbox == null) { inbox = new ActiveFolder (config.sMailbox); inbox.setDontClose (true); // Keep open for duration of channel } folderSeparator = inbox.folder.getSeparator (); activeFolder = inbox; if (imapFolders == null) { imapFolders = new ImapFolder (1); // At least inbox imapFolders.add (inbox); Folder folderDir; if (config.sFolderDir == null) { folderDir = inbox.folder; } else { folderDir = getFolder (config.sFolderDir); if (!folderDir.exists ()) { folderDir.create (Folder.HOLDS_FOLDERS); } } Folder[] storeFolders = folderDir.list (); if (DEBUG) System.err.println("storeFolders="+storeFolders); if (storeFolders != null) { if (DEBUG) System.err.println(storeFolders.length + " folders found"); imapFolders.ensureCapacity (storeFolders.length + 1); for (int i = 0; i < storeFolders.length; i++) { try { if (storeFolders[i].exists ()) { imapFolders.add (storeFolders[i].getName()); } } catch (Exception e) { System.err.println(e); } } } store.addFolderListener (folderListener); authenticated = true; if (DEBUG) System.err.println("authenticated"); } } catch (Exception e) { if (DEBUG) System.err.println(e); cleanup (); throw e; } ((ListMessages)listMessages).reset(); ((ListFolders)listFolders).reset(); } /** Clean up in preparation to shut down */ private void cleanup () { try { store.removeStoreListener (storeListener); store.removeFolderListener (folderListener); } catch (Exception e) { /* ignore */ } if (imapFolders != null) { try { imapFolders.finalize (); } catch (Exception e) { /* ignore */ } imapFolders = null; } if (activeFolder != null) { try { activeFolder.finalize (); } catch (Exception me) { /* ignore */ } activeFolder = null; } if (inbox != null) { inbox.setDontClose (false); try { inbox.finalize (); } catch (Exception me) { /* ignore */} inbox = null; } authenticated = false; try { store.close (); } catch (Exception me) { /* ignore */ } } /** * Attempt to restore our state with the imap server * @param the servlet request object */ private void reconnect () throws Exception, AuthenticationFailedException { System.err.println("reconnecting"); cleanup (); initialize (); } private void checkIMAPConnection () throws Exception, CIMAPLostConnectionException, AuthenticationFailedException { Thread.yield (); try { if (inbox != null) { int a = inbox.folder.getUnreadMessageCount (); } else { if (store != null) { store.close(); } } } catch (MessagingException me) { try { if (store != null) { store.close (); } } catch (MessagingException me2) { } } if (store == null || !store.isConnected ()) { LogService.instance().log(LogService.DEBUG, "Lost connection to store, re-initializing."); try { reconnect (); throw new CIMAPLostConnectionException (); } catch (Exception e) { if (e instanceof CIMAPLostConnectionException) { throw (CIMAPLostConnectionException)e; } LogService.instance().log(LogService.ERROR, "checkIMAPConnection:" + e); throw e; } } } /** * see if there is new mail in inbox. Invoked by the mailcheck applet * @param the servlet request object * @param the servlet response object * @param the jspwriter object */ public void checkNewMail (HttpServletRequest req, HttpServletResponse res, JspWriter out) { try { res.setContentType ("text/html"); PrintWriter myOut = res.getWriter (); if (inbox == null) { myOut.println ("<mailstate>Connection to mail server unavailable</mailstate>"); } else { try { boolean newMsgs = inbox.mailCheck (); int count = inbox.getUnreadMessageCount (); myOut.println ("<mailstate>You have " + count + " unread message" + (count == 1 ? "" : "s") + ":" + (newMsgs ? "1" : "0") + "</mailstate>"); } catch (FolderClosedException fce) { myOut.println ("<mailstate>Connection to mail server unavailable</mailstate>"); } catch (MessagingException me) { myOut.println ("<mailstate>Connection to mail server unavailable</mailstate>"); } } myOut.close (); } catch (Exception e) { LogService.instance().log(LogService.ERROR, "checkIMAPConnection:"+e); } } static private int ORDER_BY_FROM (Object o1, Object o2, int order) { try { Message m1 = (Message) o1; Message m2 = (Message) o2; Address[] addrs1 = m1.getFrom (); Address[] addrs2 = m2.getFrom (); String sPersonal1 = ( (InternetAddress) addrs1[0]).getPersonal (); String sPersonal2 = ( (InternetAddress) addrs2[0]).getPersonal (); String sAddress1 = ( (InternetAddress) addrs1[0]).getAddress (); String sAddress2 = ( (InternetAddress) addrs2[0]).getAddress (); String sFrom1 = (sPersonal1 != null ? sPersonal1 : "") + sAddress1; String sFrom2 = (sPersonal2 != null ? sPersonal2 : "") + sAddress2; return sFrom1.compareTo (sFrom2) * order; } catch (Exception e) { LogService.instance().log(LogService.WARN, e); } return 0; }; static private Comparator ORDER_BY_FROM_ASCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_FROM (o1, o2, 1); } }; static private Comparator ORDER_BY_FROM_DESCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_FROM (o1, o2, -1); } }; static private int ORDER_BY_SUBJECT (Object o1, Object o2, int order) { try { String subject1 = ( (Message) o1).getSubject (); String subject2 = ( (Message) o2).getSubject (); if (subject1 == null || subject2 == null) { return -1; } return subject1.compareToIgnoreCase (subject2) * order; } catch (Exception e) { LogService.instance().log(LogService.WARN, e); } return 0; }; static private Comparator ORDER_BY_SUBJECT_ASCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_SUBJECT (o1, o2, 1); } }; static private Comparator ORDER_BY_SUBJECT_DESCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_SUBJECT (o1, o2, -1); } }; static private int ORDER_BY_DATE (Object o1, Object o2, int order) { try { Date d1 = ( (Message) o1).getSentDate (); Date d2 = ( (Message) o2).getSentDate (); if (d1 == null || d2 == null) { return -1; } else { return d1.compareTo (d2) * order; } } catch (Exception e) { LogService.instance().log(LogService.WARN, e); } return 0; }; static private Comparator ORDER_BY_DATE_ASCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_DATE (o1, o2, 1); } }; static private Comparator ORDER_BY_DATE_DESCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_DATE (o1, o2, -1); } }; static private int ORDER_BY_SIZE (Object o1, Object o2, int order) { try { Message m1 = (Message) o1; Message m2 = (Message) o2; Integer m1size = new Integer (m1.getSize ()); Integer m2size = new Integer (m2.getSize ()); return m1size.compareTo (m2size) * order; } catch (Exception e) { LogService.instance().log(LogService.WARN, e); } return 0; }; static private Comparator ORDER_BY_SIZE_ASCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_SIZE (o1, o2, 1); } }; static private Comparator ORDER_BY_SIZE_DESCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_SIZE (o1, o2, -1); } }; static private int ORDER_BY_NAME (Object o1, Object o2, int order) { try { Folder f1 = (Folder) o1; Folder f2 = (Folder) o2; return f1.getFullName ().compareToIgnoreCase (f2.getFullName ()) * order; } catch (Exception e) { LogService.instance().log(LogService.WARN, e); } return 0; }; static private Comparator ORDER_BY_NAME_ASCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_NAME (o1, o2, 1); } }; static private Comparator ORDER_BY_NAME_DESCENDING = new Comparator () { public int compare (Object o1, Object o2) { return ORDER_BY_NAME (o1, o2, -1); } }; static private Comparator ORDER_BY_FOLDERNAME = new Comparator () { public int compare (Object o1, Object o2) { try { String f1 = (String) o1; String f2 = (String) o2; return f1.compareToIgnoreCase (f2); } catch (Exception e) { LogService.instance().log(LogService.WARN, e); } return 0; } }; /** * the ImapFolder class is used to manage the list of folders that we have */ private class ImapFolder extends Vector { public class FolderData { boolean exists; boolean specialFolder; boolean folderContainer; String fullName; String folderName; int messageCount; int unreadMessageCount; } private List specialFolders = new ArrayList (); private List normalFolders = new ArrayList (); public ImapFolder () { super (); } public ImapFolder (int initialSize) { super (initialSize); } public void finalize () { if (specialFolders != null) { specialFolders.clear (); specialFolders = null; } if (normalFolders != null) { normalFolders.clear (); normalFolders = null; } clear (); } public void add (String folderName) throws ImapFolderException { addFolder (folderName); } public void add (ActiveFolder folder) throws MessagingException { addFolder (folder.folder.getName ()); } public void add (Folder folder) throws MessagingException { addFolder (folder.getName ()); folder.close (false); // Don't need it any more } private void addFolder (String folderName) { if (duplicate (folderName)) { // Already been seen return; } if (DEBUG) System.err.println("Adding folder " + folderName); if (isSpecialFolder (folderName)) { specialFolders.add (folderName); } else { normalFolders.add (folderName); } rebuildFolderList (); } /** * Create the "public" of folders that we show */ private void rebuildFolderList () { clear (); addAll (specialFolders); if (normalFolders.size () > 0) { Collections.sort (normalFolders, ORDER_BY_FOLDERNAME); addAll (normalFolders); } } /** * Check if this folder is already in the list * @param folder name to check * @result duplicate folder */ private boolean duplicate (String folderName) { for (int i = 0; i < specialFolders.size (); i++) { String existingFolder = (String)specialFolders.get (i); if (existingFolder.equals (folderName)) { return true; } } for (int i = 0; i < normalFolders.size (); i++) { String existingFolder = (String)normalFolders.get (i); if (existingFolder.equals (folderName)) { return true; } } return false; } /** * Return the list of folders * @result folder list */ public FolderData[] getFolders () throws MessagingException { ArrayList folders = new ArrayList (this.size ()); for (int i = 0; i < this.size (); i++ ) { FolderData folderData = getFolderData (i); folders.add (folderData); } return (FolderData[])folders.toArray (new FolderData[0]); } /** * Return the data for a specific folder * @param array index of folder * @result FolderData object */ public FolderData getFolderData (int index) throws MessagingException { Thread.yield (); // Allow listener to run FolderData folderData = new FolderData (); if (index >= super.size()) { folderData.exists =false; // fix foldersEndAt GNL !!! return null; } String folderName = (String) super.get (index); Folder folder; if (folderName.equalsIgnoreCase (inbox.getFolderName ())) { folder = inbox.folder; } else { folder = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator)+folderName); } folderData.exists = folder.exists (); folderData.folderName = folder.getName (); folderData.specialFolder = isSpecialFolder (folderData.folderName); folderData.fullName = folder.getFullName (); folderData.folderContainer = folder.getType () == Folder.HOLDS_FOLDERS; if (!folderData.folderContainer) { folderData.unreadMessageCount = folder.getUnreadMessageCount (); folderData.messageCount = folder.getMessageCount (); } return folderData; } /** * Remove a folder because it has been deleted * @param folder name */ public void deleted (String folderName) throws ImapFolderException { if (isSpecialFolder (folderName)) { throw new ImapFolderException (folderName + " can't be deleted"); } normalFolders.remove (folderName); rebuildFolderList (); } /** * A folder has been rename * @param old folder name * @param new folder name */ public void rename (String oldFolderName, String newFolderName) throws ImapFolderException { if (isSpecialFolder (newFolderName)) { throw new ImapFolderException ("Can't rename " + oldFolderName + " to " + newFolderName + " since the new name is not valid"); } if (normalFolders.indexOf (oldFolderName) < 0) { throw new ImapFolderException (oldFolderName + " is not in the subscription list"); } normalFolders.remove (oldFolderName); normalFolders.add (newFolderName); rebuildFolderList (); } } /** * the MsgFolder class manages our cached version of the users messages * and tries to ensure that it remains in synch with the real list on the * imap server. * * It tries to appear as a Folder class object */ private class MsgFolder { protected Folder folder = null; private boolean specialFolder = false; private int specialFolderIndex = 0; protected boolean dontClose = false; private ArrayList folderMsgs = null; protected ArrayList searchMsgs = null; protected boolean searchActive = false; protected int unreadMessages = 0; protected volatile boolean newMessages = false; private MessageCountAdapter messageListener = new MessageCountAdapter () { public void messagesAdded (MessageCountEvent ev) { Message[] newMsgs = ev.getMessages (); synchronized (folderMsgs) { try { unreadMessages += newMsgs.length; newMessages = true; addMessages (newMsgs); } catch (MessagingException e) { LogService.instance().log(LogService.ERROR, "messageListener:"+e); } } } public void messagesRemoved (MessageCountEvent ev) { // Only happens when folder is expunged Message[] removedMsgs = ev.getMessages (); synchronized (folderMsgs) { if (folderMsgs != null) { folderMsgs.removeAll (Arrays.asList (removedMsgs)); } } } }; private ConnectionListener connectionListener = new ConnectionListener () { public void opened (ConnectionEvent e) { //LogService.instance().log(LogService.DEBUG, "received connection opened event for " + e); } public void closed (ConnectionEvent e) { //LogService.instance().log(LogService.DEBUG, "received connection closed event " + e); } public void disconnected (ConnectionEvent e) { //LogService.instance().log(LogService.DEBUG, "received connection disconnected event " + e); } }; public MsgFolder (Folder folder) throws MessagingException { this (folder, false); } public MsgFolder (String sFolder) throws MessagingException { initializeFolder (getFolder (sFolder), false); } public MsgFolder (Folder folder, boolean writeAccess) throws MessagingException { initializeFolder (folder, writeAccess); } public MsgFolder (String sFolder, boolean writeAccess) throws MessagingException { initializeFolder (getFolder (sFolder), writeAccess); } private void initializeFolder (Folder newFolder, boolean writeAccess) throws MessagingException { if (newFolder == null) { throw new MessagingException ("Null folder passed"); } folder = newFolder; String sFolderName = getFolderName (); for (int i = 0; i < sSpecialFolderNames.length; i++) { if (sFolderName.equalsIgnoreCase (sSpecialFolderNames[i])) { specialFolder = true; specialFolderIndex = i; break; } } folder.open (writeAccess ? Folder.READ_WRITE : Folder.READ_ONLY); folderMsgs = new ArrayList (folder.getMessageCount ()); unreadMessages = folder.getUnreadMessageCount (); folder.addMessageCountListener (messageListener); folder.addConnectionListener (connectionListener); folderMsgs.addAll (Arrays.asList (folder.getMessages ())); } public void finalize () throws MessagingException { if (folder != null && !dontClose) { try { folder.removeMessageCountListener (messageListener); Thread.yield(); } catch (Exception e) { } synchronized (folderMsgs) { try { if (folder.isOpen ()) { folder.close (true); } } catch (Exception e) { } folderMsgs.clear (); folderMsgs = null; clearSearch(); folder = null; } } } /** * Add new messages to our internal list * @param Array of messages to add */ private void addMessages (Message[] newMsgs) throws MessagingException { fetchHeaders (newMsgs); folderMsgs.addAll (Arrays.asList (newMsgs)); } /** * Fetch headers for a range of messages * @param Index of first message to fetch * @param Index of last message to fetch */ private void fetchHeaders (int startIndex, int endIndex, ArrayList msgs) throws MessagingException { synchronized (msgs) { Message[] newMsgs = new Message[endIndex - startIndex]; for (int i = startIndex; i < endIndex; i++) { newMsgs[i - startIndex] = (Message)msgs.get (i); } fetchHeaders (newMsgs); } } public void fetchHeaders (int startIndex, int endIndex) throws MessagingException { fetchHeaders (startIndex, endIndex, folderMsgs); } private void fetchHeaders (Message[] msgs) throws MessagingException { if (folder != null) { folder.fetch (msgs, fetchProfile); } } /** * Return the name of a folder * @result folder name */ public String getFolderName () { String folderName = folder.getName (); if (folderName.equalsIgnoreCase ("INBOX")) { folderName = "Inbox"; } return folderName; } public String getFullName () { return folder.getFullName (); } /** * Retrieve a message * @param the message index to get * @return the Message object */ public Message getMessage (int msg) { if (searchActive) { return (Message) searchMsgs.get (msg); } else { return (Message) folderMsgs.get (msg); } } /** * Retrieve a message for display * @param the message index to get * @return the Message object */ public Message openMessage (int msg) throws MessagingException { Message message = getMessage (msg); if (!message.isSet (Flags.Flag.SEEN)) { unreadMessages } return message; } public int getMessageCount () { if (searchActive) { return searchMsgs.size(); } else { return folderMsgs.size (); } } public int getUnreadMessageCount () throws MessagingException { return unreadMessages; } public boolean isFiltered() { return searchActive; } public boolean exists () throws MessagingException { return folder.exists (); } public void setDontClose (boolean dontClose) { this.dontClose = dontClose; } public void sort (Comparator c) { synchronized (folderMsgs) { Collections.sort (folderMsgs, c); } } public void search(SearchTerm criteria) throws MessagingException { Message[] msgs = folder.search(criteria); fetchHeaders (msgs); clearSearch(); searchMsgs = new ArrayList(msgs.length); searchMsgs.addAll (Arrays.asList (msgs)); searchActive = true; if (DEBUG) System.err.println("Search found " + searchMsgs.size() + " messages"); } public void clearSearch() { searchActive = false; if (searchMsgs != null) { searchMsgs.clear(); searchMsgs = null; } } /** * Remove these messages from our internal list * */ public void deleteMessage (Message[] removedMsgs) throws MessagingException { for (int i = 0; i < removedMsgs.length; i++) { if (!removedMsgs[i].isSet (Flags.Flag.SEEN)) { unreadMessages } } /* Remove the message from our list before we expunge them from the folder so that delete events generated by expunge doesn't beat us to the punch. */ synchronized (folderMsgs) { if (!folderMsgs.removeAll (Arrays.asList (removedMsgs))) { throw new MessagingException ("unable to remove messages"); } if (searchMsgs != null) { searchMsgs.removeAll (Arrays.asList (removedMsgs)); } } } } /** * ActiveFolder represents a folder open for read/write */ private class ActiveFolder extends MsgFolder { public ActiveFolder (Folder folder) throws MessagingException { super (folder, true); } public ActiveFolder (String folder) throws MessagingException { super (folder, true); } public void finalize () throws MessagingException { folder.expunge (); // When should we do this???? clearSearch(); if (!dontClose) { super.finalize (); } } public void removeMsg (String sCopyFolder) throws MessagingException, Exception { if (searchActive) { removeMsg((Message[]) searchMsgs.toArray(new Message[0]), sCopyFolder); } else { removeMsg(folder.getMessages(), sCopyFolder); } } /** * Purge message from the current folder and copy them to a specified folder * @param messages to delete * @param folder to copy them to */ public void removeMsg (Message[] removedMsgs, String sCopyFolder) throws MessagingException, Exception { if (sCopyFolder == null || sCopyFolder.equals ("")) { throw new MessagingException ("'" + sCopyFolder + "' is an invalid folder name"); } try { if (!getFolderName().equals(config.sTrashName) || // Not in trash folder !sCopyFolder.equals(config.sTrashName)) { // or not copying to trash Folder copyFolder; if (inbox.getFolderName().equalsIgnoreCase(sCopyFolder)) { copyFolder = inbox.folder; } else { copyFolder = getFolder ( (config.sFolderDir == null ? "" : config.sFolderDir + folderSeparator) + sCopyFolder); // Create destination folder if it doesn't already exist if (!copyFolder.exists ()) { copyFolder.create (Folder.HOLDS_MESSAGES); imapFolders.add (copyFolder); } } folder.copyMessages (removedMsgs, copyFolder); } Flags flags = new Flags (Flags.Flag.DELETED); flags.add (Flags.Flag.SEEN); folder.setFlags (removedMsgs, flags, true); deleteMessage (removedMsgs); // Should be safe to expunge now folder.expunge (); } catch (Exception e) { throw e; } } /** * See if any new mail has arrived since the last time we checked * @result new mail */ public boolean mailCheck () throws MessagingException { boolean newMail; folder.getMessageCount (); // query server Thread.yield (); newMail = newMessages; newMessages = false; return newMail; } } /** * Provides formatted version of message parts * @author Ken Weiner */ private class MessageParts { private Message msg = null; private String sFrom = ""; private String sTo = ""; private String sCc = ""; private String sBcc = ""; private String sSubject = ""; private String sDate = ""; private String sContentType = ""; private Object content = null; private Address[] addresses; private ArrayList attachments = new ArrayList (); private Part bodyText = null; private String lt = "&lt;"; private String gt = "&gt;"; public MessageParts (Message msg) throws IOException, MessagingException { this(msg, false); } public MessageParts (Message msg, boolean noHtmlTags) throws IOException, MessagingException { if (noHtmlTags) { lt = "<"; gt = ">"; } this.msg = msg; formatFrom (); sTo = formatRecipient(Message.RecipientType.TO); sCc = formatRecipient(Message.RecipientType.CC); sBcc = formatRecipient(Message.RecipientType.BCC); formatSubject (); formatDate (); this.sContentType = msg.getContentType (); try { this.content = msg.getContent (); } catch (UnsupportedEncodingException uee) { } findAttachments ( (Part)msg); } public void finalize() { msg = null; if (attachments != null) { attachments.clear(); attachments = null; } bodyText = null; content = null; } public String getFrom () {return sFrom;} public String getTo () {return sTo;} public String getCc () {return sCc;} public String getBcc () {return sBcc;} public String getSubject () {return sSubject;} public String getDate () {return sDate;} public String getContentType () {return sContentType;} public Object getContent () {return content;} public Part[] getAttachments () {return (Part[]) attachments.toArray (new Part[0]);} public Part getBodyText () {return bodyText;} public Message getMsg() {return msg;}; private void formatFrom () throws MessagingException { if ( (addresses = msg.getFrom ()) != null) { sFrom += "<addresses>" + formatAddress((InternetAddress) addresses[0]) + "</addresses>"; } } private String formatRecipient(Message.RecipientType type) throws MessagingException { String recipients = ""; if ( (addresses = msg.getRecipients (type)) != null) { recipients += "<addresses>"; for (int iAddr = 0; iAddr < addresses.length; iAddr++) { recipients += formatAddress((InternetAddress) addresses[iAddr]); } recipients += "</addresses>"; } if (DEBUG) System.err.println("addresses: " + recipients); return recipients; } private String formatAddress(InternetAddress ia) { String address = "<address>"; String sPersonal = ia.getPersonal (); String sAddress = ia.getAddress (); if (sPersonal != null) { address += "<personal>" + HTMLescape(sPersonal) + "</personal><email>" + HTMLescape(sAddress) + "</email>"; } else { address += "<email>" + sAddress + "</email>"; } address += "</address>"; if (DEBUG) System.err.println("addess: " + address); return address; } private void formatSubject () throws MessagingException { sSubject += (msg.getSubject () == null ? "" : msg.getSubject ()); } private void formatDate () throws MessagingException { Date date = msg.getSentDate (); sDate += date != null ? date.toString () : "Unknown"; } /** * Find the attachments. Try to determine the primary body text */ private void findAttachments (Part part) throws MessagingException, IOException { if (bodyText == null && part.isMimeType ("multipart/alternative")) { // Grab the first displayable body part Multipart mPart = (Multipart) part.getContent (); for (int i = 0; i < mPart.getCount (); i++) { part = mPart.getBodyPart (i); if (DEBUG) System.err.println("disposition: " + part.getDisposition()); if (bodyText == null && (part.getDisposition() == null || part.getDisposition().equalsIgnoreCase("inline")) && (part.isMimeType ("text/plain") || part.isMimeType ("text/html"))) { bodyText = part; if (DEBUG) System.err.println("Found text bodytext at " + i); } else if (bodyText != null && (part.getDisposition() == null || part.getDisposition().equalsIgnoreCase("inline")) && bodyText.isMimeType ("text/plain") && part.isMimeType ("text/html")) { bodyText = part; // Choose html over plain text if (DEBUG) System.err.println("Found html bodytext at " + i); } else if ((part.getDisposition() != null && part.getDisposition().equalsIgnoreCase("attachment")) || !(bodyText != null && bodyText.isMimeType ("text/html") && part.isMimeType ("text/plain"))) { if (DEBUG) System.err.println("Found attachment " + i + "=" + part.getFileName()); attachments.add (part); } } /** * Session management, part of HttpSessionBindingListener interface */ public void valueBound (HttpSessionBindingEvent event) { } public void valueUnbound (HttpSessionBindingEvent event) { cleanup (); if (metrics.showMetrics) { LogService.instance().log(LogService.INFO, "WebMail metric: " + metrics); metrics.showMetrics = false; } } /** * @depricated */ public void setContentType(String mimeType) { //response.setContentType(mimeType); } /** * @depricated */ public void addHeader(String name, String value) { //response.addHeader(name, value); } /** * @depricated */ public ServletOutputStream getOutputStream() throws IOException { //return response.getOutputStream(); return null; } }
package io.openkit.unity.android; import java.util.ArrayList; import java.util.Locale; import io.openkit.OKAchievementScore; import io.openkit.OKLeaderboard; import io.openkit.OKLoginActivity; import io.openkit.OKLoginActivityHandler; import io.openkit.OKManager; import io.openkit.OKScore; import io.openkit.OKUser; import io.openkit.OKScore.ScoreRequestResponseHandler; import io.openkit.OpenKit; import io.openkit.facebook.FacebookRequestError; import io.openkit.facebookutils.FacebookUtilities; import io.openkit.leaderboards.OKLeaderboardsActivity; import android.content.Intent; import android.util.Log; import com.unity3d.player.UnityPlayer; public class UnityPlugin { private static final String ASYNC_CALL_SUCCEEDED = "asyncCallSucceeded"; private static final String ASYNC_CALL_FAILED = "asyncCallFailed"; private static void OKBridgeLog(String format, Object... args) { Log.d("OpenKitPlugin", String.format(Locale.getDefault(), format, args)); } public static void configure(String appKey, String secretKey, String endpoint) { OKBridgeLog("Initializing OpenKit from Android native with endpoint: " + endpoint); OpenKit.configure(UnityPlayer.currentActivity, appKey, secretKey, endpoint); } public static void logoutOfOpenKit() { OKManager.INSTANCE.logoutCurrentUser(UnityPlayer.currentActivity.getApplicationContext()); OKBridgeLog("Logging out of OpenKit"); } public static void setAchievementsEnabled(boolean enabled) { OKManager.INSTANCE.setAchievementsEnabled(enabled); } public static void setLeaderboardListTag(String tag){ OKManager.INSTANCE.setLeaderboardListTag(tag); } public static void setGoogleLoginEnabled(boolean enabled) { OKManager.INSTANCE.setGoogleLoginEnabled(enabled); } public static void showLeaderboards() { OKBridgeLog("Launching Leaderboards UI"); UnityPlayer.currentActivity.runOnUiThread(new Runnable() { @Override public void run() { Intent leaderboards = new Intent(UnityPlayer.currentActivity, OKLeaderboardsActivity.class); UnityPlayer.currentActivity.startActivity(leaderboards); } }); } public static void showLeaderboard(final int leaderboardID) { OKBridgeLog("Launching Leaderboard with id: " + leaderboardID); UnityPlayer.currentActivity.runOnUiThread(new Runnable() { @Override public void run() { Intent leaderboardIntent = OKLeaderboard.getLeaderboardIntent(UnityPlayer.currentActivity,leaderboardID); UnityPlayer.currentActivity.startActivity(leaderboardIntent); } }); } /** * Shows OpenKit login UI for the given Unity App */ public static void showLoginUI() { OKBridgeLog("Launching Login UI"); UnityPlayer.currentActivity.runOnUiThread(new Runnable() { @Override public void run() { Intent loginUI = new Intent(UnityPlayer.currentActivity, OKLoginActivity.class); UnityPlayer.currentActivity.startActivity(loginUI); } }); } public static void showLoginUIWithCallback(final String gameObjectName) { OKBridgeLog("Launching Login UI with callback"); OKLoginActivity.setActivityHandler(new OKLoginActivityHandler() { @Override public void onLoginDialogComplete() { String returnString = "OpenKit login dialog finished"; UnityPlayer.UnitySendMessage(gameObjectName, ASYNC_CALL_SUCCEEDED, returnString); } }); UnityPlayer.currentActivity.runOnUiThread(new Runnable() { @Override public void run() { Intent loginUI = new Intent(UnityPlayer.currentActivity, OKLoginActivity.class); UnityPlayer.currentActivity.startActivity(loginUI); } }); } /** * Submits a given score value and leaderboard ID. Uses UnitySendMessage to send a success or fail message to the gameobjectname specified * @param scoreValue * @param leaderboardID * @param gameObjectName GameObject that acts as an event handler */ public static void submitScore(long scoreValue, int leaderboardID, int metadata, String displayString, final String gameObjectName) { OKBridgeLog("Submitting score"); OKScore score = new OKScore(); score.setScoreValue(scoreValue); score.setOKLeaderboardID(leaderboardID); score.setMetadata(metadata); score.setDisplayString(displayString); score.submitScore(new ScoreRequestResponseHandler() { @Override public void onSuccess() { UnityPlayer.UnitySendMessage(gameObjectName, "scoreSubmissionSucceeded", ""); } @Override public void onFailure(Throwable arg0) { UnityPlayer.UnitySendMessage(gameObjectName, "scoreSubmissionFailed", arg0.getLocalizedMessage()); } }); } public static void submitAchievementScore(int progress, int achievementID, final String gameObjectName) { OKBridgeLog("Submitting achievement score"); OKAchievementScore achievementScore = new OKAchievementScore(); achievementScore.setOKAchievementId(achievementID); achievementScore.setProgress(progress); achievementScore.submitAchievementScore(new OKAchievementScore.AchievementScoreRequestResponseHandler() { @Override public void onSuccess() { OKBridgeLog("Achievement score submitted successfully"); UnityPlayer.UnitySendMessage(gameObjectName, "scoreSubmissionSucceeded", ""); } @Override public void onFailure(Throwable error) { OKBridgeLog("Achievement score submission failed"); UnityPlayer.UnitySendMessage(gameObjectName, "scoreSubmissionFailed", error.getLocalizedMessage()); } }); } public static boolean isCurrentUserAuthenticated() { return (OKUser.getCurrentUser() != null); } public static int getCurrentUserOKID() { if(OpenKit.getCurrentUser() != null) return OpenKit.getCurrentUser().getOKUserID(); else return 0; } public static String getCurrentUserNick() { if(OpenKit.getCurrentUser() != null) return OpenKit.getCurrentUser().getUserNick(); else return null; } public static String getCurrentUserFBID() { if(OpenKit.getCurrentUser() != null) return OpenKit.getCurrentUser().getFBUserID(); else return null; } public static String getCurrentUserGoogleID() { if(OpenKit.getCurrentUser() != null) return OpenKit.getCurrentUser().getGoogleID(); else return null; } public static String getCurrentUserCustomID() { if(OpenKit.getCurrentUser() != null) return OpenKit.getCurrentUser().getCustomID(); else return null; } public static boolean isFBSessionOpen() { return FacebookUtilities.isFBSessionOpen(); } public static void getFacebookFriendsList(final String gameObjectName) { OKBridgeLog("getFBFriends"); UnityPlayer.currentActivity.runOnUiThread(new Runnable() { @Override public void run() { FacebookUtilities.GetFBFriends(new FacebookUtilities.GetFBFriendsRequestHandler() { @Override public void onSuccess(ArrayList<Long> friendsArray) { OKBridgeLog("getFBFriends success"); String friendsList = FacebookUtilities.getSerializedListOfFBFriends(friendsArray); UnityPlayer.UnitySendMessage(gameObjectName, ASYNC_CALL_SUCCEEDED, friendsList); } @Override public void onFail(FacebookRequestError error) { OKBridgeLog("getFBFriends fail"); if(error != null){ UnityPlayer.UnitySendMessage(gameObjectName, ASYNC_CALL_FAILED, error.getErrorMessage()); } else { UnityPlayer.UnitySendMessage(gameObjectName, ASYNC_CALL_FAILED, "Unknown error when trying to get friends from Android native"); } } }); } }); } }
package org.apache.batik.css.parser; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import org.apache.batik.css.sac.CSSOMConditionFactory; import org.apache.batik.css.sac.CSSOMSelectorFactory; import org.apache.batik.i18n.Localizable; import org.apache.batik.i18n.LocalizableSupport; import org.w3c.css.sac.ConditionFactory; import org.w3c.css.sac.Condition; import org.w3c.css.sac.CSSException; import org.w3c.css.sac.CSSParseException; import org.w3c.css.sac.DocumentHandler; import org.w3c.css.sac.ErrorHandler; import org.w3c.css.sac.InputSource; import org.w3c.css.sac.LexicalUnit; import org.w3c.css.sac.Locator; import org.w3c.css.sac.Selector; import org.w3c.css.sac.SelectorFactory; import org.w3c.css.sac.SelectorList; import org.w3c.css.sac.SimpleSelector; /** * This class implements the {@link org.w3c.css.sac.Parser} interface. * * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a> * @version $Id$ */ public class Parser implements org.w3c.css.sac.Parser, Localizable { /** * The CSS to Java encoding table. */ protected final static Map ENCODINGS = new HashMap(); static { ENCODINGS.put("iso-ir-6", "ASCII"); ENCODINGS.put("ANSI_X3.4-1986", "ASCII"); ENCODINGS.put("ISO_646.irv:1991", "ASCII"); ENCODINGS.put("ASCII", "ASCII"); ENCODINGS.put("ISO646-US", "ASCII"); ENCODINGS.put("US-ASCII", "ASCII"); ENCODINGS.put("us", "ASCII"); ENCODINGS.put("IBM367", "ASCII"); ENCODINGS.put("cp367", "ASCII"); ENCODINGS.put("csASCII", "ASCII"); ENCODINGS.put("iso-ir-100", "ISO8859_1"); ENCODINGS.put("ISO_8859-1:1987", "ISO8859_1"); ENCODINGS.put("ISO_8859-1", "ISO8859_1"); ENCODINGS.put("ISO-8859-1", "ISO8859_1"); ENCODINGS.put("latin1", "ISO8859_1"); ENCODINGS.put("l1", "ISO8859_1"); ENCODINGS.put("IBM819", "ISO8859_1"); ENCODINGS.put("CP819", "ISO8859_1"); ENCODINGS.put("csISOLatin1", "ISO8859_1"); ENCODINGS.put("iso-ir-101", "ISO8859_2"); ENCODINGS.put("ISO_8859-2:1987", "ISO8859_2"); ENCODINGS.put("ISO_8859-2", "ISO8859_2"); ENCODINGS.put("ISO-8859-2", "ISO8859_2"); ENCODINGS.put("latin2", "ISO8859_2"); ENCODINGS.put("l2", "ISO8859_2"); ENCODINGS.put("csISOLatin2", "ISO8859_2"); ENCODINGS.put("ISO_8859-3:1988", "ISO8859_3"); ENCODINGS.put("iso-ir-109", "ISO8859_3"); ENCODINGS.put("ISO_8859-3", "ISO8859_3"); ENCODINGS.put("ISO-8859-3", "ISO8859_3"); ENCODINGS.put("latin3", "ISO8859_3"); ENCODINGS.put("l3", "ISO8859_3"); ENCODINGS.put("csISOLatin3", "ISO8859_3"); ENCODINGS.put("iso-ir-110", "ISO8859_4"); ENCODINGS.put("ISO_8859-4:1988", "ISO8859_4"); ENCODINGS.put("ISO_8859-4", "ISO8859_4"); ENCODINGS.put("ISO-8859-4", "ISO8859_4"); ENCODINGS.put("latin4", "ISO8859_4"); ENCODINGS.put("l4", "ISO8859_4"); ENCODINGS.put("csISOLatin4", "ISO8859_4"); ENCODINGS.put("iso-ir-127", "ISO8859_6"); ENCODINGS.put("ISO_8859-6", "ISO8859_6"); ENCODINGS.put("ISO_8859-6:1987", "ISO8859_6"); ENCODINGS.put("ISO-8859-6", "ISO8859_6"); ENCODINGS.put("ECMA-114", "ISO8859_6"); ENCODINGS.put("ASMO-708", "ISO8859_6"); ENCODINGS.put("arabic", "ISO8859_6"); ENCODINGS.put("csISOLatinArabic", "ISO8859_6"); ENCODINGS.put("iso-ir-126", "ISO8859_7"); ENCODINGS.put("ISO_8859-7", "ISO8859_7"); ENCODINGS.put("ISO_8859-7:1987", "ISO8859_7"); ENCODINGS.put("ISO-8859-7", "ISO8859_7"); ENCODINGS.put("ELOT_928", "ISO8859_7"); ENCODINGS.put("ECMA-118", "ISO8859_7"); ENCODINGS.put("greek", "ISO8859_7"); ENCODINGS.put("greek8", "ISO8859_7"); ENCODINGS.put("csISOLatinGreek", "ISO8859_7"); ENCODINGS.put("ISO_8859-8:1988", "ISO8859_8"); ENCODINGS.put("iso-ir-138", "ISO8859_8"); ENCODINGS.put("ISO_8859-8", "ISO8859_8"); ENCODINGS.put("ISO-8859-8", "ISO8859_8"); ENCODINGS.put("hebrew", "ISO8859_8"); ENCODINGS.put("csISOLatinHebrew", "ISO8859_8"); ENCODINGS.put("ISO_8859-9:1989", "ISO8859_9"); ENCODINGS.put("iso-ir-148", "ISO8859_9"); ENCODINGS.put("ISO_8859-9", "ISO8859_9"); ENCODINGS.put("ISO-8859-9", "ISO8859_9"); ENCODINGS.put("latin5", "ISO8859_9"); ENCODINGS.put("l5", "ISO8859_9"); ENCODINGS.put("csISOLatin5", "ISO8859_9"); ENCODINGS.put("ISO_8859-15", "ISO8859_15_FDIS"); ENCODINGS.put("UTF-8", "UTF8"); ENCODINGS.put("Shift_JIS", "SJIS"); ENCODINGS.put("MS_Kanji", "SJIS"); ENCODINGS.put("csShiftJIS", "SJIS"); ENCODINGS.put("EUC-JP", "EUC_JP"); ENCODINGS.put("csEUCPkdFmtJapanese", "EUC_JP"); ENCODINGS.put("Extended_UNIX_Code_Packed_Format_for_Japanese", "EUC_JP"); ENCODINGS.put("csBig5", "Big5"); } /** * The default resource bundle base name. */ public final static String BUNDLE_CLASSNAME = "org.apache.batik.css.parser.resources.Messages"; /** * The localizable support. */ protected LocalizableSupport localizableSupport = new LocalizableSupport(BUNDLE_CLASSNAME); /** * The scanner used to scan the input source. */ protected Scanner scanner; /** * The current lexical unit. */ protected int current; /** * The document handler. */ protected DocumentHandler documentHandler = DefaultDocumentHandler.INSTANCE; /** * The selector factory. */ protected SelectorFactory selectorFactory = CSSOMSelectorFactory.INSTANCE; /** * The condition factory. */ protected ConditionFactory conditionFactory = CSSOMConditionFactory.INSTANCE; /** * The error handler. */ protected ErrorHandler errorHandler = DefaultErrorHandler.INSTANCE; /** * To store the current pseudo element. */ protected String pseudoElement; /** * The document URI. */ protected String documentURI; public String getParserVersion() { return "http: } /** * <b>SAC</b>: Implements {@link org.w3c.css.sac.Parser#setLocale(Locale)}. */ public void setLocale(Locale locale) throws CSSException { localizableSupport.setLocale(locale); } /** * Implements {@link org.apache.batik.i18n.Localizable#getLocale()}. */ public Locale getLocale() { return localizableSupport.getLocale(); } /** * Implements {@link * org.apache.batik.i18n.Localizable#formatMessage(String,Object[])}. */ public String formatMessage(String key, Object[] args) throws MissingResourceException { return localizableSupport.formatMessage(key, args); } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.Parser#setDocumentHandler(DocumentHandler)}. */ public void setDocumentHandler(DocumentHandler handler) { documentHandler = handler; } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.Parser#setSelectorFactory(SelectorFactory)}. */ public void setSelectorFactory(SelectorFactory factory) { selectorFactory = factory; } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.Parser#setConditionFactory(ConditionFactory)}. */ public void setConditionFactory(ConditionFactory factory) { conditionFactory = factory; } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.Parser#setErrorHandler(ErrorHandler)}. */ public void setErrorHandler(ErrorHandler handler) { errorHandler = handler; } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.Parser#parseStyleSheet(InputSource)}. */ public void parseStyleSheet(InputSource source) throws CSSException, IOException { scanner = new Scanner(characterStream(source, null), null); try { documentHandler.startDocument(source); current = scanner.next(); switch (current) { case LexicalUnits.CHARSET_SYMBOL: if (nextIgnoreSpaces() != LexicalUnits.STRING) { reportError("charset.string"); } else { if (nextIgnoreSpaces() != LexicalUnits.SEMI_COLON) { reportError("semicolon"); } next(); } break; case LexicalUnits.COMMENT: documentHandler.comment(scanner.currentValue()); } skipSpacesAndCDOCDC(); for (;;) { if (current == LexicalUnits.IMPORT_SYMBOL) { nextIgnoreSpaces(); parseImportRule(); } else { break; } } loop: for (;;) { switch (current) { case LexicalUnits.PAGE_SYMBOL: nextIgnoreSpaces(); parsePageRule(); break; case LexicalUnits.MEDIA_SYMBOL: nextIgnoreSpaces(); parseMediaRule(); break; case LexicalUnits.FONT_FACE_SYMBOL: nextIgnoreSpaces(); parseFontFaceRule(); break; case LexicalUnits.AT_KEYWORD: nextIgnoreSpaces(); parseAtRule(); break; case LexicalUnits.EOF: break loop; default: parseRuleSet(); } skipSpacesAndCDOCDC(); } } finally { documentHandler.endDocument(source); } } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.Parser#parseStyleSheet(String)}. */ public void parseStyleSheet(String uri) throws CSSException, IOException { parseStyleSheet(new InputSource(uri)); } /** * <b>SAC</b>: Implements {@link * org.w3c.css.sac.Parser#parseStyleDeclaration(InputSource)}. */ public void parseStyleDeclaration(InputSource source) throws CSSException, IOException { scanner = new Scanner(characterStream(source, null), null); nextIgnoreSpaces(); try { parseStyleDeclaration(false); } catch (CSSParseException e) { reportError(e); } } /** * <b>SAC</b>: Implements {@link org.w3c.css.sac.Parser#parseRule(InputSource)}. */ public void parseRule(InputSource source) throws CSSException, IOException { scanner = new Scanner(characterStream(source, null), null); nextIgnoreSpaces(); parseRule(); } /** * <b>SAC</b>: Implements {@link org.w3c.css.sac.Parser#parseSelectors(InputSource)}. */ public SelectorList parseSelectors(InputSource source) throws CSSException, IOException { scanner = new Scanner(characterStream(source, null), null); nextIgnoreSpaces(); return parseSelectorList(); } /** * <b>SAC</b>: Implements * {@link org.w3c.css.sac.Parser#parsePropertyValue(InputSource)}. */ public LexicalUnit parsePropertyValue(InputSource source) throws CSSException, IOException { scanner = new Scanner(characterStream(source, null), null); nextIgnoreSpaces(); LexicalUnit exp = null; try { exp = parseExpression(false); } catch (CSSParseException e) { reportError(e); return null; } if (current != LexicalUnits.EOF) { errorHandler.fatalError(createCSSParseException("eof.expected")); } return exp; } /** * <b>SAC</b>: Implements * {@link org.w3c.css.sac.Parser#parsePriority(InputSource)}. */ public boolean parsePriority(InputSource source) throws CSSException, IOException { scanner = new Scanner(characterStream(source, null), null); nextIgnoreSpaces(); switch (current) { case LexicalUnits.EOF: return false; case LexicalUnits.IMPORT_SYMBOL: return true; default: reportError("token"); return false; } } /** * Parses a rule. */ protected void parseRule() { switch (scanner.currentType()) { case LexicalUnits.IMPORT_SYMBOL: nextIgnoreSpaces(); parseImportRule(); break; case LexicalUnits.AT_KEYWORD: nextIgnoreSpaces(); parseAtRule(); break; case LexicalUnits.FONT_FACE_SYMBOL: nextIgnoreSpaces(); parseFontFaceRule(); break; case LexicalUnits.MEDIA_SYMBOL: nextIgnoreSpaces(); parseMediaRule(); break; case LexicalUnits.PAGE_SYMBOL: nextIgnoreSpaces(); parsePageRule(); break; default: parseRuleSet(); } } /** * Parses an unknown rule. */ protected void parseAtRule() { String text = scanner.scanAtRule(); documentHandler.ignorableAtRule(text); nextIgnoreSpaces(); } /** * Parses an import rule. Assumes the current token is '@import'. */ protected void parseImportRule() { String uri = null; switch (current) { default: reportError("string.or.uri"); return; case LexicalUnits.STRING: case LexicalUnits.URI: uri = scanner.currentValue(); nextIgnoreSpaces(); } CSSSACMediaList ml; if (current != LexicalUnits.IDENTIFIER) { ml = new CSSSACMediaList(); ml.append("all"); } else { ml = parseMediaList(); } documentHandler.importStyle(uri, ml, null); if (current != LexicalUnits.SEMI_COLON) { reportError("semicolon"); } else { next(); } } /** * Parses a media list. */ protected CSSSACMediaList parseMediaList() { CSSSACMediaList result = new CSSSACMediaList(); result.append(scanner.currentValue()); nextIgnoreSpaces(); while (current == LexicalUnits.COMMA) { nextIgnoreSpaces(); switch (current) { default: reportError("identifier"); break; case LexicalUnits.IDENTIFIER: result.append(scanner.currentValue()); nextIgnoreSpaces(); } } return result; } /** * Parses a font-face rule. */ protected void parseFontFaceRule() { try { documentHandler.startFontFace(); if (current != LexicalUnits.LEFT_CURLY_BRACE) { reportError("left.curly.brace"); } else { nextIgnoreSpaces(); boolean err = false; try { parseStyleDeclaration(true); } catch (CSSParseException e) { reportError(e); err = true; } if (!err) { if (current != LexicalUnits.RIGHT_CURLY_BRACE) { reportError("right.curly.brace"); } else { nextIgnoreSpaces(); } } } } finally { documentHandler.endFontFace(); } } /** * Parses a page rule. */ protected void parsePageRule() { String page = null; String ppage = null; if (current == LexicalUnits.IDENTIFIER) { page = scanner.currentValue(); nextIgnoreSpaces(); if (current == LexicalUnits.COLON) { nextIgnoreSpaces(); if (current != LexicalUnits.IDENTIFIER) { reportError("identifier"); return; } ppage = scanner.currentValue(); nextIgnoreSpaces(); } } try { documentHandler.startPage(page, ppage); if (current != LexicalUnits.LEFT_CURLY_BRACE) { reportError("left.curly.brace"); } else { nextIgnoreSpaces(); boolean err = false; try { parseStyleDeclaration(true); } catch (CSSParseException e) { reportError(e); err = true; } if (!err) { if (current != LexicalUnits.RIGHT_CURLY_BRACE) { reportError("right.curly.brace"); } else { nextIgnoreSpaces(); } } } } finally { documentHandler.endPage(page, ppage); } } /** * Parses a media rule. */ protected void parseMediaRule() { if (current != LexicalUnits.IDENTIFIER) { reportError("identifier"); return; } CSSSACMediaList ml = parseMediaList(); try { documentHandler.startMedia(ml); if (current != LexicalUnits.LEFT_CURLY_BRACE) { reportError("left.curly.brace"); } else { nextIgnoreSpaces(); while (current != LexicalUnits.RIGHT_CURLY_BRACE) { parseRuleSet(); } nextIgnoreSpaces(); } } finally { documentHandler.endMedia(ml); } } /** * Parses a ruleset. */ protected void parseRuleSet() { SelectorList sl = null; try { sl = parseSelectorList(); } catch (CSSParseException e) { reportError(e); return; } try { documentHandler.startSelector(sl); if (current != LexicalUnits.LEFT_CURLY_BRACE) { reportError("left.curly.brace"); } else { nextIgnoreSpaces(); boolean err = false; try { parseStyleDeclaration(true); } catch (CSSParseException e) { reportError(e); err = true; } if (!err) { if (current != LexicalUnits.RIGHT_CURLY_BRACE) { reportError("right.curly.brace"); } else { nextIgnoreSpaces(); } } } } finally { documentHandler.endSelector(sl); } } /** * Parses a selector list */ protected SelectorList parseSelectorList() { CSSSelectorList result = new CSSSelectorList(); result.append(parseSelector()); for (;;) { if (current != LexicalUnits.COMMA) { return result; } nextIgnoreSpaces(); result.append(parseSelector()); } } /** * Parses a selector. */ protected Selector parseSelector() { SimpleSelector ss = parseSimpleSelector(); Selector result = ss; pseudoElement = null; loop: for (;;) { switch (current) { default: break loop; case LexicalUnits.IDENTIFIER: case LexicalUnits.ANY: case LexicalUnits.HASH: case LexicalUnits.DOT: case LexicalUnits.LEFT_BRACKET: case LexicalUnits.COLON: result = selectorFactory.createDescendantSelector (result, parseSimpleSelector()); break; case LexicalUnits.PLUS: nextIgnoreSpaces(); result = selectorFactory.createDirectAdjacentSelector ((short)1, result, parseSimpleSelector()); break; case LexicalUnits.PRECEDE: nextIgnoreSpaces(); result = selectorFactory.createChildSelector (result, parseSimpleSelector()); } } if (pseudoElement != null) { result = selectorFactory.createChildSelector (result, selectorFactory.createPseudoElementSelector(null, pseudoElement)); } return result; } /** * Parses a simple selector. */ protected SimpleSelector parseSimpleSelector() { SimpleSelector result; switch (current) { case LexicalUnits.IDENTIFIER: result = selectorFactory.createElementSelector(null, scanner.currentValue()); next(); break; case LexicalUnits.ANY: next(); default: result = selectorFactory.createElementSelector(null, null); } Condition cond = null; loop: for (;;) { Condition c = null; switch (current) { case LexicalUnits.HASH: c = conditionFactory.createIdCondition(scanner.currentValue()); next(); break; case LexicalUnits.DOT: if (next() != LexicalUnits.IDENTIFIER) { throw createCSSParseException("identifier"); } c = conditionFactory.createClassCondition(null, scanner.currentValue()); next(); break; case LexicalUnits.LEFT_BRACKET: if (nextIgnoreSpaces() != LexicalUnits.IDENTIFIER) { throw createCSSParseException("identifier"); } String name = scanner.currentValue(); int op = nextIgnoreSpaces(); switch (op) { default: c = conditionFactory.createAttributeCondition(name, null, false, null); break; case LexicalUnits.EQUAL: case LexicalUnits.INCLUDES: case LexicalUnits.DASHMATCH: String val = null; switch (nextIgnoreSpaces()) { default: throw createCSSParseException("identifier.or.string"); case LexicalUnits.STRING: case LexicalUnits.IDENTIFIER: val = scanner.currentValue(); nextIgnoreSpaces(); } if (current != LexicalUnits.RIGHT_BRACKET) { throw createCSSParseException("right.bracket"); } next(); switch (op) { case LexicalUnits.EQUAL: c = conditionFactory.createAttributeCondition(name, null, false, val); break; case LexicalUnits.INCLUDES: c = conditionFactory.createOneOfAttributeCondition(name, null, false, val); break; default: c = conditionFactory.createBeginHyphenAttributeCondition(name, null, false, val); } } break; case LexicalUnits.COLON: switch (nextIgnoreSpaces()) { case LexicalUnits.IDENTIFIER: String val = scanner.currentValue(); if (isPseudoElement(val)) { if (pseudoElement != null) { throw createCSSParseException("duplicate.pseudo.element"); } pseudoElement = val; } else { c = conditionFactory.createPseudoClassCondition(null, val); } next(); break; case LexicalUnits.FUNCTION: String func = scanner.currentValue(); if (nextIgnoreSpaces() != LexicalUnits.IDENTIFIER) { throw createCSSParseException("identifier"); } String lang = scanner.currentValue(); if (nextIgnoreSpaces() != LexicalUnits.RIGHT_BRACE) { throw createCSSParseException("right.brace"); } if (!func.equalsIgnoreCase("lang")) { throw createCSSParseException("pseudo.function"); } c = conditionFactory.createLangCondition(lang); next(); break; default: throw createCSSParseException("identifier"); } break; default: break loop; } if (c != null) { if (cond == null) { cond = c; } else { cond = conditionFactory.createAndCondition(cond, c); } } } skipSpaces(); if (cond != null) { result = selectorFactory.createConditionalSelector(result, cond); } return result; } /** * Tells whether or not the given string represents a pseudo-element. */ protected boolean isPseudoElement(String s) { switch (s.charAt(0)) { case 'a': case 'A': return s.equalsIgnoreCase("after"); case 'b': case 'B': return s.equalsIgnoreCase("before"); case 'f': case 'F': return s.equalsIgnoreCase("first-letter") || s.equalsIgnoreCase("first-line"); } return false; } /** * Parses the given reader. */ protected void parseStyleDeclaration(boolean inSheet) throws CSSException { for (;;) { switch (current) { case LexicalUnits.EOF: if (inSheet) { throw createCSSParseException("eof"); } return; case LexicalUnits.RIGHT_CURLY_BRACE: if (!inSheet) { throw createCSSParseException("eof.expected"); } return; case LexicalUnits.SEMI_COLON: nextIgnoreSpaces(); continue; default: throw createCSSParseException("identifier"); case LexicalUnits.IDENTIFIER: } String name = scanner.currentValue(); if (nextIgnoreSpaces() != LexicalUnits.COLON) { throw createCSSParseException("colon"); } nextIgnoreSpaces(); LexicalUnit exp = null; try { exp = parseExpression(false); } catch (CSSParseException e) { reportError(e); } if (exp != null) { boolean important = false; if (current == LexicalUnits.IMPORTANT_SYMBOL) { important = true; nextIgnoreSpaces(); } documentHandler.property(name, exp, important); } } } /** * Parses a CSS2 expression. * @param lex The type of the current lexical unit. */ protected LexicalUnit parseExpression(boolean param) { LexicalUnit result = parseTerm(null); LexicalUnit curr = result; for (;;) { boolean op = false; switch (current) { case LexicalUnits.COMMA: op = true; curr = CSSLexicalUnit.createSimple(LexicalUnit.SAC_OPERATOR_COMMA, curr); nextIgnoreSpaces(); break; case LexicalUnits.DIVIDE: op = true; curr = CSSLexicalUnit.createSimple(LexicalUnit.SAC_OPERATOR_SLASH, curr); nextIgnoreSpaces(); } if (param) { if (current == LexicalUnits.RIGHT_BRACE) { if (op) { throw createCSSParseException("token"); } return result; } curr = parseTerm(curr); } else { switch (current) { case LexicalUnits.IMPORTANT_SYMBOL: case LexicalUnits.SEMI_COLON: case LexicalUnits.RIGHT_CURLY_BRACE: case LexicalUnits.EOF: if (op) { throw createCSSParseException("token"); } return result; default: curr = parseTerm(curr); } } } } /** * Parses a CSS2 term. */ protected LexicalUnit parseTerm(LexicalUnit prev) { boolean plus = true; boolean sgn = false; switch (current) { case LexicalUnits.MINUS: plus = false; case LexicalUnits.PLUS: next(); sgn = true; default: switch (current) { case LexicalUnits.INTEGER: int s = (plus) ? 1 : -1; int val = s * Integer.parseInt(scanner.currentValue()); nextIgnoreSpaces(); return CSSLexicalUnit.createInteger(val, prev); case LexicalUnits.REAL: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_REAL, number(plus), prev); case LexicalUnits.PERCENTAGE: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_PERCENTAGE, number(plus), prev); case LexicalUnits.PT: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_POINT, number(plus), prev); case LexicalUnits.PC: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_PICA, number(plus), prev); case LexicalUnits.PX: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_PIXEL, number(plus), prev); case LexicalUnits.CM: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_CENTIMETER, number(plus), prev); case LexicalUnits.MM: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_MILLIMETER, number(plus), prev); case LexicalUnits.IN: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_INCH, number(plus), prev); case LexicalUnits.EM: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_EM, number(plus), prev); case LexicalUnits.EX: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_EX, number(plus), prev); case LexicalUnits.DEG: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_DEGREE, number(plus), prev); case LexicalUnits.RAD: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_RADIAN, number(plus), prev); case LexicalUnits.GRAD: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_GRADIAN, number(plus), prev); case LexicalUnits.S: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_SECOND, number(plus), prev); case LexicalUnits.MS: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_MILLISECOND, number(plus), prev); case LexicalUnits.HZ: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_HERTZ, number(plus), prev); case LexicalUnits.KHZ: return CSSLexicalUnit.createFloat(LexicalUnit.SAC_KILOHERTZ, number(plus), prev); case LexicalUnits.DIMENSION: return dimension(plus, prev); case LexicalUnits.FUNCTION: return parseFunction(plus, prev); } if (sgn) { throw createCSSParseException("token"); } } switch (current) { case LexicalUnits.STRING: String val = scanner.currentValue(); nextIgnoreSpaces(); return CSSLexicalUnit.createString(LexicalUnit.SAC_STRING_VALUE, val, prev); case LexicalUnits.IDENTIFIER: val = scanner.currentValue(); nextIgnoreSpaces(); if (val.equalsIgnoreCase("inherit")) { return CSSLexicalUnit.createSimple(LexicalUnit.SAC_INHERIT, prev); } else { return CSSLexicalUnit.createString(LexicalUnit.SAC_IDENT, val, prev); } case LexicalUnits.URI: val = scanner.currentValue(); nextIgnoreSpaces(); return CSSLexicalUnit.createString(LexicalUnit.SAC_URI, val, prev); case LexicalUnits.HASH: return hexcolor(prev); default: new Exception().printStackTrace(); throw createCSSParseException("token" + current); } } /** * Parses a CSS2 function. */ protected LexicalUnit parseFunction(boolean positive, LexicalUnit prev) { String name = scanner.currentValue(); nextIgnoreSpaces(); LexicalUnit params = parseExpression(true); if (current != LexicalUnits.RIGHT_BRACE) { throw createCSSParseException("token"); } nextIgnoreSpaces(); predefined: switch (name.charAt(0)) { case 'r': case 'R': LexicalUnit lu; if (name.equalsIgnoreCase("rgb")) { lu = params; if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_INTEGER: case LexicalUnit.SAC_PERCENTAGE: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_OPERATOR_COMMA: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_INTEGER: case LexicalUnit.SAC_PERCENTAGE: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_OPERATOR_COMMA: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_INTEGER: case LexicalUnit.SAC_PERCENTAGE: lu = lu.getNextLexicalUnit(); } if (lu != null) { break; } return CSSLexicalUnit.createPredefinedFunction (LexicalUnit.SAC_RGBCOLOR, params, prev); } else if (name.equalsIgnoreCase("rect")) { lu = params; if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_INTEGER: if (lu.getIntegerValue() != 0) { break predefined; } lu = lu.getNextLexicalUnit(); break; case LexicalUnit.SAC_IDENT: if (!lu.getStringValue().equalsIgnoreCase("auto")) { break predefined; } lu = lu.getNextLexicalUnit(); break; case LexicalUnit.SAC_EM: case LexicalUnit.SAC_EX: case LexicalUnit.SAC_PIXEL: case LexicalUnit.SAC_CENTIMETER: case LexicalUnit.SAC_MILLIMETER: case LexicalUnit.SAC_INCH: case LexicalUnit.SAC_POINT: case LexicalUnit.SAC_PICA: case LexicalUnit.SAC_PERCENTAGE: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_OPERATOR_COMMA: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_INTEGER: if (lu.getIntegerValue() != 0) { break predefined; } lu = lu.getNextLexicalUnit(); break; case LexicalUnit.SAC_IDENT: if (!lu.getStringValue().equalsIgnoreCase("auto")) { break predefined; } lu = lu.getNextLexicalUnit(); break; case LexicalUnit.SAC_EM: case LexicalUnit.SAC_EX: case LexicalUnit.SAC_PIXEL: case LexicalUnit.SAC_CENTIMETER: case LexicalUnit.SAC_MILLIMETER: case LexicalUnit.SAC_INCH: case LexicalUnit.SAC_POINT: case LexicalUnit.SAC_PICA: case LexicalUnit.SAC_PERCENTAGE: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_OPERATOR_COMMA: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_INTEGER: if (lu.getIntegerValue() != 0) { break predefined; } lu = lu.getNextLexicalUnit(); break; case LexicalUnit.SAC_IDENT: if (!lu.getStringValue().equalsIgnoreCase("auto")) { break predefined; } lu = lu.getNextLexicalUnit(); break; case LexicalUnit.SAC_EM: case LexicalUnit.SAC_EX: case LexicalUnit.SAC_PIXEL: case LexicalUnit.SAC_CENTIMETER: case LexicalUnit.SAC_MILLIMETER: case LexicalUnit.SAC_INCH: case LexicalUnit.SAC_POINT: case LexicalUnit.SAC_PICA: case LexicalUnit.SAC_PERCENTAGE: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_OPERATOR_COMMA: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_INTEGER: if (lu.getIntegerValue() != 0) { break predefined; } lu = lu.getNextLexicalUnit(); break; case LexicalUnit.SAC_IDENT: if (!lu.getStringValue().equalsIgnoreCase("auto")) { break predefined; } lu = lu.getNextLexicalUnit(); break; case LexicalUnit.SAC_EM: case LexicalUnit.SAC_EX: case LexicalUnit.SAC_PIXEL: case LexicalUnit.SAC_CENTIMETER: case LexicalUnit.SAC_MILLIMETER: case LexicalUnit.SAC_INCH: case LexicalUnit.SAC_POINT: case LexicalUnit.SAC_PICA: case LexicalUnit.SAC_PERCENTAGE: lu = lu.getNextLexicalUnit(); } if (lu != null) { break; } return CSSLexicalUnit.createPredefinedFunction (LexicalUnit.SAC_RECT_FUNCTION, params, prev); } break; case 'c': case 'C': if (name.equalsIgnoreCase("counter")) { lu = params; if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_IDENT: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_OPERATOR_COMMA: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_IDENT: lu = lu.getNextLexicalUnit(); } if (lu != null) { break; } return CSSLexicalUnit.createPredefinedFunction (LexicalUnit.SAC_COUNTER_FUNCTION, params, prev); } else if (name.equalsIgnoreCase("counters")) { lu = params; if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_IDENT: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_OPERATOR_COMMA: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_STRING_VALUE: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_OPERATOR_COMMA: lu = lu.getNextLexicalUnit(); } if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_IDENT: lu = lu.getNextLexicalUnit(); } if (lu != null) { break; } return CSSLexicalUnit.createPredefinedFunction (LexicalUnit.SAC_COUNTERS_FUNCTION, params, prev); } break; case 'a': case 'A': if (name.equalsIgnoreCase("attr")) { lu = params; if (lu == null) { break; } switch (lu.getLexicalUnitType()) { default: break predefined; case LexicalUnit.SAC_IDENT: lu = lu.getNextLexicalUnit(); } if (lu != null) { break; } return CSSLexicalUnit.createString (LexicalUnit.SAC_ATTR, params.getStringValue(), prev); } } return CSSLexicalUnit.createFunction(name, params, prev); } /** * Converts a hash unit to a RGB color. */ protected LexicalUnit hexcolor(LexicalUnit prev) { String val = scanner.currentValue(); int len = val.length(); LexicalUnit params = null; switch (len) { case 3: char rc = Character.toLowerCase(val.charAt(0)); char gc = Character.toLowerCase(val.charAt(1)); char bc = Character.toLowerCase(val.charAt(2)); if (!ScannerUtilities.isCSSHexadecimalCharacter(rc) || !ScannerUtilities.isCSSHexadecimalCharacter(gc) || !ScannerUtilities.isCSSHexadecimalCharacter(bc)) { throw createCSSParseException("rgb.color"); } int t; int r = t = (rc >= '0' && rc <= '9') ? rc - '0' : rc - 'a' + 10; t <<= 4; r |= t; int g = t = (gc >= '0' && gc <= '9') ? gc - '0' : gc - 'a' + 10; t <<= 4; g |= t; int b = t = (bc >= '0' && bc <= '9') ? bc - '0' : bc - 'a' + 10; t <<= 4; b |= t; params = CSSLexicalUnit.createInteger(r, null); LexicalUnit tmp; tmp = CSSLexicalUnit.createSimple(LexicalUnit.SAC_OPERATOR_COMMA, params); tmp = CSSLexicalUnit.createInteger(g, tmp); tmp = CSSLexicalUnit.createSimple(LexicalUnit.SAC_OPERATOR_COMMA, tmp); tmp = CSSLexicalUnit.createInteger(b, tmp); break; case 6: char rc1 = Character.toLowerCase(val.charAt(0)); char rc2 = Character.toLowerCase(val.charAt(1)); char gc1 = Character.toLowerCase(val.charAt(2)); char gc2 = Character.toLowerCase(val.charAt(3)); char bc1 = Character.toLowerCase(val.charAt(4)); char bc2 = Character.toLowerCase(val.charAt(5)); if (!ScannerUtilities.isCSSHexadecimalCharacter(rc1) || !ScannerUtilities.isCSSHexadecimalCharacter(rc2) || !ScannerUtilities.isCSSHexadecimalCharacter(gc1) || !ScannerUtilities.isCSSHexadecimalCharacter(gc2) || !ScannerUtilities.isCSSHexadecimalCharacter(bc1) || !ScannerUtilities.isCSSHexadecimalCharacter(bc2)) { throw createCSSParseException("rgb.color"); } r = (rc1 >= '0' && rc1 <= '9') ? rc1 - '0' : rc1 - 'a' + 10; r <<= 4; r |= (rc2 >= '0' && rc2 <= '9') ? rc2 - '0' : rc2 - 'a' + 10; g = (gc1 >= '0' && gc1 <= '9') ? gc1 - '0' : gc1 - 'a' + 10; g <<= 4; g |= (gc2 >= '0' && gc2 <= '9') ? gc2 - '0' : gc2 - 'a' + 10; b = (bc1 >= '0' && bc1 <= '9') ? bc1 - '0' : bc1 - 'a' + 10; b <<= 4; b |= (bc2 >= '0' && bc2 <= '9') ? bc2 - '0' : bc2 - 'a' + 10; params = CSSLexicalUnit.createInteger(r, null); tmp = CSSLexicalUnit.createSimple(LexicalUnit.SAC_OPERATOR_COMMA, params); tmp = CSSLexicalUnit.createInteger(g, tmp); tmp = CSSLexicalUnit.createSimple(LexicalUnit.SAC_OPERATOR_COMMA, tmp); tmp = CSSLexicalUnit.createInteger(b, tmp); break; default: throw createCSSParseException("rgb.color"); } nextIgnoreSpaces(); return CSSLexicalUnit.createPredefinedFunction(LexicalUnit.SAC_RGBCOLOR, params, prev); } /** * Returns the Java encoding string mapped with the given CSS encoding string. */ protected String javaEncoding(String encoding) { String result = (String)ENCODINGS.get(encoding); if (result == null) { throw new CSSException(formatMessage("encoding", new Object[] { encoding })); } return result; } /** * Converts the given input source into a Reader. * @param is The input source. * @param enc The encoding or null. */ protected Reader characterStream(InputSource source, String enc) { Reader r = source.getCharacterStream(); if (r != null) { return r; } InputStream is = source.getByteStream(); if (is != null) { return characterStream(source, is, enc); } String uri = source.getURI(); if (uri != null) { try { URL url = new URL(uri); return characterStream(source, url.openStream(), enc); } catch (MalformedURLException e) { throw new CSSException(e); } catch (IOException e) { throw new CSSException(e); } } throw new CSSException("Empty source"); } /** * Converts the given input stream into a Reader. * @param is The input source. * @param enc The encoding or null. */ protected Reader characterStream(InputSource source, InputStream is, String enc) { documentURI = source.getURI(); documentURI = (documentURI == null) ? "" : documentURI; try { String encoding = source.getEncoding(); if (encoding == null && enc == null) { return new InputStreamReader(is); } else if (encoding != null && enc != null) { if (!javaEncoding(encoding).equals(javaEncoding(enc))) { throw new CSSException(formatMessage("encoding", new Object[] { enc })); } return new InputStreamReader(is, javaEncoding(encoding)); } else { return new InputStreamReader(is, javaEncoding((enc != null) ? enc : encoding)); } } catch (UnsupportedEncodingException e) { throw new CSSException(e); } } /** * Skips the white spaces. */ protected int skipSpaces() { int lex = scanner.currentType(); while (lex == LexicalUnits.SPACE) { lex = next(); } return lex; } /** * Skips the white spaces and CDO/CDC untis. */ protected int skipSpacesAndCDOCDC() { loop: for (;;) { switch (current) { default: break loop; case LexicalUnits.COMMENT: case LexicalUnits.SPACE: case LexicalUnits.CDO: case LexicalUnits.CDC: } next(); } return current; } /** * Converts the current lexical unit to a float. */ protected float number(boolean positive) { try { float sgn = (positive) ? 1 : -1; String val = scanner.currentValue(); nextIgnoreSpaces(); return sgn * Float.parseFloat(val); } catch (NumberFormatException e) { throw createCSSParseException("number.format"); } } /** * Converts the current lexical unit to a dimension. */ protected LexicalUnit dimension(boolean positive, LexicalUnit prev) { try { float sgn = (positive) ? 1 : -1; String val = scanner.currentValue(); int i; loop: for (i = 0; i < val.length(); i++) { switch (val.charAt(i)) { default: break loop; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': } } nextIgnoreSpaces(); return CSSLexicalUnit.createDimension (sgn * Float.parseFloat(val.substring(0, i)), val.substring(i), prev); } catch (NumberFormatException e) { throw createCSSParseException("number.format"); } } /** * Advances to the next token, ignoring comments. */ protected int next() { try { for (;;) { current = scanner.next(); if (current == LexicalUnits.COMMENT) { documentHandler.comment(scanner.currentValue()); } else { break; } } return current; } catch (ParseException e) { reportError(e.getMessage()); return current; } } /** * Advances to the next token and skip the spaces, ignoring comments. */ protected int nextIgnoreSpaces() { try { loop: for (;;) { current = scanner.next(); switch (current) { case LexicalUnits.COMMENT: documentHandler.comment(scanner.currentValue()); break; default: break loop; case LexicalUnits.SPACE: } } return current; } catch (ParseException e) { reportError(e.getMessage()); return current; } } /** * Reports a parsing error. */ protected void reportError(String key) { reportError(createCSSParseException(formatMessage(key, null))); } /** * Reports a parsing error. */ protected void reportError(CSSParseException e) { errorHandler.error(e); int brackets = 1; for (;;) { switch (current) { case LexicalUnits.EOF: return; case LexicalUnits.SEMI_COLON: case LexicalUnits.RIGHT_BRACKET: if (--brackets == 0) { nextIgnoreSpaces(); return; } case LexicalUnits.LEFT_BRACKET: brackets++; } nextIgnoreSpaces(); } } /** * Creates a parse exception. */ protected CSSParseException createCSSParseException(String key) { return new CSSParseException(formatMessage(key, null), documentURI, scanner.getLine(), scanner.getColumn()); } }
package edu.wustl.common.security; import java.util.List; import java.util.Vector; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.security.exceptions.SMTransactionException; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.security.AuthenticationManager; import gov.nih.nci.security.AuthorizationManager; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.UserProvisioningManager; import gov.nih.nci.security.authorization.domainobjects.User; import gov.nih.nci.security.dao.SearchCriteria; import gov.nih.nci.security.dao.UserSearchCriteria; import gov.nih.nci.security.exceptions.CSException; import gov.nih.nci.security.exceptions.CSTransactionException; public class SecurityManager { private static AuthenticationManager authenticationManager = null; private static AuthorizationManager authorizationManager = null; private Class requestingClass=null; private static final String CATISSUE_CORE_CONTEXT_NAME = "catissuecore"; private static final String ADMINISTRATOR_ROLE="1"; private static final String SUPERVISOR_ROLE="2"; private static final String TECHNICIAN_ROLE="3"; private static final String ADMINISTRATOR_GROUP="ADMINISTRATOR_GROUP"; private static final String SUPERVISOR_GROUP="SUPERVISOR_GROUP"; private static final String TECHNICIAN_GROUP="TECHNICIAN_GROUP"; /** * @param class1 */ public SecurityManager(Class class1) { requestingClass = class1; } /** * @param class1 * @return */ public static SecurityManager getInstance(Class class1) { return new SecurityManager(class1); } /** * Returns the AuthenticationManager for the caTISSUE Core. This method follows the * singleton pattern so that only one AuthenticationManager is created for * the caTISSUE Core. * * @return * @throws CSException */ protected AuthenticationManager getAuthenticationManager() throws CSException { if (authenticationManager == null) { synchronized (requestingClass) { if (authenticationManager == null) { authenticationManager = SecurityServiceProvider .getAuthenticationManager(CATISSUE_CORE_CONTEXT_NAME); } } } return authenticationManager; } /** * Returns the Authorization Manager for the caTISSUE Core. * This method follows the singleton pattern so that * only one AuthorizationManager is created. * * @return * @throws CSException */ protected AuthorizationManager getAuthorizationManager() throws CSException { if (authorizationManager == null) { synchronized (requestingClass) { if (authorizationManager == null) { authorizationManager = SecurityServiceProvider .getAuthorizationManager(CATISSUE_CORE_CONTEXT_NAME); } } } return authorizationManager; } /** * Returns the UserProvisioningManager singleton object. * * @return * @throws CSException */ protected UserProvisioningManager getUserProvisioningManager() throws CSException { return (UserProvisioningManager) getAuthorizationManager(); } /** * Returns true or false depending on the person gets authenticated or not. * @param requestingClass * @param loginName login name * @param password password * @return * @throws CSException */ public boolean login(String loginName, String password) throws SMException { boolean loginSuccess = false; try { Logger.out.debug("login name: "+loginName+" passowrd: "+password); AuthenticationManager authMngr=getAuthenticationManager(); loginSuccess =authMngr.login( loginName, password); } catch (CSException ex) { Logger.out.debug("Authentication|"+requestingClass+"|"+loginName+"|login|Success| Authentication is not successful for user "+loginName+"|" + ex.getMessage()); throw new SMException (ex.getMessage(), ex); } return loginSuccess; } /** * This method creates a new User in the database based on the data passed * @param user user to be created * @throws SMTransactionException If there is any exception in creating the User */ public void createUser(User user) throws SMTransactionException { try { getUserProvisioningManager().createUser(user); } catch (CSTransactionException e) { Logger.out.debug("Unable to create user: Exception: "+e.getMessage()); throw new SMTransactionException (e.getMessage(), e); } catch (CSException e) { Logger.out.debug("Unable to create user: Exception: "+e); } } /** * This method returns the User object from the database for the passed User's Login Name. * If no User is found then null is returned * @param loginName Login name of the user * @return * @throws SMException */ public User getUser(String loginName) throws SMException { try { return getAuthorizationManager().getUser(loginName); } catch (CSException e) { Logger.out.debug("Unable to get user: Exception: "+e.getMessage()); throw new SMException (e.getMessage(), e); } } /** * This method checks whether a user exists in the database or not * @param loginName Login name of the user * @return TRUE is returned if a user exists else FALSE is returned * @throws SMException */ public boolean userExists(String loginName) throws SMException { boolean userExists=true; try { if(getUser(loginName)==null) { userExists = false; } } catch (SMException e) { Logger.out.debug("Unable to get user: Exception: "+e.getMessage()); throw e; } return userExists; } /** * This method returns Vactor of all the role objects defined for the application from the database * @return * @throws SMException */ public Vector getRoles()throws SMException { Vector roles=new Vector(); UserProvisioningManager userProvisioningManager=null; try { userProvisioningManager=getUserProvisioningManager(); roles.add(userProvisioningManager.getRoleById(ADMINISTRATOR_ROLE)); roles.add(userProvisioningManager.getRoleById(SUPERVISOR_ROLE)); roles.add(userProvisioningManager.getRoleById(TECHNICIAN_ROLE)); } catch (CSException e) { Logger.out.debug("Unable to get roles: Exception: "+e.getMessage()); throw new SMException (e.getMessage(), e); } return roles; } /** * Assigns a Role to a User * @param userName - the User Name to to whom the Role will be assigned * @param roleID - The id of the Role which is to be assigned to the user * @throws SMException */ public void assignRoleToUser(String userName, String roleID) throws SMException { UserProvisioningManager userProvisioningManager=null; try { userProvisioningManager=getUserProvisioningManager(); if(roleID.equals(ADMINISTRATOR_ROLE)) { userProvisioningManager.assignUserToGroup(userName,ADMINISTRATOR_GROUP); } else if(roleID.equals(SUPERVISOR_ROLE)) { userProvisioningManager.assignUserToGroup(userName,SUPERVISOR_GROUP); } else if(roleID.equals(TECHNICIAN_ROLE)) { userProvisioningManager.assignUserToGroup(userName,TECHNICIAN_GROUP); } } catch (CSException e) { Logger.out.debug("UNABLE TO ASSIGN ROLE TO USER: Exception: "+e.getMessage()); throw new SMException (e.getMessage(), e); } } /** * Modifies an entry for an existing User in the database based on the data passed * @param user - the User object that needs to be modified in the database * @throws SMException if there is any exception in modifying the User in the database */ public void modifyUser(User user) throws SMException { try { getUserProvisioningManager().modifyUser(user); } catch (CSException e) { Logger.out.debug("Unable to modify user: Exception: "+e.getMessage()); throw new SMException (e.getMessage(), e); } } /** * Returns the User object for the passed User id * @param userId - The id of the User object which is to be obtained * @return The User object from the database for the passed User id * @throws SMException if the User object is not found for the given id */ public User getUserById(String userId) throws SMException { try { return getUserProvisioningManager().getUserById(userId); } catch (CSException e) { Logger.out.debug("Unable to get user by Id: Exception: "+e.getMessage()); throw new SMException (e.getMessage(), e); } } /** * Returns list of the User objects for the passed email address * @param emailAddress - Email Address for which users need to be searched * @return * @throws SMException if there is any exception while querying the database */ public List getUsersByEmail(String emailAddress) throws SMException { try { User user = new User(); user.setEmailId(emailAddress); SearchCriteria searchCriteria = new UserSearchCriteria(user); return getUserProvisioningManager().getObjects(searchCriteria); } catch (CSException e) { Logger.out.debug("Unable to get users by emailAddress: Exception: "+e.getMessage()); throw new SMException (e.getMessage(), e); } } }
package scalai; public class EvaluatorResult { // // Public Cases case Void; case Value(Object value, String type); case Error(EvaluatorException exception); // }
package scalac.ast.printer; import scalac.ast.*; import scalac.symtab.*; import scalac.util.Debug; import scalac.Global; import scalac.Unit; import scalac.util.Name; import java.io.*; import java.util.*; /** * Text pretty printer for Scala abstract syntax trees. * * @author Michel Schinz, Matthias Zenger * @version 1.0 */ public class TextTreePrinter implements TreePrinter { protected PrintWriter out; protected final boolean autoFlush; protected int indent = 0; protected final int INDENT_STEP = 2; protected String INDENT_STRING = " "; protected final int MAX_INDENT = INDENT_STRING.length(); public TextTreePrinter(OutputStream stream) { this(stream, false); } public TextTreePrinter(OutputStream stream, boolean autoFlush) { this.autoFlush = autoFlush; this.out = new PrintWriter(stream); } public TextTreePrinter() { this(System.out); } public void begin() { } public void end() { flush(); } public void flush() { out.flush(); } public TreePrinter print(String str) { out.print(str); if (autoFlush) flush(); return this; } public TreePrinter println() { out.println(); if (autoFlush) flush(); return this; } public void beginSection(int level, String title) { out.println("[[" + title + "]]"); flush(); } protected void indent() { indent += Math.min(MAX_INDENT, INDENT_STEP); } protected void undent() { indent -= Math.max(0, INDENT_STEP); } protected void printString(String str) { out.print(str); if (autoFlush) flush(); } protected void printNewLine() { out.println(); while (indent > INDENT_STRING.length()) { INDENT_STRING = INDENT_STRING + INDENT_STRING; } if (indent > 0) out.write(INDENT_STRING, 0, indent); if (autoFlush) flush(); } public static class SymbolUsage { public case Definition; public case Use; } public static class Text { public case None; public case Space; public case Newline; public case Simple(String str); public case Literal(String str); public case Keyword(String name); public case Identifier(Symbol symbol, String name, SymbolUsage usage); public case Sequence(Text[] elements); } protected void print(Text text) { switch (text) { case None : break; case Space : printString(" "); break; case Newline : printNewLine(); break; case Simple(String str) : printString(str); break; case Literal(String str) : printString(str); break; case Keyword(String name) : printString(name); break; case Identifier(Symbol sym, String name, _) : printString(name); if (sym != null && Global.instance.uniqid) printString("#" + Global.instance.uniqueID.id(sym)); break; case Sequence(Text[] elements) : print(elements); break; } } protected void print(Text[] texts) { for (int i = 0; i < texts.length; ++i) print(texts[i]); } protected static final Text KW_ABSTRACT = Text.Keyword("abstract"); protected static final Text KW_CASE = Text.Keyword("case"); protected static final Text KW_CLASS = Text.Keyword("class"); protected static final Text KW_CONSTR = Text.Keyword("constr"); protected static final Text KW_DEF = Text.Keyword("def"); protected static final Text KW_DO = Text.Keyword("do"); protected static final Text KW_ELSE = Text.Keyword("else"); protected static final Text KW_EXTENDS = Text.Keyword("extends"); protected static final Text KW_FINAL = Text.Keyword("final"); protected static final Text KW_FOR = Text.Keyword("for"); protected static final Text KW_IF = Text.Keyword("if"); protected static final Text KW_IMPORT = Text.Keyword("import"); protected static final Text KW_INTERFACE = Text.Keyword("interface"); protected static final Text KW_LET = Text.Keyword("let"); protected static final Text KW_OBJECT = Text.Keyword("object"); protected static final Text KW_NEW = Text.Keyword("new"); protected static final Text KW_NULL = Text.Keyword("null"); protected static final Text KW_OUTER = Text.Keyword("outer"); protected static final Text KW_OVERRIDE = Text.Keyword("override"); protected static final Text KW_PACKAGE = Text.Keyword("package"); protected static final Text KW_PRIVATE = Text.Keyword("private"); protected static final Text KW_PROTECTED = Text.Keyword("protected"); protected static final Text KW_QUALIFIED = Text.Keyword("qualified"); protected static final Text KW_STATIC = Text.Keyword("static"); protected static final Text KW_SUPER = Text.Keyword("super"); protected static final Text KW_THIS = Text.Keyword("this"); protected static final Text KW_TYPE = Text.Keyword("type"); protected static final Text KW_VAL = Text.Keyword("val"); protected static final Text KW_VAR = Text.Keyword("var"); protected static final Text KW_WITH = Text.Keyword("with"); protected static final Text KW_YIELD = Text.Keyword("yield"); protected static final Text TXT_ERROR = Text.Simple("<error>"); protected static final Text TXT_UNKNOWN = Text.Simple("<unknown>"); protected static final Text TXT_NULL = Text.Simple("<null>"); protected static final Text TXT_OBJECT_COMMENT = Text.Simple("/*object*/ "); protected static final Text TXT_EMPTY = Text.Simple("<empty>"); protected static final Text TXT_QUOTE = Text.Simple("\""); protected static final Text TXT_PLUS = Text.Simple("+"); protected static final Text TXT_COLON = Text.Simple(":"); protected static final Text TXT_SEMICOLON = Text.Simple(";"); protected static final Text TXT_DOT = Text.Simple("."); protected static final Text TXT_COMMA = Text.Simple(","); protected static final Text TXT_EQUAL = Text.Simple("="); protected static final Text TXT_SUPERTYPE = Text.Simple(">:"); protected static final Text TXT_SUBTYPE = Text.Simple("<:"); protected static final Text TXT_HASH = Text.Simple(" protected static final Text TXT_RIGHT_ARROW = Text.Simple("=>"); protected static final Text TXT_LEFT_PAREN = Text.Simple("("); protected static final Text TXT_RIGHT_PAREN = Text.Simple(")"); protected static final Text TXT_LEFT_BRACE = Text.Simple("{"); protected static final Text TXT_RIGHT_BRACE = Text.Simple("}"); protected static final Text TXT_LEFT_BRACKET = Text.Simple("["); protected static final Text TXT_RIGHT_BRACKET = Text.Simple("]"); protected static final Text TXT_BAR = Text.Simple("|"); protected static final Text TXT_AT = Text.Simple("@"); protected static final Text TXT_WITH_SP = Text.Sequence(new Text[]{ Text.Space, KW_WITH, Text.Space }); protected static final Text TXT_BLOCK_BEGIN = Text.Sequence(new Text[]{ TXT_LEFT_BRACE, Text.Newline }); protected static final Text TXT_BLOCK_END = Text.Sequence(new Text[]{ Text.Newline, TXT_RIGHT_BRACE }); protected static final Text TXT_BLOCK_SEP = Text.Sequence(new Text[]{ TXT_SEMICOLON, Text.Newline }); protected static final Text TXT_COMMA_SP = Text.Sequence(new Text[]{ TXT_COMMA, Text.Space }); protected static final Text TXT_ELSE_NL = Text.Sequence(new Text[]{ KW_ELSE, Text.Newline }); protected static final Text TXT_BAR_SP = Text.Sequence(new Text[]{ Text.Space, TXT_BAR, Text.Space }); public void print(Unit unit) { printUnitHeader(unit); if (unit.body != null) { for (int i = 0; i < unit.body.length; ++i) { print(unit.body[i]); print(TXT_BLOCK_SEP); } } else print(TXT_NULL); printUnitFooter(unit); flush(); } protected void printUnitHeader(Unit unit) { print(Text.Simple("// Scala source: " + unit.source + "\n")); } protected void printUnitFooter(Unit unit) { print(Text.Newline); } public TreePrinter print(Tree tree) { switch (tree) { case Bad(): print(TXT_ERROR); break; case Empty: print(TXT_EMPTY); break; case ClassDef(int mods, Name name, Tree.TypeDef[] tparams, Tree.ValDef[][] vparams, Tree tpe, Tree.Template impl): printModifiers(mods); print((mods & Modifiers.INTERFACE) != 0 ? KW_INTERFACE : KW_CLASS); print(Text.Space); printSymbolDefinition(tree.symbol(), name); printParams(tparams); printParams(vparams); printOpt(TXT_COLON, tpe, false); printTemplate(KW_EXTENDS, impl, true); break; case PackageDef(Tree packaged, Tree.Template impl): print(KW_PACKAGE); print(Text.Space); print(packaged); printTemplate(KW_WITH, impl, true); break; case ModuleDef(int mods, Name name, Tree tpe, Tree.Template impl): printModifiers(mods); print(KW_OBJECT); print(Text.Space); printSymbolDefinition(tree.symbol(), name); printOpt(TXT_COLON, tpe, false); printTemplate(KW_EXTENDS, impl, true); break; case ValDef(int mods, Name name, Tree tpe, Tree rhs): printModifiers(mods); if ((mods & Modifiers.MUTABLE) != 0) print(KW_VAR); else { if ((mods & Modifiers.MODUL) != 0) print(TXT_OBJECT_COMMENT); print(KW_VAL); } print(Text.Space); printSymbolDefinition(tree.symbol(), name); printOpt(TXT_COLON, tpe, false); if ((mods & Modifiers.DEFERRED) == 0) { print(Text.Space); print(TXT_EQUAL); print(Text.Space); if (rhs == Tree.Empty) print("_"); else print(rhs); } break; case PatDef(int mods, Tree pat, Tree rhs): printModifiers(mods); print(KW_VAL); print(Text.Space); print(pat); printOpt(TXT_EQUAL, rhs, true); break; case DefDef(int mods, Name name, Tree.TypeDef[] tparams, Tree.ValDef[][] vparams, Tree tpe, Tree rhs): printModifiers(mods); if (name.isConstrName()) print(KW_CONSTR); else print(KW_DEF); print(Text.Space); printSymbolDefinition(tree.symbol(), name); printParams(tparams); printParams(vparams); printOpt(TXT_COLON, tpe, false); printOpt(TXT_EQUAL, rhs, true); break; case TypeDef(int mods, Name name, Tree rhs, Tree lobound): printModifiers(mods); print(KW_TYPE); print(Text.Space); printSymbolDefinition(tree.symbol(), name); if ((mods & (Modifiers.DEFERRED | Modifiers.PARAM)) != 0) { printBounds(lobound, rhs); } else { printOpt(TXT_EQUAL, rhs, true); } break; case Import(Tree expr, Name[] selectors): print(KW_IMPORT); print(Text.Space); print(expr); print(TXT_DOT); print(TXT_LEFT_BRACE); for (int i = 0; i < selectors.length; i = i + 2) { if (i > 0) print(TXT_COMMA_SP); print(selectors[i].toString()); if (i + 1 < selectors.length && selectors[i] != selectors[i+1]) { print(TXT_RIGHT_ARROW); print(selectors[i+1].toString()); } } print(TXT_RIGHT_BRACE); break; case CaseDef(Tree pat, Tree guard, Tree body): print(KW_CASE); print(Text.Space); print(pat); printOpt(KW_IF, guard, true); print(Text.Space); print(TXT_RIGHT_ARROW); print(Text.Space); print(body); break; case LabelDef(Tree.Ident[] params, Tree rhs): assert tree.symbol() != null; printSymbolDefinition(tree.symbol(), null); printArray(params, TXT_LEFT_PAREN, TXT_RIGHT_PAREN, TXT_COMMA_SP); print(rhs); break; case Block(Tree[] stats): printArray(stats, TXT_BLOCK_BEGIN, TXT_BLOCK_END, TXT_BLOCK_SEP); break; case Sequence(Tree[] trees): // sure ? was Tuple before... printArray(trees, TXT_LEFT_BRACKET, TXT_RIGHT_BRACKET, TXT_COMMA_SP); break; case Subsequence(Tree[] trees): if( trees.length > 0 ) printArray(trees, TXT_LEFT_PAREN, TXT_RIGHT_PAREN, TXT_COMMA_SP); else { print( TXT_LEFT_PAREN ); print( TXT_COMMA ); print( TXT_RIGHT_PAREN ); } break; case Alternative(Tree[] trees): printArray(trees, TXT_LEFT_PAREN, TXT_RIGHT_PAREN, TXT_BAR_SP); break; case Bind(Name name, Tree t): printSymbolDefinition(tree.symbol(), name); print(Text.Space); print(TXT_AT); print(Text.Space); print( t ); break; case Visitor(Tree.CaseDef[] cases): printArray(cases, TXT_BLOCK_BEGIN, TXT_BLOCK_END, Text.Newline); break; case Function(Tree.ValDef[] vparams, Tree body): print(TXT_LEFT_BRACE); printParams(vparams); print(Text.Space); print(TXT_RIGHT_ARROW); print(Text.Space); print(body); print(TXT_RIGHT_BRACE); break; case Assign(Tree lhs, Tree rhs): print(lhs); print(Text.Space); print(TXT_EQUAL); print(Text.Space); print(rhs); break; case If(Tree cond, Tree thenp, Tree elsep): print(KW_IF); print(Text.Space); print(TXT_LEFT_PAREN); print(cond); print(TXT_RIGHT_PAREN); indent(); print(Text.Newline); print(thenp); undent(); print(Text.Newline); indent(); printOpt(TXT_ELSE_NL, elsep, false); undent(); printType(tree); break; case New(Tree.Template templ): printTemplate(KW_NEW, templ, false); printType(tree); break; case Typed(Tree expr, Tree tpe): print(TXT_LEFT_PAREN); print(expr); print(TXT_RIGHT_PAREN); print(Text.Space); print(TXT_COLON); print(Text.Space); print(tpe); printType(tree); break; case TypeApply(Tree fun, Tree[] targs): print(fun); printArray(targs, TXT_LEFT_BRACKET, TXT_RIGHT_BRACKET, TXT_COMMA_SP); printType(tree); break; case Apply(Tree fun, Tree[] vargs): if (fun instanceof Tree.TypeTerm) print(fun.type.resultType().symbol().fullName().toString()); else print(fun); printArray(vargs, TXT_LEFT_PAREN, TXT_RIGHT_PAREN, TXT_COMMA_SP); printType(tree); break; case Super(Tree tpe): if (tpe != Tree.Empty) print(TXT_LEFT_PAREN); print(KW_SUPER); if (tpe != Tree.Empty) { print(Text.Space); print(TXT_COLON); print(Text.Space); print(tpe); print(TXT_RIGHT_PAREN); } printType(tree); break; case This(Tree qualifier): if (qualifier != Tree.Empty) { print(qualifier); print(TXT_DOT); } print(KW_THIS); printType(tree); break; case Select(Tree qualifier, Name name): print(qualifier); print(TXT_DOT); printSymbolUse(tree.symbol(), name); printType(tree); break; case Ident(Name name): printSymbolUse(tree.symbol(), name); printType(tree); break; case Literal(Object obj): String str; if (obj instanceof String) str = "\"" + obj + "\""; else if (obj instanceof Character) str = "\'" + obj + "\'"; else str = String.valueOf(obj); print(Text.Literal(str)); printType(tree); break; case TypeTerm(): print(tree.type.toString()); break; case SingletonType(Tree ref): print(ref); print(TXT_DOT); print(KW_TYPE); break; case SelectFromType(Tree qualifier, Name selector): print(qualifier); print(Text.Space); print(TXT_HASH); print(Text.Space); printSymbolUse(tree.symbol(), selector); break; case FunType(Tree[] argtpes, Tree restpe): printArray(argtpes, TXT_LEFT_PAREN, TXT_RIGHT_PAREN, TXT_COMMA_SP); print(TXT_RIGHT_ARROW); print(restpe); break; case CompoundType(Tree[] baseTypes, Tree[] refinements): printArray(baseTypes, Text.None, Text.None, TXT_WITH_SP); printArray(refinements, TXT_BLOCK_BEGIN, TXT_BLOCK_END, Text.Newline); break; case AppliedType(Tree tpe, Tree[] args): print(tpe); indent(); print(TXT_LEFT_BRACKET); for (int i = 0; i < args.length; ++i) { if (i > 0) print(TXT_COMMA_SP); print(args[i]); } undent(); print(TXT_RIGHT_BRACKET); break; case Template(Tree[] parents, Tree[] body): Debug.abort("unexpected case", tree); break; default: print(TXT_UNKNOWN); break; } //print("{" + tree.type + "}");//DEBUG if (autoFlush) flush(); return this; } // Printing helpers protected void printArray(Tree[] trees, Text open, Text close, Text sep) { indent(); print(open); for (int i = 0; i < trees.length; ++i) { if (i > 0) print(sep); print(trees[i]); } undent(); print(close); } protected void printOpt(Text prefix, Tree tree, boolean spaceBefore) { if (tree != Tree.Empty) { if (spaceBefore) print(Text.Space); print(prefix); print(Text.Space); print(tree); } } // Printing of symbols protected String symbolString(Symbol symbol, Name name) { if (symbol != null) return symbol.name.toString(); else return name.toString(); } protected void printSymbolDefinition(Symbol symbol, Name name) { print(Text.Identifier(symbol, symbolString(symbol, name), SymbolUsage.Definition)); } protected void printSymbolUse(Symbol symbol, Name name) { print(Text.Identifier(symbol, symbolString(symbol, name), SymbolUsage.Use)); } // Printing of trees protected void printType(Tree tree) { if (Global.instance.printtypes) { print(TXT_LEFT_BRACE); if (tree.type != null) print(Text.Simple(tree.type.toString())); else print(TXT_NULL); print(TXT_RIGHT_BRACE); } } protected void printModifiers(int flags) { if ((flags & Modifiers.ABSTRACTCLASS) != 0) { print(KW_ABSTRACT); print(Text.Space); } if ((flags & Modifiers.FINAL) != 0) { print(KW_FINAL); print(Text.Space); } if ((flags & Modifiers.PRIVATE) != 0) { print(KW_PRIVATE); print(Text.Space); } if ((flags & Modifiers.PROTECTED) != 0) { print(KW_PROTECTED); print(Text.Space); } if ((flags & Modifiers.QUALIFIED) != 0) { print(KW_QUALIFIED); print(Text.Space); } if ((flags & Modifiers.OVERRIDE) != 0) { print(KW_OVERRIDE); print(Text.Space); } if ((flags & Modifiers.CASE) != 0) { print(KW_CASE); print(Text.Space); } if ((flags & Modifiers.DEF) != 0) { print(KW_DEF); print(Text.Space); } if ((flags & Modifiers.STATIC) != 0) { print(KW_STATIC); print(Text.Space); } } protected void printTemplate(Text prefix, Tree.Template templ, boolean spaceBefore) { if (! (templ.parents.length == 0 || (templ.parents.length == 1 && templ.parents[0] == Tree.Empty))) { if (spaceBefore) print(Text.Space); print(prefix); print(Text.Space); printArray(templ.parents, Text.None, Text.None, TXT_WITH_SP); } if (templ.body.length > 0) { print(Text.Space); printArray(templ.body, TXT_BLOCK_BEGIN, TXT_BLOCK_END, TXT_BLOCK_SEP); } } protected void printParams(Tree.TypeDef[] tparams) { if (tparams.length > 0) { print(TXT_LEFT_BRACKET); for (int i = 0; i < tparams.length; i++) { if (i > 0) print(TXT_COMMA_SP); printParam(tparams[i]); } print(TXT_RIGHT_BRACKET); } } protected void printParams(Tree.ValDef[][] vparamss) { for (int i = 0; i < vparamss.length; ++i) printParams(vparamss[i]); } protected void printParams(Tree.ValDef[] vparams) { print(TXT_LEFT_PAREN); for (int i = 0; i < vparams.length; ++i) { if (i > 0) print(TXT_COMMA_SP); printParam(vparams[i]); } print(TXT_RIGHT_PAREN); } protected void printParam(Tree tree) { switch (tree) { case TypeDef(int mods, Name name, Tree bound, Tree lobound): printModifiers(mods); printSymbolDefinition(tree.symbol(), name); printBounds(lobound, bound); break; case ValDef(int mods, Name name, Tree tpe, Tree.Empty): printModifiers(mods); printSymbolDefinition(tree.symbol(), name); printOpt(TXT_COLON, tpe, false); break; default: Debug.abort("bad parameter: " + tree); } } protected void printBounds(Tree lobound, Tree hibound) { if (lobound.toString() != "scala.All") printOpt(TXT_SUPERTYPE, lobound, true); if (hibound.toString() != "scala.Any") printOpt(TXT_SUBTYPE, hibound, true); } }
package controllers; import java.util.ArrayList; import models.campaign.Campaign; import models.campaign.Level; import models.campaign.World; /** * Loads data from serialized file */ public class Load { /** * Loads the serialized file, deserializes it, and creates the World * * @param world the world to load */ public static World loadWorld(String worldName){ return null; //compiler } /** * Loads the serialized file, deserializes it, and creates the Level * * @param level the level to load */ public static Level loadLevel(String levelName){ return null; } /** * Loads the serialized file, deserializes it, and creates the Campaign * * @param campaign the campaign to load */ public static Campaign loadCampaign(String campaignName){ return null; } /** * Gets the worlds that aren't associated with a level * * @return A list of world names */ public static ArrayList<String> getWorlds(){ return null; } /** * Gets the levels that aren't associated with a campaign * * @return A list of level names */ public static ArrayList<String> getLevels(){ return null; } /** * Gets a list of the different campaigns * * @return A list of campaign names */ public static ArrayList<String> getCampaigns(){ return null; } }
package org.spine3.tools.gcs; import com.google.api.gax.paging.Page; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.storage.Blob; import com.google.cloud.storage.Bucket; import com.google.cloud.storage.Storage; import com.google.cloud.storage.Storage.BlobListOption; import com.google.cloud.storage.Storage.BucketGetOption; import com.google.cloud.storage.StorageOptions; import com.google.common.collect.Ordering; import org.gradle.api.Action; import org.gradle.api.Project; import org.gradle.api.Task; import org.json.JSONObject; import org.slf4j.Logger; import org.spine3.gradle.SpinePlugin; import javax.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import static com.google.common.base.Preconditions.checkNotNull; import static org.slf4j.LoggerFactory.getLogger; import static org.spine3.gradle.TaskName.BUILD; import static org.spine3.gradle.TaskName.CLEAN_GCS; /** * The plugin for Google Cloud Storage, that cleans the folder with the specified period. * * @author Dmytro Grankin */ public class GcsPlugin extends SpinePlugin { private static final String PROJECT_ID_KEY = "project_id"; private Extension extension; @Override public void apply(Project project) { log().debug("Applying the GCS plugin"); extension = Extension.createFor(project); final Action<Task> cleanGcsAction = new Action<Task>() { @Override public void execute(Task task) { cleanGcs(); } }; final GradleTask task = newTask(CLEAN_GCS, cleanGcsAction).insertBeforeTask(BUILD) .applyNowTo(project); log().debug("GCS Gradle plugin initialized with the Gradle task: {}", task); } private void cleanGcs() { final Storage storage = getStorage(); final Bucket bucket = storage.get(extension.getBucket(), BucketGetOption.fields()); if (bucket == null) { throw new IllegalStateException("Specified bucket was not found."); } final Page<Blob> blobs = bucket.list(BlobListOption.prefix(extension.getCleaningFolder())); if (!blobs.iterateAll() .iterator() .hasNext()) { log().info("Folder `{}` is empty. Nothing to clean.", extension.getCleaningFolder()); return; } final Date lastCleaningDate = new Date(getMinCreationDate(blobs)); final Date nextCleaningDate = new Date(lastCleaningDate.getTime() + extension.getCleaningInternal() .toMillis()); final Date now = new Date(); log().debug("Last cleaning date is `{}`.", lastCleaningDate); log().debug("Next cleaning date is `{}`.", nextCleaningDate); final boolean isCleaningRequired = nextCleaningDate.before(now); if (isCleaningRequired) { for (Blob blob : blobs.iterateAll()) { storage.delete(blob.getBlobId()); } log().info("Folder `{}` in bucket `{}` cleaned.", extension.getCleaningFolder(), extension.getBucket()); } else { log().info("Cleaning is not required yet."); } } private Storage getStorage() { final byte[] keyFileBytes = extension.getKeyFileContent() .getBytes(); final InputStream serviceAccountFile = new ByteArrayInputStream(keyFileBytes); final ServiceAccountCredentials credentials; try { credentials = ServiceAccountCredentials.fromStream(serviceAccountFile); } catch (IOException e) { throw new IllegalStateException("Invalid key file content was specified.", e); } final JSONObject json = new JSONObject(extension.getKeyFileContent()); final String projectId = (String) json.get(PROJECT_ID_KEY); return StorageOptions.newBuilder() .setProjectId(projectId) .setCredentials(credentials) .build() .getService(); } private static long getMinCreationDate(Page<Blob> blobs) { final Ordering<Blob> creationDateOrdering = new Ordering<Blob>() { @Override public int compare(@Nullable Blob left, @Nullable Blob right) { checkNotNull(left); checkNotNull(right); return left.getCreateTime() .compareTo(right.getCreateTime()); } }; final Blob oldestBlob = creationDateOrdering.min(blobs.iterateAll()); return oldestBlob.getCreateTime(); } private static Logger log() { return LogSingleton.INSTANCE.value; } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = getLogger(GcsPlugin.class); } }
package org.gluu.oxauth.service; import org.apache.commons.lang3.ArrayUtils; import org.gluu.oxauth.model.config.StaticConfiguration; import org.gluu.oxauth.model.configuration.AppConfiguration; import org.gluu.oxauth.model.ldap.ClientAuthorization; import org.gluu.oxauth.model.registration.Client; import org.gluu.persist.PersistenceEntryManager; import org.gluu.persist.exception.EntryPersistenceException; import org.gluu.persist.model.base.SimpleBranch; import org.gluu.util.StringHelper; import org.slf4j.Logger; import javax.inject.Inject; import javax.inject.Named; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @author Javier Rojas Blum * @version March 4, 2020 */ @Named public class ClientAuthorizationsService { @Inject private Logger log; @Inject private PersistenceEntryManager ldapEntryManager; @Inject private ClientService clientService; @Inject private StaticConfiguration staticConfiguration; @Inject private AppConfiguration appConfiguration; public void addBranch() { SimpleBranch branch = new SimpleBranch(); branch.setOrganizationalUnitName("authorizations"); branch.setDn(createDn(null)); ldapEntryManager.persist(branch); } public boolean containsBranch() { return ldapEntryManager.contains(createDn(null), SimpleBranch.class); } public void prepareBranch() { String baseDn = createDn(null); if (!ldapEntryManager.hasBranchesSupport(baseDn)) { return; } // Create client authorizations branch if needed if (!containsBranch()) { addBranch(); } } public ClientAuthorization find(String userInum, String clientId) { prepareBranch(); final String id = createId(userInum, clientId); try { return ldapEntryManager.find(ClientAuthorization.class, createDn(id)); } catch (EntryPersistenceException e) { log.trace("Unable to find client persistence for {}", id); return null; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } public void clearAuthorizations(ClientAuthorization clientAuthorization, boolean persistInPersistence) { if (clientAuthorization == null) { return; } if (persistInPersistence) { ldapEntryManager.remove(clientAuthorization); } } public void add(String userInum, String clientId, Set<String> scopes) { log.trace("Attempting to add client authorization, scopes:" + scopes + ", clientId: " + clientId + ", userInum: " + userInum); Client client = clientService.getClient(clientId); // oxAuth #441 Pre-Authorization + Persist Authorizations... don't write anything // If a client has pre-authorization=true, there is no point to create the entry under // ou=clientAuthorizations it will negatively impact performance, grow the size of the // ldap database, and serve no purpose. prepareBranch(); ClientAuthorization clientAuthorization = find(userInum, clientId); if (clientAuthorization == null) { final String id = createId(userInum, clientId); clientAuthorization = new ClientAuthorization(); clientAuthorization.setId(id); clientAuthorization.setDn(createDn(id)); clientAuthorization.setClientId(clientId); clientAuthorization.setUserId(userInum); clientAuthorization.setScopes(scopes.toArray(new String[scopes.size()])); clientAuthorization.setDeletable(!client.getAttributes().getKeepClientAuthorizationAfterExpiration()); clientAuthorization.setExpirationDate(client.getExpirationDate()); clientAuthorization.setTtl(appConfiguration.getDynamicRegistrationExpirationTime()); ldapEntryManager.persist(clientAuthorization); } else if (ArrayUtils.isNotEmpty(clientAuthorization.getScopes())) { Set<String> set = new HashSet<>(scopes); set.addAll(Arrays.asList(clientAuthorization.getScopes())); if (set.size() != scopes.size()) { clientAuthorization.setScopes(set.toArray(new String[set.size()])); ldapEntryManager.merge(clientAuthorization); } } } public static String createId(String userId, String clientId) { return userId + "_" + clientId; } public String createDn(String oxId) { String baseDn = staticConfiguration.getBaseDn().getAuthorizations(); if (StringHelper.isEmpty(oxId)) { return baseDn; } return String.format("oxId=%s,%s", oxId, baseDn); } }
package io.smartlogic.smartchat.fragments; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.Point; import android.hardware.Camera; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import io.smartlogic.smartchat.Constants; import io.smartlogic.smartchat.R; import io.smartlogic.smartchat.activities.SmartChatPreviewActivity; import io.smartlogic.smartchat.views.CameraPreview; public class CameraFragment extends Fragment { private static String TAG = "CameraFragment"; private static int RESULT_LOAD_IMAGE = 1; private Camera mCamera; private CameraPreview mPreview; private FrameLayout mPreviewLayout; private Camera.PictureCallback mPicture = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { File outputDir = getActivity().getExternalCacheDir(); try { File pictureFile = File.createTempFile("smartchat", ".jpg", outputDir); FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); new ResizeTask(pictureFile.getPath()).execute(); Log.d(TAG, "Captured " + pictureFile.toString()); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } } }; private int mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_camera, null); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { Button captureButton = (Button) getView().findViewById(R.id.capture); captureButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // get an image from the camera mCamera.takePicture(null, null, mPicture); } } ); Button switchCamera = (Button) getView().findViewById(R.id.switch_camera); switchCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { removeCameraInstance(); if (mCameraId == Camera.CameraInfo.CAMERA_FACING_FRONT) { mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK; } else { mCameraId = getFrontCameraId(); } resumeCamera(); } }); Button uploadFromGallery = (Button) getView().findViewById(R.id.upload_from_gallery); uploadFromGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, RESULT_LOAD_IMAGE); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Uri selectedImage = data.getData(); if (selectedImage != null) { try { InputStream inputStream = getActivity().getContentResolver().openInputStream(selectedImage); File pictureFile = File.createTempFile("smartchat", ".jpg", getActivity().getExternalCacheDir()); OutputStream outputStream = new FileOutputStream(pictureFile); try { final byte[] buffer = new byte[1024]; int read; while ((read = inputStream.read(buffer)) != -1) outputStream.write(buffer, 0, read); outputStream.flush(); } finally { outputStream.close(); } Intent intent = new Intent(getActivity(), SmartChatPreviewActivity.class); intent.putExtra(Constants.EXTRA_PHOTO_PATH, pictureFile.getPath()); startActivity(intent); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * A safe way to get an instance of the Camera object. */ private Camera getCameraInstance(int cameraId) { Camera c = null; try { c = Camera.open(cameraId); // attempt to get a Camera instance } catch (Exception e) { // Camera is not available (in use or does not exist) } return c; // returns null if camera is unavailable } private int getFrontCameraId() { Camera.CameraInfo ci = new Camera.CameraInfo(); for (int i = 0; i < Camera.getNumberOfCameras(); i++) { Camera.getCameraInfo(i, ci); if (ci.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { return i; } } return Camera.CameraInfo.CAMERA_FACING_BACK; // No front-facing camera found } public void resumeCamera() { mCamera = getCameraInstance(mCameraId); Camera.Parameters parameters = mCamera.getParameters(); setPictureSize(parameters); setPreviewSize(parameters); parameters.setRotation(90); mCamera.setDisplayOrientation(90); parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); mCamera.setParameters(parameters); // Create our Preview view and set it as the content of our activity. mPreview = new CameraPreview(getActivity(), mCamera); mPreviewLayout = (FrameLayout) getView().findViewById(R.id.camera_preview); mPreviewLayout.addView(mPreview); mPreview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCamera.autoFocus(new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { Log.d(TAG, "started autofocus"); } }); } }); } private void setPictureSize(Camera.Parameters parameters) { Display display = getActivity().getWindowManager().getDefaultDisplay(); Point screenSize = new Point(); display.getSize(screenSize); float screenRatio = (float) screenSize.x / screenSize.y; List<Camera.Size> sizes = parameters.getSupportedPictureSizes(); Camera.Size selectedSize = parameters.getPictureSize(); float startingRatio = (float) selectedSize.height / selectedSize.width; Log.i(TAG, "Screen ratio: " + screenRatio); Log.i(TAG, "Starting ratio: " + startingRatio); Log.i(TAG, "Current size: " + selectedSize.width + "x" + selectedSize.height); boolean foundMatchingSize = false; if (sizes != null) { for (Camera.Size size : sizes) { float ratio = (float) size.height / size.width; Log.i(TAG, "Found picture size: " + size.width + "x" + size.height + " with ratio: " + ratio); if (ratio == screenRatio) { selectedSize = size; foundMatchingSize = true; break; } } if (!foundMatchingSize) { for (Camera.Size size : sizes) { float ratio = (float) size.height / size.width; Log.i(TAG, "Found picture size: " + size.width + "x" + size.height + " with ratio: " + ratio); if (ratio == startingRatio) { selectedSize = size; break; } } } } if (selectedSize != null) { Log.i(TAG, "Setting picture size: " + selectedSize.width + "x" + selectedSize.height); parameters.setPictureSize(selectedSize.width, selectedSize.height); } } private void setPreviewSize(Camera.Parameters parameters) { Display display = getActivity().getWindowManager().getDefaultDisplay(); Point screenSize = new Point(); display.getSize(screenSize); List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes(); Camera.Size previewSize = parameters.getPreviewSize(); Log.i(TAG, "Preview size: " + previewSize.width + "x" + previewSize.height); if (previewSizes != null) { Integer currentDifference = null; for (Camera.Size size : previewSizes) { float ratio = (float) size.height / size.width; int difference = Math.abs((screenSize.y + screenSize.x) - (size.height + size.width)); Log.i(TAG, "Found preview size: " + size.width + "x" + size.height + " with ratio: " + ratio + " and difference of " + difference); if (currentDifference == null || difference < currentDifference) { currentDifference = difference; previewSize = size; } } } if (previewSize != null) { Log.i(TAG, "Setting screen size: " + previewSize.width + "x" + previewSize.height); parameters.setPreviewSize(previewSize.width, previewSize.height); } } public void removeCameraInstance() { if (mCamera != null) { mCamera.cancelAutoFocus(); mCamera.release(); mCamera = null; } mPreviewLayout.removeView(mPreview); mPreview = null; } @Override public void onPause() { super.onPause(); removeCameraInstance(); } @Override public void onResume() { super.onResume(); resumeCamera(); } private class ResizeTask extends AsyncTask<Void, Void, Void> { private String filePath; private String resizedPhotoPath; public ResizeTask(String filePath) { this.filePath = filePath; } @Override protected Void doInBackground(Void... unused) { try { Bitmap bitmap = BitmapFactory.decodeFile(filePath); bitmap = rotateImage(bitmap); bitmap = scaleImage(bitmap); File pictureFile = File.createTempFile("smartchat", ".jpg", getActivity().getExternalCacheDir()); OutputStream out = new FileOutputStream(pictureFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); bitmap.recycle(); new File(filePath).delete(); resizedPhotoPath = pictureFile.getPath(); } catch (IOException e) { e.printStackTrace(); } return null; } private Bitmap scaleImage(Bitmap bitmap) { Display display = getActivity().getWindowManager().getDefaultDisplay(); Point point = new Point(); display.getSize(point); if (bitmap.getWidth() > point.x || bitmap.getHeight() > point.y) { int height = point.y; int width = (int) (point.y * ((float) bitmap.getWidth() / (float) bitmap.getHeight())); Bitmap scaled = Bitmap.createScaledBitmap(bitmap, width, height, false); bitmap.recycle(); return scaled; } return bitmap; } private Bitmap rotateImage(Bitmap bitmap) { if (bitmap.getWidth() > bitmap.getHeight()) { Matrix matrix = new Matrix(); if (mCameraId == Camera.CameraInfo.CAMERA_FACING_FRONT) { matrix.postRotate(-90); } else { matrix.postRotate(90); } Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); bitmap.recycle(); return rotated; } return bitmap; } @Override protected void onPostExecute(Void aVoid) { Intent intent = new Intent(getActivity(), SmartChatPreviewActivity.class); intent.putExtra(Constants.EXTRA_PHOTO_PATH, resizedPhotoPath); startActivity(intent); } } }
package dae.project; import com.jme3.asset.AssetManager; import com.jme3.bullet.collision.shapes.BoxCollisionShape; import com.jme3.bullet.collision.shapes.PlaneCollisionShape; import com.jme3.bullet.control.RigidBodyControl; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Matrix3f; import com.jme3.math.Plane; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.shape.Box; import com.jme3.texture.Texture; import dae.GlobalObjects; import dae.components.ComponentType; import dae.prefabs.AxisEnum; import dae.prefabs.Prefab; import dae.prefabs.magnets.GridMagnet; import dae.prefabs.magnets.MagnetParameter; import dae.prefabs.types.ObjectType; /** * * @author Koen */ public class Grid extends Prefab { private float width = 100.0f; private float length = 100.0f; private GridMagnet magnet; private AxisEnum currentUpAxis; private Geometry yGeometry; private Geometry zGeometry; private Geometry currentGeometry; public Grid() { this.setName("Ground"); objectType = GlobalObjects.getInstance().getObjectsTypeCategory().getObjectType("Standard", "Ground"); } /** * Constructs a new Ground object * * @param width the width of the ground object. * @param length the length of the ground object; */ public Grid(float width, float length, Material groundMaterial) { this.setName("Ground"); objectType = GlobalObjects.getInstance().getObjectsTypeCategory().getObjectType("Standard", "Ground"); this.width = width; this.length = length; initialize(groundMaterial); } @Override public void create(String name, AssetManager manager, ObjectType type, String extraInfo) { this.setName(name); this.setCategory("Standard"); this.setType("Ground"); Material mat = createStandardMaterial(manager, "Textures/refPattern.png", Texture.WrapMode.Repeat, ColorRGBA.White); initialize(mat); } public float getWidth() { return width; } public void setWidth(float width) { this.width = width; } public float getLength() { return length; } public void setLength(float length) { this.length = length; } public void setUpAxis(AxisEnum upAxis) { if (upAxis != currentUpAxis) { currentUpAxis = upAxis; currentGeometry.removeFromParent(); if (currentUpAxis == AxisEnum.Z) { attachChild(zGeometry); magnet.setRotationAxis(Vector3f.UNIT_Z); currentGeometry = zGeometry; } else { attachChild(yGeometry); magnet.setRotationAxis(Vector3f.UNIT_Y); currentGeometry = yGeometry; } } } private void initialize(Material groundMaterial) { GlobalObjects go = GlobalObjects.getInstance(); // currentUpAxis = go.getUpAxis(); currentUpAxis = AxisEnum.Y; Box zUpBox = new Box(width, length, 0.01f); zUpBox.scaleTextureCoordinates(new Vector2f(width, length));// create cube shape at the origin Box yUpBox = new Box(width, 0.01f, length); yUpBox.scaleTextureCoordinates(new Vector2f(width, length));// create cube shape at the origin yGeometry = new Geometry("GroundPlane", yUpBox); // create cube geometry from the shape yGeometry.setMaterial(groundMaterial); yGeometry.setLocalTranslation(0, -0.01f, 0); zGeometry = new Geometry("GroundPlane", zUpBox); // create cube geometry from the shape zGeometry.setMaterial(groundMaterial); zGeometry.setLocalTranslation(0, 0, -0.01f); this.setOriginalMaterial(groundMaterial); // set the cube's material magnet = new GridMagnet(); PlaneCollisionShape shape; if (currentUpAxis == AxisEnum.Z) { attachChild(zGeometry); magnet.setRotationAxis(Vector3f.UNIT_Z); currentGeometry = zGeometry; shape = new PlaneCollisionShape(new Plane(Vector3f.UNIT_Z,0)); } else { attachChild(yGeometry); magnet.setRotationAxis(Vector3f.UNIT_Y); currentGeometry = yGeometry; shape = new PlaneCollisionShape(new Plane(Vector3f.UNIT_Y,0)); } magnet.setLocalFrame(Matrix3f.IDENTITY); magnet.setRotationRange(GlobalObjects.getInstance().getDefaultRotationRange()); MagnetParameter mp = new MagnetParameter(ComponentType.PREFAB,"grid", "grid"); mp.addMagnet(magnet); this.setMagnets(mp); shape.setMargin(0.1f); this.addControl(new RigidBodyControl(shape,0.0f)); } }
package com.orm; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.orm.dsl.Column; import com.orm.dsl.MultiUnique; import com.orm.dsl.NotNull; import com.orm.dsl.Unique; import com.orm.util.MigrationFileParser; import com.orm.util.NamingHelper; import com.orm.util.NumberComparator; import com.orm.util.QueryBuilder; import com.orm.util.ReflectionUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.orm.util.ReflectionUtil.getDomainClasses; public class SchemaGenerator { private Context context; public static final String NULL = " NULL"; public static final String NOT_NULL = " NOT NULL"; public static final String UNIQUE = " UNIQUE"; public static final String SUGAR = "Sugar"; public SchemaGenerator(Context context) { this.context = context; } public void createDatabase(SQLiteDatabase sqLiteDatabase) { List<Class> domainClasses = getDomainClasses(context); for (Class domain : domainClasses) { createTable(domain, sqLiteDatabase); } } public void doUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { List<Class> domainClasses = getDomainClasses(context); String sql = "select count(*) from sqlite_master where type='table' and name='%s';"; for (Class domain : domainClasses) { String tableName = NamingHelper.toSQLName(domain); Cursor c = sqLiteDatabase.rawQuery(String.format(sql, tableName), null); if (c.moveToFirst() && c.getInt(0) == 0) { createTable(domain, sqLiteDatabase); } else { addColumns(domain, sqLiteDatabase); } } executeSugarUpgrade(sqLiteDatabase, oldVersion, newVersion); } private ArrayList<String> getColumnNames(SQLiteDatabase sqLiteDatabase, String tableName) { Cursor resultsQuery = sqLiteDatabase.query(tableName, null, null, null, null, null, null); //Check if columns match vs the one on the domain class ArrayList<String> columnNames = new ArrayList<>(); for (int i = 0; i < resultsQuery.getColumnCount(); i++) { String columnName = resultsQuery.getColumnName(i); columnNames.add(columnName); } resultsQuery.close(); return columnNames; } public void deleteTables(SQLiteDatabase sqLiteDatabase) { List<Class> tables = getDomainClasses(context); for (Class table : tables) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + NamingHelper.toSQLName(table)); } } private boolean executeSugarUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { boolean isSuccess = false; try { List<String> files = Arrays.asList(this.context.getAssets().list("sugar_upgrades")); Collections.sort(files, new NumberComparator()); for (String file : files) { Log.i(SUGAR, "filename : " + file); try { int version = Integer.valueOf(file.replace(".sql", "")); if ((version > oldVersion) && (version <= newVersion)) { executeScript(db, file); isSuccess = true; } } catch (NumberFormatException e) { Log.i(SUGAR, "not a sugar script. ignored." + file); } } } catch (IOException e) { Log.e(SUGAR, e.getMessage()); } return isSuccess; } private void executeScript(SQLiteDatabase db, String file) { try { InputStream is = this.context.getAssets().open("sugar_upgrades/" + file); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } MigrationFileParser migrationFileParser = new MigrationFileParser(sb.toString()); for(String statement: migrationFileParser.getStatements()){ Log.i("Sugar script", statement); if (!statement.isEmpty()) { db.execSQL(statement); } } } catch (IOException e) { Log.e(SUGAR, e.getMessage()); } Log.i(SUGAR, "Script executed"); } private void addColumns(Class<?> table, SQLiteDatabase sqLiteDatabase) { List<Field> fields = ReflectionUtil.getTableFields(table); String tableName = NamingHelper.toSQLName(table); ArrayList<String> presentColumns = getColumnNames(sqLiteDatabase, tableName); ArrayList<String> alterCommands = new ArrayList<>(); for (Field column : fields) { String columnName = NamingHelper.toSQLName(column); String columnType = QueryBuilder.getColumnType(column.getType()); if (column.isAnnotationPresent(Column.class)) { Column columnAnnotation = column.getAnnotation(Column.class); columnName = columnAnnotation.name(); } if (!presentColumns.contains(columnName)) { StringBuilder sb = new StringBuilder("ALTER TABLE "); sb.append(tableName).append(" ADD COLUMN ").append(columnName).append(" ").append(columnType); if (column.isAnnotationPresent(NotNull.class)) { if (columnType.endsWith(" NULL")) { sb.delete(sb.length() - 5, sb.length()); } sb.append(" NOT NULL"); } // Unique is not working on ALTER TABLE // if (column.isAnnotationPresent(Unique.class)) { // sb.append(" UNIQUE"); alterCommands.add(sb.toString()); } } for (String command : alterCommands) { Log.i("Sugar", command); sqLiteDatabase.execSQL(command); } } protected String createTableSQL(Class<?> table) { KeyWord link = new KeyWord(); Log.i(SUGAR, "Create table if not exists"); List<Field> fields = ReflectionUtil.getTableFields(table); String tableName = NamingHelper.toSQLName(table); if(link.ReservedWords(tableName)) { return "ERROR, SQLITE KEYWORD USED IN " +tableName; } StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS "); sb.append(tableName).append(" ( ID INTEGER PRIMARY KEY AUTOINCREMENT "); for (Field column : fields) { String columnName = NamingHelper.toSQLName(column); String columnType = QueryBuilder.getColumnType(column.getType()); if (columnType != null) { if (columnName.equalsIgnoreCase("Id")) { continue; } if (column.isAnnotationPresent(Column.class)) { Column columnAnnotation = column.getAnnotation(Column.class); columnName = columnAnnotation.name(); sb.append(", ").append(columnName).append(" ").append(columnType); if (columnAnnotation.notNull()) { if (columnType.endsWith(NULL)) { sb.delete(sb.length() - 5, sb.length()); } sb.append(NOT_NULL); } if (columnAnnotation.unique()) { sb.append(UNIQUE); } } else { sb.append(", ").append(columnName).append(" ").append(columnType); if (column.isAnnotationPresent(NotNull.class)) { if (columnType.endsWith(NULL)) { sb.delete(sb.length() - 5, sb.length()); } sb.append(NOT_NULL); } if (column.isAnnotationPresent(Unique.class)) { sb.append(UNIQUE); } } } } if (table.isAnnotationPresent(MultiUnique.class)) { String constraint = table.getAnnotation(MultiUnique.class).value(); sb.append(", UNIQUE("); String[] constraintFields = constraint.split(","); for(int i = 0; i < constraintFields.length; i++) { String columnName = NamingHelper.toSQLNameDefault(constraintFields[i]); sb.append(columnName); if(i < (constraintFields.length -1)) { sb.append(","); } } sb.append(") ON CONFLICT REPLACE"); } sb.append(" ) "); Log.i(SUGAR, "Creating table " + tableName); return sb.toString(); } private void createTable(Class<?> table, SQLiteDatabase sqLiteDatabase) { String createSQL = createTableSQL(table); if (!createSQL.isEmpty()) { try { sqLiteDatabase.execSQL(createSQL); } catch (SQLException e) { e.printStackTrace(); } } } }
package jordan.bettercraft.init; import jordan.bettercraft.main.Reference; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.GameRegistry; public class BetterArmor { public static Item STEEL_HELMET; public static Item STEEL_CHESTPIECE; public static Item STEEL_PANTS; public static Item STEEL_BOOTS; public static void init() { STEEL_HELMET = registerItem(new ItemArmor(BetterArmorMaterial.STEEL, 1, EntityEquipmentSlot.HEAD), "steel_helmet").setUnlocalizedName("steel_helmet").setCreativeTab(BetterTabs.tabBetterCombat); STEEL_CHESTPIECE = registerItem(new ItemArmor(BetterArmorMaterial.STEEL, 1, EntityEquipmentSlot.HEAD), "steel_chestpiece").setUnlocalizedName("steel_chestpiece").setCreativeTab(BetterTabs.tabBetterCombat); STEEL_PANTS = registerItem(new ItemArmor(BetterArmorMaterial.STEEL, 2, EntityEquipmentSlot.HEAD), "steel_pants").setUnlocalizedName("steel_pants").setCreativeTab(BetterTabs.tabBetterCombat); STEEL_BOOTS = registerItem(new ItemArmor(BetterArmorMaterial.STEEL, 1, EntityEquipmentSlot.HEAD), "steel_boots").setUnlocalizedName("steel_boots").setCreativeTab(BetterTabs.tabBetterCombat); } public static void registerRenders() { //steel registerRender(STEEL_HELMET); registerRender(STEEL_CHESTPIECE); registerRender(STEEL_PANTS); registerRender(STEEL_BOOTS); } public static void registerRender(Item item) { Minecraft.getMinecraft().getRenderItem().getItemModelMesher() .register(item, 0, new ModelResourceLocation(Reference.MODID + ":" + item.getUnlocalizedName().substring(5), "inventory")); } //registerItem Start\\ public static Item registerItem(Item item, String name) { return registerItem(item, name, null); } public static Item registerItem(Item item, String name, CreativeTabs tab) { GameRegistry.register(item, new ResourceLocation(Reference.MODID, name)); return item; } //registerItem End\\ }
package cgeo.geocaching.maps.routing; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.utils.Log; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Xml; import java.util.LinkedList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public final class Routing { private static final double UPDATE_MIN_DISTANCE_KILOMETERS = 0.005; private static final double MAX_ROUTING_DISTANCE_KILOMETERS = 5.0; private static final int UPDATE_MIN_DELAY_SECONDS = 3; private static BRouterServiceConnection brouter; private static Geopoint lastDirectionUpdatePoint; private static Geopoint[] lastRoutingPoints; private static Geopoint lastDestination; private static long timeLastUpdate; private Routing() { // utility class } public static void connect() { if (brouter != null && brouter.isConnected()) { //already connected return; } brouter = new BRouterServiceConnection(); final Intent intent = new Intent(); intent.setClassName("btools.routingapp", "btools.routingapp.BRouterService"); if (!getContext().bindService(intent, brouter, Context.BIND_AUTO_CREATE)) { brouter = null; } } private static ContextWrapper getContext() { return CgeoApplication.getInstance(); } public static void disconnect() { if (brouter != null && brouter.isConnected()) { getContext().unbindService(brouter); brouter = null; } } @Nullable public static Geopoint[] getTrack(final Geopoint start, final Geopoint destination) { if (brouter == null) { return null; } // avoid updating to frequently final long timeNow = System.currentTimeMillis(); if ((timeNow - timeLastUpdate) < 1000 * UPDATE_MIN_DELAY_SECONDS) { return lastRoutingPoints; } // Disable routing for huge distances if (start.distanceTo(destination) > MAX_ROUTING_DISTANCE_KILOMETERS) { return null; } // Use cached route if current position has not changed more than 5m // TODO: Maybe adjust this to current zoomlevel if (lastDirectionUpdatePoint != null && destination == lastDestination && start.distanceTo(lastDirectionUpdatePoint) < UPDATE_MIN_DISTANCE_KILOMETERS) { return lastRoutingPoints; } // now really calculate a new route lastDestination = destination; lastRoutingPoints = calculateRouting(start, destination); lastDirectionUpdatePoint = start; timeLastUpdate = timeNow; return lastRoutingPoints; } private static Geopoint[] calculateRouting(final Geopoint start, final Geopoint dest) { final Bundle params = new Bundle(); params.putString("trackFormat", "gpx"); params.putDoubleArray("lats", new double[]{start.getLatitude(), dest.getLatitude()}); params.putDoubleArray("lons", new double[]{start.getLongitude(), dest.getLongitude()}); params.putString("v", Settings.getRoutingMode().parameterValue); final String gpx = brouter.getTrackFromParams(params); return parseGpxTrack(gpx); } @Nullable private static Geopoint[] parseGpxTrack(final String gpx) { try { final LinkedList<Geopoint> result = new LinkedList<>(); Xml.parse(gpx, new DefaultHandler() { @Override public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { if (qName.equalsIgnoreCase("trkpt")) { final String lat = atts.getValue("lat"); if (lat != null) { final String lon = atts.getValue("lon"); if (lon != null) { result.add(new Geopoint(lat, lon)); } } } } }); return result.toArray(new Geopoint[result.size()]); } catch (final SAXException e) { Log.e("cannot parse brouter output", e); } return null; } public static void invalidateRouting() { lastDirectionUpdatePoint = null; timeLastUpdate = 0; } public static boolean isAvailable() { return brouter != null; } }
package java; /** * * @author lynxar */ public class Login extends javax.swing.JFrame { /** * Creates new form kanban */ public Login() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { girisbtn = new javax.swing.JButton(); emaillabel = new javax.swing.JLabel(); sifrelabel = new javax.swing.JLabel(); emailTf = new javax.swing.JTextField(); sifreTf = new javax.swing.JTextField(); sunuttumbtn = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); girisbtn.setText("Giriş"); emaillabel.setText("Email :"); sifrelabel.setText("Şifre :"); sunuttumbtn.setText("Şifremi Unuttum"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(44, 44, 44) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(sifrelabel) .addComponent(emaillabel)) .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(emailTf, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE) .addComponent(sifreTf))) .addGroup(layout.createSequentialGroup() .addGap(91, 91, 91) .addComponent(girisbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(sunuttumbtn))) .addGap(0, 22, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(emaillabel) .addComponent(emailTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(17, 17, 17) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(sifrelabel) .addComponent(sifreTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(girisbtn) .addComponent(sunuttumbtn)) .addContainerGap(41, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Login().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField emailTf; private javax.swing.JLabel emaillabel; private javax.swing.JButton girisbtn; private javax.swing.JTextField sifreTf; private javax.swing.JLabel sifrelabel; private javax.swing.JButton sunuttumbtn; // End of variables declaration//GEN-END:variables }
package ru.job4j.map; import java.util.Calendar; import java.util.Objects; public class User { private String name; private int children; private Calendar birthday; public User(String name, int children, Calendar birthday) { this.name = name; this.children = children; this.birthday = birthday; } @Override public int hashCode() { return Objects.hash(name, children, birthday); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return children == user.children && Objects.equals(name, user.name) && Objects.equals(birthday, user.birthday); } }
package com.intellij.psi.impl; import com.intellij.ant.PsiAntElement; import com.intellij.aspects.psi.PsiAdvice; import com.intellij.aspects.psi.PsiAspect; import com.intellij.aspects.psi.PsiPointcutDef; import com.intellij.aspects.psi.gen.PsiErrorIntroduction; import com.intellij.aspects.psi.gen.PsiParentsIntroduction; import com.intellij.aspects.psi.gen.PsiSofteningIntroduction; import com.intellij.aspects.psi.gen.PsiWarningIntroduction; import com.intellij.compiler.CompilerConfiguration; import com.intellij.ide.IconUtilEx; import com.intellij.j2ee.J2EERolesUtil; import com.intellij.j2ee.ejb.role.EjbClassRole; import com.intellij.j2ee.ejb.role.EjbMethodRole; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.source.jsp.jspJava.JspClass; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.xml.XmlTag; import com.intellij.ui.LayeredIcon; import com.intellij.ui.RowIcon; import com.intellij.util.Icons; import javax.swing.*; public abstract class ElementBase extends UserDataHolderBase implements Iconable { public Icon getIcon(int flags) { if (!(this instanceof PsiElement)) return null; return getIcon((PsiElement) this, flags, ((PsiElement) this).isWritable()); } private static Icon getIcon(PsiElement element, int flags, boolean elementWritable) { RowIcon baseIcon; boolean showReadStatus = (flags & ICON_FLAG_READ_STATUS) != 0; PsiModifierList modifierList = PsiUtil.getModifierList(element); if (element instanceof PsiDirectory) { Icon symbolIcon; final PsiDirectory psiDirectory = (PsiDirectory)element; if (psiDirectory.getPackage() != null) { symbolIcon = Icons.PACKAGE_ICON; } else { symbolIcon = Icons.DIRECTORY_CLOSED_ICON; } boolean isExcluded = false; final VirtualFile vFile = psiDirectory.getVirtualFile(); if (vFile != null) { final Project project = psiDirectory.getProject(); if (ProjectRootManager.getInstance(project).getFileIndex().isInSource(vFile) && CompilerConfiguration.getInstance(project).isExcludedFromCompilation(vFile)) { isExcluded = true; } } baseIcon = createLockableExcludableIcon(symbolIcon, showReadStatus && !elementWritable, isExcluded); } else if (element instanceof PsiPackage) { baseIcon = createLockableIcon(Icons.PACKAGE_ICON, showReadStatus && !elementWritable); } else if (element instanceof PsiFile) { PsiFile file = (PsiFile)element; Icon symbolIcon = IconUtilEx.getIcon(file.getVirtualFile(), flags & ~ICON_FLAG_READ_STATUS, file.getProject()); baseIcon = createLockableIcon(symbolIcon, showReadStatus && !elementWritable); } else if (element instanceof PsiClass) { Icon symbolIcon; final PsiClass aClass = (PsiClass)element; final EjbClassRole role = J2EERolesUtil.getEjbRole(aClass); if (role != null) { symbolIcon = role.getIcon(); } else { if (aClass instanceof PsiAspect) { symbolIcon = Icons.ASPECT_ICON; } else if (aClass.isAnnotationType()) { symbolIcon = Icons.ANNOTATION_TYPE_ICON; } else if (aClass.isEnum()) { symbolIcon = Icons.ENUM_ICON; } else if (aClass.isInterface()) { symbolIcon = modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC) ? Icons.STATIC_INTERFACE_ICON : Icons.INTERFACE_ICON; } else if (aClass instanceof JspClass) { symbolIcon = Icons.JSP_ICON; } else { symbolIcon = modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC) ? Icons.STATIC_CLASS_ICON : Icons.CLASS_ICON; } } boolean isExcluded = false; final PsiFile containingFile = aClass.getContainingFile(); if (containingFile != null) { final VirtualFile vFile = containingFile.getVirtualFile(); if (vFile != null) { final Project project = aClass.getProject(); if (ProjectRootManager.getInstance(project).getFileIndex().isInSource(vFile) && CompilerConfiguration.getInstance(project).isExcludedFromCompilation(vFile)) { isExcluded = true; } } } baseIcon = createLockableExcludableIcon(symbolIcon, showReadStatus && !elementWritable, isExcluded); } else if (element instanceof PsiMethod) { final EjbMethodRole role = J2EERolesUtil.getEjbRole((PsiMethod)element); Icon methodIcon = role == null ? modifierList.hasModifierProperty(PsiModifier.STATIC) ? Icons.STATIC_METHOD_ICON : Icons.METHOD_ICON : role.getIcon(); baseIcon = createLockableIcon(methodIcon, false); } else if (element instanceof PsiField) { Icon fieldIcon = ((PsiField)element).hasModifierProperty(PsiModifier.STATIC) ? Icons.STATIC_FIELD_ICON : Icons.FIELD_ICON; baseIcon = createLockableIcon(fieldIcon, false); } else if (element instanceof PsiParameter) { baseIcon = createLockableIcon(Icons.PARAMETER_ICON, false); } else if (element instanceof PsiVariable) { baseIcon = createLockableIcon(Icons.VARIABLE_ICON, false); } else if (element instanceof PsiPointcutDef) { baseIcon = createLockableIcon(Icons.POINTCUT_ICON, false); } else if (element instanceof PsiParentsIntroduction) { baseIcon = createLockableIcon(Icons.PARENTS_INTRODUCTION_ICON, false); } else if (element instanceof PsiErrorIntroduction) { baseIcon = createLockableIcon(Icons.ERROR_INTRODUCTION_ICON, false); } else if (element instanceof PsiWarningIntroduction) { baseIcon = createLockableIcon(Icons.WARNING_INTRODUCTION_ICON, false); } else if (element instanceof PsiSofteningIntroduction) { baseIcon = createLockableIcon(Icons.SOFTENING_INTRODUCTION_ICON, false); } else if (element instanceof PsiAdvice) { baseIcon = createLockableIcon(Icons.ADVICE_ICON, false); } else if (element instanceof XmlTag) { return Icons.XML_TAG_ICON; } else if (element instanceof PsiAntElement) { return ((PsiAntElement)element).getRole().getIcon(); } else { return null; } if ((flags & ICON_FLAG_VISIBILITY) != 0) { IconUtilEx.setVisibilityIcon(modifierList, baseIcon); } return baseIcon; } private static RowIcon createLockableIcon(Icon icon, boolean isLocked) { return createLockableExcludableIcon(icon, isLocked, false); } private static RowIcon createLockableExcludableIcon(Icon icon, boolean isLocked, boolean isExcluded) { if (isExcluded || isLocked) { LayeredIcon layeredIcon = new LayeredIcon(1 + (isLocked? 1 : 0) + (isExcluded? 1 : 0)); int layer = 0; layeredIcon.setIcon(icon, layer++); if (isLocked) { layeredIcon.setIcon(Icons.LOCKED_ICON, layer++); } if (isExcluded) { layeredIcon.setIcon(Icons.EXCLUDED_FROM_COMPILE_ICON, layer); } icon = layeredIcon; } RowIcon baseIcon = new RowIcon(2); baseIcon.setIcon(icon, 0); return baseIcon; } }
// $OldId: AddInterfaces.java,v 1.40 2002/11/08 11:56:47 schinz Exp $ package scalac.transformer; import scalac.*; import scalac.util.*; import scalac.ast.*; import scalac.symtab.*; import Tree.*; import java.util.*; // TODO see why lambda-lifted functions end up in the interface /** * Add, for each class, an interface with the same name, to be used * later by mixin expansion. More specifically: * * - at the end of the name of every class, the string "$class" is * added, * * - an interface with the original name of the class is created, and * contains all directly bound members of the class (as abstract * members), * * - the interface is added to the mixin base classes of the class. * * @author Michel Schinz * @version 1.0 */ class AddInterfaces extends SubstTransformer { /** Mapping from class symbols to their interface symbol. */ public final Map/*<Symbol,Symbol>*/ classToInterface; protected final Map/*<Symbol,Symbol>*/ ifaceToClass; protected final SymbolMapApplier ifaceToClassApplier; protected final Map/*<Symbol,Symbol>*/ ifaceMemberToClass; // Mapping from class symbol to its type parameters mapping. protected final Map/*<Symbol,Map<Symbol,Symbol>>*/ typeParamsMaps; // Mapping from a class member symbol to its value and type // parameters mapping. protected final Map/*<Symbol,Map<Symbol,Symbol>>*/ funParamsMaps; protected final Set/*<Symbol>*/ createdIFaces = new HashSet(); public AddInterfaces(Global global, AddInterfacesPhase descr) { super(global, descr, global.make); classToInterface = descr.classToInterface; ifaceToClass = descr.interfaceToClass; ifaceMemberToClass = descr.ifaceMemberToClass; ifaceToClassApplier = new SymbolMapApplier(ifaceToClass); typeParamsMaps = new HashMap(); funParamsMaps = new HashMap(); } public void apply() { // Phase 1: create all new symbols ClassSymCreator creator = new ClassSymCreator(global); for (int i = 0; i < global.units.length; ++i) creator.traverse(global.units[i].body); // Phase 2: transform the tree to add interfaces and use the // new symbols where needed. super.apply(); } protected final static Tree.ValDef[][] EMPTY_PARAMS = new Tree.ValDef[][]{ new Tree.ValDef[0] }; protected void uniqueName(Symbol sym, StringBuffer buf) { Symbol owner = sym.owner(); if (owner != Symbol.NONE) { uniqueName(owner, buf); buf.append('$'); } buf.append(sym.name.toString()); } protected Name uniqueName(Symbol sym) { StringBuffer buf = new StringBuffer(); uniqueName(sym, buf); Name newName = Name.fromString(buf.toString()); if (sym.name.isTypeName()) return newName.toTypeName(); else if (sym.name.isConstrName()) return newName.toConstrName(); else return newName; } protected final static String CLASS_SUFFIX = "$class"; protected boolean hasClassSuffix(Name name) { return name.toString().endsWith(CLASS_SUFFIX); } protected Name className(Name interfaceName) { assert !hasClassSuffix(interfaceName) : interfaceName; String interfaceStr = interfaceName.toString(); Name className = Name.fromString(interfaceStr + CLASS_SUFFIX); if (interfaceName.isTypeName()) return className.toTypeName(); else if (interfaceName.isConstrName()) return className.toConstrName(); else return className; } // Modifiers for which we do not create interfaces. protected int NO_INTERFACE_MODS = (Modifiers.MODUL | Modifiers.SYNTHETIC | Modifiers.JAVA); protected boolean needInterface(Symbol sym) { return (sym != Symbol.NONE) && ((sym.primaryConstructorClass().flags & NO_INTERFACE_MODS) == 0); } protected boolean memberGoesInInterface(Symbol member) { switch (member.kind) { case Kinds.TYPE: case Kinds.ALIAS: return true; case Kinds.CLASS: return needInterface(member); case Kinds.VAL: return member.isMethod() && !member.isPrimaryConstructor(); default: throw Debug.abort("unknown kind: " + member.kind); } } protected Type removeValueParams(Type tp) { switch (tp) { case MethodType(Symbol[] vparams, Type result): return new Type.MethodType(Symbol.EMPTY_ARRAY, result); case PolyType(Symbol[] tps, Type result): return new Type.PolyType(tps, removeValueParams(result)); default: return tp; } } protected Tree mkAbstract(Tree tree) { Symbol symbol = tree.symbol(); if (symbol.isMethod()) return gen.DefDef(symbol, Tree.Empty); else switch (symbol.kind) { case Kinds.TYPE: case Kinds.ALIAS: return tree; case Kinds.CLASS: return classInterface((ClassDef)tree); default: throw new ApplicationError("invalid symbol kind for me", symbol); } } protected Symbol getClassSym(Symbol ifaceSym) { assert !hasClassSuffix(ifaceSym.name) : ifaceSym.name; if (!needInterface(ifaceSym)) return ifaceSym; else { assert ifaceToClass.containsKey(ifaceSym); return (Symbol)ifaceToClass.get(ifaceSym); } } protected Symbol[] vparams(Type tp) { switch (tp) { case MethodType(Symbol[] vparams, _): return vparams; case PolyType(_, Type result): return vparams(result); case OverloadedType(_, _): throw global.fail("can't get vparams of this type", tp); default: return Symbol.EMPTY_ARRAY; } } protected Type cloneSymbolsInMethodType(Type type, Symbol newOwner, SymbolMapApplier smApplier, Map symbolMap) { switch (type) { case NoType: case ThisType(_): case TypeRef(_, _, _): case SingleType(_, _): case CompoundType(_, _): return type; case MethodType(Symbol[] vparams, Type result): { Symbol[] newVParams = new Symbol[vparams.length]; for (int i = 0; i < vparams.length; ++i) { newVParams[i] = vparams[i].cloneSymbol(); newVParams[i].setOwner(newOwner); newVParams[i].setType(smApplier.apply(newVParams[i].info())); symbolMap.put(vparams[i], newVParams[i]); } return new Type.MethodType(newVParams, cloneSymbolsInMethodType(result, newOwner, smApplier, symbolMap)); } case PolyType(Symbol[] tparams, Type result): { Symbol[] newTParams = new Symbol[tparams.length]; for (int i = 0; i < tparams.length; ++i) { newTParams[i] = tparams[i].cloneSymbol(); newTParams[i].setOwner(newOwner); symbolMap.put(tparams[i], newTParams[i]); } return new Type.PolyType(newTParams, cloneSymbolsInMethodType(result, newOwner, smApplier, symbolMap)); } default: throw global.fail("unexpected method type: " + Debug.toString(type)); } } protected static class ThisTypeSubst { Symbol fromSym; Type toType; ThisTypeSubst outer; public ThisTypeSubst(Symbol fromSym, Type toType, ThisTypeSubst outer) { this.fromSym = fromSym; this.toType = toType; this.outer = outer; } public Type apply(Type tp) { switch (tp) { case ThisType(Symbol sym): if (sym == fromSym) return toType; else if (outer != null) return outer.apply(tp); else return tp; case TypeRef(Type pre, Symbol sym, Type[] args): return new Type.TypeRef(apply(pre), sym, apply(args)); case SingleType(Type pre, Symbol sym): return Type.singleType(apply(pre), sym); case CompoundType(Type[] parts, Scope members): return Type.compoundType(apply(parts), members, tp.symbol()); case MethodType(Symbol[] vparams, Type result): return new Type.MethodType(vparams, apply(result)); case PolyType(Symbol[] tparams, Type result): return new Type.PolyType(tparams, apply(result)); case OverloadedType(Symbol[] alts, Type[] alttypes): return new Type.OverloadedType(alts, apply(alttypes)); case CovarType(Type t): return new Type.CovarType(apply(t)); case NoType: return tp; default: throw Debug.abort("unknown type",tp); } } public Type[] apply(Type[] tps) { Type[] newTps = new Type[tps.length]; for (int i = 0; i < newTps.length; ++i) newTps[i] = apply(tps[i]); return newTps; } } // Return the interface corresponding to the given class. protected Tree classInterface(ClassDef classDef) { Template impl = classDef.impl; Symbol ifaceSym = classDef.symbol(); // Create tree for interface. List/*<Tree>*/ ifaceBody = new ArrayList(); Tree[] body = impl.body; for (int i = 0; i < body.length; ++i) { Tree elem = body[i]; if (elem.hasSymbol() && elem.symbol().owner() == ifaceSym) { if (memberGoesInInterface(elem.symbol())) ifaceBody.add(mkAbstract(elem)); } } Tree[] parentConstr = gen.mkParentConstrs(impl.pos, ifaceSym.nextInfo().parents()); Template ifaceTmpl = make.Template(impl.pos, parentConstr, (Tree[])ifaceBody.toArray(new Tree[ifaceBody.size()])); ifaceTmpl.setSymbol(impl.symbol().cloneSymbol()); ifaceTmpl.setType(ifaceSym.nextInfo()); int ifaceMods = classDef.mods | Modifiers.ABSTRACTCLASS | Modifiers.INTERFACE | Modifiers.STATIC; ClassDef interfaceDef = (ClassDef)make.ClassDef(classDef.pos, ifaceMods, classDef.name, classDef.tparams, EMPTY_PARAMS, classDef.tpe, ifaceTmpl); interfaceDef.setType(Type.NoType); interfaceDef.setSymbol(ifaceSym); createdIFaces.add(ifaceSym); return interfaceDef; } protected Type fixClassSymbols(Type type) { switch (type) { case Type.NoType: case ThisType(_): return type; case TypeRef(Type pre, Symbol sym, Type[] args): return new Type.TypeRef(fixClassSymbols(pre), getClassSym(sym), args); case SingleType(Type pre, Symbol sym): return Type.singleType(fixClassSymbols(pre), sym); case CompoundType(Type[] parts, Scope members): return Type.compoundType(fixClassSymbols(parts), members, getClassSym(type.symbol())); case MethodType(Symbol[] vparams, Type result): return new Type.MethodType(vparams, fixClassSymbols(result)); case PolyType(Symbol[] tparams, Type result): return new Type.PolyType(tparams, fixClassSymbols(result)); default: throw global.fail("unexpected type ",type); } } protected Type[] fixClassSymbols(Type[] types) { Type[] newTypes = new Type[types.length]; for (int i = 0; i < types.length; ++i) newTypes[i] = fixClassSymbols(types[i]); return newTypes; } protected Tree fixClassSymbols(Tree tree) { switch (tree) { case Apply(Tree fun, Tree[] args): return copy.Apply(tree, fixClassSymbols(fun), args); case TypeApply(Tree fun, Tree[] args): return copy.TypeApply(tree, fixClassSymbols(fun), args); case Select(Tree qualifier, Name selector): { Symbol classSym = getClassSym(tree.symbol()); return copy.Select(tree, qualifier, classSym.name).setSymbol(classSym); } case Ident(Name name): { Symbol classSym = getClassSym(tree.symbol()); return copy.Ident(tree, classSym.name).setSymbol(classSym); } default: throw global.fail("unexpected tree",tree); } } protected LinkedList/*<List<Tree>>*/ bodyStack = new LinkedList(); protected ThisTypeSubst thisTypeSubst = null; public Tree[] transform(Tree[] trees) { List newTrees = new ArrayList(); bodyStack.addFirst(newTrees); for (int i = 0; i < trees.length; ++i) newTrees.add(transform(trees[i])); bodyStack.removeFirst(); return (Tree[]) newTrees.toArray(new Tree[newTrees.size()]); } public TypeDef[] transform(TypeDef[] ts) { return super.transform(ts); } public Tree transform(Tree tree) { if (thisTypeSubst != null) tree.setType(thisTypeSubst.apply(tree.type())); switch (tree) { case ClassDef(int mods, Name name, TypeDef[] tparams, ValDef[][] vparams, Tree tpe, Template impl) : { global.log("adding interface for " + tree.symbol() + " (need one? " + needInterface(tree.symbol()) + ")"); Symbol interfaceSym = tree.symbol(); if (needInterface(interfaceSym)) { ClassDef classDef = (ClassDef) tree; // First insert interface for class in enclosing body... if (! createdIFaces.contains(interfaceSym)) { Tree interfaceDef = classInterface(classDef); List/*<Tree>*/ enclosingBody = (List)bodyStack.getFirst(); enclosingBody.add(interfaceDef); } // ...then transform the class. Symbol classSym = getClassSym(interfaceSym); assert typeParamsMaps.containsKey(classSym) : classSym; Map/*<Symbol,Symbol>*/ tparamsMap = (Map)typeParamsMaps.get(classSym); SymbolMapApplier tparamsSM = new SymbolMapApplier(tparamsMap); // Make the class implement the interface, and make sure // to use class symbols for base classes. Type interfaceBaseType = tparamsSM.apply(interfaceSym.type()); Type[] newBaseTypes; // 1. modify type of class symbol Type newClassInfo; switch (classSym.nextInfo()) { case CompoundType(Type[] baseTypes, Scope members): { newBaseTypes = new Type[baseTypes.length + 1]; newBaseTypes[0] = fixClassSymbols(baseTypes[0]); newBaseTypes[1] = interfaceBaseType; for (int i = 2; i < newBaseTypes.length; ++i) newBaseTypes[i] = fixClassSymbols(baseTypes[i-1]); newClassInfo = Type.compoundType(newBaseTypes, members, classSym); classSym.updateInfo(newClassInfo); } break; default: throw global.fail("invalid info() for class", classSym); } // 2. modify tree accordingly pushSymbolSubst(tparamsMap); thisTypeSubst = new ThisTypeSubst(interfaceSym, classSym.thisType(), thisTypeSubst); Tree[] parents = transform(impl.parents); Tree[] newParents = new Tree[parents.length + 1]; newParents[0] = parents[0]; newParents[1] = gen.mkParentConstr(impl.pos, interfaceBaseType); for (int i = 2; i < newParents.length; ++i) newParents[i] = parents[i-1]; // Use new member symbols for class members. Tree[] body = impl.body; for (int i = 0; i < body.length; ++i) { Tree member = body[i]; if (member.hasSymbol()) { Symbol sym = member.symbol(); if (sym.kind != Kinds.CLASS && ifaceMemberToClass.containsKey(sym)) member.setSymbol((Symbol)ifaceMemberToClass.get(sym)); } } // Transform body List newBody = new LinkedList(); for (int i = 0; i < body.length; ++i) { switch (body[i]) { case TypeDef(_, _, _): break; default: newBody.add(transform(body[i])); } } Template newImpl = copy.Template(impl, newParents, (Tree[])newBody.toArray(new Tree[newBody.size()])); newImpl.setType(newClassInfo); Tree newTree = copy.ClassDef(classDef, classSym.flags, classSym.name.toTypeName(), transform(tparams), transform(vparams), transform(tpe), newImpl) .setSymbol(classSym); thisTypeSubst = thisTypeSubst.outer; popSymbolSubst(); return newTree; } else { // No interface needed, we just adapt the class type // to use class symbols. Symbol classSym = interfaceSym; classSym.updateInfo(fixClassSymbols(classSym.info())); return super.transform(tree); } } case Template(Tree[] parents, Tree[] body): { return copy.Template(tree, transform(parents), transform(body)) .setType(fixClassSymbols(tree.type)); } case DefDef(_, _, _, _, Tree tpe, _): { Symbol sym = tree.symbol(); if (funParamsMaps.containsKey(sym)) { Map funParamsMap = (Map)funParamsMaps.get(sym); pushSymbolSubst(funParamsMap); Tree newTree = super.transform(tree); popSymbolSubst(); return newTree; } return super.transform(tree); } case ValDef(_, _, _, _): { Symbol sym = tree.symbol(); Symbol owner = sym.owner(); if (!sym.isParameter() && ifaceMemberToClass.containsKey(owner)) { Symbol newOwner = (Symbol)ifaceMemberToClass.get(owner); sym.setOwner(newOwner); global.log("new owner for " + Debug.show(sym) + " => " + newOwner); } return super.transform(tree); } case This(Ident qualifier): { Symbol qualSym = qualifier.symbol(); if (needInterface(qualSym)) return gen.This(tree.pos, getClassSym(qualSym)); else return super.transform(tree); } case Select(Super(_), Name selector): { // Use class member symbol for "super" references. Symbol sym = tree.symbol(); if (needInterface(sym.classOwner())) { assert ifaceMemberToClass.containsKey(sym); Symbol classSym = (Symbol)ifaceMemberToClass.get(sym); return super.transform(tree).setSymbol(classSym); } else return super.transform(tree); } default: { Tree newTree = super.transform(tree); // Use class symbols for constructor calls. switch (newTree) { case New(Template templ): return copy.New(newTree, templ) .setType(templ.parents[0].type); case Apply(TypeApply(Tree fun, Tree[] targs), Tree[] vargs): { Tree tFun = ((Tree.Apply)newTree).fun; if (fun.hasSymbol() && fun.symbol().isPrimaryConstructor()) return copy.Apply(newTree, tFun, vargs) .setType(fixClassSymbols(newTree.type)); else return newTree; } case Apply(Tree fun, Tree[] args): { if (fun.hasSymbol() && fun.symbol().isPrimaryConstructor()) { fun.setSymbol(getClassSym(fun.symbol())); fun.setType(fixClassSymbols(fun.type)); return (copy.Apply(newTree, super.syncTree(fun), args)) .setType(fixClassSymbols(newTree.type)); } else return newTree; } case TypeApply(Tree fun, Tree[] args): { if (fun.hasSymbol() && fun.symbol().isPrimaryConstructor()) { fun.setSymbol(getClassSym(fun.symbol())); fun.setType(fixClassSymbols(fun.type)); return (copy.TypeApply(newTree, super.syncTree(fun), args)) .setType(fixClassSymbols(newTree.type)); } else return newTree; } default: return newTree; } } } } // Class protected class ClassSymCreator extends Traverser { // Mapping from interface type parameters to class type // parameters. final HashMap/*<Symbol,Symbol>*/ tparamsMap = new HashMap(); public ClassSymCreator(Global global) { super(global); } protected Symbol cloneAndMaybeRenameSymbol(Symbol sym) { assert !sym.isPrimaryConstructor() : sym; Symbol clone = sym.cloneSymbol(); if (clone.kind == Kinds.CLASS) { clone.name = className(clone.name); Symbol constrClone = clone.constructor(); constrClone.name = className(constrClone.name); } return clone; } protected void makeClassSymbol(Symbol ifaceSym) { Symbol classSym = cloneAndMaybeRenameSymbol(ifaceSym); ifaceToClass.put(ifaceSym, classSym); ifaceToClass.put(ifaceSym.constructor(), classSym.constructor()); ifaceSym.owner().members().enter(classSym); } public void traverse(Tree tree) { switch(tree) { case ClassDef(_, _, _, _, _, Template impl): { Symbol ifaceSym = tree.symbol(); if (!needInterface(ifaceSym)) { super.traverse(impl); break; } // The class needs an interface. Create new symbols // for the class itself, its constructor, its type // parameters and its members. Then modify what was // the class symbol to turn it into an interface // symbol. // At the end of this part, one inconsistency remains: // the base types of the new class symbols still refer // to interface symbols. This is fixed later, when // symbols exist for *all* classes. Symbol ifaceConstrSym = ifaceSym.constructor(); ifaceConstrSym.updateInfo(removeValueParams(ifaceConstrSym.info())); if (! ifaceToClass.containsKey(ifaceSym)) makeClassSymbol(ifaceSym); Symbol classSym = (Symbol)ifaceToClass.get(ifaceSym); Symbol classConstrSym = classSym.constructor(); if (ifaceToClass.containsKey(classSym.owner())) { Symbol newOwner = (Symbol)ifaceToClass.get(classSym.owner()); classSym.setOwner(newOwner); classConstrSym.setOwner(newOwner); } Symbol[] ifaceTParams = ifaceSym.typeParams(); if (ifaceTParams.length > 0) { for (int i = 0; i < ifaceTParams.length; ++i) { Symbol classTParam = ifaceTParams[i].cloneSymbol(); classTParam.setOwner(classConstrSym); tparamsMap.put(ifaceTParams[i], classTParam); } } assert !typeParamsMaps.containsKey(classSym); Map cloneMap = new HashMap(); cloneMap.putAll(tparamsMap); typeParamsMaps.put(classSym, cloneMap); SymbolMapApplier tparamsSM = new SymbolMapApplier(cloneMap); classConstrSym.setInfo(tparamsSM.apply(classConstrSym.info())); Symbol[] vparams = vparams(classConstrSym.nextInfo()); for (int i = 0; i < vparams.length; ++i) { vparams[i].setOwner(classConstrSym); vparams[i].updateInfo(tparamsSM.apply(vparams[i].info())); } Scope newIFaceMembers = new Scope(); Scope classMembers = new Scope(); Scope.SymbolIterator symIt = ifaceSym.members().iterator(); while (symIt.hasNext()) { Symbol ifaceMemberSym = symIt.next(); ifaceMemberSym.updateInfo(tparamsSM.apply(ifaceMemberSym.info())); if (! memberGoesInInterface(ifaceMemberSym)) { ifaceMemberSym.setOwner(classSym); classMembers.enter(ifaceMemberSym); continue; } // When encountering a constructor of a nested // class, clone its class to make sure the // constructor is cloned correctly. if (ifaceMemberSym.isPrimaryConstructor() && !ifaceToClass.containsKey(ifaceMemberSym)) { makeClassSymbol(ifaceMemberSym.primaryConstructorClass()); } // Make private members public and give them a // unique name. if (Modifiers.Helper.isPrivate(ifaceMemberSym.flags)) { ifaceMemberSym.name = uniqueName(ifaceMemberSym); ifaceMemberSym.flags ^= Modifiers.PRIVATE; } ifaceMemberSym.flags &= ~Modifiers.PROTECTED; newIFaceMembers.enter(ifaceMemberSym); // Type members are moved to the interface. // Therefore, no symbol has to be created for // their class equivalent. if (ifaceMemberSym.kind == Kinds.TYPE || ifaceMemberSym.kind == Kinds.ALIAS) continue; Symbol[] alternatives = ifaceMemberSym.alternatives(); Symbol classMemberSym = null; for (int a = 0; a < alternatives.length; ++a) { Symbol iSym = alternatives[a]; Symbol cSym; if (Modifiers.Helper.isPrivate(iSym.flags)) { iSym.name = uniqueName(iSym); iSym.flags ^= Modifiers.PRIVATE; } iSym.flags &= ~Modifiers.PROTECTED; if (ifaceToClass.containsKey(iSym)) cSym = (Symbol)ifaceToClass.get(iSym); else cSym = cloneAndMaybeRenameSymbol(iSym); iSym.updateInfo(tparamsSM.apply(iSym.info())); cSym.setInfo(tparamsSM.apply(cSym.info())); Symbol[] vpms = vparams(iSym.nextInfo()); for (int p = 0; p < vpms.length; ++p) vpms[p].updateInfo(tparamsSM.apply(vpms[p].info())); // Clone parameter symbols for methods. if (cSym.isMethod()) { Map funSymMap = new HashMap(); Type newInfo = cloneSymbolsInMethodType(cSym.info(), cSym, tparamsSM, funSymMap); if (! funSymMap.isEmpty()) funParamsMaps.put(cSym, funSymMap); } cSym.setOwner(classSym); classMemberSym = (classMemberSym == null ? cSym : classMemberSym.overloadWith(cSym)); if (iSym.kind == Kinds.CLASS) { ifaceToClass.put(iSym, cSym); ifaceToClass.put(iSym.constructor(), cSym.constructor()); } else { iSym.flags |= Modifiers.DEFERRED; ifaceMemberToClass.put(iSym, cSym); } } if (!ifaceMemberToClass.containsKey(ifaceMemberSym) && ifaceMemberSym.kind != Kinds.CLASS) ifaceMemberToClass.put(ifaceMemberSym, classMemberSym); classMembers.enter(classMemberSym); } switch (classSym.info()) { case CompoundType(Type[] parts, Scope members): classSym.setInfo(Type.compoundType(tparamsSM.apply(parts), classMembers, classSym)); break; default: global.fail("unexpected type for class", ifaceSym.info()); } Type cConstrType = classConstrSym.info(); classConstrSym.updateInfo(cConstrType.subst(new Symbol[]{ifaceSym}, new Symbol[]{classSym})); ifaceSym.flags |= (Modifiers.ABSTRACTCLASS | Modifiers.INTERFACE | Modifiers.STATIC); classToInterface.put(classSym, ifaceSym); super.traverse(impl); if (ifaceTParams.length > 0) for (int i = 0; i < ifaceTParams.length; ++i) tparamsMap.remove(ifaceTParams[i]); // Remove Java classes from interface base classes. switch (ifaceSym.info()) { case CompoundType(Type[] basetypes, Scope members): ArrayList newBT_L = new ArrayList(basetypes.length); for (int i = 0; i < basetypes.length; ++i) if (! basetypes[i].symbol().isJava()) newBT_L.add(basetypes[i]); Type[] newBT; if (newBT_L.size() != basetypes.length) newBT = (Type[]) newBT_L.toArray(new Type[newBT_L.size()]); else newBT = basetypes; ifaceSym.updateInfo(Type.compoundType(newBT, newIFaceMembers, ifaceSym)); break; default: Debug.abort("unexpected type for class", ifaceSym.info()); } } break; default: super.traverse(tree); } } } }
package com.arrow.acn.client.cloud.azure; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang3.StringUtils; import com.arrow.acn.client.IotParameters; import com.arrow.acn.client.api.AcnClient; import com.arrow.acn.client.cloud.CloudConnectorAbstract; import com.arrow.acn.client.cloud.TransferMode; import com.arrow.acn.client.model.AzureConfigModel; import com.arrow.acs.AcsLogicalException; import com.arrow.acs.AcsRuntimeException; import com.arrow.acs.AcsSystemException; import com.arrow.acs.AcsUtils; import com.arrow.acs.JsonUtils; import com.arrow.acs.client.api.MqttHttpChannel; import com.arrow.acs.client.model.CloudRequestModel; import com.arrow.acs.client.model.CloudResponseModel; import com.microsoft.azure.sdk.iot.device.DeviceClient; import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; import com.microsoft.azure.sdk.iot.device.IotHubEventCallback; import com.microsoft.azure.sdk.iot.device.IotHubMessageResult; import com.microsoft.azure.sdk.iot.device.IotHubStatusCode; import com.microsoft.azure.sdk.iot.device.Message; import com.microsoft.azure.sdk.iot.device.MessageCallback; public class AzureConnector extends CloudConnectorAbstract implements MqttHttpChannel { public static final String PROPERTY_MESSAGE_TYPE = "message_type"; public static final String PROPERTY_HID = "hid"; public enum MessageType { TELEMETRY, COMMAND, API_REQUEST, API_RESPONSE } private final AzureConfigModel model; private DeviceClient client; private AtomicLong eventCounter = new AtomicLong(); private LocalEventCallback eventCallback = new LocalEventCallback(); private LocalMessageCallback messageCallback = new LocalMessageCallback(); public AzureConnector(AcnClient acnClient, String gatewayHid, AzureConfigModel model) { super(acnClient, gatewayHid); this.model = model; } @Override public void start() { String method = "start"; AcsUtils.notNull(model, "model is NULL"); try { if (client == null) { logInfo(method, "creating azure client ..."); client = new DeviceClient(model.getConnectionString(), IotHubClientProtocol.MQTT); client.setMessageCallback(messageCallback, null); logInfo(method, "connecting azure client ..."); client.open(); // route API calls to MQTT logInfo(method, "routing REST calls to MQTT ..."); acnClient.setMqttHttpChannel(this); } else { logWarn(method, "client is already initialized"); } } catch (AcsRuntimeException e) { throw e; } catch (Throwable t) { throw new AcsSystemException("Unable to start azure connector", t); } } @Override public void stop() { String method = "stop"; if (client != null) { try { logInfo(method, "stopping client ..."); client.closeNow(); } catch (Throwable e) { } client = null; } super.stop(); } @Override public void send(IotParameters payload) { String method = "send"; if (client != null) { String json = JsonUtils.toJson(payload); Message message = new Message(json); message.setProperty(PROPERTY_MESSAGE_TYPE, MessageType.TELEMETRY.name()); message.setProperty(PROPERTY_HID, payload.getDeviceHid()); long counter = eventCounter.getAndIncrement(); logDebug(method, "counter: %d, json size: %d", counter, json.length()); client.sendEventAsync(message, eventCallback, counter); } else { logError(method, "client is NULL"); } } @Override public void sendBatch(List<IotParameters> batch, TransferMode transferMode) { if (transferMode == TransferMode.GZIP_BATCH) { throw new AcsLogicalException( "TransferMode not supported for Azure integration: " + TransferMode.GZIP_BATCH.name()); } if (batch != null) { batch.forEach(this::send); } } @Override public CloudResponseModel sendRequest(CloudRequestModel request, long timeoutSecs) { String method = "sendRequest"; if (!terminating && client != null) { try { String json = JsonUtils.toJson(request); Message message = new Message(json); message.setProperty(PROPERTY_MESSAGE_TYPE, MessageType.API_REQUEST.name()); message.setProperty(PROPERTY_HID, getGatewayHid()); long counter = eventCounter.getAndIncrement(); logDebug(method, "counter: %d, json size: %d", counter, json.length()); CloudResponseWrapper wrapper = new CloudResponseWrapper(); responseMap.put(request.getRequestId(), wrapper); client.sendEventAsync(message, eventCallback, counter); CloudResponseModel response = wrapper.waitForResponse(timeoutSecs); if (response == null) { throw new AcsLogicalException("Timeout waiting for response from MQTT channel"); } return response; } catch (AcsRuntimeException e) { logError(method, e); throw e; } catch (Exception e) { logError(method, e); throw new AcsLogicalException("sendRequest failed", e); } finally { responseMap.remove(request.getRequestId()); } } else { throw new AcsLogicalException("connector is terminating!"); } } class LocalMessageCallback implements MessageCallback { public IotHubMessageResult execute(Message msg, Object context) { String method = "messageCallback"; String messageType = msg.getProperty(PROPERTY_MESSAGE_TYPE); byte[] payload = msg.getBytes(); logInfo(method, "messageType: %s, payload size: %d", messageType, payload.length); if (StringUtils.equalsIgnoreCase(messageType, AzureConnector.MessageType.COMMAND.name())) { try { service.submit(() -> { logDebug(method, "submitting command payload ..."); validateAndProcessEvent(getGatewayHid(), payload); }); } catch (Exception e) { logError(method, e); } } else if (StringUtils.equalsIgnoreCase(messageType, AzureConnector.MessageType.API_RESPONSE.name())) { service.submit(() -> { try { CloudResponseModel responseModel = JsonUtils.fromJsonBytes(payload, CloudResponseModel.class); logDebug(method, "responseModel: %s", JsonUtils.toJson(responseModel)); CloudResponseWrapper wrapper = responseMap.get(responseModel.getRequestId()); if (wrapper != null) { logDebug(method, "marking request complete: %s", responseModel.getRequestId()); wrapper.complete(responseModel); } } catch (Exception e) { logError(method, e); } }); } else { String content = new String(payload, Message.DEFAULT_IOTHUB_MESSAGE_CHARSET); logError(method, "unsupported message type: %s, content: %s", messageType, content); } return IotHubMessageResult.COMPLETE; } } class LocalEventCallback implements IotHubEventCallback { public void execute(IotHubStatusCode status, Object context) { String method = "eventCallback"; Long counter = (Long) context; logDebug(method, "counter: %d, status: %s", counter, status.name()); } } }
package com.bek_qa.addressbook; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.*; public class NewEntryTests { FirefoxDriver wd; @BeforeMethod public void setUp() throws Exception { wd = new FirefoxDriver(); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); wd.get("http://localhost/addressbook/"); login("admin", "secret"); } private void login(String username, String password) { wd.findElement(By.id("LoginForm")).click(); wd.findElement(By.name("user")).click(); wd.findElement(By.name("user")).clear(); wd.findElement(By.name("user")).sendKeys(username); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).clear(); wd.findElement(By.name("pass")).sendKeys(password); wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); } @Test public void testNewEntry() { clickAddNewEntry(); enterMyInfo(new ContactData("Bek", "Ken", "2872 E.Broad St", "2872 E.Broad St\nColumbus, OH 43204", "(614)300-0733", "iskk@yahoo.com")); saveEnteredInfo(); } private void saveEnteredInfo() { wd.findElement(By.xpath("//div[@id='content']/form/input[21]")).click(); } private void enterMyInfo(ContactData contactData) { wd.findElement(By.name("firstname")).click(); wd.findElement(By.name("firstname")).clear(); wd.findElement(By.name("firstname")).sendKeys(contactData.getfName()); wd.findElement(By.name("middlename")).click(); wd.findElement(By.name("lastname")).click(); wd.findElement(By.name("lastname")).clear(); wd.findElement(By.name("lastname")).sendKeys(contactData.getlName()); wd.findElement(By.name("address")).click(); wd.findElement(By.name("address")).clear(); wd.findElement(By.name("address")).sendKeys(contactData.getStreet()); wd.findElement(By.name("address")).click(); wd.findElement(By.name("address")).clear(); wd.findElement(By.name("address")).sendKeys(contactData.getCityStZip()); wd.findElement(By.name("home")).click(); wd.findElement(By.name("mobile")).click(); wd.findElement(By.name("mobile")).clear(); wd.findElement(By.name("mobile")).sendKeys(contactData.getCellNumber()); wd.findElement(By.name("email")).click(); wd.findElement(By.name("email")).clear(); wd.findElement(By.name("email")).sendKeys(contactData.geteMail()); } private void clickAddNewEntry() { wd.findElement(By.linkText("add new")).click(); } @AfterMethod public void tearDown() { wd.quit(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } }
package ru.qa.addressbook; import org.openqa.selenium.firefox.FirefoxOptions; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; import java.util.concurrent.TimeUnit; import java.util.Date; import java.io.File; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.*; import static org.openqa.selenium.OutputType.*; public class GroupCreationTests { FirefoxDriver wd; @BeforeMethod public void setUp() throws Exception { wd = new FirefoxDriver(new FirefoxOptions().setLegacy(true)); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); wd.get("http://localhost/addressbook/"); wd.findElement(By.name("user")).click(); wd.findElement(By.name("user")).clear(); wd.findElement(By.name("user")).sendKeys("admin"); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).clear(); wd.findElement(By.name("pass")).sendKeys("secret"); wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); } @Test public void testGroupCreation() { wd.findElement(By.linkText("groups")).click(); wd.findElement(By.name("new")).click(); wd.findElement(By.name("group_name")).click(); wd.findElement(By.name("group_name")).clear(); wd.findElement(By.name("group_name")).sendKeys("name 1"); wd.findElement(By.name("group_header")).click(); wd.findElement(By.name("group_header")).clear(); wd.findElement(By.name("group_header")).sendKeys("header 1"); wd.findElement(By.name("group_footer")).click(); wd.findElement(By.name("group_footer")).clear(); wd.findElement(By.name("group_footer")).sendKeys("footer 1"); wd.findElement(By.name("submit")).click(); wd.findElement(By.linkText("group page")).click(); } @AfterMethod public void tearDown() { wd.quit(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } }
package org.mozilla.gecko.gfx; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.PixelFormat; import android.graphics.SurfaceTexture; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.widget.FrameLayout; import org.libreoffice.LibreOfficeMainActivity; import java.lang.reflect.Method; import java.nio.IntBuffer; /** * A view rendered by the layer compositor. * * This view delegates to LayerRenderer to actually do the drawing. Its role is largely that of a * mediator between the LayerRenderer and the LayerController. * * Note that LayerView is accessed by Robocop via reflection. */ public class LayerView extends FrameLayout { private static String LOGTAG = LayerView.class.getName(); private GeckoLayerClient mLayerClient; private TouchEventHandler mTouchEventHandler; private GLController mGLController; private InputConnectionHandler mInputConnectionHandler; private LayerRenderer mRenderer; private long mRenderTime; private boolean mRenderTimeReset; /* Must be a PAINT_xxx constant */ private int mPaintState = PAINT_NONE; private SurfaceView mSurfaceView; private TextureView mTextureView; private Listener mListener; /* Flags used to determine when to show the painted surface. The integer * order must correspond to the order in which these states occur. */ public static final int PAINT_NONE = 0; public static final int PAINT_BEFORE_FIRST = 1; public static final int PAINT_AFTER_FIRST = 2; boolean shouldUseTextureView() { // we can only use TextureView on ICS or higher /*if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { Log.i(LOGTAG, "Not using TextureView: not on ICS+"); return false; } try { // and then we can only use it if we have a hardware accelerated window Method m = View.class.getMethod("isHardwareAccelerated", new Class[0]); return (Boolean) m.invoke(this); } catch (Exception e) { Log.i(LOGTAG, "Not using TextureView: caught exception checking for hw accel: " + e.toString()); return false; }*/ return false; } public LayerView(Context context, AttributeSet attrs) { super(context, attrs); if (shouldUseTextureView()) { mTextureView = new TextureView(context); mTextureView.setSurfaceTextureListener(new SurfaceTextureListener()); addView(mTextureView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } else { mSurfaceView = new SurfaceView(context); addView(mSurfaceView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(new SurfaceListener()); holder.setFormat(PixelFormat.RGB_565); } mGLController = new GLController(this); } void connect(GeckoLayerClient layerClient) { mLayerClient = layerClient; mTouchEventHandler = new TouchEventHandler(getContext(), this, layerClient); mRenderer = new LayerRenderer(this); mInputConnectionHandler = null; setFocusable(true); setFocusableInTouchMode(true); createGLThread(); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) requestFocus(); return mTouchEventHandler.handleEvent(event); } @Override public boolean onHoverEvent(MotionEvent event) { return mTouchEventHandler.handleEvent(event); } public GeckoLayerClient getLayerClient() { return mLayerClient; } public TouchEventHandler getTouchEventHandler() { return mTouchEventHandler; } /** The LayerRenderer calls this to indicate that the window has changed size. */ public void setViewportSize(IntSize size) { mLayerClient.setViewportSize(new FloatSize(size)); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { if (mInputConnectionHandler != null) return mInputConnectionHandler.onCreateInputConnection(outAttrs); return null; } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (mInputConnectionHandler != null) return mInputConnectionHandler.onKeyPreIme(keyCode, event); return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mInputConnectionHandler != null) return mInputConnectionHandler.onKeyDown(keyCode, event); return false; } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (mInputConnectionHandler != null) return mInputConnectionHandler.onKeyLongPress(keyCode, event); return false; } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { if (mInputConnectionHandler != null) return mInputConnectionHandler.onKeyMultiple(keyCode, repeatCount, event); return false; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (mInputConnectionHandler != null) return mInputConnectionHandler.onKeyUp(keyCode, event); return false; } public void requestRender() { if (mRenderControllerThread != null) { mRenderControllerThread.renderFrame(); } if (mListener != null) { mListener.renderRequested(); } synchronized(this) { if (!mRenderTimeReset) { mRenderTimeReset = true; mRenderTime = System.nanoTime(); } } } public void addLayer(Layer layer) { mRenderer.addLayer(layer); } public void removeLayer(Layer layer) { mRenderer.removeLayer(layer); } /** * Returns the time elapsed between the first call of requestRender() after * the last call of getRenderTime(), in nanoseconds. */ public long getRenderTime() { synchronized(this) { mRenderTimeReset = false; return System.nanoTime() - mRenderTime; } } public int getMaxTextureSize() { return mRenderer.getMaxTextureSize(); } /** Used by robocop for testing purposes. Not for production use! This is called via reflection by robocop. */ public IntBuffer getPixels() { return mRenderer.getPixels(); } public void setLayerRenderer(LayerRenderer renderer) { mRenderer = renderer; } public LayerRenderer getLayerRenderer() { return mRenderer; } /* paintState must be a PAINT_xxx constant. The state will only be changed * if paintState represents a state that occurs after the current state. */ public void setPaintState(int paintState) { if (paintState > mPaintState) { Log.d(LOGTAG, "LayerView paint state set to " + paintState); mPaintState = paintState; } } public int getPaintState() { return mPaintState; } public LayerRenderer getRenderer() { return mRenderer; } public void setListener(Listener listener) { mListener = listener; } Listener getListener() { return mListener; } public GLController getGLController() { return mGLController; } public Bitmap getDrawable(String name) { Context context = getContext(); Resources resources = context.getResources(); int resourceID = resources.getIdentifier(name, "drawable", context.getPackageName()); BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; return BitmapFactory.decodeResource(context.getResources(), resourceID, options); } Bitmap getBackgroundPattern() { return getDrawable("background"); } Bitmap getShadowPattern() { return getDrawable("shadow"); } private void onSizeChanged(int width, int height) { mGLController.surfaceChanged(width, height); if (mRenderControllerThread != null) { mRenderControllerThread.surfaceChanged(width, height); } if (mListener != null) { mListener.surfaceChanged(width, height); } } private void onDestroyed() { mGLController.surfaceDestroyed(); if (mRenderControllerThread != null) { mRenderControllerThread.surfaceDestroyed(); } if (mListener != null) { mListener.compositionPauseRequested(); } } public Object getNativeWindow() { if (mSurfaceView != null) return mSurfaceView.getHolder(); return mTextureView.getSurfaceTexture(); } /** This function is invoked by Gecko (compositor thread) via JNI; be careful when modifying signature. */ public static GLController registerCxxCompositor() { try { LayerView layerView = LibreOfficeMainActivity.mAppContext.getLayerClient().getView(); layerView.mListener.compositorCreated(); return layerView.getGLController(); } catch (Exception e) { Log.e(LOGTAG, "Error registering compositor!", e); return null; } } public interface Listener { void compositorCreated(); void renderRequested(); void compositionPauseRequested(); void compositionResumeRequested(int width, int height); void surfaceChanged(int width, int height); } private class SurfaceListener implements SurfaceHolder.Callback { public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { onSizeChanged(width, height); } public void surfaceCreated(SurfaceHolder holder) { if (mRenderControllerThread != null) { mRenderControllerThread.surfaceCreated(); } } public void surfaceDestroyed(SurfaceHolder holder) { onDestroyed(); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { setViewportSize(new IntSize(right - left, bottom - top)); } } private class SurfaceTextureListener implements TextureView.SurfaceTextureListener { public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { // We don't do this for surfaceCreated above because it is always followed by a surfaceChanged, // but that is not the case here. if (mRenderControllerThread != null) { mRenderControllerThread.surfaceCreated(); } onSizeChanged(width, height); } public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { onDestroyed(); return true; // allow Android to call release() on the SurfaceTexture, we are done drawing to it } public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { onSizeChanged(width, height); } public void onSurfaceTextureUpdated(SurfaceTexture surface) { } } private RenderControllerThread mRenderControllerThread; public synchronized void createGLThread() { if (mRenderControllerThread != null) { throw new LayerViewException ("createGLThread() called with a GL thread already in place!"); } Log.e(LOGTAG, "### Creating GL thread!"); mRenderControllerThread = new RenderControllerThread(mGLController); mRenderControllerThread.start(); notifyAll(); } public synchronized Thread destroyGLThread() { // Wait for the GL thread to be started. Log.e(LOGTAG, "### Waiting for GL thread to be created..."); while (mRenderControllerThread == null) { try { wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } Log.e(LOGTAG, "### Destroying GL thread!"); Thread thread = mRenderControllerThread; mRenderControllerThread.shutdown(); mRenderControllerThread = null; return thread; } public synchronized void recreateSurface() { if (mRenderControllerThread == null) { throw new LayerViewException("recreateSurface() called with no GL thread active!"); } mRenderControllerThread.recreateSurface(); } public static class LayerViewException extends RuntimeException { public static final long serialVersionUID = 1L; LayerViewException(String e) { super(e); } } }
import java.net.URL; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import jnipap.Connection; import jnipap.VRF; import jnipap.Pool; import jnipap.Prefix; import jnipap.Connection; import jnipap.AddPrefixOptions; import jnipap.JnipapException; import jnipap.DuplicateException; import org.junit.Before; import org.junit.After; import org.junit.Test; import org.junit.Ignore; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * Unit tests for jnipap * * @author Lukas Garberg <lukas@spritelink.net> */ @RunWith(JUnit4.class) public class JnipapTester { public Connection connection; /** * Create connection to NIPAP server */ @Before public void createConnection() { URL url; try { url = new URL("http://127.0.0.1:1337/RPC2"); this.connection = new Connection(url, "unittest", "gottatest"); this.connection.authoritative_source = "test"; } catch (Exception e) { fail("Operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); } } /** * Test adding and getting a VRF */ @Test public void addGetVrf() { VRF vrf1, vrf2; vrf1 = new VRF(); vrf1.rt = "123:456"; vrf1.name = "Test VRF vrf1.description = "A test VRF."; try { vrf1.save(this.connection); vrf2 = VRF.get(this.connection, vrf1.id); } catch (JnipapException e) { fail("Operation resulted in exception " + e.getMessage()); return; } assertEquals("Added VRF differs from fetched VRF", vrf1, vrf2); } /** * Test adding a VRF and (smart) searching for it */ @Test public void addSmartSearchVrf() { VRF vrf1; vrf1 = new VRF(); vrf1.rt = "1234:5678"; vrf1.name = "Test VRF vrf1.description = "Another test VRF."; try { vrf1.save(this.connection); } catch (JnipapException e) { fail("Operation resulted in exception " + e.getMessage()); return; } // Search! try { Map result = VRF.search(this.connection, "1234:5678", new HashMap<>()); int len = ((List)result.get("result")).size(); if (len < 1) { fail("Smart search operation returned to few elements (" + len + ")"); } } catch (JnipapException e) { fail("Smart seach operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); return; } } /** * Test adding and getting a pool */ @Test public void addGetPool() { Pool pool1, pool2; pool1 = new Pool(); pool1.name = "Test pool pool1.description = "A first test pool."; pool1.default_type = "assignment"; pool1.ipv4_default_prefix_length = 28; pool1.ipv6_default_prefix_length = 64; try { pool1.save(this.connection); pool2 = Pool.get(this.connection, pool1.id); } catch (JnipapException e) { fail("Operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); return; } assertEquals("Added pool differs from fetched pool", pool1, pool2); } /** * Test adding a pool and (smart) searching for it */ @Test public void addSmartSearchPool() { Pool pool1; pool1 = new Pool(); pool1.name = "Test pool pool1.description = "A second test pool."; pool1.default_type = "assignment"; pool1.ipv4_default_prefix_length = 28; pool1.ipv6_default_prefix_length = 64; try { pool1.save(this.connection); } catch (JnipapException e) { fail("Save operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); return; } // Search! try { Map result = Pool.search(this.connection, "pool", new HashMap<>()); int len = ((List)result.get("result")).size(); if (len < 1) { fail("Smart search operation returned to few elements (" + len + ")"); } } catch (JnipapException e) { fail("Smart seach operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); } } /** * Test adding and getting a prefix */ @Test public void addGetPrefix() { Prefix prefix1, prefix2; prefix1 = new Prefix(); prefix1.prefix = "192.168.0.0/16"; prefix1.type = "reservation"; prefix1.description = "RFC1918 class B block"; try { prefix1.save(this.connection); prefix2 = Prefix.get(this.connection, prefix1.id); } catch (JnipapException e) { fail("Operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); return; } assertEquals("Added prefix differs from fetched prefix", prefix1, prefix2); } /** * Test adding prefixes and (smart) searching for them */ @Test public void addSmartSearchPrefix() { // Add three prefixes so we have some data to search for Prefix prefix1, prefix2, prefix3; prefix1 = new Prefix(); prefix1.prefix = "10.0.0.0/8"; prefix1.type = "reservation"; prefix1.description = "RFC1918 class A block"; prefix2 = new Prefix(); prefix2.prefix = "10.0.0.0/24"; prefix2.type = "assignment"; prefix2.description = "subnet"; prefix3 = new Prefix(); prefix3.prefix = "10.0.0.1/32"; prefix3.type = "host"; prefix3.description = "TEST TEST"; try { prefix1.save(this.connection); prefix2.save(this.connection); prefix3.save(this.connection); } catch (JnipapException e) { fail("Save operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); } // Search! try { Map result = Prefix.search(this.connection, "TEST TEST", new HashMap<>()); int len = ((List)result.get("result")).size(); if (len < 1) { fail("Smart search operation returned to few elements (" + len + ")"); } } catch (JnipapException e) { fail("Smart seach operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); } } /** * Test adding prefixes and performing a recursive remove */ @Test public void addRecursiveRemovePrefix() { // Add a parent and child prefix Prefix prefix1, prefix2, prefix3; prefix1 = new Prefix(); prefix1.prefix = "11.0.0.0/8"; prefix1.type = "reservation"; prefix1.description = "RFC1918 class A block"; prefix2 = new Prefix(); prefix2.prefix = "11.0.0.0/24"; prefix2.type = "assignment"; prefix2.description = "subnet"; prefix3 = new Prefix(); prefix3.prefix = "11.0.0.1/32"; prefix3.type = "host"; prefix3.description = "TEST TEST"; try { prefix1.save(this.connection); prefix2.save(this.connection); prefix3.save(this.connection); } catch (JnipapException e) { fail("Save operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); } // Perform a recursive remove of the added prefixes try { prefix1.remove(this.connection, Boolean.TRUE); } catch (JnipapException e) { fail("Save operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); } // Search! try { // Add option to include all children Map opts = new HashMap<String, Object>(); opts.put("children_depth", -1); Map result = Prefix.search(this.connection, "11.0.0.0/8", opts); int len = ((List)result.get("result")).size(); if (len > 0) { fail("Smart search operation returned too many elements (" + len + "), should be 0"); } } catch (JnipapException e) { fail("Smart seach operation resulted in " + e.getClass().getName() + " with message \"" + e.getMessage() + "\""); } } }
package com.almeros.android.multitouch; import android.content.Context; import android.view.MotionEvent; public class RotateGestureDetector extends TwoFingerGestureDetector { /** * Listener which must be implemented which is used by RotateGestureDetector * to perform callbacks to any implementing class which is registered to a * RotateGestureDetector via the constructor. * * @see RotateGestureDetector.SimpleOnRotateGestureListener */ public interface OnRotateGestureListener { public boolean onRotate(RotateGestureDetector detector); public boolean onRotateBegin(RotateGestureDetector detector); public void onRotateEnd(RotateGestureDetector detector); } /** * Helper class which may be extended and where the methods may be * implemented. This way it is not necessary to implement all methods * of OnRotateGestureListener. */ public static class SimpleOnRotateGestureListener implements OnRotateGestureListener { public boolean onRotate(RotateGestureDetector detector) { return false; } public boolean onRotateBegin(RotateGestureDetector detector) { return true; } public void onRotateEnd(RotateGestureDetector detector) { // Do nothing, overridden implementation may be used } } private final OnRotateGestureListener mListener; private final float FOCUS_THRESHOLD = 25f; private boolean mSloppyGesture; private float mFocusX; private float mFocusY; public RotateGestureDetector(Context context, OnRotateGestureListener listener) { super(context); mListener = listener; } private void determineFocusPoint(MotionEvent curr) { mFocusX = (curr.getX(0) + curr.getX(1)) * 0.5f; mFocusY = (curr.getY(0) + curr.getY(1)) * 0.5f; } @Override protected void handleStartProgressEvent(int actionCode, MotionEvent event){ switch (actionCode) { case MotionEvent.ACTION_POINTER_DOWN: // At least the second finger is on screen now resetState(); // In case we missed an UP/CANCEL event mPrevEvent = MotionEvent.obtain(event); mTimeDelta = 0; updateStateByEvent(event); // See if we have a sloppy gesture mSloppyGesture = isSloppyGesture(event); if(!mSloppyGesture){ // No, start gesture now mGestureInProgress = mListener.onRotateBegin(this); } break; case MotionEvent.ACTION_MOVE: if (!mSloppyGesture) { break; } // See if we still have a sloppy gesture mSloppyGesture = isSloppyGesture(event); if(!mSloppyGesture){ // No, start normal gesture now mGestureInProgress = mListener.onRotateBegin(this); } break; case MotionEvent.ACTION_POINTER_UP: if (!mSloppyGesture) { break; } break; } } @Override protected void handleInProgressEvent(int actionCode, MotionEvent event){ switch (actionCode) { case MotionEvent.ACTION_POINTER_UP: // Gesture ended but updateStateByEvent(event); if (!mSloppyGesture) { mListener.onRotateEnd(this); } resetState(); break; case MotionEvent.ACTION_CANCEL: if (!mSloppyGesture) { mListener.onRotateEnd(this); } resetState(); break; case MotionEvent.ACTION_MOVE: updateStateByEvent(event); // Only accept the event if our relative pressure is within // a certain limit. This can help filter shaky data as a // finger is lifted. if (mCurrPressure / mPrevPressure > PRESSURE_THRESHOLD) { determineFocusPoint(event); final boolean updatePrevious = mListener.onRotate(this); if (updatePrevious) { mPrevEvent.recycle(); mPrevEvent = MotionEvent.obtain(event); } } break; } } @Override protected void resetState() { super.resetState(); mSloppyGesture = false; } public float getFocusX() { return mFocusX; } public float getFocusY() { return mFocusY; } /** * Return the rotation difference from the previous rotate event to the current * event. (radians) * * @return The current rotation //difference in degrees. */ public float getRotationRadiansDelta() { double diffRadians = Math.atan2(mPrevFingerDiffY, mPrevFingerDiffX) - Math.atan2(mCurrFingerDiffY, mCurrFingerDiffX); return (float) (diffRadians); } /** * Return the rotation difference from the previous rotate event to the current * event. (degrees) * * @return The current rotation //difference in degrees. */ public float getRotationDegreesDelta() { double diffRadians = Math.atan2(mPrevFingerDiffY, mPrevFingerDiffX) - Math.atan2(mCurrFingerDiffY, mCurrFingerDiffX); return (float) (diffRadians * 180 / Math.PI); } }
package org.appcelerator.titanium.view; import java.io.IOException; import java.util.Arrays; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Path.Direction; import android.graphics.Path.FillType; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.PaintDrawable; import android.graphics.drawable.StateListDrawable; import android.util.AttributeSet; import android.util.Log; public class TiBackgroundDrawable extends StateListDrawable { //private int backgroundColor; //private Bitmap backgroundImage; private static final String TAG = "TiBackgroundDrawable"; private Drawable background; private Border border; private RectF outerRect, innerRect; private static final int NOT_SET = -1; private int alpha = NOT_SET; private Path path; private Paint paint; public TiBackgroundDrawable() { background = new ColorDrawable(Color.TRANSPARENT); border = null; outerRect = new RectF(); innerRect = new RectF(); paint = new Paint(Paint.ANTI_ALIAS_FLAG); } @Override public void draw(Canvas canvas) { if (border != null) { paint.setColor(border.color); if (border.radius > 0) { canvas.drawRoundRect(outerRect, border.radius, border.radius, paint); } else { canvas.drawRect(outerRect, paint); } } //paint.setColor(backgroundColor); if (background != null) { background.setBounds((int)innerRect.left, (int)innerRect.top, (int)innerRect.right, (int)innerRect.bottom); } canvas.save(); if (border != null && border.radius > 0) { // This still happens sometimes when hw accelerated so, catch and warn try { canvas.clipPath(path); } catch (Exception e) { Log.w(TAG, "clipPath failed on canvas: " + e.getMessage()); } } else { // innerRect == outerRect if there is no border //canvas.drawRect(innerRect, paint); canvas.clipRect(innerRect); } if (background != null) { if (alpha > NOT_SET) { background.setAlpha(alpha); } background.draw(canvas); } canvas.restore(); /*if (backgroundImage != null && !backgroundImage.isRecycled()) { canvas.drawBitmap(backgroundImage, null, innerRect, paint); }*/ } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); outerRect.set(bounds); int padding = 0; if (border != null) { padding = (int)border.width; } innerRect.set(bounds.left+padding, bounds.top+padding, bounds.right-padding, bounds.bottom-padding); if (background != null) { background.setBounds((int)innerRect.left, (int)innerRect.top, (int)innerRect.right, (int)innerRect.bottom); } if (border != null && border.radius > 0) { path = new Path(); float radii[] = new float[8]; Arrays.fill(radii, border.radius); path.addRoundRect(innerRect, radii, Direction.CW); path.setFillType(FillType.EVEN_ODD); } } @Override protected boolean onStateChange(int[] stateSet) { boolean changed = super.onStateChange(stateSet); changed = setState(stateSet); boolean drawableChanged = false; if (background != null) { // Log.e("TiBackground", "background="+background.getClass().getSimpleName()+",state.len="+stateSet.length); // for (int i = 0; i < stateSet.length; i++) { // Log.e("TiBackground", " state[" + i + "]=" + stateSet[i]); drawableChanged = background.setState(stateSet); if (drawableChanged) { invalidateSelf(); } } return changed || drawableChanged; } @Override public void addState(int[] stateSet, Drawable drawable) { if (background instanceof StateListDrawable) { ((StateListDrawable)background).addState(stateSet, drawable); } } @Override protected boolean onLevelChange(int level) { boolean changed = super.onLevelChange(level); boolean backgroundChanged = false; if (background instanceof StateListDrawable) { backgroundChanged = ((StateListDrawable)background).setLevel(level); } return changed || backgroundChanged; } @Override public void invalidateSelf() { super.invalidateSelf(); if (background instanceof StateListDrawable) { ((StateListDrawable)background).invalidateSelf(); } } @Override public void invalidateDrawable(Drawable who) { super.invalidateDrawable(who); if (background instanceof StateListDrawable) { ((StateListDrawable)background).invalidateDrawable(who); } } @Override public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) throws XmlPullParserException, IOException { super.inflate(r, parser, attrs); if (background != null) { background.inflate(r, parser, attrs); } } public void releaseDelegate() { if (background != null) { if (background instanceof BitmapDrawable) { ((BitmapDrawable)background).getBitmap().recycle(); } background.setCallback(null); background = null; } } public static class Border { public static final int SOLID = 0; private int color = Color.TRANSPARENT; private float radius = 0; private float width = 0; private int style = SOLID; public int getColor() { return color; } public void setColor(int color) { this.color = color; } public float getRadius() { return radius; } public void setRadius(float radius) { this.radius = radius; } public float getWidth() { return width; } public void setWidth(float width) { this.width = width; } public int getStyle() { return style; } public void setStyle(int style) { this.style = style; } } public void setBorder(Border border) { this.border = border; } public Border getBorder() { return border; } public void setBackgroundColor(int backgroundColor) { //this.background = new ColorDrawable(backgroundColor); releaseDelegate(); this.background = new PaintDrawable(backgroundColor); } public void setBackgroundImage(Bitmap backgroundImage) { releaseDelegate(); this.background = new BitmapDrawable(backgroundImage); } public void setBackgroundDrawable(Drawable drawable) { releaseDelegate(); this.background = drawable; onStateChange(getState()); } @Override public void setAlpha(int alpha) { super.setAlpha(alpha); this.alpha = alpha; } // public Drawable getBackgroundDrawable() { // return background; }
package cz.muni.fi.pa165.mushrooms.facade; import cz.muni.fi.pa165.mushrooms.dto.MushroomHunterDTO; import java.util.List; /** * TODO: create javadoc * * @author bencikpeter, bohdancvejn, bkompis, Lindar84, Buvko */ public interface MushroomHunterFacade { MushroomHunterDTO findHunterById(Long userId); // TODO: do we want ID's in DTO? o.O MushroomHunterDTO findHunterByNickname(String nickname); /** * Register the given user with the given unencrypted password. */ void registerHunter(MushroomHunterDTO hunter, String unencryptedPassword); void deleteHunter(MushroomHunterDTO hunter); void updateHunter(MushroomHunterDTO hunter); void updatePassword(MushroomHunterDTO hunter, String oldUnencryptedPassword, String newUnencryptedPassword); /** * Find all registered users */ List<MushroomHunterDTO> findAllHunters(); /** * Try to authenticate a mushroomHunter. Return true only if the hashed password matches the records. */ boolean authenticate(MushroomHunterDTO u); /** * Check if the given mushroom hunter has administrator privileges. */ boolean isAdmin(MushroomHunterDTO u); }
package ca.nrc.cadc.uws.web; import ca.nrc.cadc.date.DateUtil; import ca.nrc.cadc.util.StringUtil; import ca.nrc.cadc.uws.ExecutionPhase; import ca.nrc.cadc.uws.Job; import ca.nrc.cadc.uws.JobAttribute; import ca.nrc.cadc.uws.JobInfo; import ca.nrc.cadc.uws.Parameter; import ca.nrc.cadc.xml.XmlUtil; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; import org.apache.log4j.Logger; import org.jdom.JDOMException; /** * Simple class used to read job description from the request and create a new Job. * @author pdowler */ public class JobCreator { private static final Logger log = Logger.getLogger(JobCreator.class); protected static final DateFormat dateFormat = DateUtil.getDateFormat(DateUtil.IVOA_DATE_FORMAT, DateUtil.UTC); protected static final String URLENCODED = "application/x-www-form-urlencoded"; protected static final String TEXT_XML = "text/xml"; protected static final String MULTIPART = "multipart/form-data"; protected InlineContentHandler inlineContentHandler; public JobCreator(InlineContentHandler inlineContentHandler) { this.inlineContentHandler = inlineContentHandler; } public Job create(HttpServletRequest request) throws FileUploadException, IOException { Job job = new Job(); job.setExecutionPhase(ExecutionPhase.PENDING); job.setParameterList(new ArrayList<Parameter>()); if (request.getMethod().equals("GET")) { Enumeration<String> names = request.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); processParameter(job, name, request.getParameterValues(name)); } } else { String contentType = request.getContentType(); if (contentType != null) { int i = contentType.indexOf(';'); if (i > 0) contentType = contentType.substring(0, i); } log.debug("Content-Type: " + contentType); if (contentType != null && contentType.equalsIgnoreCase(URLENCODED)) { Enumeration<String> names = request.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); processParameter(job, name, request.getParameterValues(name)); } } else if (inlineContentHandler != null) { if (contentType != null && contentType.startsWith(MULTIPART)) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator itemIterator = upload.getItemIterator(request); processMultiPart(job, itemIterator); } else { processStream(null, contentType, request.getInputStream()); } inlineContentHandler.setParameterList(job.getParameterList()); job.setParameterList(inlineContentHandler.getParameterList()); job.setJobInfo(inlineContentHandler.getJobInfo()); } } try { URL u = new URL(request.getRequestURL().toString()); job.setRequestPath(u.getPath()); } catch(MalformedURLException oops) { log.error("failed to get request path", oops); } job.setRemoteIP(request.getRemoteAddr()); return job; } protected void processParameter(Job job, String name, String[] values) { if (JobAttribute.isValue(name)) processUWSParameter(job, name, values); else processJobParameter(job, name, values); } private void processUWSParameter(Job job, String name, String[] values) { String value = values[0]; if (name.equalsIgnoreCase(JobAttribute.RUN_ID.getAttributeName())) { job.setRunID(value); } else if (name.equalsIgnoreCase(JobAttribute.DESTRUCTION_TIME.getAttributeName())) { if (StringUtil.hasText(value)) { try { job.setDestructionTime(dateFormat.parse(value)); } catch (ParseException e) { log.error("Cannot parse Destruction Time to IVOA date format " + value, e); throw new IllegalArgumentException("Cannot parse Destruction Time to IVOA date format " + value, e); } } else { job.setDestructionTime(null); } } else if(name.equalsIgnoreCase(JobAttribute.EXECUTION_DURATION.getAttributeName())) { if (StringUtil.hasText(value)) job.setExecutionDuration(Long.parseLong(value)); } else if (name.equalsIgnoreCase(JobAttribute.QUOTE.getAttributeName())) { if (StringUtil.hasText(value)) { try { job.setQuote(dateFormat.parse(value)); } catch (ParseException e) { log.error("Cannot parse Quote to IVOA date format " + value, e); throw new IllegalArgumentException("Cannot parse Quote to IVOA date format " + value, e); } } else { job.setQuote(null); } } } protected void processJobParameter(Job job, String name, String[] values) { for (String value : values) job.getParameterList().add(new Parameter(name, value)); } protected void processMultiPart(Job job, FileItemIterator itemIterator) throws FileUploadException, IOException { while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) processParameter(job, name, new String[] { Streams.asString(stream) }); else processStream(name, item.getContentType(), stream); } } protected void processStream(String name, String contentType, InputStream inputStream) throws IOException { inlineContentHandler.accept(name, contentType, inputStream); } }
package net.md_5.bungee; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import java.util.Queue; import java.util.Set; import lombok.Getter; import lombok.RequiredArgsConstructor; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.event.ServerConnectedEvent; import net.md_5.bungee.api.event.ServerKickEvent; import net.md_5.bungee.api.event.ServerSwitchEvent; import net.md_5.bungee.api.score.Objective; import net.md_5.bungee.api.score.Scoreboard; import net.md_5.bungee.api.score.Team; import net.md_5.bungee.chat.ComponentSerializer; import net.md_5.bungee.connection.CancelSendSignal; import net.md_5.bungee.connection.DownstreamBridge; import net.md_5.bungee.connection.LoginResult; import net.md_5.bungee.forge.ForgeConstants; import net.md_5.bungee.forge.ForgeServerHandler; import net.md_5.bungee.forge.ForgeUtils; import net.md_5.bungee.netty.ChannelWrapper; import net.md_5.bungee.netty.HandlerBoss; import net.md_5.bungee.netty.PacketHandler; import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.MinecraftOutput; import net.md_5.bungee.protocol.Protocol; import net.md_5.bungee.protocol.ProtocolConstants; import net.md_5.bungee.protocol.packet.EncryptionRequest; import net.md_5.bungee.protocol.packet.Handshake; import net.md_5.bungee.protocol.packet.Kick; import net.md_5.bungee.protocol.packet.Login; import net.md_5.bungee.protocol.packet.LoginSuccess; import net.md_5.bungee.protocol.packet.PluginMessage; import net.md_5.bungee.protocol.packet.Respawn; import net.md_5.bungee.protocol.packet.ScoreboardObjective; import net.md_5.bungee.protocol.packet.SetCompression; @RequiredArgsConstructor public class ServerConnector extends PacketHandler { private final ProxyServer bungee; private ChannelWrapper ch; private final UserConnection user; private final BungeeServerInfo target; private State thisState = State.LOGIN_SUCCESS; @Getter private ForgeServerHandler handshakeHandler; private enum State { LOGIN_SUCCESS, ENCRYPT_RESPONSE, LOGIN, FINISHED; } @Override public void exception(Throwable t) throws Exception { String message = "Exception Connecting:" + Util.exception( t ); if ( user.getServer() == null ) { user.disconnect( message ); } else { user.sendMessage( ChatColor.RED + message ); } } @Override public void connected(ChannelWrapper channel) throws Exception { this.ch = channel; this.handshakeHandler = new ForgeServerHandler( user, ch, target ); Handshake originalHandshake = user.getPendingConnection().getHandshake(); Handshake copiedHandshake = new Handshake( originalHandshake.getProtocolVersion(), originalHandshake.getHost(), originalHandshake.getPort(), 2 ); if ( BungeeCord.getInstance().config.isIpForward() ) { String newHost = copiedHandshake.getHost() + "\00" + user.getAddress().getHostString() + "\00" + user.getUUID(); LoginResult profile = user.getPendingConnection().getLoginProfile(); if ( profile != null && profile.getProperties() != null && profile.getProperties().length > 0 ) { newHost += "\00" + BungeeCord.getInstance().gson.toJson( profile.getProperties() ); } copiedHandshake.setHost( newHost ); } else if ( !user.getExtraDataInHandshake().isEmpty() ) { // Only restore the extra data if IP forwarding is off. // TODO: Add support for this data with IP forwarding. copiedHandshake.setHost( copiedHandshake.getHost() + user.getExtraDataInHandshake() ); } channel.write( copiedHandshake ); channel.setProtocol( Protocol.LOGIN ); channel.write( user.getPendingConnection().getLoginRequest() ); } @Override public void disconnected(ChannelWrapper channel) throws Exception { user.getPendingConnects().remove( target ); } @Override public void handle(LoginSuccess loginSuccess) throws Exception { Preconditions.checkState( thisState == State.LOGIN_SUCCESS, "Not expecting LOGIN_SUCCESS" ); ch.setProtocol( Protocol.GAME ); thisState = State.LOGIN; // Only reset the Forge client when: // 1) The user is switching servers (so has a current server) // 2) The handshake is complete // 3) The user is currently on a modded server (if we are on a vanilla server, // we may be heading for another vanilla server, so we don't need to reset.) // user.getServer() gets the user's CURRENT server, not the one we are trying // to connect to. // We will reset the connection later if the current server is vanilla, and // we need to switch to a modded connection. However, we always need to reset the // connection when we have a modded server regardless of where we go - doing it // here makes sense. if ( user.getServer() != null && user.getForgeClientHandler().isHandshakeComplete() && user.getServer().isForgeServer() ) { user.getForgeClientHandler().resetHandshake(); } throw CancelSendSignal.INSTANCE; } @Override public void handle(SetCompression setCompression) throws Exception { user.setCompressionThreshold( setCompression.getThreshold() ); ch.setCompressionThreshold( setCompression.getThreshold() ); } @Override public void handle(Login login) throws Exception { Preconditions.checkState( thisState == State.LOGIN, "Not expecting LOGIN" ); ServerConnection server = new ServerConnection( ch, target ); ServerConnectedEvent event = new ServerConnectedEvent( user, server ); bungee.getPluginManager().callEvent( event ); ch.write( BungeeCord.getInstance().registerChannels() ); Queue<DefinedPacket> packetQueue = target.getPacketQueue(); synchronized ( packetQueue ) { while ( !packetQueue.isEmpty() ) { ch.write( packetQueue.poll() ); } } for ( PluginMessage message : user.getPendingConnection().getRegisterMessages() ) { ch.write( message ); } if ( user.getSettings() != null ) { ch.write( user.getSettings() ); } if ( user.getForgeClientHandler().getClientModList() == null && !user.getForgeClientHandler().isHandshakeComplete() ) // Vanilla { user.getForgeClientHandler().setHandshakeComplete(); } if ( user.getServer() == null ) { // Once again, first connection user.setClientEntityId( login.getEntityId() ); user.setServerEntityId( login.getEntityId() ); // Set tab list size, this sucks balls, TODO: what shall we do about packet mutability // Forge allows dimension ID's > 127 Login modLogin; if ( handshakeHandler != null && handshakeHandler.isServerForge() ) { modLogin = new Login( login.getEntityId(), login.getGameMode(), login.getDimension(), login.getDifficulty(), (byte) user.getPendingConnection().getListener().getTabListSize(), login.getLevelType(), login.isReducedDebugInfo() ); } else { modLogin = new Login( login.getEntityId(), login.getGameMode(), (byte) login.getDimension(), login.getDifficulty(), (byte) user.getPendingConnection().getListener().getTabListSize(), login.getLevelType(), login.isReducedDebugInfo() ); } user.unsafe().sendPacket( modLogin ); if ( user.getPendingConnection().getVersion() < ProtocolConstants.MINECRAFT_1_8 ) { MinecraftOutput out = new MinecraftOutput(); out.writeStringUTF8WithoutLengthHeaderBecauseDinnerboneStuffedUpTheMCBrandPacket( ProxyServer.getInstance().getName() + " (" + ProxyServer.getInstance().getVersion() + ")" ); user.unsafe().sendPacket( new PluginMessage( "MC|Brand", out.toArray(), handshakeHandler.isServerForge() ) ); } else { ByteBuf brand = ByteBufAllocator.DEFAULT.heapBuffer(); DefinedPacket.writeString( bungee.getName() + " (" + bungee.getVersion() + ")", brand ); user.unsafe().sendPacket( new PluginMessage( "MC|Brand", brand.array().clone(), handshakeHandler.isServerForge() ) ); brand.release(); } } else { user.getTabListHandler().onServerChange(); Scoreboard serverScoreboard = user.getServerSentScoreboard(); for ( Objective objective : serverScoreboard.getObjectives() ) { user.unsafe().sendPacket( new ScoreboardObjective( objective.getName(), objective.getValue(), "integer", (byte) 1 ) ); // TODO: } for ( Team team : serverScoreboard.getTeams() ) { user.unsafe().sendPacket( new net.md_5.bungee.protocol.packet.Team( team.getName() ) ); } serverScoreboard.clear(); user.sendDimensionSwitch(); user.setServerEntityId( login.getEntityId() ); user.unsafe().sendPacket( new Respawn( login.getDimension(), login.getDifficulty(), login.getGameMode(), login.getLevelType() ) ); // Remove from old servers user.getServer().setObsolete( true ); user.getServer().disconnect( "Quitting" ); } // TODO: Fix this? if ( !user.isActive() ) { server.disconnect( "Quitting" ); // Silly server admins see stack trace and die bungee.getLogger().warning( "No client connected for pending server!" ); return; } // Add to new server // TODO: Move this to the connected() method of DownstreamBridge target.addPlayer( user ); user.getPendingConnects().remove( target ); user.setDimensionChange( false ); user.setServer( server ); ch.getHandle().pipeline().get( HandlerBoss.class ).setHandler( new DownstreamBridge( bungee, user, server ) ); bungee.getPluginManager().callEvent( new ServerSwitchEvent( user ) ); thisState = State.FINISHED; throw CancelSendSignal.INSTANCE; } @Override public void handle(EncryptionRequest encryptionRequest) throws Exception { throw new RuntimeException( "Server is online mode!" ); } @Override public void handle(Kick kick) throws Exception { ServerInfo def = bungee.getServerInfo( user.getPendingConnection().getListener().getFallbackServer() ); if ( Objects.equal( target, def ) ) { def = null; } ServerKickEvent event = bungee.getPluginManager().callEvent( new ServerKickEvent( user, target, ComponentSerializer.parse( kick.getMessage() ), def, ServerKickEvent.State.CONNECTING ) ); if ( event.isCancelled() && event.getCancelServer() != null ) { user.connect( event.getCancelServer() ); throw CancelSendSignal.INSTANCE; } String message = bungee.getTranslation( "connect_kick", target.getName(), event.getKickReason() ); if ( user.isDimensionChange() ) { user.disconnect( message ); } else { user.sendMessage( message ); } throw CancelSendSignal.INSTANCE; } @Override public void handle(PluginMessage pluginMessage) throws Exception { if ( pluginMessage.getTag().equals( ForgeConstants.FML_REGISTER ) ) { Set<String> channels = ForgeUtils.readRegisteredChannels( pluginMessage ); boolean isForgeServer = false; for ( String channel : channels ) { if ( channel.equals( ForgeConstants.FML_HANDSHAKE_TAG ) ) { // If we have a completed handshake and we have been asked to register a FML|HS // packet, let's send the reset packet now. Then, we can continue the message sending. // The handshake will not be complete if we reset this earlier. if ( user.getServer() != null && user.getForgeClientHandler().isHandshakeComplete() ) { user.getForgeClientHandler().resetHandshake(); } isForgeServer = true; break; } } if ( isForgeServer && !this.handshakeHandler.isServerForge() ) { // We now set the server-side handshake handler for the client to this. handshakeHandler.setServerAsForgeServer(); user.setForgeServerHandler( handshakeHandler ); } } // We must bypass our handler once handshake is complete in order to send DimensionRegisterPacket's during Login. if ( !handshakeHandler.isHandshakeComplete() && ( pluginMessage.getTag().equals( ForgeConstants.FML_HANDSHAKE_TAG ) || pluginMessage.getTag().equals( ForgeConstants.FORGE_REGISTER ) ) ) { handshakeHandler.handle( pluginMessage ); if ( user.getForgeClientHandler().checkUserOutdated() ) { ch.close(); user.getPendingConnects().remove( target ); } // We send the message as part of the handler, so don't send it here. throw CancelSendSignal.INSTANCE; } else { // We have to forward these to the user, especially with Forge as stuff might break // This includes any REGISTER messages we intercepted earlier. user.unsafe().sendPacket( pluginMessage ); } } @Override public String toString() { return "[" + user.getName() + "] <-> ServerConnector [" + target.getName() + "]"; } }
package railo.runtime.op; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.sql.Blob; import java.sql.Clob; import java.text.DateFormat; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.regex.Pattern; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import railo.commons.date.DateTimeUtil; import railo.commons.date.JREDateTimeUtil; import railo.commons.i18n.FormatUtil; import railo.commons.lang.CFTypes; import railo.commons.lang.StringUtil; import railo.runtime.Component; import railo.runtime.coder.Base64Util; import railo.runtime.converter.WDDXConverter; import railo.runtime.engine.ThreadLocalPageContext; import railo.runtime.exp.ExpressionException; import railo.runtime.exp.PageException; import railo.runtime.ext.function.Function; import railo.runtime.java.JavaObject; import railo.runtime.op.date.DateCaster; import railo.runtime.op.validators.ValidateCreditCard; import railo.runtime.text.xml.XMLCaster; import railo.runtime.text.xml.XMLUtil; import railo.runtime.text.xml.struct.XMLStruct; import railo.runtime.type.Array; import railo.runtime.type.Collection; import railo.runtime.type.ObjectWrap; import railo.runtime.type.Objects; import railo.runtime.type.Query; import railo.runtime.type.Struct; import railo.runtime.type.UDF; import railo.runtime.type.dt.DateTime; /** * Object to test if a Object is a specific type */ public final class Decision { private static final String STRING_DEFAULT_VALUE = "this is a unique string"; private static Pattern emailPattern; private static Pattern ssnPattern; private static Pattern phonePattern; private static Pattern urlPattern; private static Pattern zipPattern; /** * tests if value is a simple value (Number,String,Boolean,Date,Printable) * @param value value to test * @return is value a simple value */ public static boolean isSimpleValue(Object value){ return (value instanceof Number) || (value instanceof String) || (value instanceof Boolean) || (value instanceof Date) || ((value instanceof Castable) && !(value instanceof Objects) && !(value instanceof Collection)); } /** * tests if value is Numeric * @param value value to test * @return is value numeric */ public static boolean isNumeric(Object value) { if(value instanceof Number) return true; else if(value instanceof String) { return isNumeric(value.toString()); } else return false; } public static boolean isCastableToNumeric(Object o) { if(isNumeric(o)) return true; else if(isBoolean(o)) return true; else if(isDateSimple(o,false)) return true; else if(o == null) return true; else if(o instanceof ObjectWrap) return isCastableToNumeric(((ObjectWrap)o).getEmbededObject("notanumber")); else if(o instanceof Castable) { return Decision.isValid(((Castable)o).castToDoubleValue(Double.NaN)); } return false; } public static boolean isCastableToDate(Object o) { if(isDateAdvanced(o, true)) return true; else if(isBoolean(o)) return true; else if(o instanceof ObjectWrap) return isCastableToDate(((ObjectWrap)o).getEmbededObject("notadate")); else if(o instanceof Castable) { return ((Castable)o).castToDateTime(null)!=null; } return false; } /** * tests if value is Numeric * @param value value to test * @return is value numeric */ public static boolean isNumeric(Object value, boolean alsoBooleans) { if(alsoBooleans && isBoolean(value)) return true; return isNumeric(value); } /** * tests if String value is Numeric * @param str value to test * @return is value numeric */ public static boolean isNumeric(String str) { if(str==null) return false; str=str.trim(); int pos=0; int len=str.length(); if(len==0) return false; char curr=str.charAt(pos); if(curr=='+' || curr=='-') { if(len==++pos) return false; curr=str.charAt(pos); } boolean hasDot=false; boolean hasExp=false; for(;pos<len;pos++) { curr=str.charAt(pos); if(curr<'0') { if(curr=='.') { if(pos+1>=len || hasDot) return false; hasDot=true; } else return false; } else if(curr>'9') { if(curr=='e' || curr=='E') { if(pos+1>=len || hasExp) return false; hasExp=true; hasDot=true; } else return false; } } if(hasExp){ try{ Double.parseDouble(str); return true; } catch( NumberFormatException e){ return false; } } return true; } public static boolean isInteger(Object value) { return isInteger(value,false); } public static boolean isInteger(Object value,boolean alsoBooleans) { if(!alsoBooleans && value instanceof Boolean) return false; double dbl = Caster.toDoubleValue(value,Double.NaN); if(!Decision.isValid(dbl)) return false; int i=(int)dbl; return i==dbl; } /** tests if String value is Hex Value * @param str value to test * @return is value numeric */ public static boolean isHex(String str) { if(str==null || str.length()==0) return false; for(int i=str.length()-1;i>=0;i char c=str.charAt(i); if(!(c>='0' && c<='9')) { c=Character.toLowerCase(c); if(!(c=='a' || c=='b' || c=='c' || c=='d' || c=='e' || c=='f'))return false; } } return true; } /** tests if String value is UUID Value * @param str value to test * @return is value numeric * @deprecated use instead <code>isUUId(Object obj)</code> */ public static boolean isUUID(Object obj) { return isUUId(obj); } /** tests if String value is UUID Value * @param str value to test * @return is value numeric */ public static boolean isUUId(Object obj) { String str=Caster.toString(obj,null); if(str==null) return false; if(str.length()==35) { return Decision.isHex(str.substring(0,8)) && str.charAt(8)=='-' && Decision.isHex(str.substring(9,13)) && str.charAt(13)=='-' && Decision.isHex(str.substring(14,18)) && str.charAt(18)=='-' && Decision.isHex(str.substring(19)); } return false; } /** * @param obj * @return * @deprecated use instead <code>isGUId(Object)</code> */ public static boolean isGUID(Object obj) { return isGUId(obj); } public static boolean isGUId(Object obj) { String str=Caster.toString(obj,null); if(str==null) return false; // GUID if(str.length()==36) { return Decision.isHex(str.substring(0,8)) && str.charAt(8)=='-' && Decision.isHex(str.substring(9,13)) && str.charAt(13)=='-' && Decision.isHex(str.substring(14,18)) && str.charAt(18)=='-' && Decision.isHex(str.substring(19,23)) && str.charAt(23)=='-' && Decision.isHex(str.substring(24)); } return false; } public static boolean isGUIdSimple(Object obj) { String str=Caster.toString(obj,null); if(str==null) return false; // GUID if(str.length()==36) { return str.charAt(8)=='-' && str.charAt(13)=='-' && str.charAt(18)=='-' && str.charAt(23)=='-'; } return false; } /** * tests if value is a Boolean (Numbers are not acctepeted) * @param value value to test * @return is value boolean */ public static boolean isBoolean(Object value) { if(value instanceof Boolean) return true; else if(value instanceof String) { return isBoolean(value.toString()); } else if(value instanceof ObjectWrap) return isBoolean(((ObjectWrap)value).getEmbededObject(null)); else return false; } public static boolean isCastableToBoolean(Object value) { if(value instanceof Boolean) return true; if(value instanceof Number) return true; else if(value instanceof String) { String str = (String)value; return isBoolean(str) || isNumeric(str); } else if(value instanceof Castable) { return ((Castable)value).castToBoolean(null)!=null; } else if(value instanceof ObjectWrap) return isCastableToBoolean(((ObjectWrap)value).getEmbededObject(null)); else return false; } public static boolean isBoolean(Object value, boolean alsoNumbers) { if(isBoolean(value)) return true; else if(alsoNumbers) return isNumeric(value); else return false; } /** * tests if value is a Boolean * @param str value to test * @return is value boolean */ public static boolean isBoolean(String str) { //str=str.trim(); if(str.length()<2) return false; switch(str.charAt(0)) { case 't': case 'T': return str.equalsIgnoreCase("true"); case 'f': case 'F': return str.equalsIgnoreCase("false"); case 'y': case 'Y': return str.equalsIgnoreCase("yes"); case 'n': case 'N': return str.equalsIgnoreCase("no"); } return false; } /** * tests if value is DateTime Object * @param value value to test * @param alsoNumbers interpret also a number as date * @return is value a DateTime Object */ public static boolean isDate(Object value,boolean alsoNumbers) { return isDateSimple(value, alsoNumbers); } public static boolean isDateSimple(Object value,boolean alsoNumbers) { //return DateCaster.toDateEL(value)!=null; if(value instanceof DateTime) return true; else if(value instanceof Date) return true; // wrong timezone but this isent importend because date will not be importend else if(value instanceof String) return DateCaster.toDateSimple(value.toString(),alsoNumbers,TimeZone.getDefault(),null)!=null; else if(value instanceof ObjectWrap) { return isDateSimple(((ObjectWrap)value).getEmbededObject(null),alsoNumbers); } else if(value instanceof Castable) { return ((Castable)value).castToDateTime(null)!=null; } else if(alsoNumbers && value instanceof Number) return true; else if(value instanceof Calendar) return true; return false; } public static boolean isDateAdvanced(Object value,boolean alsoNumbers) { //return DateCaster.toDateEL(value)!=null; if(value instanceof DateTime) return true; else if(value instanceof Date) return true; // wrong timezone but this isent importend because date will not be importend else if(value instanceof String) return DateCaster.toDateAdvanced(value.toString(),alsoNumbers,TimeZone.getDefault(),null)!=null; else if(value instanceof Castable) { return ((Castable)value).castToDateTime(null)!=null; } else if(alsoNumbers && value instanceof Number) return true; else if(value instanceof ObjectWrap) { return isDateAdvanced(((ObjectWrap)value).getEmbededObject(null),alsoNumbers); } else if(value instanceof Calendar) return true; return false; } private static char[] DATE_DEL=new char[]{'.','/','-'}; public static boolean isUSDate(Object value) { String str = Caster.toString(value,""); return isUSorEuroDateEuro(str,false); } public static boolean isUSDate(String str) { return isUSorEuroDateEuro(str,false); } public static boolean isEuroDate(Object value) { String str = Caster.toString(value,""); return isUSorEuroDateEuro(str,true); } public static boolean isEuroDate(String str) { return isUSorEuroDateEuro(str,true); } private static boolean isUSorEuroDateEuro(String str, boolean isEuro) { if(StringUtil.isEmpty(str)) return false; for(int i=0;i<DATE_DEL.length;i++) { Array arr = railo.runtime.type.List.listToArrayRemoveEmpty(str,DATE_DEL[i]); if(arr.size()!=3) continue; int month=Caster.toIntValue( arr.get(isEuro?2:1,Constants.INTEGER_0),Integer.MIN_VALUE); int day=Caster.toIntValue( arr.get(isEuro?1:2,Constants.INTEGER_0),Integer.MIN_VALUE); int year=Caster.toIntValue( arr.get(3,Constants.INTEGER_0),Integer.MIN_VALUE); if(month==Integer.MIN_VALUE) continue; if(month>12) continue; if(day==Integer.MIN_VALUE) continue; if(day>31) continue; if(year==Integer.MIN_VALUE) continue; if(DateTimeUtil.getInstance().toTime(null,year, month, day, 0, 0, 0,0, Long.MIN_VALUE)==Long.MIN_VALUE) continue; return true; } return false; } public static boolean isCastableToStruct(Object o) { if(isStruct(o)) return true; if(o == null) return false; else if(o instanceof ObjectWrap) { if(o instanceof JavaObject ) return true; return isCastableToStruct(((ObjectWrap)o).getEmbededObject(null)); } if(Decision.isSimpleValue(o)){ return false; } //if(isArray(o) || isQuery(o)) return false; return false; } /** * tests if object is a struct * @param o * @return is struct or not */ public static boolean isStruct(Object o) { if(o instanceof Struct) return true; else if(o instanceof Map)return true; else if(o instanceof Node)return true; return false; } /** * can this type be casted to a array * @param o * @return * @throws PageException */ public static boolean isCastableToArray(Object o) { if(isArray(o)) return true; else if(o instanceof XMLStruct) return true; else if(o instanceof Struct) { Struct sct=(Struct) o; Collection.Key[] keys=sct.keys(); try { for(int i=0;i<keys.length;i++) Caster.toIntValue(keys[i].toString()); return true; } catch (Exception e) { return false; } } return false; } /** * tests if object is a array * @param o * @return is array or not */ public static boolean isArray(Object o) { if(o instanceof Array) return true; if(o instanceof List) return true; if(isNativeArray(o)) return true; if(o instanceof ObjectWrap) { return isArray(((ObjectWrap)o).getEmbededObject(null)); } return false; } /** * tests if object is a native java array * @param o * @return is a native (java) array */ public static boolean isNativeArray(Object o) { //return o.getClass().isArray(); if(o instanceof Object[]) return true; else if(o instanceof boolean[]) return true; else if(o instanceof byte[]) return true; else if(o instanceof char[]) return true; else if(o instanceof short[]) return true; else if(o instanceof int[]) return true; else if(o instanceof long[]) return true; else if(o instanceof float[]) return true; else if(o instanceof double[]) return true; return false; } /** * tests if object is catable to a binary * @param object * @return boolean */ public static boolean isCastableToBinary(Object object,boolean checkBase64String) { if(isBinary(object))return true; if(object instanceof InputStream) return true; if(object instanceof ByteArrayOutputStream) return true; if(object instanceof Blob) return true; // Base64 String if(!checkBase64String) return false; String str = Caster.toString(object,null); if(str==null) return false; return Base64Util.isBase64(str); } /** * tests if object is a binary * @param object * @return boolean */ public static boolean isBinary(Object object) { if(object instanceof byte[]) return true; if(object instanceof ObjectWrap) return isBinary(((ObjectWrap)object).getEmbededObject("")); return false; } /** * tests if object is a Component * @param object * @return boolean */ public static boolean isComponent(Object object) { return object instanceof Component; } /** * tests if object is a Query * @param object * @return boolean */ public static boolean isQuery(Object object) { if(object instanceof Query)return true; else if(object instanceof ObjectWrap) { return isQuery(((ObjectWrap)object).getEmbededObject(null)); } return false; } /** * tests if object is a binary * @param object * @return boolean */ public static boolean isUserDefinedFunction(Object object) { return object instanceof UDF; } /** * tests if year is a leap year * @param year year to check * @return boolean */ public static final boolean isLeapYear(int year) { return DateTimeUtil.getInstance().isLeapYear(year); //return new GregorianCalendar().isLeapYear(year); } /** * tests if object is a WDDX Object * @param o Object to check * @return boolean */ public static boolean isWddx(Object o) { if(!(o instanceof String)) return false; String str=o.toString(); if(!(str.indexOf("wddxPacket")>0)) return false; // wrong timezone but this isent importend because date will not be used WDDXConverter converter =new WDDXConverter(TimeZone.getDefault(),false); try { converter.deserialize(Caster.toString(o),true); } catch (Exception e) { return false; } return true; } /** * tests if object is a XML Object * @param o Object to check * @return boolean */ public static boolean isXML(Object o) { if(o instanceof Node || o instanceof NodeList) return true; if(o instanceof ObjectWrap) { return isXML(((ObjectWrap)o).getEmbededObject(null)); } try { XMLCaster.toXMLStruct(XMLUtil.parse(XMLUtil.toInputSource(null, o),null,false),false); return true; } catch(Exception outer) { return false; } } public static boolean isVoid(Object o) { if(o==null)return true; else if(o instanceof String) return o.toString().length()==0; else if(o instanceof Number) return ((Number)o).intValue()==0; else if(o instanceof Boolean) return ((Boolean)o).booleanValue()==false ; else if(o instanceof ObjectWrap)return isVoid(((ObjectWrap)o).getEmbededObject(("isnotnull"))); return false; } /** * tests if object is a XML Element Object * @param o Object to check * @return boolean */ public static boolean isXMLElement(Object o) { return o instanceof Element; } /** * tests if object is a XML Document Object * @param o Object to check * @return boolean */ public static boolean isXMLDocument(Object o) { return o instanceof Document; } /** * tests if object is a XML Root Element Object * @param o Object to check * @return boolean */ public static boolean isXMLRootElement(Object o) { if(o instanceof Node) { Node n=(Node)o; if(n instanceof XMLStruct)n=((XMLStruct)n).toNode(); return n.getOwnerDocument()!=null && n.getOwnerDocument().getDocumentElement()==n; } return false; } /** * @param string * @return returns if string represent a variable name */ public static boolean isVariableName(Object obj) { if(obj instanceof String) return isVariableName((String)obj); return false; } /** * @param string * @return returns if string represent a variable name */ public static boolean isVariableName(String string) { if(string.length()==0)return false; int len=string.length(); int pos=0; while(pos<len) { char first=string.charAt(pos); if(!((first>='a' && first<='z')||(first>='A' && first<='Z')||(first=='_'))) return false; pos++; for(;pos<len;pos++) { char c=string.charAt(pos); if(!((c>='a' && c<='z')||(c>='A' && c<='Z')||(c>='0' && c<='9')||(c=='_'))) break; } if(pos==len) return true; if(string.charAt(pos)=='.')pos++; } return false; } /** * @param string * @return returns if string represent a variable name */ public static boolean isSimpleVariableName(String string) { if(string.length()==0)return false; char first=string.charAt(0); if(!((first>='a' && first<='z')||(first>='A' && first<='Z')||(first=='_'))) return false; for(int i=string.length()-1;i>0;i char c=string.charAt(i); if(!((c>='a' && c<='z')||(c>='A' && c<='Z')||(c>='0' && c<='9')||(c=='_'))) return false; } return true; } /** * @param string * @return returns if string represent a variable name */ public static boolean isSimpleVariableName(Collection.Key key) { String strKey = key.getLowerString(); if(strKey.length()==0)return false; char first=strKey.charAt(0); if(!((first>='a' && first<='z')||(first=='_'))) return false; for(int i=strKey.length()-1;i>0;i char c=strKey.charAt(i); if(!((c>='a' && c<='z')||(c>='0' && c<='9')||(c=='_'))) return false; } return true; } /** * returns if object is a cold fusion object * @param o Object to check * @return is or not */ public static boolean isObject(Object o) { return isComponent(o) || (!isArray(o) && !isQuery(o) && !isSimpleValue(o) && !isStruct(o) && !isUserDefinedFunction(o) && !isXML(o)); } /** * @param obj * @return return if a String is "Empty", that means NULL or String with length 0 (whitespaces will not counted) */ public static boolean isEmpty(Object obj) { if(obj instanceof String)return StringUtil.isEmpty((String)obj); return obj==null; } /** * @deprecated use instead <code>StringUtil.isEmpty(String)</code> * @param str * @return return if a String is "Empty", that means NULL or String with length 0 (whitespaces will not counted) */ public static boolean isEmpty(String str) { return StringUtil.isEmpty(str); } /** * @deprecated use instead <code>StringUtil.isEmpty(String)</code> * @param str * @param trim * @return return if a String is "Empty", that means NULL or String with length 0 (whitespaces will not counted) */ public static boolean isEmpty(String str, boolean trim) { return StringUtil.isEmpty(str,trim); } /** * returns if a value is a credit card * @param value * @return is credit card */ public static boolean isCreditCard(Object value) { return ValidateCreditCard.isValid(Caster.toString(value,"0")); } /** * returns if given object is a email * @param value * @return */ public static boolean isEmail(Object value) { String str = Caster.toString(value,null); if(str==null)return false; if(emailPattern==null) emailPattern=Pattern.compile("^[\\%\\+a-zA-Z_0-9-]+(\\.[\\%\\+a-zA-Z_0-9-]+)*@([a-zA-Z_0-9-]+\\.)+[a-zA-Z]{2,7}$"); return emailPattern.matcher(str).matches(); } /** * returns if given object is a social security number (usa) * @param value * @return */ public static boolean isSSN(Object value) { String str = Caster.toString(value,null); if(str==null)return false; if(ssnPattern==null) ssnPattern=Pattern.compile("^[0-9]{3}[-|]{1}[0-9]{2}[-|]{1}[0-9]{4}$"); return ssnPattern.matcher(str.trim()).matches(); } /** * returns if given object is a phone * @param value * @return */ public static boolean isPhone(Object value) { String str = Caster.toString(value,null); if(str==null)return false; if(phonePattern==null) phonePattern=Pattern.compile("^(\\+?1?[ \\-\\.]?([\\(]?([1-9][0-9]{2})[\\)]?))?[ ,\\-,\\.]?([^0-1]){1}([0-9]){2}[ ,\\-,\\.]?([0-9]){4}(( )((x){0,1}([0-9]){1,5}){0,1})?$"); return phonePattern.matcher(str.trim()).matches(); } /** * returns if given object is a URL * @param value * @return */ public static boolean isURL(Object value) { String str = Caster.toString(value,null); if(str==null)return false; if(urlPattern==null) urlPattern=Pattern.compile("^((http|https|ftp|file)\\:\\/\\/([a-zA-Z0-0]*:[a-zA-Z0-0]*(@))?[a-zA-Z0-9-\\.]+(\\.[a-zA-Z]{2,3})?(:[a-zA-Z0-9]*)?\\/?([a-zA-Z0-9-\\._\\? \\,\\'\\/\\+&amp;%\\$#\\=~])*)|((mailto)\\:[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+\\.)+[a-zA-Z0-9]{2,7})|((news)\\: [a-zA-Z0-9\\.]*)$"); return urlPattern.matcher(str.trim()).matches(); } /** * returns if given object is a zip code * @param value * @return */ public static boolean isZipCode(Object value) { String str = Caster.toString(value,null); if(str==null)return false; if(zipPattern==null) zipPattern=Pattern.compile("([0-9]{5,5})|([0-9]{5,5}[- ]{1}[0-9]{4,4})"); return zipPattern.matcher(str.trim()).matches(); } public static boolean isString(Object o) { if(o instanceof String) return true; else if(o instanceof Boolean) return true; else if(o instanceof Number) return true; else if(o instanceof Date) return true; else if(o instanceof Castable) { return ((Castable)o).castToString(STRING_DEFAULT_VALUE)!=STRING_DEFAULT_VALUE; } else if(o instanceof Clob) return true; else if(o instanceof Node) return true; else if(o instanceof Map || o instanceof List || o instanceof Function) return false; else if(o == null) return true; else if(o instanceof ObjectWrap) return isString(((ObjectWrap)o).getEmbededObject("")); return true; } public static boolean isCastableToString(Object o) { return isString(o); } public static boolean isValid(String type, Object value) throws ExpressionException { type=StringUtil.toLowerCase(type.trim()); char first = type.charAt(0); switch(first) { case 'a': if("any".equals(type)) return true; if("array".equals(type)) return isArray(value); break; case 'b': if("binary".equals(type)) return isBinary(value); if("boolean".equals(type)) return isBoolean(value,true); break; case 'c': if("creditcard".equals(type)) return isCreditCard(value); if("component".equals(type)) return isComponent(value); if("cfc".equals(type)) return isComponent(value); break; case 'd': if("date".equals(type)) return isDateAdvanced(value,true); // ist zwar nicht logisch aber ident. zu Neo if("double".equals(type)) return isCastableToNumeric(value); break; case 'e': if("eurodate".equals(type)) return isEuroDate(value); if("email".equals(type)) return isEmail(value); break; case 'f': if("float".equals(type)) return isNumeric(value,true); break; case 'g': if("guid".equals(type)) return isGUId(value); break; case 'i': if("integer".equals(type)) return isInteger(value,false); break; case 'n': if("numeric".equals(type)) return isCastableToNumeric(value); if("number".equals(type)) return isCastableToNumeric(value); if("node".equals(type)) return isXML(value); break; case 'p': if("phone".equals(type)) return isPhone(value); break; case 'q': if("query".equals(type)) return isQuery(value); break; case 's': if("simple".equals(type)) return isSimpleValue(value); if("struct".equals(type)) return isStruct(value); if("ssn".equals(type)) return isSSN(value); if("social_security_number".equals(type))return isSSN(value); if("string".equals(type)) return isString(value); break; case 't': if("telephone".equals(type)) return isPhone(value); if("time".equals(type)) return isDateAdvanced(value,false); break; case 'u': if("usdate".equals(type)) return isUSDate(value); if("uuid".equals(type)) return isUUId(value); if("url".equals(type)) return isURL(value); break; case 'v': if("variablename".equals(type)) return isVariableName(Caster.toString(value,"")); break; case 'x': if("xml".equals(type)) return isXML(value); // DIFF 23 break; case 'z': if("zip".equals(type)) return isZipCode(value); if("zipcode".equals(type)) return isZipCode(value); break; } throw new ExpressionException("invalid type ["+type+"], valid types are [any,array,binary,boolean,component,creditcard,date,time,email,eurodate,float,numeric,guid,integer,query,simple,ssn,string,struct,telephone,URL,UUID,USdate,variableName,zipcode]"); } public static boolean isCastableTo(String type, Object o, boolean alsoPattern) { type=StringUtil.toLowerCase(type).trim(); if(type.length()>2) { char first=type.charAt(0); switch(first) { case 'a': if(type.equals("any")) { return true; } else if(type.equals("array")) { return isCastableToArray(o); } break; case 'b': if(type.equals("boolean") || type.equals("bool")) { return isCastableToBoolean(o); } else if(type.equals("binary")) { return isCastableToBinary(o,true); } else if(type.equals("base64")) { return Caster.toBase64(o,null)!=null; } break; case 'c': if(alsoPattern && type.equals("creditcard")) { return Caster.toCreditCard(o,null)!=null; } break; case 'd': if(type.equals("date")) { return isDateAdvanced(o, true); } else if(type.equals("datetime")) { return isDateAdvanced(o, true); } else if(type.equals("double")) { return isCastableToNumeric(o); } else if(type.equals("decimal")) { return Caster.toDecimal(o,null)!=null; } break; case 'e': if(type.equals("eurodate")) { return isDateAdvanced(o, true); } else if(alsoPattern && type.equals("email")) { return Caster.toEmail(o,null)!= null; } break; case 'f': if(type.equals("float")) { return isCastableToNumeric(o); } break; case 'g': if(type.equals("guid")) { return isGUId(o); } break; case 'i': if(type.equals("integer") || type.equals("int")) { return isCastableToNumeric(o); } break; case 'l': if(type.equals("long")) { return isCastableToNumeric(o); } break; case 'n': if(type.equals("numeric")) { return isCastableToNumeric(o); } else if(type.equals("number")) { return isCastableToNumeric(o); } break; case 'o': if(type.equals("object")) { return true; } else if(type.equals("other")) { return true; } break; case 'p': if(alsoPattern && type.equals("phone")) { return Caster.toPhone(o,null)!=null; } break; case 'q': if(type.equals("query")) { return isQuery(o); } break; case 's': if(type.equals("string")) { return isCastableToString(o); } else if(type.equals("struct")) { return isCastableToStruct(o); } else if(type.equals("short")) { return isCastableToNumeric(o); } else if(alsoPattern && (type.equals("ssn") ||type.equals("social_security_number"))) { return Caster.toSSN(o,null)!=null; } break; case 't': if(type.equals("timespan")) { return Caster.toTimespan(o,null)!=null; } if(type.equals("time")) { return isDateAdvanced(o, true); } if(alsoPattern && type.equals("telephone")) { return Caster.toPhone(o,null)!=null; } case 'u': if(type.equals("uuid")) { return isUUId(o); } if(type.equals("usdate")) { return isDateAdvanced(o, true); //return DateCaster.toDate(o,pc.getTimeZone()); } if(alsoPattern && type.equals("url")) { return Caster.toURL(o,null)!=null; } break; case 'v': if(type.equals("variablename")) { return isVariableName(o); } else if(type.equals("void")) { return isVoid(o);//Caster.toVoid(o,Boolean.TRUE)!=Boolean.TRUE; } else if(type.equals("variable_name")) { return isVariableName(o); } else if(type.equals("variable-name")) { return isVariableName(o); } break; case 'x': if(type.equals("xml")) { return isXML(o); } break; case 'z': if(alsoPattern && (type.equals("zip") || type.equals("zipcode"))) { return Caster.toZip(o,null)!=null; } break; } } if(o instanceof Component) { Component comp=((Component)o); return comp.instanceOf(type); } if(isArrayType(type) && isArray(o)){ String t=type.substring(0,type.length()-2); Array arr = Caster.toArray(o,null); if(arr!=null){ Iterator it = arr.valueIterator(); while(it.hasNext()){ if(!isCastableTo(t, it.next(), alsoPattern)) return false; } return true; } } return false; } private static boolean isArrayType(String type) { return type.endsWith("[]"); } public static boolean isCastableTo(short type,String strType, Object o) { switch(type){ case CFTypes.TYPE_ANY: return true; case CFTypes.TYPE_STRING: return isCastableToString(o); case CFTypes.TYPE_BOOLEAN: return isCastableToBoolean(o); case CFTypes.TYPE_NUMERIC: return isCastableToNumeric(o); case CFTypes.TYPE_STRUCT: return isCastableToStruct(o); case CFTypes.TYPE_ARRAY: return isCastableToArray(o); case CFTypes.TYPE_QUERY: return isQuery(o); case CFTypes.TYPE_DATETIME: return isDateAdvanced(o, true); case CFTypes.TYPE_VOID: return isVoid(o);//Caster.toVoid(o,Boolean.TRUE)!=Boolean.TRUE; case CFTypes.TYPE_BINARY: return isCastableToBinary(o,true); case CFTypes.TYPE_TIMESPAN: return Caster.toTimespan(o,null)!=null; case CFTypes.TYPE_UUID: return isUUId(o); case CFTypes.TYPE_GUID: return isGUId(o); case CFTypes.TYPE_VARIABLE_NAME:return isVariableName(o); case CFTypes.TYPE_XML: return isXML(o); } if(o instanceof Component) { Component comp=((Component)o); return comp.instanceOf(strType); } if(isArrayType(strType) && isArray(o)){ String t=strType.substring(0,strType.length()-2); Array arr = Caster.toArray(o,null); if(arr!=null){ Iterator it = arr.valueIterator(); while(it.hasNext()){ if(!isCastableTo(type,t, it.next())) return false; } return true; } } return false; } public synchronized static boolean isDate(String str,Locale locale, TimeZone tz,boolean lenient) { str=str.trim(); tz=ThreadLocalPageContext.getTimeZone(tz); DateFormat[] df; // get Calendar Calendar c=JREDateTimeUtil.getCalendar(locale); // datetime df=FormatUtil.getDateTimeFormats(locale,false);//dfc[FORMATS_DATE_TIME]; for(int i=0;i<df.length;i++) { try { synchronized(c) { df[i].parse(str); return true; } } catch (ParseException e) {} } // date df=FormatUtil.getDateFormats(locale,false);//dfc[FORMATS_DATE]; for(int i=0;i<df.length;i++) { try { df[i].setTimeZone(tz); synchronized(c) { df[i].parse(str); return true; } } catch (ParseException e) {} } // time df=FormatUtil.getTimeFormats(locale,false);//dfc[FORMATS_TIME]; for(int i=0;i<df.length;i++) { try { df[i].setTimeZone(tz); synchronized(c) { df[i].parse(str); return true; } } catch (ParseException e) {} } if(lenient) return isDateSimple(str, false); return false; } /** * Checks if number is valid (not infinity or NaN) * @param dbl * @return */ public static boolean isValid(double dbl) { return !Double.isNaN(dbl) && !Double.isInfinite(dbl); } }
package railo.runtime.op; import java.io.IOException; import java.math.BigDecimal; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import railo.commons.date.DateTimeUtil; import railo.runtime.Component; import railo.runtime.exp.ExpressionException; import railo.runtime.exp.PageException; import railo.runtime.i18n.LocaleFactory; import railo.runtime.op.date.DateCaster; import railo.runtime.type.Collection; import railo.runtime.type.Collection.Key; import railo.runtime.type.dt.DateTime; import railo.runtime.type.dt.DateTimeImpl; import railo.runtime.type.wrap.ListAsArray; import railo.runtime.type.wrap.MapAsStruct; /** * class to compare objects and primitive value types * * */ public final class Operator { private static final Object NULL = new Object(); /** * compares two Objects * @param left * @param right * @return different of objects as int * @throws PageException */ public static int compare(Object left, Object right) throws PageException { //print.dumpStack(); if(left instanceof String) return compare((String)left,right); else if(left instanceof Number) return compare(((Number)left).doubleValue(),right); else if(left instanceof Boolean) return compare(((Boolean)left).booleanValue(),right); else if(left instanceof Date) return compare((Date)left ,right); else if(left instanceof Castable) return compare(((Castable)left) ,right); else if(left instanceof Locale) return compare(((Locale)left) ,right); else if(left==null) return compare("",right); /*/NICE disabled at the moment left Comparable else if(left instanceof Comparable) { return ((Comparable)left).compareTo(right); } */ else if(left instanceof Character) return compare( ((Character)left).toString() , right ); else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right ); else { return error(false,true); } } public static int compare(Locale left, Object right) throws PageException { if(right instanceof String) return compare(left,(String)right); else if(right instanceof Number) return compare(left,Caster.toString(right)); else if(right instanceof Boolean) return compare(left,Caster.toString(right)); else if(right instanceof Date) return compare(left,Caster.toString(right)); else if(right instanceof Castable) return compare(left,((Castable)right).castToString()); else if(right instanceof Locale) return left.toString().compareTo(right.toString()); else if(right==null) return compare( left, "" ); else if(right instanceof Character) return compare(left,((Character)right).toString()); else if(right instanceof Calendar) return compare(left, Caster.toString(((Calendar)right).getTime()) ); else return error(false,true); } public static int compare(Object left, Locale right) throws PageException { return -compare(right,left); } public static int compare(Locale left, String right) { Locale rightLocale = LocaleFactory.getLocale(right, null); if(rightLocale==null) return LocaleFactory.toString(left).compareTo(right); return left.toString().compareTo(rightLocale.toString()); } public static int compare(String left, Locale right) { return -compare(right,left); } /** * compares a Object with a String * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(Object left, String right) throws PageException { if(left instanceof String) return compare((String)left, right ); else if(left instanceof Number) return compare( ((Number)left).doubleValue() , right ); else if(left instanceof Boolean) return compare( ((Boolean)left).booleanValue(), right ); else if(left instanceof Date) return compare( (Date)left , right ); else if(left instanceof Castable) return ((Castable)left).compareTo(right ); else if(left instanceof Locale) return compare( (Locale)left , right ); else if(left==null) return "".compareToIgnoreCase(right); else if(left instanceof Character) return compare( ((Character)left).toString() , right ); else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right ); else return error(false,true); } /** * compares a String with a Object * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(String left, Object right) throws PageException { if(right instanceof String) return compare(left,(String)right); else if(right instanceof Number) return compare(left,((Number)right).doubleValue()); else if(right instanceof Boolean) return compare(left,((Boolean)right).booleanValue()?1:0); else if(right instanceof Date) return compare(left,(Date)right); else if(right instanceof Castable) return -((Castable)right).compareTo(left);//compare(left ,((Castable)right).castToString()); else if(right instanceof Locale) return compare(left ,(Locale)right); else if(right==null) return left.compareToIgnoreCase(""); else if(right instanceof Character) return compare(left ,((Character)right).toString()); else if(right instanceof Calendar) return compare(left, ((Calendar)right).getTime() ); else return error(false,true); } /** * compares a Object with a double * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(Object left, double right) throws PageException { if(left instanceof Number) return compare( ((Number)left).doubleValue() ,right ); else if(left instanceof String) return compare( (String)left, right ); else if(left instanceof Boolean) return compare( ((Boolean)left).booleanValue()?1D:0D , right ); else if(left instanceof Date) return compare( ((Date)left) ,right); else if(left instanceof Castable) return ((Castable)left).compareTo(right); //else if(left instanceof Castable) return compare(((Castable)left).castToDoubleValue() , right ); else if(left instanceof Locale) return compare( ((Locale)left), Caster.toString(right)); else if(left==null) return -1; else if(left instanceof Character) return compare(((Character)left).toString(),right); else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right ); else { return error(false,true); } } /** * compares a double with a Object * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(double left, Object right) throws PageException { if(right instanceof Number) return compare(left,((Number)right).doubleValue()); else if(right instanceof String) return compare(left,(String)right); else if(right instanceof Boolean) return compare(left,((Boolean)right).booleanValue()?1D:0D); else if(right instanceof Date) return compare(left,((Date)right)); else if(right instanceof Castable) return -((Castable)right).compareTo(left);//compare(left ,((Castable)right).castToDoubleValue()); else if(right instanceof Locale) return compare(Caster.toString(left) ,((Locale)right)); else if(right==null) return 1; else if(right instanceof Character) return compare(left ,((Character)right).toString()); else if(right instanceof Calendar) return compare(left, ((Calendar)right).getTime() ); else return error(true,false); } /** * compares a Object with a boolean * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(Object left, boolean right) throws PageException { if(left instanceof Boolean) return compare(((Boolean)left).booleanValue(),right); else if(left instanceof String) return compare((String)left,right); else if(left instanceof Number) return compare(((Number)left).doubleValue(),right?1D:0D); else if(left instanceof Date) return compare(((Date)left),right?1:0); else if(left instanceof Castable) return ((Castable)left).compareTo(right ); else if(left instanceof Locale) return compare(((Locale)left),Caster.toString(right)); else if(left==null) return -1; else if(left instanceof Character) return compare(((Character)left).toString(),right); else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right?1:0 ); else return error(false,true); } /** * compares a boolean with a Object * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(boolean left, Object right) throws PageException { if(right instanceof Boolean) return compare(left,((Boolean)right).booleanValue()); else if(right instanceof String) return compare(left?1:0,(String)right); else if(right instanceof Number) return compare(left?1D:0D,((Number)right).doubleValue()); else if(right instanceof Date) return compare(left?1:0,((Date)right)); else if(right instanceof Castable) return -((Castable)right).compareTo(left);//compare(left ,((Castable)right).castToBooleanValue()); else if(right instanceof Locale) return compare(Caster.toString(left),((Locale)right)); else if(right==null) return 1; else if(right instanceof Character) return compare(left ,((Character)right).toString()); else if(right instanceof Calendar) return compare(left?1:0, ((Calendar)right).getTime() ); else return error(true,false); } /** * compares a Object with a Date * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(Object left, Date right) throws PageException { if(left instanceof String) return compare((String)left,right); else if(left instanceof Number) return compare(((Number)left).doubleValue() ,right.getTime()/1000 ); else if(left instanceof Boolean) return compare( ((Boolean)left).booleanValue()?1D:0D , right.getTime()/1000 ); else if(left instanceof Date) return compare( ((Date)left) , right ); else if(left instanceof Castable) return ((Castable)left).compareTo(Caster.toDatetime(right,null) ); else if(left instanceof Locale) return compare( ((Locale)left) , Caster.toString(right)); else if(left==null) return compare("", right); else if(left instanceof Character) return compare(((Character)left).toString(),right); else if(left instanceof Calendar) return compare( ((Calendar)left).getTime() , right ); else return error(false,true); } /** * compares a Date with a Object * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(Date left, Object right) throws PageException { if(right instanceof String) return compare(left,(String)right); else if(right instanceof Number) return compare(left.getTime()/1000,((Number)right).doubleValue()); else if(right instanceof Boolean) return compare(left.getTime()/1000,((Boolean)right).booleanValue()?1D:0D); else if(right instanceof Date) return compare(left.getTime()/1000,((Date)right).getTime()/1000); else if(right instanceof Castable) return -((Castable)right).compareTo(Caster.toDate(left,null));//compare(left ,(Date)((Castable)right).castToDateTime()); else if(right instanceof Locale) return compare(Caster.toString(left),(Locale)right); else if(right==null) return compare(left,""); else if(right instanceof Character) return compare(left ,((Character)right).toString()); else if(right instanceof Calendar) return compare(left.getTime()/1000, ((Calendar)right).getTime().getTime()/1000 ); else return error(true,false); } public static int compare(Castable left, Object right) throws PageException { if(right instanceof String) return left.compareTo((String)right); else if(right instanceof Number) return left.compareTo(((Number)right).doubleValue()); else if(right instanceof Boolean) return left.compareTo(((Boolean)right).booleanValue()?1d:0d); else if(right instanceof Date) return left.compareTo(Caster.toDate(right,null)); else if(right instanceof Castable) return compare(left.castToString() , ((Castable)right).castToString() ); else if(right instanceof Locale) return compare(left.castToString() , (Locale)right); else if(right == null) return compare(left.castToString(), "" ); else if(right instanceof Character) return left.compareTo(((Character)right).toString()); else if(right instanceof Calendar) return left.compareTo(new DateTimeImpl(((Calendar)right).getTime()) ); else return error(true,false); } public static int compare(Object left, Castable right) throws PageException { return -compare(right,left); } /** * compares a String with a String * @param left * @param right * @return difference as int */ public static int compare(String left, String right) { if(Decision.isNumeric(left)) { if(Decision.isNumeric(right)){ // long numbers if(left.length()>9 || right.length()>9) { try{ return new BigDecimal(left).compareTo(new BigDecimal(right)); } catch(Throwable t){} } return compare(Caster.toDoubleValue(left,Double.NaN),Caster.toDoubleValue(right,Double.NaN)); } return compare(Caster.toDoubleValue(left,Double.NaN),right); } if(Decision.isBoolean(left)) return compare(Caster.toBooleanValue(left,false)?1D:0D,right); // NICE Date compare, perhaps datetime to double return left.compareToIgnoreCase(right); } /** * compares a String with a double * @param left * @param right * @return difference as int */ public static int compare(String left, double right) { if(Decision.isNumeric(left)) { if(left.length()>9) { try{ return new BigDecimal(left).compareTo(new BigDecimal(right)); } catch(Throwable t){} } return compare(Caster.toDoubleValue(left,Double.NaN),right); } if(Decision.isBoolean(left)) return compare(Caster.toBooleanValue(left,false),right); if(left.length()==0) return -1; char leftFirst=left.charAt(0); if(leftFirst>='0' && leftFirst<='9') return left.compareToIgnoreCase(Caster.toString(right)); return leftFirst-'0'; } /** * compares a String with a boolean * @param left * @param right * @return difference as int */ public static int compare(String left, boolean right) { if(Decision.isBoolean(left)) return compare(Caster.toBooleanValue(left,false),right); if(Decision.isNumeric(left)) return compare(Caster.toDoubleValue(left,Double.NaN),right?1d:0d); if(left.length()==0) return -1; char leftFirst=left.charAt(0); //print.ln(left+".compareTo("+Caster.toString(right)+")"); //p(left); if(leftFirst>='0' && leftFirst<='9') return left.compareToIgnoreCase(Caster.toString(right?1D:0D)); return leftFirst-'0'; } /** * compares a String with a Date * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(String left, Date right) throws PageException { return -compare(right,left); } /** * compares a double with a String * @param left * @param right * @return difference as int */ public static int compare(double left, String right) { return -compare(right,left); } /** * compares a double with a double * @param left * @param right * @return difference as int */ public static int compare(double left, double right) { if((left)<(right))return -1; else if((left)>(right))return 1; else return 0; } /** * compares a double with a boolean * @param left * @param right * @return difference as int */ public static int compare(double left, boolean right) { return compare(left,right?1d:0d); } /** * compares a double with a Date * @param left * @param right * @return difference as int */ public static int compare(double left, Date right) { return compare(DateTimeUtil.getInstance().toDateTime(left).getTime()/1000,right.getTime()/1000); } /** * compares a boolean with a double * @param left * @param right * @return difference as int */ public static int compare(boolean left, double right) { return compare(left?1d:0d, right); } /** * compares a boolean with a double * @param left * @param right * @return difference as int */ public static int compare(boolean left, String right) { return -compare(right,left); } /** * compares a boolean with a boolean * @param left * @param right * @return difference as int */ public static int compare(boolean left, boolean right) { if(left)return right?0:1; return right?-1:0; } /** * compares a boolean with a Date * @param left * @param right * @return difference as int */ public static int compare(boolean left, Date right) { return compare(left?1D:0D,right); } /** * compares a Date with a String * @param left * @param right * @return difference as int * @throws PageException */ public static int compare(Date left, String right) throws PageException { if(Decision.isNumeric(right)) return compare(left.getTime()/1000,Caster.toDoubleValue(right)); DateTime dt=DateCaster.toDateAdvanced(right,true,null,null); if(dt!=null) { return compare(left.getTime()/1000,dt.getTime()/1000); } return Caster.toString(left).compareToIgnoreCase(right); } /** * compares a Date with a double * @param left * @param right * @return difference as int */ public static int compare(Date left, double right) { return compare(left.getTime()/1000, DateTimeUtil.getInstance().toDateTime(right).getTime()/1000); } /** * compares a Date with a boolean * @param left * @param right * @return difference as int */ public static int compare(Date left, boolean right) { return compare(left,right?1D:0D); } /** * compares a Date with a Date * @param left * @param right * @return difference as int */ public static int compare(Date left, Date right) { return compare(left.getTime()/1000,right.getTime()/1000); } private static int error(boolean leftIsOk, boolean rightIsOk) throws ExpressionException { // TODO remove this method throw new ExpressionException("can't compare complex object types as simple value"); } /** * Method to compare to different values, return true of objects are same otherwise false * @param left left value to compare * @param right right value to compare * @param caseSensitive check case sensitive or not * @return is same or not * @throws PageException */ public static boolean equals(Object left, Object right, boolean caseSensitive) throws PageException { if(caseSensitive) { try { return Caster.toString(left).equals(Caster.toString(right)); } catch (ExpressionException e) { return compare(left,right)==0; } } return compare(left,right)==0; } public static boolean equalsEL(Object left, Object right, boolean caseSensitive, boolean allowComplexValues) { if(!allowComplexValues || (Decision.isSimpleValue(left) && Decision.isSimpleValue(right))){ try { return equals(left, right, caseSensitive); } catch (PageException e) { return false; } } return equalsComplexEL(left, right, caseSensitive,false); } public static boolean equalsComplexEL(Object left, Object right, boolean caseSensitive, boolean checkOnlyPublicAppearance) { return _equalsComplexEL(null,left, right, caseSensitive,checkOnlyPublicAppearance); } public static boolean _equalsComplexEL(Set<Object> done,Object left, Object right, boolean caseSensitive, boolean checkOnlyPublicAppearance) { if(left==right) return true; if(Decision.isSimpleValue(left) && Decision.isSimpleValue(right)){ try { return equals(left, right, caseSensitive); } catch (PageException e) { return false; } } if(left==null) return right==null; if(done==null)done=new HashSet<Object>(); else if(done.contains(left) && done.contains(right)) return true; done.add(left); done.add(right); if(left instanceof Component && right instanceof Component) return __equalsComplexEL(done,(Component)left, (Component)right,caseSensitive,checkOnlyPublicAppearance); if(left instanceof Collection && right instanceof Collection) return __equalsComplexEL(done,(Collection)left, (Collection)right,caseSensitive,checkOnlyPublicAppearance); if(left instanceof List && right instanceof List) return __equalsComplexEL(done,ListAsArray.toArray((List)left), ListAsArray.toArray((List)right),caseSensitive,checkOnlyPublicAppearance); if(left instanceof Map && right instanceof Map) return __equalsComplexEL(done,MapAsStruct.toStruct((Map)left,true), MapAsStruct.toStruct((Map)right,true),caseSensitive,checkOnlyPublicAppearance); return left.equals(right); } private static boolean __equalsComplexEL(Set<Object> done,Component left, Component right,boolean caseSensitive, boolean checkOnlyPublicAppearance) { if(left==null || right==null) { if(left==right) return true; return false; } if(!left.getPageSource().equals(right.getPageSource())) return false; if(!checkOnlyPublicAppearance && !__equalsComplexEL(done,left.getComponentScope(),right.getComponentScope(), caseSensitive,checkOnlyPublicAppearance)) return false; if(!__equalsComplexEL(done,(Collection)left,(Collection)right, caseSensitive,checkOnlyPublicAppearance)) return false; return true; } private static boolean __equalsComplexEL(Set<Object> done,Collection left, Collection right,boolean caseSensitive, boolean checkOnlyPublicAppearance) { if(left.size()!=right.size()) return false; Iterator<Key> it = left.keyIterator(); Key k; Object l,r; while(it.hasNext()){ k=it.next(); l=left.get(k,NULL); r=right.get(k,NULL); if(l==NULL || r==NULL) { if(l==r) continue; return false; } if(!_equalsComplexEL(done,r, l, caseSensitive,checkOnlyPublicAppearance)) { return false; } } return true; } public static boolean equals(Object left, Object right, boolean caseSensitive, boolean allowComplexValues) throws PageException { if(!allowComplexValues || (Decision.isSimpleValue(left) && Decision.isSimpleValue(right))) return equals(left, right, caseSensitive); return equalsComplex(left, right, caseSensitive); } public static boolean equalsComplex(Object left, Object right, boolean caseSensitive) throws PageException { return _equalsComplex(null,left, right, caseSensitive); } public static boolean _equalsComplex(Set<Object> done,Object left, Object right, boolean caseSensitive) throws PageException { if(Decision.isSimpleValue(left) && Decision.isSimpleValue(right)){ return equals(left, right, caseSensitive); } if(left==null) return right==null; if(done==null)done=new HashSet<Object>(); else if(done.contains(left) && done.contains(right)) return true; done.add(left); done.add(right); if(left instanceof Collection && right instanceof Collection) return __equalsComplex(done,(Collection)left, (Collection)right,caseSensitive); if(left instanceof List && right instanceof List) return __equalsComplex(done,ListAsArray.toArray((List)left), ListAsArray.toArray((List)right),caseSensitive); if(left instanceof Map && right instanceof Map) return __equalsComplex(done,MapAsStruct.toStruct((Map)left,true), MapAsStruct.toStruct((Map)right,true),caseSensitive); return left.equals(right); } private static boolean __equalsComplex(Set<Object> done,Collection left, Collection right,boolean caseSensitive) throws PageException { if(left.size()!=right.size()) return false; Iterator<Key> it = left.keyIterator(); Key k; Object l,r; while(it.hasNext()){ k=it.next(); r=right.get(k,NULL); if(r==NULL) return false; l=left.get(k,NULL); if(!_equalsComplex(done,r, l, caseSensitive)) return false; } return true; } /** * check if left is inside right (String-> ignore case) * @param left string to check * @param right substring to find in string * @return return if substring has been found * @throws PageException */ public static boolean ct(Object left, Object right) throws PageException { return Caster.toString(left).toLowerCase().indexOf(Caster.toString(right).toLowerCase())!=-1; } /** * Equivalence: Return True if both operands are True or both are False. The EQV operator is the opposite of the XOR operator. For example, True EQV True is True, but True EQV False is False. * @param left value to check * @param right value to check * @return result of operation * @throws PageException */ public static boolean eqv(Object left, Object right) throws PageException { return eqv(Caster.toBooleanValue(left),Caster.toBooleanValue(right)); } /** * Equivalence: Return True if both operands are True or both are False. The EQV operator is the opposite of the XOR operator. For example, True EQV True is True, but True EQV False is False. * @param left value to check * @param right value to check * @return result of operation */ public static boolean eqv(boolean left, boolean right) { return (left==true && right==true) || (left==false && right==false); } /** * Implication: The statement A IMP B is the equivalent of the logical statement * "If A Then B." A IMP B is False only if A is True and B is False. It is True in all other cases. * @param left value to check * @param right value to check * @return result * @throws PageException */ public static boolean imp(Object left, Object right) throws PageException { return imp(Caster.toBooleanValue(left),Caster.toBooleanValue(right)); } /** * Implication: The statement A IMP B is the equivalent of the logical statement * "If A Then B." A IMP B is False only if A is True and B is False. It is True in all other cases. * @param left value to check * @param right value to check * @return result */ public static boolean imp(boolean left, boolean right) { return !(left==true && right==false); } /** * check if left is not inside right (String-> ignore case) * @param left string to check * @param right substring to find in string * @return return if substring NOT has been found * @throws PageException */ public static boolean nct(Object left, Object right) throws PageException { return !ct(left,right); } /** * simple reference compersion * @param left * @param right * @return * @throws PageException */ public static boolean eeq(Object left, Object right) throws PageException { return left==right; } /** * simple reference compersion * @param left * @param right * @return * @throws PageException */ public static boolean neeq(Object left, Object right) throws PageException { return left!=right; } /** * calculate the exponent of the left value * @param left value to get exponent from * @param right exponent count * @return return expoinended value * @throws PageException */ public static double exponent(Object left, Object right) throws PageException { return StrictMath.pow(Caster.toDoubleValue(left),Caster.toDoubleValue(right)); } public static double exponent(double left, double right) { return StrictMath.pow(left,right); } public static double intdiv(double left, double right) { return ((int)left)/((int)right); } public static double div(double left, double right) { if(right==0d) throw new ArithmeticException("Division by zero is not possible"); return left/right; } public static float exponent(float left, float right) { return (float) StrictMath.pow(left,right); } /** * concat 2 CharSequences * @param left * @param right * @return concated String */ public static CharSequence concat(CharSequence left, CharSequence right) { if(left instanceof Appendable) { try { ((Appendable)left).append(right); return left; } catch (IOException e) {} } return new StringBuilder(left).append(right); } /** * plus operation * @param left * @param right * @return result of the opertions */ public final static double plus(double left, double right) { return left+right; } /** * minus operation * @param left * @param right * @return result of the opertions */ public static double minus(double left, double right) { return left-right; } /** * modulus operation * @param left * @param right * @return result of the opertions */ public static double modulus(double left, double right) { return left%right; } /** * divide operation * @param left * @param right * @return result of the opertions */ public static double divide(double left, double right) { return left/right; } /** * multiply operation * @param left * @param right * @return result of the opertions */ public static double multiply(double left, double right) { return left*right; } /** * bitand operation * @param left * @param right * @return result of the opertions */ public static double bitand(double left, double right) { return (int)left&(int)right; } /** * bitand operation * @param left * @param right * @return result of the opertions */ public static double bitor(double left, double right) { return (int)left|(int)right; } public static Double divRef(Object left, Object right) throws PageException { double r = Caster.toDoubleValue(right); if(r==0d) throw new ArithmeticException("Division by zero is not possible"); return Caster.toDouble(Caster.toDoubleValue(left)/r); } public static Double exponentRef(Object left, Object right) throws PageException { return Caster.toDouble(StrictMath.pow(Caster.toDoubleValue(left),Caster.toDoubleValue(right))); } public static Double intdivRef(Object left, Object right) throws PageException { return Caster.toDouble(Caster.toIntValue(left)/Caster.toIntValue(right)); } public static Double plusRef(Object left, Object right) throws PageException { return Caster.toDouble(Caster.toDoubleValue(left)+Caster.toDoubleValue(right)); } public static Double minusRef(Object left, Object right) throws PageException { return Caster.toDouble(Caster.toDoubleValue(left)-Caster.toDoubleValue(right)); } public static Double modulusRef(Object left, Object right) throws PageException { return Caster.toDouble(Caster.toDoubleValue(left)%Caster.toDoubleValue(right)); } public static Double divideRef(Object left, Object right) throws PageException { return Caster.toDouble(Caster.toDoubleValue(left)/Caster.toDoubleValue(right)); } public static Double multiplyRef(Object left, Object right) throws PageException { return Caster.toDouble(Caster.toDoubleValue(left)*Caster.toDoubleValue(right)); } }
/** * The main GUI for the project. * * @author Julia McClellan, Luke Giacalone, Hyun Choi * @version 05/18/2016 */ import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.nimbus.NimbusLookAndFeel; public class GUI extends JFrame { private ArrayList<Inventory> inventories; private Inventory selected; private JPanel display, options; /** * Constructs the GUI for the given inventories. * * @param i The inventories in the program. */ public GUI(ArrayList<Inventory> i) { try { UIManager.setLookAndFeel(new NimbusLookAndFeel()); } catch(Throwable e){} addMenu(); inventories = i; JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridy = 0; c.anchor = GridBagConstraints.NORTHWEST; options = new JPanel(); panel.add(options, c); c.gridy++; display = new JPanel(); panel.add(display, c); if(inventories != null && inventories.size() != 0) { for(Inventory inventory: inventories) { options.add(new InventoryButton(inventory)); } updateSelected(inventories.get(0)); } add(panel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); this.setResizable(false); } /** * Replaces the inventory in the central panel with the new inventory. * * @param i The inventory to display. */ private void updateSelected(Inventory i) { display.setVisible(false); selected = i; display.removeAll(); display.add(i.getGUI()); display.setVisible(true); } private void addMenu() { JMenuBar menu = new JMenuBar(); JMenu file = new JMenu("File"); JMenu newMenu = new JMenu("New"); JMenuItem inventory = new JMenuItem("Inventory"); inventory.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); newMenu.add(inventory); newMenu.add(new JMenuItem("Item")); file.add(newMenu); file.add(new JMenuItem("Export")); file.add(new JMenuItem("Print")); menu.add(file); JMenu edit = new JMenu("Edit"); JMenuItem undo = new JMenuItem("Undo"); undo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(Operation.canUndo()) Operation.undoLast(); } }); edit.add(undo); JMenuItem redo = new JMenuItem("Redo"); redo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(Operation.canRedo()) Operation.redoLast(); } }); edit.add(redo); menu.add(edit); this.setJMenuBar(menu); } /** * A button for the menu bar to select an inventory. */ private class InventoryButton extends JPanel { private Inventory inventory; /** * Constructs the panel. * * @param i The inventory to be selected with this panel. */ public InventoryButton(Inventory i) { inventory = i; setBorder(BorderFactory.createCompoundBorder(new LineBorder(Color.BLACK, 1, true), new EmptyBorder(2, 2, 2, 2))); setBackground(Color.WHITE); add(new JLabel(i.getName())); addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent arg0) { updateSelected(inventory); } public void mouseEntered(MouseEvent arg0) { setBackground(Color.LIGHT_GRAY); } public void mouseExited(MouseEvent arg0) { setBackground(Color.WHITE); } public void mousePressed(MouseEvent arg0){} public void mouseReleased(MouseEvent arg0){} }); } } }
package com.allenbarr.MockTrialTabulation; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TextField; import javafx.scene.input.KeyCombination; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Modality; import javafx.stage.Stage; /** * * @author captainbowtie */ public class MockTrialTabulation extends Application { final private MenuBar menuBar = new MenuBar(); final private Menu fileMenu = new Menu("File"); final private MenuItem save = new MenuItem("Save..."); final private MenuItem saveToServer = new MenuItem("Save to Server..."); final private MenuItem open = new MenuItem("Open..."); final private MenuItem openFromServer = new MenuItem("Open from Server..."); private Tournament tournament = new Tournament(); final private Stage primaryStage = new Stage(); private boolean firstPDChange = true; @Override public void start(Stage primaryStage) { displayTeamNumberPrompt(); fileMenu.getItems().add(open); fileMenu.getItems().add(openFromServer); fileMenu.getItems().add(new SeparatorMenuItem()); fileMenu.getItems().add(save); fileMenu.getItems().add(saveToServer); menuBar.getMenus().add(fileMenu); menuBar.setUseSystemMenuBar(true); open.setOnAction(e -> { loadTournament(); }); open.setAccelerator(KeyCombination.keyCombination("Meta+O")); openFromServer.setOnAction(e-> { loadTournamentFromServer(); }); save.setOnAction(e -> { saveTournament(); }); save.setAccelerator(KeyCombination.keyCombination("Meta+S")); save.setDisable(true); saveToServer.setOnAction(e -> { saveTournamentToServer(); }); saveToServer.setDisable(true); } private void displayTeamNumberPrompt() { primaryStage.setTitle("Mock Trial Tabulation"); GridPane grid = new GridPane(); Label numberPrompt = new Label("Number of teams:"); grid.add(numberPrompt, 0, 1); TextField numberOfTeams = new TextField(); numberOfTeams.setPrefColumnCount(2); grid.add(numberOfTeams, 1, 1); Button btn = new Button("Okay"); btn.setOnAction((ActionEvent e) -> { if (!isInteger(numberOfTeams.getText())) { Alert notANumber = new Alert(AlertType.ERROR); notANumber.setContentText("The text entered for the number of " + "teams is not a valid number. " + "Please enter a valid number."); notANumber.showAndWait(); } else if (Integer.parseInt(numberOfTeams.getText()) < 8) { Alert notEnoughTeams = new Alert(AlertType.ERROR); notEnoughTeams.setContentText("You need at least eight teams at" + "your tournament to use this program."); notEnoughTeams.showAndWait(); }else if(Integer.parseInt(numberOfTeams.getText())%2!=0){ Alert oddNumberTeams = new Alert(AlertType.ERROR); oddNumberTeams.setContentText("You need an even number of teams at" + " a mock trial tournament."); oddNumberTeams.showAndWait(); } else{ displayTeamDataPrompt(Integer.parseInt(numberOfTeams.getText())); } }); grid.add(btn, 1, 4); VBox vbox = new VBox(); vbox.getChildren().add(menuBar); vbox.getChildren().add(grid); Scene scene = new Scene(vbox); scene.getStylesheets().add(MockTrialTabulation.class.getResource("MockTrialTabulation.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } private void displayTeamDataPrompt(int numberOfTeams) { GridPane grid = new GridPane(); Label teamNumberLabel = new Label("Team Number:"); grid.add(teamNumberLabel, 0, 0); TextField teamNumberField = new TextField(); teamNumberField.setPrefColumnCount(4); grid.add(teamNumberField, 1, 0); Label teamNameLabel = new Label("Team Name:"); grid.add(teamNameLabel, 0, 1); TextField teamNameField = new TextField(); teamNameField.setPrefColumnCount(12); grid.add(teamNameField, 1, 1); CheckBox isByeTeam = new CheckBox("This team is the bye-team"); grid.add(isByeTeam, 0, 2); Button addImpermissibleButton = new Button("Add Impermissible Match..."); addImpermissibleButton.setOnAction(e -> { int numRows = getRowCount(grid); GridPane.setRowIndex(grid.getChildren().get(6), numRows); GridPane.setRowIndex(grid.getChildren().get(5), numRows - 1); Button deleteImpermissibleButton = new Button("X"); deleteImpermissibleButton.setOnAction(ev -> { for (int a = grid.getChildren().indexOf(ev.getSource()); a <= grid.getChildren().size(); a = a + 3) { if (a + 1 != grid.getChildren().size()) { TextField lowerTextField = (TextField) grid.getChildren().get(a + 2); String impermissibleTeamNumber = lowerTextField.getText(); TextField upperTextField = (TextField) grid.getChildren().get(a - 1); upperTextField.setText(impermissibleTeamNumber); } else { int numRowsDelete = getRowCount(grid); grid.getChildren().remove(a); grid.getChildren().remove(a - 1); grid.getChildren().remove(a - 2); GridPane.setRowIndex(grid.getChildren().get(6), numRowsDelete - 2); GridPane.setRowIndex(grid.getChildren().get(5), numRowsDelete - 3); primaryStage.sizeToScene(); } } }); deleteImpermissibleButton.setId("deleteImpermissibleButton"); grid.add(new Label("Impermissible Match " + (numRows - 4) + ":"), 0, numRows - 2); grid.add(new TextField(), 1, numRows - 2); grid.add(deleteImpermissibleButton, 2, numRows - 2); primaryStage.sizeToScene(); }); grid.add(addImpermissibleButton, 0, 3); Button okayButton = new Button("Next Team"); okayButton.setOnAction((ActionEvent e) -> { if (!isInteger(teamNumberField.getText())) { Alert notANumber = new Alert(AlertType.ERROR); notANumber.setContentText("The text entered for the team number" + " is not a valid team number. " + "Please enter a valid team number."); notANumber.showAndWait(); } else { int impermissibleMatchesAllNumbers = 0; int rowCount = getRowCount(grid); final ArrayList<Integer> impermissibleMatches = new ArrayList<>(); for (int a = 0; a < rowCount - 5; a++) { if (!isInteger(((TextField) grid.getChildren().get(a * 3 + 8)).getText())) { impermissibleMatchesAllNumbers = a + 1; } else { impermissibleMatches.add(Integer.parseInt(((TextField) grid.getChildren().get(a * 3 + 8)).getText())); } } if (impermissibleMatchesAllNumbers != 0) { Alert notANumber = new Alert(AlertType.ERROR); notANumber.setContentText("The text entered for impermissible" + " match " + (impermissibleMatchesAllNumbers) + " is " + "not a valid team number. " + "Please enter a valid team number."); notANumber.showAndWait(); } else { tournament.addTeam(Integer.parseInt(teamNumberField.getText()), teamNameField.getText(), impermissibleMatches, isByeTeam.isSelected()); if (tournament.getTeams().size() == numberOfTeams) { displayTabulationWindow(); } else { for (int i = grid.getChildren().size() - 1; i > 6; i grid.getChildren().remove(i); } teamNumberField.setText(""); teamNameField.setText(""); isByeTeam.setSelected(false); GridPane.setRowIndex(grid.getChildren().get(6), 4); GridPane.setRowIndex(grid.getChildren().get(5), 3); } if (tournament.getTeams().size() == numberOfTeams - 1) { okayButton.setText("Continue"); } } } }); grid.add(okayButton, 1, 4); primaryStage.getScene().setRoot(grid); primaryStage.sizeToScene(); } private void displayTabulationWindow() { save.setDisable(false); saveToServer.setDisable(false); final Button[] teamNumberButtons = new Button[tournament.getTeams().size()]; final Label[] teamNameLabels = new Label[tournament.getTeams().size()]; final Label[][] teamSideLabels = new Label[tournament.getTeams().size()][4]; final Label[][] teamOpponentLabels = new Label[tournament.getTeams().size()][4]; final TextField[][] teamPDFields = new TextField[tournament.getTeams().size()][8]; final Label[] teamRecordLabels = new Label[tournament.getTeams().size()]; final Label[] teamCSLabels = new Label[tournament.getTeams().size()]; final Label[] teamPDLabels = new Label[tournament.getTeams().size()]; GridPane grid = new GridPane(); for (int a = 0; a < tournament.getTeams().size(); a++) { teamNumberButtons[a] = new Button(Integer.toString(tournament.getTeam(a).getTeamNumber())); teamNameLabels[a] = new Label(tournament.getTeam(a).getTeamName()); for (int b = 0; b < 4; b++) { teamSideLabels[a][b] = new Label(); teamOpponentLabels[a][b] = new Label(); teamPDFields[a][b] = new TextField(); teamPDFields[a][b + 4] = new TextField(); teamPDFields[a][b].setPrefColumnCount(2); teamPDFields[a][b + 4].setPrefColumnCount(2); } if (tournament.getTeam(a).isRound1Plaintiff()) { teamSideLabels[a][0].setText("π vs."); teamSideLabels[a][1].setText("∆ vs."); } else { teamSideLabels[a][0].setText("∆ vs."); teamSideLabels[a][1].setText("π vs."); } if (tournament.getTeam(a).isRound3Plaintiff()) { teamSideLabels[a][2].setText("π vs."); teamSideLabels[a][3].setText("∆ vs."); } else { teamSideLabels[a][2].setText("∆ vs."); teamSideLabels[a][3].setText("π vs."); } teamOpponentLabels[a][0].setText(Integer.toString(tournament.getTeam(a).getRound1Opponent())); teamOpponentLabels[a][1].setText(Integer.toString(tournament.getTeam(a).getRound2Opponent())); teamOpponentLabels[a][2].setText(Integer.toString(tournament.getTeam(a).getRound3Opponent())); teamOpponentLabels[a][3].setText(Integer.toString(tournament.getTeam(a).getRound4Opponent())); teamPDFields[a][0].setText(Integer.toString(tournament.getTeam(a).getRound1Ballot1PD())); teamPDFields[a][1].setText(Integer.toString(tournament.getTeam(a).getRound1Ballot2PD())); teamPDFields[a][2].setText(Integer.toString(tournament.getTeam(a).getRound2Ballot1PD())); teamPDFields[a][3].setText(Integer.toString(tournament.getTeam(a).getRound2Ballot2PD())); teamPDFields[a][4].setText(Integer.toString(tournament.getTeam(a).getRound3Ballot1PD())); teamPDFields[a][5].setText(Integer.toString(tournament.getTeam(a).getRound3Ballot2PD())); teamPDFields[a][6].setText(Integer.toString(tournament.getTeam(a).getRound4Ballot1PD())); teamPDFields[a][7].setText(Integer.toString(tournament.getTeam(a).getRound4Ballot2PD())); for (int b = 0; b < 8; b++) { teamPDFields[a][b].textProperty().addListener((observable, oldValue, newValue) -> { if (firstPDChange) { firstPDChange = false; for (int c = 0; c < tournament.getTeams().size(); c++) { for (int d = 0; d < 8; d++) { if (teamPDFields[c][d].textProperty().equals(observable)) { if (isInteger(newValue) && Integer.parseInt(newValue) < 141 && Integer.parseInt(newValue) > -141) { int opponentIndex = 0; switch (d) { case 0: tournament.getTeam(c).setRound1Ballot1PD(Integer.parseInt(newValue)); opponentIndex = tournament.getTeamIndex(tournament.getTeam(c).getRound1Opponent()); teamPDFields[opponentIndex][d].setText(Integer.toString(-1 * Integer.parseInt(newValue))); tournament.getTeam(opponentIndex).setRound1Ballot1PD(-1 * Integer.parseInt(newValue)); break; case 1: tournament.getTeam(c).setRound1Ballot2PD(Integer.parseInt(newValue)); opponentIndex = tournament.getTeamIndex(tournament.getTeam(c).getRound1Opponent()); teamPDFields[opponentIndex][d].setText(Integer.toString(-1 * Integer.parseInt(newValue))); tournament.getTeam(opponentIndex).setRound1Ballot2PD(-1 * Integer.parseInt(newValue)); break; case 2: tournament.getTeam(c).setRound2Ballot1PD(Integer.parseInt(newValue)); opponentIndex = tournament.getTeamIndex(tournament.getTeam(c).getRound2Opponent()); teamPDFields[opponentIndex][d].setText(Integer.toString(-1 * Integer.parseInt(newValue))); tournament.getTeam(opponentIndex).setRound2Ballot1PD(-1 * Integer.parseInt(newValue)); break; case 3: tournament.getTeam(c).setRound2Ballot2PD(Integer.parseInt(newValue)); opponentIndex = tournament.getTeamIndex(tournament.getTeam(c).getRound2Opponent()); teamPDFields[opponentIndex][d].setText(Integer.toString(-1 * Integer.parseInt(newValue))); tournament.getTeam(opponentIndex).setRound2Ballot2PD(-1 * Integer.parseInt(newValue)); break; case 4: tournament.getTeam(c).setRound3Ballot1PD(Integer.parseInt(newValue)); opponentIndex = tournament.getTeamIndex(tournament.getTeam(c).getRound3Opponent()); teamPDFields[opponentIndex][d].setText(Integer.toString(-1 * Integer.parseInt(newValue))); tournament.getTeam(opponentIndex).setRound3Ballot1PD(-1 * Integer.parseInt(newValue)); break; case 5: tournament.getTeam(c).setRound3Ballot2PD(Integer.parseInt(newValue)); opponentIndex = tournament.getTeamIndex(tournament.getTeam(c).getRound3Opponent()); teamPDFields[opponentIndex][d].setText(Integer.toString(-1 * Integer.parseInt(newValue))); tournament.getTeam(opponentIndex).setRound3Ballot2PD(-1 * Integer.parseInt(newValue)); break; case 6: tournament.getTeam(c).setRound4Ballot1PD(Integer.parseInt(newValue)); opponentIndex = tournament.getTeamIndex(tournament.getTeam(c).getRound4Opponent()); teamPDFields[opponentIndex][d].setText(Integer.toString(-1 * Integer.parseInt(newValue))); tournament.getTeam(opponentIndex).setRound4Ballot1PD(-1 * Integer.parseInt(newValue)); break; case 7: tournament.getTeam(c).setRound4Ballot2PD(Integer.parseInt(newValue)); opponentIndex = tournament.getTeamIndex(tournament.getTeam(c).getRound4Opponent()); teamPDFields[opponentIndex][d].setText(Integer.toString(-1 * Integer.parseInt(newValue))); tournament.getTeam(opponentIndex).setRound4Ballot2PD(-1 * Integer.parseInt(newValue)); break; } teamPDFields[c][d].setBackground(new Background(new BackgroundFill(Color.WHITE, new CornerRadii(3.0), new Insets(0.0)))); } else { teamPDFields[c][d].setBackground(new Background(new BackgroundFill(Color.LIGHTCORAL, null, null))); } } } } for (int c = 0; c < tournament.getTeams().size(); c++) { teamRecordLabels[c].setText(tournament.getTeam(c).getWins() + "-" + tournament.getTeam(c).getLoses() + "-" + tournament.getTeam(c).getTies()); teamCSLabels[c].setText("CS: " + tournament.getTeamCS(tournament.getTeam(c).getTeamNumber())); teamPDLabels[c].setText("PD: " + tournament.getTeam(c).getPD()); } firstPDChange = true; } }); } teamRecordLabels[a] = new Label(tournament.getTeam(a).getWins() + "-" + tournament.getTeam(a).getLoses() + "-" + tournament.getTeam(a).getTies()); teamCSLabels[a] = new Label("CS: " + tournament.getTeamCS(tournament.getTeam(a).getTeamNumber())); teamPDLabels[a] = new Label("PD: " + tournament.getTeam(a).getPD()); } for (int a = 0; a < tournament.getTeams().size(); a++) { grid.add(teamNumberButtons[a], 0, a * 2); grid.add(teamNameLabels[a], 0, a * 2 + 1); for (int b = 0; b < 4; b++) { grid.add(teamSideLabels[a][b], b * 2 + 1, a * 2); grid.add(teamOpponentLabels[a][b], b * 2 + 2, a * 2); grid.add(teamPDFields[a][b * 2], b * 2 + 1, a * 2 + 1); grid.add(teamPDFields[a][b * 2 + 1], b * 2 + 2, a * 2 + 1); } grid.add(teamRecordLabels[a], 9, a * 2, 2, 1); grid.add(teamCSLabels[a], 9, a * 2 + 1); grid.add(teamPDLabels[a], 10, a * 2 + 1); } //Upper Info Display final Label teamNumberHighLowLabel = new Label(); if (tournament.isLowerTeamNumberIsHigherRank()) { teamNumberHighLowLabel.setText("Lower Team Numbers Are Ranked Better"); } else { teamNumberHighLowLabel.setText("Higher Team Numbers Are Ranked Better"); } final Label roundOddEvenPlaintiffLabel = new Label(); if (tournament.isRound3Rank1IsPlaintiff()) { roundOddEvenPlaintiffLabel.setText("In round 3, even pairings are flip sides"); } else { roundOddEvenPlaintiffLabel.setText("In round 3, odd pairings flip sides"); } HBox upperHBox = new HBox(); upperHBox.getChildren().add(teamNumberHighLowLabel); upperHBox.getChildren().add(roundOddEvenPlaintiffLabel); upperHBox.setSpacing(5); //Pairing Buttons //TODO: consider moving pairing buttons to a menu? Button pairRound1 = new Button("Pair Round 1"); Button pairRound2 = new Button("Pair Round 2"); Button pairRound3 = new Button("Pair Round 3"); Button pairRound4 = new Button("Pair Round 4"); Button generateTabSummary = new Button("Generate Tab Summary"); pairRound1.setOnAction(e -> { boolean pointDifferentialsSane = true; for (int a = 0; a < tournament.getTeams().size(); a++) { for (int b = 0; b < 8; b++) { String text = teamPDFields[a][b].getText(); if (!isInteger(text) || Integer.parseInt(text) > 140 || Integer.parseInt(text) < -140) { pointDifferentialsSane = false; Alert pdError = new Alert(AlertType.ERROR); pdError.setContentText("There is an error in the point " + "differentials. Please review the round " + b / 2 + 1 + " entry for team " + tournament.getTeam(a).getTeamNumber()); pdError.showAndWait(); b = 8; a = tournament.getTeams().size(); } } } if (pointDifferentialsSane) { displayPairingConfirmationDialog(tournament.pairRound1(), 1); } }); pairRound2.setOnAction(e -> { boolean pointDifferentialsSane = true; for (int a = 0; a < tournament.getTeams().size(); a++) { for (int b = 0; b < 8; b++) { String text = teamPDFields[a][b].getText(); if (!isInteger(text) || Integer.parseInt(text) > 140 || Integer.parseInt(text) < -140) { pointDifferentialsSane = false; Alert pdError = new Alert(AlertType.ERROR); pdError.setContentText("There is an error in the point " + "differentials. Please review the round " + b / 2 + 1 + " entry for team " + tournament.getTeam(a).getTeamNumber()); pdError.showAndWait(); b = 8; a = tournament.getTeams().size(); } } } if (pointDifferentialsSane) { displayPairingConfirmationDialog(tournament.pairRound2(), 2); } }); pairRound3.setOnAction(e -> { boolean pointDifferentialsSane = true; for (int a = 0; a < tournament.getTeams().size(); a++) { for (int b = 0; b < 8; b++) { String text = teamPDFields[a][b].getText(); if (!isInteger(text) || Integer.parseInt(text) > 140 || Integer.parseInt(text) < -140) { pointDifferentialsSane = false; Alert pdError = new Alert(AlertType.ERROR); pdError.setContentText("There is an error in the point " + "differentials. Please review the round " + b / 2 + 1 + " entry for team " + tournament.getTeam(a).getTeamNumber()); pdError.showAndWait(); b = 8; a = tournament.getTeams().size(); } } } if (pointDifferentialsSane) { displayPairingConfirmationDialog(tournament.pairRound3(), 3); } }); pairRound4.setOnAction(e -> { boolean pointDifferentialsSane = true; for (int a = 0; a < tournament.getTeams().size(); a++) { for (int b = 0; b < 8; b++) { String text = teamPDFields[a][b].getText(); if (!isInteger(text) || Integer.parseInt(text) > 140 || Integer.parseInt(text) < -140) { pointDifferentialsSane = false; Alert pdError = new Alert(AlertType.ERROR); pdError.setContentText("There is an error in the point " + "differentials. Please review the round " + b / 2 + 1 + " entry for team " + tournament.getTeam(a).getTeamNumber()); pdError.showAndWait(); b = 8; a = tournament.getTeams().size(); } } } if (pointDifferentialsSane) { displayPairingConfirmationDialog(tournament.pairRound4(), 4); } }); generateTabSummary.setOnAction(e -> { generateTabSummaryPrompt(); }); HBox buttonBox = new HBox(); buttonBox.getChildren().addAll(pairRound1, pairRound2, pairRound3, pairRound4, generateTabSummary); ScrollPane scrollPane = new ScrollPane(grid); scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS); VBox mainVBox = new VBox(); mainVBox.getChildren().add(menuBar); mainVBox.getChildren().add(upperHBox); mainVBox.getChildren().add(scrollPane); mainVBox.getChildren().add(buttonBox); primaryStage.hide(); primaryStage.getScene().setRoot(mainVBox); primaryStage.show(); } private void displayPairingConfirmationDialog(int[][] proposedPairings, int roundNumber) { final ComboBox[][] teamSelectors = new ComboBox[proposedPairings.length][2]; final Label[] vsText = new Label[proposedPairings.length]; final Stage pairingConfirmation = new Stage(); GridPane grid = new GridPane(); for (int a = 0; a < proposedPairings.length; a++) { teamSelectors[a][0] = new ComboBox(); teamSelectors[a][1] = new ComboBox(); vsText[a] = new Label("vs."); for (int b = 0; b < tournament.getTeams().size(); b++) { teamSelectors[a][0].getItems().add(tournament.getTeam(b).getTeamNumber()); teamSelectors[a][1].getItems().add(tournament.getTeam(b).getTeamNumber()); } } grid.add(new Label("Proposed Round " + roundNumber + " Pairings"), 0, 0, 3, 1); for (int a = 0; a < teamSelectors.length; a++) { teamSelectors[a][0].getSelectionModel().select(Integer.valueOf(proposedPairings[a][0])); teamSelectors[a][1].getSelectionModel().select(Integer.valueOf(proposedPairings[a][1])); grid.add(teamSelectors[a][0], 0, a + 1); grid.add(vsText[a], 1, a + 1); grid.add(teamSelectors[a][1], 2, a + 1); } Button cancelButton = new Button("Cancel"); cancelButton.setCancelButton(true); cancelButton.setOnAction(e -> { pairingConfirmation.hide(); }); Button acceptButton = new Button("Accept"); acceptButton.setDefaultButton(true); acceptButton.setOnAction(e -> { for (int a = 0; a < teamSelectors.length; a++) { boolean impermissibleMatch = tournament.getTeam(teamSelectors[a][0].getSelectionModel().getSelectedIndex()).getImpermissibleMatches().contains(tournament.getTeam(teamSelectors[a][1].getSelectionModel().getSelectedIndex()).getTeamNumber()); if (impermissibleMatch) { Alert confirmImpermissible = new Alert(Alert.AlertType.CONFIRMATION); confirmImpermissible.setContentText("You have an impermissible match."); ((Button) confirmImpermissible.getDialogPane().lookupButton(ButtonType.OK)).setText("Pair Anyway"); confirmImpermissible.showAndWait(); } boolean wrongP = false; boolean wrongD = false; if (roundNumber == 2) { wrongP = tournament.getTeam(teamSelectors[a][0].getSelectionModel().getSelectedIndex()).isRound1Plaintiff(); wrongD = !tournament.getTeam(teamSelectors[a][1].getSelectionModel().getSelectedIndex()).isRound1Plaintiff(); } else if (roundNumber == 4) { wrongP = tournament.getTeam(teamSelectors[a][0].getSelectionModel().getSelectedIndex()).isRound3Plaintiff(); wrongD = !tournament.getTeam(teamSelectors[a][1].getSelectionModel().getSelectedIndex()).isRound3Plaintiff(); } if (wrongP) { Alert confirmWrongP = new Alert(Alert.AlertType.CONFIRMATION); confirmWrongP.setContentText("You have a team going plaintiff in both round 1 and round 2. NOTE: EVENTUALLY THIS PROGRAM WILL SUPPORT THIS, BUT RIGHT NOW IT DOES NOT. YOU SHOULD HIT CANCEL."); ((Button) confirmWrongP.getDialogPane().lookupButton(ButtonType.OK)).setText("Pair Anyway"); confirmWrongP.showAndWait(); } if (wrongD) { Alert confirmWrongD = new Alert(Alert.AlertType.CONFIRMATION); confirmWrongD.setContentText("You have a team going defense in both round 1 and round 2. NOTE: EVENTUALLY THIS PROGRAM WILL SUPPORT THIS, BUT RIGHT NOW IT DOES NOT. YOU SHOULD HIT CANCEL."); ((Button) confirmWrongD.getDialogPane().lookupButton(ButtonType.OK)).setText("Pair Anyway"); confirmWrongD.showAndWait(); } } boolean[] teamPresent = new boolean[tournament.getTeams().size()]; for (int a = 0; a < teamSelectors.length; a++) { teamPresent[teamSelectors[a][0].getSelectionModel().getSelectedIndex()] = true; teamPresent[teamSelectors[a][1].getSelectionModel().getSelectedIndex()] = true; } for (int a = 0; a < teamPresent.length; a++) { if (teamPresent[a] == false) { Alert confirmMissingTeam = new Alert(Alert.AlertType.CONFIRMATION); confirmMissingTeam.setContentText("You are missing team XXXX. NOTE: EVENTUALLY THIS PROGRAM WILL SUPPORT THIS, BUT RIGHT NOW IT DOES NOT. YOU SHOULD HIT CANCEL."); ((Button) confirmMissingTeam.getDialogPane().lookupButton(ButtonType.OK)).setText("They got bored and left. Pair anyway."); confirmMissingTeam.showAndWait(); } } int[][] pairings = new int[proposedPairings.length][2]; for (int a = 0; a < pairings.length; a++) { pairings[a][0] = teamSelectors[a][0].getSelectionModel().getSelectedIndex(); pairings[a][1] = teamSelectors[a][1].getSelectionModel().getSelectedIndex(); } tournament.writePairingsToTournament(pairings, roundNumber); pairingConfirmation.hide(); displayTabulationWindow(); }); grid.add(cancelButton, 0, teamSelectors.length + 1); grid.add(acceptButton, 2, teamSelectors.length + 1); Scene gridDisplay = new Scene(grid); pairingConfirmation.setScene(gridDisplay); pairingConfirmation.initModality(Modality.WINDOW_MODAL); pairingConfirmation.showAndWait(); } /** * Prompts user for file location to save tournament data to, and then * passes that location on to a class which writes the tournament to the * location */ private void saveTournament() { FileChooser saveLocationChooser = new FileChooser(); saveLocationChooser.setTitle("Save Tournament"); saveLocationChooser.setInitialFileName("Untitled.csv"); saveLocationChooser.getExtensionFilters().add(new ExtensionFilter("Mock Trial Tabulation Files", "*.csv")); File saveLocation = saveLocationChooser.showSaveDialog(new Stage()); } /** * Prompts the user for a domain name and writes the tournament to a running * mock trial tabulation server at that domain */ private void saveTournamentToServer() { //TODO: make prompt for url rather than hard coded server Socket socket=null; PrintWriter toServer=null; BufferedReader fromServer=null; ObjectOutputStream oos=null; ObjectInputStream ois=null; try { //TODO: prompt for server socket = new Socket("localhost", 1985); toServer = new PrintWriter(socket.getOutputStream(), true); fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream())); oos = new ObjectOutputStream(socket.getOutputStream()); ois = new ObjectInputStream(socket.getInputStream()); } catch (IOException ex) { ex.printStackTrace(); } toServer.println("setTournament"); String checkResponse = null; try { checkResponse = fromServer.readLine(); if (checkResponse.equals("setTournament")) { oos.writeObject(tournament); } } catch (IOException ex) { Logger.getLogger(MockTrialTabulation.class.getName()).log(Level.SEVERE, null, ex); } } /** * Prompts user for file location to load tournament data from, and then * passes that location on to a class which reads the tournament from the * location * */ private void loadTournament() { FileChooser openLocationChooser = new FileChooser(); openLocationChooser.setTitle("Open Tournament"); openLocationChooser.getExtensionFilters().add(new ExtensionFilter("Mock Trial Tabulation Files", "*.csv")); File tournamentFileLocation = openLocationChooser.showOpenDialog(new Stage()); if (tournamentFileLocation != null && tournamentFileLocation.exists()) { try { tournament = SpreadsheetHandler.loadFromSpreadsheet(tournamentFileLocation); displayTabulationWindow(); } catch (Exception e) { Alert loadError = new Alert(AlertType.ERROR); loadError.setContentText("Unable to load tournament from" + " specified file. Technical details: " + e.toString()); loadError.showAndWait(); } } } private void loadTournamentFromServer() { Socket socket=null; PrintWriter toServer=null; BufferedReader fromServer=null; ObjectOutputStream oos=null; ObjectInputStream ois=null; try { //TODO: prompt for server socket = new Socket("localhost", 1985); toServer = new PrintWriter(socket.getOutputStream(), true); fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream())); oos = new ObjectOutputStream(socket.getOutputStream()); ois = new ObjectInputStream(socket.getInputStream()); } catch (IOException ex) { ex.printStackTrace(); } toServer.println("getTournament"); String checkResponse = null; try { checkResponse = fromServer.readLine(); if (checkResponse.equals("getTournament")) { tournament = (Tournament) ois.readObject(); displayTabulationWindow(); } } catch (IOException | ClassNotFoundException ex) { ex.printStackTrace(); } } private void generateTabSummaryPrompt() { FileChooser saveLocationChooser = new FileChooser(); saveLocationChooser.setTitle("Generate Tab Summary"); File saveLocation = saveLocationChooser.showSaveDialog(new Stage()); TabSummaryWriter.createTabSummary(tournament, saveLocation); } private int getRowCount(GridPane pane) { int numRows = pane.getRowConstraints().size(); for (int i = 0; i < pane.getChildren().size(); i++) { Node child = pane.getChildren().get(i); if (child.isManaged()) { Integer rowIndex = GridPane.getRowIndex(child); if (rowIndex != null) { numRows = Math.max(numRows, rowIndex + 1); } } } return numRows; } public static boolean isInteger(String s) { return isInteger(s, 10); } public static boolean isInteger(String s, int radix) { if (s.isEmpty()) { return false; } for (int i = 0; i < s.length(); i++) { if (i == 0 && s.charAt(i) == '-') { if (s.length() == 1) { return false; } else { continue; } } if (Character.digit(s.charAt(i), radix) < 0) { return false; } } return true; } }
package org.quattor.pan.utils; import static org.quattor.pan.utils.MessageUtils.MSG_MISSING_SAX_TRANSFORMER; import static org.quattor.pan.utils.MessageUtils.MSG_UNEXPECTED_EXCEPTION_WHILE_WRITING_OUTPUT; import java.util.Properties; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import org.quattor.pan.exceptions.CompilerError; public class XmlUtils { private XmlUtils() { } public static TransformerHandler getSaxTransformerHandler() { try { // Generate the transformer factory. Need to guarantee that we get a // SAXTransformerFactory. TransformerFactory factory = TransformerFactory.newInstance(); if (!factory.getFeature(SAXTransformerFactory.FEATURE)) { throw CompilerError.create(MSG_MISSING_SAX_TRANSFORMER); } // Only set the indentation if the returned TransformerFactory // supports it. if (factory.getFeature("indent-number")) { factory.setAttribute("indent-number", Integer.valueOf(4)); } // Can safely cast the factory to a SAX-specific one. Get the // handler to feed with SAX events. SAXTransformerFactory saxfactory = (SAXTransformerFactory) factory; TransformerHandler handler = saxfactory.newTransformerHandler(); // Set parameters of the embedded transformer. Transformer transformer = handler.getTransformer(); Properties properties = new Properties(); properties.setProperty(OutputKeys.INDENT, "yes"); properties.setProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperties(properties); return handler; } catch (TransformerConfigurationException tce) { Error error = CompilerError .create(MSG_UNEXPECTED_EXCEPTION_WHILE_WRITING_OUTPUT); error.initCause(tce); throw error; } } }
package com.intellij.find; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter; import com.intellij.find.impl.FindInProjectUtil; import com.intellij.find.replaceInProject.ReplaceInProjectManager; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.actions.EditorActionUtil; import com.intellij.openapi.editor.actions.IncrementalFindAction; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.event.CaretEvent; import com.intellij.openapi.editor.event.CaretListener; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.markup.HighlighterLayer; import com.intellij.openapi.editor.markup.HighlighterTargetArea; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.ui.LightweightHint; import com.intellij.usageView.UsageInfo; import com.intellij.usages.*; import com.intellij.usages.impl.UsageViewImpl; import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.*; import java.util.stream.Stream; public class FindUtil { private static final Key<Direction> KEY = Key.create("FindUtil.KEY"); private FindUtil() { } @Nullable private static VirtualFile getVirtualFile(@NotNull Editor myEditor) { Project project = myEditor.getProject(); PsiFile file = project != null ? PsiDocumentManager.getInstance(project).getPsiFile(myEditor.getDocument()) : null; return file != null ? file.getVirtualFile() : null; } public static void initStringToFindWithSelection(FindModel findModel, @Nullable Editor editor) { if (editor != null) { String s = editor.getSelectionModel().getSelectedText(); if (s != null && s.length() < 10000) { FindModel.initStringToFind(findModel, s); } } } public static void configureFindModel(boolean replace, @Nullable Editor editor, FindModel model, boolean firstSearch) { boolean isGlobal = true; String stringToFind = firstSearch ? "" : model.getStringToFind(); final SelectionModel selectionModel = editor != null ? editor.getSelectionModel() : null; String selectedText = selectionModel != null ? selectionModel.getSelectedText() : null; if (!StringUtil.isEmpty(selectedText)) { stringToFind = selectedText; } model.setReplaceState(replace); boolean multiline = stringToFind.contains("\n"); if (replace && multiline) { isGlobal = false; stringToFind = ""; multiline = false; } model.setStringToFind(stringToFind); model.setMultiline(multiline); model.setGlobal(isGlobal); model.setPromptOnReplace(false); } public static void updateFindInFileModel(@Nullable Project project, @NotNull FindModel with, boolean saveFindString) { FindModel model = FindManager.getInstance(project).getFindInFileModel(); model.setCaseSensitive(with.isCaseSensitive()); model.setWholeWordsOnly(with.isWholeWordsOnly()); model.setRegularExpressions(with.isRegularExpressions()); model.setSearchContext(with.getSearchContext()); if (saveFindString && !with.getStringToFind().isEmpty()) { model.setStringToFind(with.getStringToFind()); } if (with.isReplaceState()) { model.setPreserveCase(with.isPreserveCase()); if (saveFindString) model.setStringToReplace(with.getStringToReplace()); } } public static void useFindStringFromFindInFileModel(FindModel findModel, Editor editor) { if (editor != null) { EditorSearchSession editorSearchSession = EditorSearchSession.get(editor); if (editorSearchSession != null) { FindModel currentFindModel = editorSearchSession.getFindModel(); findModel.setStringToFind(currentFindModel.getStringToFind()); if (findModel.isReplaceState()) findModel.setStringToReplace(currentFindModel.getStringToReplace()); } } } private enum Direction { UP, DOWN } public static void findWordAtCaret(Project project, Editor editor) { int caretOffset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); CharSequence text = document.getCharsSequence(); int start = 0; int end = document.getTextLength(); if (!editor.getSelectionModel().hasSelection()) { for (int i = caretOffset - 1; i >= 0; i char c = text.charAt(i); if (!Character.isJavaIdentifierPart(c)) { start = i + 1; break; } } for (int i = caretOffset; i < document.getTextLength(); i++) { char c = text.charAt(i); if (!Character.isJavaIdentifierPart(c)) { end = i; break; } } } else { start = editor.getSelectionModel().getSelectionStart(); end = editor.getSelectionModel().getSelectionEnd(); } if (start >= end) { return; } FindManager findManager = FindManager.getInstance(project); FindInProjectSettings findInProjectSettings = FindInProjectSettings.getInstance(project); String s = text.subSequence(start, end).toString(); findInProjectSettings.addStringToFind(s); findManager.getFindInFileModel().setStringToFind(s); findManager.setFindWasPerformed(); findManager.clearFindingNextUsageInFile(); FindModel model = new FindModel(); model.setStringToFind(s); model.setCaseSensitive(true); model.setWholeWordsOnly(!editor.getSelectionModel().hasSelection()); EditorSearchSession searchSession = EditorSearchSession.get(editor); if (searchSession != null) { searchSession.setTextInField(model.getStringToFind()); } findManager.setFindNextModel(model); doSearch(project, editor, caretOffset, true, model, true); } public static void find(@NotNull final Project project, @NotNull final Editor editor) { ApplicationManager.getApplication().assertIsDispatchThread(); final FindManager findManager = FindManager.getInstance(project); String s = editor.getSelectionModel().getSelectedText(); final FindModel model = findManager.getFindInFileModel().clone(); if (StringUtil.isEmpty(s)) { model.setGlobal(true); } else { if (s.indexOf('\n') >= 0) { model.setGlobal(false); } else { model.setStringToFind(s); model.setGlobal(true); } } model.setReplaceState(false); model.setFindAllEnabled(PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()) != null); findManager.showFindDialog(model, () -> { if (model.isFindAll()) { findManager.setFindNextModel(model); findAllAndShow(project, editor, model); return; } if (!model.isGlobal() && editor.getSelectionModel().hasSelection()) { int offset = model.isForward() ? editor.getSelectionModel().getSelectionStart() : editor.getSelectionModel().getSelectionEnd(); ScrollType scrollType = model.isForward() ? ScrollType.CENTER_DOWN : ScrollType.CENTER_UP; moveCaretAndDontChangeSelection(editor, offset, scrollType); } int offset; if (model.isGlobal()) { if (model.isFromCursor()) { offset = editor.getCaretModel().getOffset(); } else { offset = model.isForward() ? 0 : editor.getDocument().getTextLength(); } } else { // in selection if (!editor.getSelectionModel().hasSelection()) { // TODO[anton] actually, this should never happen - Find dialog should not allow such combination findManager.setFindNextModel(null); return; } offset = model.isForward() ? editor.getSelectionModel().getSelectionStart() : editor.getSelectionModel().getSelectionEnd(); } findManager.setFindNextModel(null); findManager.getFindInFileModel().copyFrom(model); doSearch(project, editor, offset, true, model, true); }); } @Nullable public static List<Usage> findAll(@NotNull Project project, @NotNull Editor editor, @NotNull FindModel findModel) { return findAll(project, PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()), findModel); } @Nullable private static List<Usage> findAll(@NotNull Project project, @Nullable PsiFile psiFile, @NotNull FindModel findModel) { if (psiFile == null || project.isDisposed()) return null; Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile); if (document == null) return null; CharSequence text = document.getCharsSequence(); int textLength = document.getTextLength(); FindManager findManager = FindManager.getInstance(project); findModel.setForward(true); // when find all there is no diff in direction int offset = 0; VirtualFile virtualFile = psiFile.getVirtualFile(); final List<Usage> usages = new ArrayList<>(); while (offset < textLength) { FindResult result = findManager.findString(text, offset, findModel, virtualFile); if (!result.isStringFound()) break; usages.add(new UsageInfo2UsageAdapter(new UsageInfo(psiFile, result.getStartOffset(), result.getEndOffset()))); final int prevOffset = offset; offset = result.getEndOffset(); if (prevOffset == offset) { // for regular expr the size of the match could be zero -> could be infinite loop in finding usages! ++offset; } } return usages; } public static void findAllAndShow(@NotNull Project project, @NotNull Editor editor, @NotNull FindModel findModel) { findAllAndShow(project, PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()), findModel); } private static void findAllAndShow(@NotNull Project project, @Nullable PsiFile psiFile, @NotNull FindModel findModel) { List<Usage> usages = findAll(project, psiFile, findModel); if (usages == null) return; final UsageTarget[] usageTargets = {new FindInProjectUtil.StringUsageTarget(project, findModel)}; final UsageViewPresentation usageViewPresentation = FindInProjectUtil.setupViewPresentation(false, findModel); UsageView view = UsageViewManager.getInstance(project).showUsages(usageTargets, usages.toArray(Usage.EMPTY_ARRAY), usageViewPresentation); view.setRerunAction(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { findAllAndShow(project, psiFile, findModel); } @Override public boolean isEnabled() { return !project.isDisposed() && psiFile.isValid(); } }); } public static void searchBack(Project project, FileEditor fileEditor, @Nullable DataContext dataContext) { if (!(fileEditor instanceof TextEditor)) return; TextEditor textEditor = (TextEditor)fileEditor; Editor editor = textEditor.getEditor(); searchBack(project, editor, dataContext); } public static void searchBack(final Project project, final Editor editor, @Nullable DataContext context) { FindManager findManager = FindManager.getInstance(project); if (!findManager.findWasPerformed() && !findManager.selectNextOccurrenceWasPerformed()) { new IncrementalFindAction().getHandler().execute(editor, context); return; } FindModel model = findManager.getFindNextModel(editor); if (model == null) { model = findManager.getFindInFileModel(); } model = model.clone(); model.setForward(!model.isForward()); if (!model.isGlobal() && !editor.getSelectionModel().hasSelection()) { model.setGlobal(true); } int offset; if (Direction.UP.equals(editor.getUserData(KEY)) && !model.isForward()) { offset = editor.getDocument().getTextLength(); } else if (Direction.DOWN.equals(editor.getUserData(KEY)) && model.isForward()) { offset = 0; } else { editor.putUserData(KEY, null); offset = editor.getCaretModel().getOffset(); if (!model.isForward() && offset > 0) { offset } } searchAgain(project, editor, offset, model); } public static boolean searchAgain(Project project, FileEditor fileEditor, @Nullable DataContext context) { if (!(fileEditor instanceof TextEditor)) return false; TextEditor textEditor = (TextEditor)fileEditor; Editor editor = textEditor.getEditor(); return searchAgain(project, editor, context); } private static boolean searchAgain(final Project project, final Editor editor, @Nullable DataContext context) { FindManager findManager = FindManager.getInstance(project); if (!findManager.findWasPerformed() && !findManager.selectNextOccurrenceWasPerformed()) { new IncrementalFindAction().getHandler().execute(editor, context); return false; } FindModel model = findManager.getFindNextModel(editor); if (model == null) { model = findManager.getFindInFileModel(); } model = model.clone(); int offset; if (Direction.DOWN.equals(editor.getUserData(KEY)) && model.isForward()) { offset = 0; } else if (Direction.UP.equals(editor.getUserData(KEY)) && !model.isForward()) { offset = editor.getDocument().getTextLength(); } else { editor.putUserData(KEY, null); offset = model.isGlobal() && model.isForward() ? editor.getSelectionModel().getSelectionEnd() : editor.getCaretModel().getOffset(); if (!model.isForward() && offset > 0) { offset } } return searchAgain(project, editor, offset, model); } private static boolean searchAgain(Project project, Editor editor, int offset, FindModel model) { if (!model.isGlobal() && !editor.getSelectionModel().hasSelection()) { model.setGlobal(true); } model.setFromCursor(false); if (model.isReplaceState()) { model.setPromptOnReplace(true); model.setReplaceAll(false); replace(project, editor, offset, model); return true; } else { doSearch(project, editor, offset, true, model, true); return false; } } public static void replace(@NotNull Project project, @NotNull Editor editor) { final FindManager findManager = FindManager.getInstance(project); final FindModel model = findManager.getFindInFileModel().clone(); final String s = editor.getSelectionModel().getSelectedText(); if (!StringUtil.isEmpty(s)) { if (s.indexOf('\n') >= 0) { model.setGlobal(false); } else { model.setStringToFind(s); model.setGlobal(true); } } else { model.setGlobal(true); } model.setReplaceState(true); findManager.showFindDialog(model, () -> { if (!model.isGlobal() && editor.getSelectionModel().hasSelection()) { int offset = model.isForward() ? editor.getSelectionModel().getSelectionStart() : editor.getSelectionModel().getSelectionEnd(); ScrollType scrollType = model.isForward() ? ScrollType.CENTER_DOWN : ScrollType.CENTER_UP; moveCaretAndDontChangeSelection(editor, offset, scrollType); } int offset; if (model.isGlobal()) { if (model.isFromCursor()) { offset = editor.getCaretModel().getOffset(); if (!model.isForward()) { offset++; } } else { offset = model.isForward() ? 0 : editor.getDocument().getTextLength(); } } else { // in selection if (!editor.getSelectionModel().hasSelection()) { // TODO[anton] actually, this should never happen - Find dialog should not allow such combination findManager.setFindNextModel(null); return; } offset = model.isForward() ? editor.getSelectionModel().getSelectionStart() : editor.getSelectionModel().getSelectionEnd(); } if (s != null && editor.getSelectionModel().hasSelection() && s.equals(model.getStringToFind())) { if (model.isFromCursor() && model.isForward()) { offset = Math.min(editor.getSelectionModel().getSelectionStart(), offset); } else if (model.isFromCursor() && !model.isForward()) { offset = Math.max(editor.getSelectionModel().getSelectionEnd(), offset); } } findManager.setFindNextModel(null); findManager.getFindInFileModel().copyFrom(model); replace(project, editor, offset, model); }); } public static boolean replace(@NotNull Project project, @NotNull Editor editor, int offset, @NotNull FindModel model) { return replace(project, editor, offset, model, (range, replace) -> true); } public static boolean replace(@NotNull Project project, @NotNull Editor editor, int offset, @NotNull FindModel model, ReplaceDelegate delegate) { Document document = editor.getDocument(); if (!FileDocumentManager.getInstance().requestWriting(document, project)) { return false; } document.startGuardedBlockChecking(); boolean toPrompt = model.isPromptOnReplace(); try { doReplace(project, editor, model, offset, toPrompt, delegate); } catch (ReadOnlyFragmentModificationException e) { EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e); } finally { document.stopGuardedBlockChecking(); } return true; } private static void doReplace(@NotNull Project project, @NotNull Editor editor, @NotNull FindModel aModel, int caretOffset, boolean toPrompt, ReplaceDelegate delegate) { FindManager findManager = FindManager.getInstance(project); final FindModel model = aModel.clone(); int occurrences = 0; List<Pair<TextRange, String>> rangesToChange = new ArrayList<>(); boolean replaced = false; boolean reallyReplaced = false; int offset = caretOffset; Document document = editor.getDocument(); while (offset >= 0 && offset < document.getTextLength()) { caretOffset = offset; FindResult result = doSearch(project, editor, offset, !replaced, model, toPrompt); if (result == null) { break; } int startResultOffset = result.getStartOffset(); model.setFromCursor(true); int startOffset = result.getStartOffset(); int endOffset = result.getEndOffset(); String foundString = document.getCharsSequence().subSequence(startOffset, endOffset).toString(); String toReplace; try { toReplace = findManager.getStringToReplace(foundString, model, startOffset, document.getCharsSequence()); } catch (FindManager.MalformedReplacementStringException e) { if (!ApplicationManager.getApplication().isUnitTestMode()) { Messages.showErrorDialog(project, e.getMessage(), FindBundle.message("find.replace.invalid.replacement.string.title")); } break; } if (toPrompt) { int promptResult = findManager.showPromptDialog(model, FindBundle.message("find.replace.dialog.title")); if (promptResult == FindManager.PromptResult.SKIP) { offset = model.isForward() ? result.getEndOffset() : startResultOffset; continue; } if (promptResult == FindManager.PromptResult.CANCEL) { break; } if (promptResult == FindManager.PromptResult.ALL) { toPrompt = false; } } int newOffset; if (delegate == null || delegate.shouldReplace(result, toReplace)) { if (toPrompt) { //[SCR 7258] if (!reallyReplaced) { editor.getCaretModel().moveToOffset(0); reallyReplaced = true; } } TextRange textRange = doReplace(project, document, model, result, toReplace, toPrompt, rangesToChange); replaced = true; newOffset = model.isForward() ? textRange.getEndOffset() : textRange.getStartOffset(); if (textRange.isEmpty()) ++newOffset; occurrences++; } else { newOffset = model.isForward() ? result.getEndOffset() : result.getStartOffset(); } if (newOffset == offset) { newOffset += model.isForward() ? 1 : -1; } offset = newOffset; } if (replaced) { if (toPrompt) { if (caretOffset > document.getTextLength()) { caretOffset = document.getTextLength(); } editor.getCaretModel().moveToOffset(caretOffset); } else { CharSequence text = document.getCharsSequence(); final StringBuilder newText = new StringBuilder(document.getTextLength()); Collections.sort(rangesToChange, Comparator.comparingInt(o -> o.getFirst().getStartOffset())); int offsetBefore = 0; for (Pair<TextRange, String> pair : rangesToChange) { TextRange range = pair.getFirst(); String replace = pair.getSecond(); newText.append(text, offsetBefore, range.getStartOffset()); //before change if (delegate == null || delegate.shouldReplace(range, replace)) { newText.append(replace); } else { newText.append(text.subSequence(range.getStartOffset(), range.getEndOffset())); } offsetBefore = range.getEndOffset(); if (offsetBefore < caretOffset) { caretOffset += replace.length() - range.getLength(); } } newText.append(text, offsetBefore, text.length()); //tail if (caretOffset > newText.length()) { caretOffset = newText.length(); } final int finalCaretOffset = caretOffset; CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { document.setText(newText); editor.getCaretModel().moveToOffset(finalCaretOffset); if (model.isGlobal()) { editor.getSelectionModel().removeSelection(); } }), null, null); } } ReplaceInProjectManager.reportNumberReplacedOccurrences(project, occurrences); } private static boolean selectionMayContainRange(SelectionModel selection, TextRange range) { int[] starts = selection.getBlockSelectionStarts(); int[] ends = selection.getBlockSelectionEnds(); return starts.length != 0 && new TextRange(starts[0], ends[starts.length - 1]).contains(range); } private static boolean selectionStrictlyContainsRange(SelectionModel selection, TextRange range) { int[] starts = selection.getBlockSelectionStarts(); int[] ends = selection.getBlockSelectionEnds(); for (int i = 0; i < starts.length; ++i) { if (new TextRange(starts[i], ends[i]).contains(range)) { //todo return true; } } return false; } @Nullable private static FindResult doSearch(@NotNull Project project, @NotNull final Editor editor, int offset, boolean toWarn, @NotNull FindModel model, boolean adjustEditor) { FindManager findManager = FindManager.getInstance(project); Document document = editor.getDocument(); final FindResult result = findManager.findString(document.getCharsSequence(), offset, model, getVirtualFile(editor)); boolean isFound = result.isStringFound(); final SelectionModel selection = editor.getSelectionModel(); if (isFound && !model.isGlobal()) { if (!selectionMayContainRange(selection, result)) { isFound = false; } else if (!selectionStrictlyContainsRange(selection, result)) { final int[] starts = selection.getBlockSelectionStarts(); for (int newOffset : starts) { if (newOffset > result.getStartOffset()) { return doSearch(project, editor, newOffset, toWarn, model, adjustEditor); } } } } if (!isFound) { if (toWarn) { processNotFound(editor, model.getStringToFind(), model, project); } return null; } if (adjustEditor) { final CaretModel caretModel = editor.getCaretModel(); final ScrollingModel scrollingModel = editor.getScrollingModel(); int oldCaretOffset = caretModel.getOffset(); boolean forward = oldCaretOffset < result.getStartOffset(); final ScrollType scrollType = forward ? ScrollType.CENTER_DOWN : ScrollType.CENTER_UP; if (model.isGlobal()) { int targetCaretPosition = result.getEndOffset(); if (selection.getSelectionEnd() - selection.getSelectionStart() == result.getLength()) { // keeping caret's position relative to selection // use case: FindNext is used after SelectNextOccurrence action targetCaretPosition = caretModel.getOffset() - selection.getSelectionStart() + result.getStartOffset(); } if (caretModel.getCaretAt(editor.offsetToVisualPosition(targetCaretPosition)) != null) { // if there's a different caret at target position, don't move current caret/selection // use case: FindNext is used after SelectNextOccurrence action return result; } caretModel.moveToOffset(targetCaretPosition); selection.removeSelection(); scrollingModel.scrollToCaret(scrollType); scrollingModel.runActionOnScrollingFinished( () -> { scrollingModel.scrollTo(editor.offsetToLogicalPosition(result.getStartOffset()), scrollType); scrollingModel.scrollTo(editor.offsetToLogicalPosition(result.getEndOffset()), scrollType); } ); } else { moveCaretAndDontChangeSelection(editor, result.getStartOffset(), scrollType); moveCaretAndDontChangeSelection(editor, result.getEndOffset(), scrollType); } IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); EditorColorsManager manager = EditorColorsManager.getInstance(); TextAttributes selectionAttributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); if (!model.isGlobal()) { final RangeHighlighterEx segmentHighlighter = (RangeHighlighterEx)editor.getMarkupModel().addRangeHighlighter( result.getStartOffset(), result.getEndOffset(), HighlighterLayer.SELECTION + 1, selectionAttributes, HighlighterTargetArea.EXACT_RANGE); MyListener listener = new MyListener(editor, segmentHighlighter); caretModel.addCaretListener(listener); } else { selection.setSelection(result.getStartOffset(), result.getEndOffset()); } } return result; } private static class MyListener implements CaretListener { private final Editor myEditor; private final RangeHighlighter mySegmentHighlighter; private MyListener(@NotNull Editor editor, @NotNull RangeHighlighter segmentHighlighter) { myEditor = editor; mySegmentHighlighter = segmentHighlighter; } @Override public void caretPositionChanged(@NotNull CaretEvent e) { removeAll(); } private void removeAll() { myEditor.getCaretModel().removeCaretListener(this); mySegmentHighlighter.dispose(); } } public static void processNotFound(final Editor editor, String stringToFind, FindModel model, Project project) { String message = FindBundle.message("find.search.string.not.found.message", stringToFind); short position = HintManager.UNDER; if (model.isGlobal()) { final FindModel newModel = model.clone(); FindManager findManager = FindManager.getInstance(project); Document document = editor.getDocument(); FindResult result = findManager.findString(document.getCharsSequence(), newModel.isForward() ? 0 : document.getTextLength(), model, getVirtualFile(editor)); if (!result.isStringFound()) { result = null; } FindModel modelForNextSearch = findManager.getFindNextModel(editor); if (modelForNextSearch == null) { modelForNextSearch = findManager.getFindInFileModel(); } if (result != null) { if (newModel.isForward()) { AnAction action = ActionManager.getInstance().getAction( modelForNextSearch.isForward() ? IdeActions.ACTION_FIND_NEXT : IdeActions.ACTION_FIND_PREVIOUS); String shortcutsText = KeymapUtil.getFirstKeyboardShortcutText(action); if (!shortcutsText.isEmpty()) { message = FindBundle.message("find.search.again.from.top.hotkey.message", message, shortcutsText); } else { message = FindBundle.message("find.search.again.from.top.action.message", message); } editor.putUserData(KEY, Direction.DOWN); } else { AnAction action = ActionManager.getInstance().getAction( modelForNextSearch.isForward() ? IdeActions.ACTION_FIND_PREVIOUS : IdeActions.ACTION_FIND_NEXT); String shortcutsText = KeymapUtil.getFirstKeyboardShortcutText(action); if (!shortcutsText.isEmpty()) { message = FindBundle.message("find.search.again.from.bottom.hotkey.message", message, shortcutsText); } else { message = FindBundle.message("find.search.again.from.bottom.action.message", message); } editor.putUserData(KEY, Direction.UP); position = HintManager.ABOVE; } } CaretListener listener = new CaretListener() { @Override public void caretPositionChanged(@NotNull CaretEvent e) { editor.putUserData(KEY, null); editor.getCaretModel().removeCaretListener(this); } }; editor.getCaretModel().addCaretListener(listener); } JComponent component = HintUtil.createInformationLabel(JDOMUtil.escapeText(message, false, false)); final LightweightHint hint = new LightweightHint(component); HintManagerImpl.getInstanceImpl().showEditorHint(hint, editor, position, HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING, 0, false); } public static TextRange doReplace(final Project project, final Document document, @NotNull FindModel model, FindResult result, @NotNull String stringToReplace, boolean reallyReplace, List<? super Pair<TextRange, String>> rangesToChange) { final int startOffset = result.getStartOffset(); final int endOffset = result.getEndOffset(); int newOffset; if (reallyReplace) { newOffset = doReplace(project, document, startOffset, endOffset, stringToReplace); } else { final String converted = StringUtil.convertLineSeparators(stringToReplace); TextRange textRange = new TextRange(startOffset, endOffset); rangesToChange.add(Pair.create(textRange, converted)); newOffset = endOffset; } int start = startOffset; int end = newOffset; if (model.isRegularExpressions()) { String toFind = model.getStringToFind(); if (model.isForward()) { if (StringUtil.endsWithChar(toFind, '$')) { int i = 0; int length = toFind.length(); while (i + 2 <= length && toFind.charAt(length - i - 2) == '\\') i++; if (i % 2 == 0) end++; //This $ is a special symbol in regexp syntax } else if (StringUtil.startsWithChar(toFind, '^')) { while (end < document.getTextLength() && document.getCharsSequence().charAt(end) != '\n') end++; } } else { if (StringUtil.startsWithChar(toFind, '^')) { start } else if (StringUtil.endsWithChar(toFind, '$')) { while (start >= 0 && document.getCharsSequence().charAt(start) != '\n') start } } } return new TextRange(start, end); } private static int doReplace(Project project, final Document document, final int startOffset, final int endOffset, final String stringToReplace) { final String converted = StringUtil.convertLineSeparators(stringToReplace); CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { //[ven] I doubt converting is a good solution to SCR 21224 document.replaceString(startOffset, endOffset, converted); }), null, null); return startOffset + converted.length(); } private static void moveCaretAndDontChangeSelection(final Editor editor, int offset, ScrollType scrollType) { LogicalPosition pos = editor.offsetToLogicalPosition(offset); editor.getCaretModel().moveToLogicalPosition(pos); editor.getScrollingModel().scrollToCaret(scrollType); } @FunctionalInterface public interface ReplaceDelegate { boolean shouldReplace(TextRange range, String replace); } public static <T> UsageView showInUsageView(@Nullable PsiElement sourceElement, @NotNull T[] targets, @NotNull Function<? super T, ? extends Usage> usageConverter, @NotNull String title, @Nullable Consumer<? super UsageViewPresentation> presentationSetup, @NotNull Project project) { if (targets.length == 0) return null; final UsageViewPresentation presentation = new UsageViewPresentation(); presentation.setCodeUsagesString(title); presentation.setTabName(title); presentation.setTabText(title); if (presentationSetup != null) { presentationSetup.consume(presentation); } UsageTarget[] usageTargets = sourceElement == null ? UsageTarget.EMPTY_ARRAY : new UsageTarget[]{new PsiElement2UsageTargetAdapter(sourceElement)}; UsageView view = UsageViewManager.getInstance(project).showUsages(usageTargets, Usage.EMPTY_ARRAY, presentation); ProgressManager.getInstance().run(new Task.Backgroundable(project, "Updating Usage View...") { @Override public void run(@NotNull ProgressIndicator indicator) { UsageViewImpl impl = (UsageViewImpl)view; for (T pointer : targets) { if (impl.isDisposed()) break; ApplicationManager.getApplication().runReadAction(() -> { Usage usage = usageConverter.fun(pointer); if (usage != null) { view.appendUsage(usage); } }); } UIUtil.invokeLaterIfNeeded(() -> { if (!impl.isDisposed()) impl.expandRoot(); }); } }); return view; } @Nullable public static UsageView showInUsageView(@Nullable PsiElement sourceElement, @NotNull PsiElement[] targets, @NotNull String title, @NotNull Project project) { if (targets.length == 0) return null; PsiElement[] primary = sourceElement == null ? PsiElement.EMPTY_ARRAY : new PsiElement[]{sourceElement}; SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(project); SmartPsiElementPointer[] pointers = Stream.of(targets).map(smartPointerManager::createSmartPsiElementPointer).toArray(SmartPsiElementPointer[]::new); // usage view will load document/AST so still referencing all these PSI elements might lead to out of memory //noinspection UnusedAssignment targets = PsiElement.EMPTY_ARRAY; return showInUsageView(sourceElement, pointers, p -> { PsiElement element = p.getElement(); return element == null ? null : UsageInfoToUsageConverter.convert(primary, new UsageInfo(element)); }, title, null, project); } /** * Creates a selection in editor per each search result. Existing carets and selections in editor are discarded. * * @param caretShiftFromSelectionStart if non-negative, defines caret position relative to selection start, for each created selection. * if negative, carets will be positioned at selection ends */ public static void selectSearchResultsInEditor(@NotNull Editor editor, @NotNull Iterator<? extends FindResult> resultIterator, int caretShiftFromSelectionStart) { if (!editor.getCaretModel().supportsMultipleCarets()) { return; } ArrayList<CaretState> caretStates = new ArrayList<>(); while (resultIterator.hasNext()) { FindResult findResult = resultIterator.next(); int caretOffset = getCaretPosition(findResult, caretShiftFromSelectionStart); int selectionStartOffset = findResult.getStartOffset(); int selectionEndOffset = findResult.getEndOffset(); EditorActionUtil.makePositionVisible(editor, caretOffset); EditorActionUtil.makePositionVisible(editor, selectionStartOffset); EditorActionUtil.makePositionVisible(editor, selectionEndOffset); caretStates.add(new CaretState(editor.offsetToLogicalPosition(caretOffset), editor.offsetToLogicalPosition(selectionStartOffset), editor.offsetToLogicalPosition(selectionEndOffset))); } if (caretStates.isEmpty()) { return; } editor.getCaretModel().setCaretsAndSelections(caretStates); } /** * Attempts to add a new caret to editor, with selection corresponding to given search result. * * @param caretShiftFromSelectionStart if non-negative, defines caret position relative to selection start, for each created selection. * if negative, caret will be positioned at selection end * @return {@code true} if caret was added successfully, {@code false} if it cannot be done, e.g. because a caret already * exists at target position */ public static boolean selectSearchResultInEditor(@NotNull Editor editor, @NotNull FindResult result, int caretShiftFromSelectionStart) { if (!editor.getCaretModel().supportsMultipleCarets()) { return false; } int caretOffset = getCaretPosition(result, caretShiftFromSelectionStart); LogicalPosition caretPosition = editor.offsetToLogicalPosition(caretOffset); if (caretShiftFromSelectionStart == 0) caretPosition = caretPosition.leanForward(true); EditorActionUtil.makePositionVisible(editor, caretOffset); Caret newCaret = editor.getCaretModel().addCaret(editor.logicalToVisualPosition(caretPosition)); if (newCaret == null) { return false; } else { int selectionStartOffset = result.getStartOffset(); int selectionEndOffset = result.getEndOffset(); EditorActionUtil.makePositionVisible(editor, selectionStartOffset); EditorActionUtil.makePositionVisible(editor, selectionEndOffset); newCaret.setSelection(selectionStartOffset, selectionEndOffset); return true; } } private static int getCaretPosition(FindResult findResult, int caretShiftFromSelectionStart) { return caretShiftFromSelectionStart < 0 ? findResult.getEndOffset() : Math.min(findResult.getStartOffset() + caretShiftFromSelectionStart, findResult.getEndOffset()); } }
package com.intellij.ui; import com.intellij.ide.StartupProgress; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.List; /** * To customize your IDE splash go to YourIdeNameApplicationInfo.xml and edit 'logo' tag. For more information see documentation for * the tag attributes in ApplicationInfo.xsd file. * * @author Konstantin Bulenkov */ public class Splash extends JDialog implements StartupProgress { @Nullable public static Rectangle BOUNDS; private final Icon myImage; private final ApplicationInfoEx myInfo; private int myProgressHeight; private Color myProgressColor = null; private int myProgressX; private int myProgressY; private float myProgress; private boolean mySplashIsVisible; private int myProgressLastPosition = 0; private final JLabel myLabel; private Icon myProgressTail; public Splash(@NotNull ApplicationInfoEx info) { super((Frame)null, false); myInfo = info; if (info instanceof ApplicationInfoImpl) { final ApplicationInfoImpl appInfo = (ApplicationInfoImpl)info; myProgressHeight = appInfo.getProgressHeight(); myProgressColor = appInfo.getProgressColor(); myProgressX = appInfo.getProgressX(); myProgressY = appInfo.getProgressY(); myProgressTail = appInfo.getProgressTailIcon(); } setUndecorated(true); if (!(SystemInfo.isLinux)) { setResizable(false); } setFocusableWindowState(false); Icon originalImage = IconLoader.getIcon(info.getSplashImageUrl()); myImage = new SplashImage(IconLoader.getIconSnapshot(originalImage), info.getSplashTextColor()); myLabel = new JLabel(myImage) { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); mySplashIsVisible = true; myProgressLastPosition = 0; paintProgress(g); } }; Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(myLabel, BorderLayout.CENTER); Dimension size = getPreferredSize(); if (Registry.is("suppress.focus.stealing")) { setAutoRequestFocus(false); } setSize(size); pack(); setLocationInTheCenterOfScreen(); } private void setLocationInTheCenterOfScreen() { Rectangle bounds = getGraphicsConfiguration().getBounds(); if (SystemInfo.isWindows) { JBInsets.removeFrom(bounds, ScreenUtil.getScreenInsets(getGraphicsConfiguration())); } setLocation(UIUtil.getCenterPoint(bounds, getSize())); } @SuppressWarnings("deprecation") public void show() { super.show(); toFront(); //noinspection AssignmentToStaticFieldFromInstanceMethod BOUNDS = getBounds(); //Sometimes this causes deadlock in EDT //myLabel.paintImmediately(0, 0, myImage.getIconWidth(), myImage.getIconHeight()); } @Override public void showProgress(String message, float progress) { if (getProgressColor() == null) return; if (progress - myProgress > 0.01) { myProgress = progress; myLabel.paintImmediately(0, 0, myImage.getIconWidth(), myImage.getIconHeight()); } } @Override public void dispose() { super.dispose(); removeAll(); DialogWrapper.cleanupRootPane(rootPane); rootPane = null; } private void paintProgress(Graphics g) { final Color color = getProgressColor(); if (color == null) return; if (!mySplashIsVisible) { myImage.paintIcon(this, g, 0, 0); mySplashIsVisible = true; } int totalWidth = myImage.getIconWidth() - getProgressX() + 3; final int progressWidth = (int)(totalWidth * myProgress); final int width = progressWidth - myProgressLastPosition; g.setColor(color); g.fillRect(getProgressX(), getProgressY(), width, getProgressHeight()); if (myProgressTail != null) { myProgressTail.paintIcon(this, g, (int)(getProgressX() + width - (myProgressTail.getIconWidth() / uiScale(1f) / 2f * uiScale(1f))), (int)(getProgressY() - (myProgressTail.getIconHeight() - getProgressHeight()) / uiScale(1f) / 2f * uiScale(1f))); //I'll buy you a beer if you understand this line without playing with it } myProgressLastPosition = progressWidth; } private Color getProgressColor() { return myProgressColor; } private int getProgressHeight() { return (int)uiScale((float)myProgressHeight); } private int getProgressX() { return (int)uiScale((float)myProgressX); } private int getProgressY() { return (int)uiScale((float)myProgressY); } public static boolean showLicenseeInfo(Graphics g, int x, int y, final int height, final Color textColor, ApplicationInfo info) { if (ApplicationInfoImpl.getShadowInstance().showLicenseeInfo()) { final LicensingFacade provider = LicensingFacade.getInstance(); if (provider != null) { UIUtil.applyRenderingHints(g); final String licensedToMessage = provider.getLicensedToMessage(); final List<String> licenseRestrictionsMessages = provider.getLicenseRestrictionsMessages(); Font font = SystemInfo.isMacOSElCapitan ? createFont(".SF NS Text") : SystemInfo.isMacOSYosemite ? createFont("HelveticaNeue-Regular") : null; if (font == null || UIUtil.isDialogFont(font)) { font = createFont(UIUtil.ARIAL_FONT_NAME); } g.setFont(UIUtil.getFontWithFallback(font)); g.setColor(textColor); if (!(info instanceof ApplicationInfoImpl)) { return false; } int offsetX = Math.max(uiScale(15), uiScale(((ApplicationInfoImpl)info).getProgressX())); int offsetY = ((ApplicationInfoImpl)info).getLicenseOffsetY(); g.drawString(licensedToMessage, x + offsetX, y + height - uiScale(offsetY)); if (licenseRestrictionsMessages.size() > 0) { g.drawString(licenseRestrictionsMessages.get(0), x + offsetX, y + height - uiScale(offsetY - 16)); } } return true; } return false; } @NotNull protected static Font createFont(String name) { return new Font(name, Font.PLAIN, uiScale(12)); } private static final float JBUI_INIT_SCALE = JBUI.scale(1f); private static float uiScale(float f) { return f * JBUI_INIT_SCALE; } private static int uiScale(int i) { return (int)(i * JBUI_INIT_SCALE); } private final class SplashImage implements Icon { private final Icon myIcon; private final Color myTextColor; private boolean myRedrawing; public SplashImage(Icon originalIcon, Color textColor) { myIcon = originalIcon; myTextColor = textColor; } public void paintIcon(Component c, Graphics g, int x, int y) { if (!myRedrawing) { try { Thread.sleep(10); } catch (InterruptedException ignore) {} myRedrawing = true; } myIcon.paintIcon(c, g, x, y); showLicenseeInfo(g, x, y, getIconHeight(), myTextColor, myInfo); } public int getIconWidth() { return myIcon.getIconWidth(); } public int getIconHeight() { return myIcon.getIconHeight(); } } }
package ftc8390.vv; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.HardwareMap; public class Shooter { public DcMotor leftMotor; public DcMotor rightMotor; public double shootSpeed; public void init(HardwareMap hardwareMap) { leftMotor = hardwareMap.dcMotor.get("lsm"); rightMotor = hardwareMap.dcMotor.get("rsm"); runUsingEncoders(); // MAKE SURE TO PUT SHOOTER MOTORS INTO FLOAT MODE SO THEY DON'T BREAK!!! leftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); rightMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); shootSpeed = .23; } public void turnOn() { leftMotor.setPower(shootSpeed); rightMotor.setPower(-shootSpeed); } public void turnOff() { leftMotor.setPower(0); rightMotor.setPower(0); } public void setPower(double power) { leftMotor.setPower(power); rightMotor.setPower(-power); } public void stopAndResetEncoders() { leftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } public void runUsingEncoders() { leftMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void runWithoutEncoders() { leftMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); rightMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } }