file_id
stringlengths
5
10
content
stringlengths
110
41.7k
repo
stringlengths
7
108
path
stringlengths
8
211
token_length
int64
35
8.19k
original_comment
stringlengths
11
5.72k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
73
41.6k
30571_8
package thirtyone; import battlecode.common.*; public class Enlightment extends MyRobot { //Util: array of directions static final Direction[] directions = { Direction.NORTH, Direction.NORTHEAST, Direction.EAST, Direction.SOUTHEAST, Direction.SOUTH, Direction.SOUTHWEST, Direction.WEST, Direction.NORTHWEST, }; int[] buildDirCont = new int[directions.length]; enum TypeDescription { SLANDERER, MUCKRAKER, POLITICIAN, BIG_POLITICIAN, BIG_MUCKRAKER, CONQUEROR, SMALL_POLITICIAN } TypeDescription[] typeDescriptions = TypeDescription.values(); double[] typeProportions = new double[TypeDescription.values().length]; double[] currentProportions = new double[TypeDescription.values().length]; //double totalCurrentProportions = 0; //double totalProportions = 0; final double bigMuckrakerOffset = 3; final int SLANDERER_ADVANCE = 2; final int MIN_BIG_POLI_INF = 200; final int BIG_MUCK_INF = 143; final int WAIT_TURNS_CONQUER = 20; final int SMALL_POLITICIAN_INFLUENCE = 16; final int SMALL_POLI_ROUND = 70; final int MAX_ENEMY_M_INFLUENCE = (1 << 7) - 2; final int ADDITIONAL_INF_COUNTER = GameConstants.EMPOWER_TAX + 3; final int INT_BITS = 32; final int POLI_ARRAY_SIZE = 1 + (MAX_ENEMY_M_INFLUENCE + ADDITIONAL_INF_COUNTER + INT_BITS - 1)/INT_BITS; int[] myPolis; void updateTypeProportions(){ //int turnsAlive = rc.getRoundNum() - turnCreation; double turns = rc.getRoundNum(); typeProportions[TypeDescription.SLANDERER.ordinal()] = Math.max(3.0, 3.5 - turns/200); typeProportions[TypeDescription.POLITICIAN.ordinal()] = Math.min(4.5, 2.0 + turns/100); typeProportions[TypeDescription.BIG_POLITICIAN.ordinal()] = Math.min(2.0, 2.0 + turns/100); typeProportions[TypeDescription.MUCKRAKER.ordinal()] = Math.max(2.5, 4.5 - turns/100); typeProportions[TypeDescription.BIG_MUCKRAKER.ordinal()] = Math.max(0.5, 0.5); typeProportions[TypeDescription.CONQUEROR.ordinal()] = Math.max(10000, 10000); typeProportions[TypeDescription.SMALL_POLITICIAN.ordinal()] = Math.min(4.5, 2.0 + turns/100); } void addBigMuckOffset(){ currentProportions[TypeDescription.BIG_MUCKRAKER.ordinal()] += bigMuckrakerOffset; currentProportions[TypeDescription.CONQUEROR.ordinal()] = -10; } //Util: default order (TODO: optimize this, make this adaptive?) /*TypeDescription[] typeOrder = { TypeDescription.SLANDERER, TypeDescription.BIG_POLITICIAN, TypeDescription.MUCKRAKER, TypeDescription.POLITICIAN, //TypeDescription.SLANDERER, //TypeDescription.POLITICIAN, //TypeDescription.MUCKRAKER, //TypeDescription.POLITICIAN, };*/ final int strongMuckrakersIncome = 50; //Bidding info int infBeginning = 0; //influence at the beginning of our turn int infEnd = 0; //influence at the end of our turn int income = 0; //income (beginning - end) //We update these at the beginning of each round CustomRInfo closestEnemyMuckraker; CustomRInfo closestEnemyPolitician; int enemyCombinedAttack; int CDTurns; //cooldown turns (depends on passability) //Building info //int currentType = 0; //current type we are trying to build int smallPoliticianIndex = 1; //politician index (this decides the influence given) int muckrakerIndex = 1; //muckraker index (this decides the influence given) boolean safe = false; boolean localSafe = false; int lastTurnEnemy = -100; int turnCreation; final int MIN_TURNS_SAFE = 40; final int MIN_TURNS_WITHOUT_ENEMY = 20; final int SAFE_CONVICTION = 4; public Enlightment(RobotController rc){ super(rc); infEnd = rc.getInfluence(); turnCreation = rc.getRoundNum(); lastTurnEnemy = rc.getRoundNum(); computeInitialSlandIndex(); addBigMuckOffset(); if (rc.getRoundNum() < 10) safe = true; try{ CDTurns = (int) Math.ceil(RobotType.ENLIGHTENMENT_CENTER.actionRadiusSquared/rc.sensePassability(rc.getLocation())); } catch (Exception e){ e.printStackTrace(); } } //necessary slanderer influence to get one more production/turn. final int[] influences = new int[] { 21, 41, 63, 85, 107, 130, 154, 178, 203, 228, 255, 282, 310, 339, 368, 399, 431, 463, 497, 532, 568, 605, 643, 683, 724, 766, 810, 855, 902, 949 }; int currentMaxIndex; //maximum slanderer we ever build final int maxSlandererInf = influences[influences.length - 1]; void increaseMuckrakerIndex(){ if (income > strongMuckrakersIncome) ++muckrakerIndex; } boolean shouldBuild1HPMuck(){ return (income <= strongMuckrakersIncome); } int getMaxSlandererIndex(){ //return Math.min(influences.length - 1, 10 + Math.max(0, income - 50)/5); //return influences.length - 1; return currentMaxIndex; } int getMaxSlandererInf(){ return influences[getMaxSlandererIndex()]; } void computeInitialSlandIndex(){ for (int i = influences.length; i-- > 0; ){ if (influences[i] <= rc.getInfluence()){ currentMaxIndex = i; return; } } } void checkIndex(int inf){ if (inf < getMaxSlandererInf()) return; for (int i = 0; i < influences.length; ++i){ if (influences[i] >= inf){ currentMaxIndex = Math.min(influences.length - 1, i+SLANDERER_ADVANCE); return; } } } boolean isSafe(){ if (safe) return true; if (rc.getRoundNum() - lastTurnEnemy >= MIN_TURNS_WITHOUT_ENEMY) return true; return false; //return true; } public void play(){ //update income info infBeginning = rc.getInfluence(); income = infBeginning - infEnd; //bids (TODO: improve this) bid(); //updates information about environment updateStatus(); //build robots buildNewRobots(); comm.debugNeutralEC(); //update the influence at the end of turn infEnd = rc.getInfluence(); } //Right now this just updates the locations of the closest enemy muckraker and politician (null if none found) void updateStatus(){ if (rc.getRoundNum() - turnCreation >= MIN_TURNS_SAFE) safe = true; updateTypeProportions(); closestEnemyMuckraker = null; closestEnemyPolitician = null; enemyCombinedAttack = 0; myPolis = new int[POLI_ARRAY_SIZE]; MapLocation myLoc = rc.getLocation(); double enemyBuff = rc.getEmpowerFactor(rc.getTeam().opponent(), 0); RobotInfo[] allies = rc.senseNearbyRobots(2, rc.getTeam()); for (RobotInfo r : allies){ if (r.getType() != RobotType.POLITICIAN) continue; int c = r.getConviction(); if (c/INT_BITS >= POLI_ARRAY_SIZE) continue; myPolis[c/INT_BITS] |= (1 << (c%INT_BITS)); } RobotInfo[] enemies = rc.senseNearbyRobots(rc.getType().sensorRadiusSquared, rc.getTeam().opponent()); for (RobotInfo r : enemies){ lastTurnEnemy = rc.getRoundNum(); switch(r.getType()){ case POLITICIAN: int d = myLoc.distanceSquaredTo(r.getLocation()); if (closestEnemyPolitician == null || d < myLoc.distanceSquaredTo(closestEnemyPolitician.mLoc)){ closestEnemyPolitician = new CustomRInfo(r); } enemyCombinedAttack += Math.max(0, (int)(enemyBuff*(r.getConviction() - GameConstants.EMPOWER_TAX))); break; case MUCKRAKER: d = myLoc.distanceSquaredTo(r.getLocation()); if (closestEnemyMuckraker == null || d < myLoc.distanceSquaredTo(closestEnemyMuckraker.mLoc)){ closestEnemyMuckraker = new CustomRInfo(r); } break; } } if (closestEnemyMuckraker != null) return; allies = rc.senseNearbyRobots(rc.getType().sensorRadiusSquared, rc.getTeam()); try { for (RobotInfo r : allies) { CustomRInfo cr = comm.getMuckrakerConvEC(rc.getFlag(r.ID)); if (cr == null) continue; rc.setIndicatorLine(myLoc, cr.mLoc, 255, 0, 0); if (cr.conviction >= MAX_ENEMY_M_INFLUENCE) continue; int c = getConvictionToKillMuckraker(cr.conviction); if ((myPolis[c/INT_BITS] & (1 << (c%INT_BITS))) > 0) continue; int d = myLoc.distanceSquaredTo(cr.mLoc); if (closestEnemyMuckraker == null || d < myLoc.distanceSquaredTo(closestEnemyMuckraker.mLoc)){ closestEnemyMuckraker = cr; } } } catch (Exception e){ e.printStackTrace(); } } //generic method to build robots void buildNewRobots(){ NewRobot r = getNewRobot(closestEnemyPolitician != null, closestEnemyMuckraker != null); build (r); } //class that encodes the next robot we want to build class NewRobot{ RobotType robotType; //type TypeDescription typeDesc; int influence; //influence MapLocation closestLoc = null; //if we want to prioritize building it towards a given location boolean standardBuild = true; //if it comes from the standard build (in this case we must increase the counter after building it) boolean count = false; public NewRobot(RobotType robotType, TypeDescription typeDesc, int influence, boolean standardBuild, boolean count){ this.robotType = robotType; this.typeDesc = typeDesc; this.influence = influence; this.standardBuild = standardBuild; this.count = count; } public NewRobot(RobotType robotType, TypeDescription typeDesc, int influence, MapLocation closestLoc, boolean standardBuild, boolean count){ this.robotType = robotType; this.typeDesc = typeDesc; this.influence = influence; this.closestLoc = closestLoc; this.standardBuild = standardBuild; this.count = count; } } final double eps = 1e-5; //Builds a robot trying to minimize (distanceToObjective)/passability void build(NewRobot r){ try { if (r == null) return; Direction bestSpawnDir = null; double bestSpawnValue = 0; for (Direction dir : directions) { if (!rc.canBuildRobot(r.robotType, dir, r.influence)) continue; double v = getValue(r, dir); if (bestSpawnDir == null || v < bestSpawnValue - eps || (Math.abs(v - bestSpawnValue) < 2*eps && buildDirCont[bestSpawnDir.ordinal()] < buildDirCont[dir.ordinal()])){ bestSpawnDir = dir; bestSpawnValue = v; } } if (bestSpawnDir != null && rc.canBuildRobot(r.robotType, bestSpawnDir, r.influence)){ rc.buildRobot(r.robotType, bestSpawnDir, r.influence); if (r.robotType == RobotType.SLANDERER) checkIndex(r.influence); if (r.standardBuild){ if (r.robotType == RobotType.MUCKRAKER) increaseMuckrakerIndex(); } if (r.count) buildDirCont[bestSpawnDir.ordinal()]++; if (r.typeDesc != null){ double addP = 1.0/typeProportions[r.typeDesc.ordinal()]; currentProportions[r.typeDesc.ordinal()] += addP; //totalCurrentProportions += addP; if (r.typeDesc == TypeDescription.CONQUEROR){ if (r.closestLoc != null) comm.markConqueror(r.closestLoc); } if (r.typeDesc == TypeDescription.SMALL_POLITICIAN){ currentProportions[TypeDescription.POLITICIAN.ordinal()] += addP; } if (r.typeDesc == TypeDescription.POLITICIAN) ++smallPoliticianIndex; } } } catch (Exception e){ e.printStackTrace(); } } //updated current type after building a unit the standard way /*void advanceUnitType(){ currentType = (currentType + 1)%typeOrder.length; }*/ //heuristic to choose position double getValue(NewRobot r, Direction dir) throws GameActionException { double dist = 1; if (r.closestLoc != null){ dist = rc.getLocation().add(dir).distanceSquaredTo(r.closestLoc); } return dist/rc.sensePassability(rc.getLocation().add(dir)); } //Decides which robot to build NewRobot getNewRobot(boolean attacked, boolean nearbyMuckraker){ //Case we are being attacked if (attacked){ NewRobot r = getNewRobot(false, nearbyMuckraker); if (r.influence + enemyCombinedAttack + SAFE_CONVICTION <= rc.getInfluence()) return r; //if we can build whatever we wanted and still resist the attack we are fine if (closestEnemyPolitician == null) return r; //this shouldn't happen... return new NewRobot(RobotType.MUCKRAKER, TypeDescription.MUCKRAKER, 1, closestEnemyPolitician.mLoc, false, true); //build muckrakers to block attack } //Case there is an enemy muckraker trolling around if (nearbyMuckraker){ if (closestEnemyMuckraker == null || !comm.slanderersNearby()){ //TODO: remove nearbyPolitician return getNewRobot(false, false); } //build a politician that kills the muckraker int politicianConviction = getConvictionToKillMuckraker(closestEnemyMuckraker.conviction); if (politicianConviction > rc.getConviction()) return new NewRobot(RobotType.MUCKRAKER, TypeDescription.MUCKRAKER, 1, lowestContDir(), false, true); return new NewRobot(RobotType.POLITICIAN, TypeDescription.POLITICIAN, politicianConviction, closestEnemyMuckraker.mLoc, false, false); } //standard case return getStandardNewRobot(); } //min influence to kill a muckracker with given conviction int getConvictionToKillMuckraker(int muckrakerConviction){ //int ans = (int) ((double)(muckrakerConviction)/rc.getEmpowerFactor(rc.getTeam(), 30)) + ADDITIONAL_INF_COUNTER; int ans = muckrakerConviction + ADDITIONAL_INF_COUNTER; return Math.max(ans, poliTiers[0]); } //checks if there's already a politician that can kill the muckraker efficiently boolean nearbyPolitician(int muckConviction){ RobotInfo[] robots = rc.senseNearbyRobots(2, rc.getTeam()); for (RobotInfo r : robots){ if (r.getType() != RobotType.POLITICIAN) continue; int conv = r.getConviction(); if ((int)(rc.getEmpowerFactor(rc.getTeam(), 25)*conv) <= muckConviction + GameConstants.EMPOWER_TAX) continue; if (1.5*(double)muckConviction + GameConstants.EMPOWER_TAX + 5 < r.getConviction()) continue; return true; } return false; } //this is what we do if there are no emergencies (enemy politicians or muckrakers nearby) NewRobot getStandardNewRobot(){ //System.err.println("Getting standard unit");//while ((closestEnemyMuckraker != null || !isSafe()) && getTypeStandard() == TypeDescription.SLANDERER) advanceUnitType(); TypeDescription type = getTypeStandard(); //we choose the type (right now this just gets typeOrder[currentType]) switch(type){ case MUCKRAKER: return new NewRobot(RobotType.MUCKRAKER, TypeDescription.MUCKRAKER, getMuckrakerInfluence(), lowestContDir(), true, getMuckrakerInfluence() > Util.MUCK_ATTACK_THRESHOLD); //standard muckraker build case SLANDERER: int slandererInf = getSlandererInf(rc.getInfluence() - getSafetyInfRaw()); if (slandererInf > 0) return new NewRobot(RobotType.SLANDERER, TypeDescription.SLANDERER, slandererInf, true, false); //build slanderer with maximal influence break; case POLITICIAN: int politicianInf = getSmallPoliticianInfluence(); if (politicianInf > 0) return new NewRobot(RobotType.POLITICIAN, TypeDescription.POLITICIAN, politicianInf, true, false); //standard politician build break; case BIG_POLITICIAN: int bpInf = getBigPoliInf(); if (bpInf > 0) return new NewRobot(RobotType.POLITICIAN, TypeDescription.BIG_POLITICIAN, bpInf, true, false); //dump all our remaining influence into big poli break; case BIG_MUCKRAKER: int bmInf = getBigMuckInf(); if (bmInf > 0) return new NewRobot(RobotType.MUCKRAKER, TypeDescription.BIG_MUCKRAKER, bmInf, true, false); //dump all our remaining influence into big poli break; case CONQUEROR: int conqInf = getInfConqueror(); Communication.RInfo r = comm.getBestNeutralEC(2*getMaxSlandererInf()); MapLocation loc = null; if (r != null) loc = comm.getBestNeutralEC(2*getMaxSlandererInf()).getMapLocation(); if (loc != null) { if (conqInf > 0) return new NewRobot(RobotType.POLITICIAN, TypeDescription.CONQUEROR, conqInf, loc,true, false); } break; case SMALL_POLITICIAN: int spInf = SMALL_POLITICIAN_INFLUENCE; if (spInf <= rc.getInfluence()){ return new NewRobot(RobotType.POLITICIAN, TypeDescription.SMALL_POLITICIAN, spInf,true, false); } break; } return new NewRobot(RobotType.MUCKRAKER, TypeDescription.MUCKRAKER, 1, lowestContDir(), false, true); //if we couldnt build what we wanted, build a muckraker } int getSafetyInfRaw(){ if (enemyCombinedAttack > 0) return SAFE_CONVICTION + enemyCombinedAttack; return 0; } int getSafetyInf(){ int safety = getSafetyInfRaw(); //check if we have enough to resist attack int safety2 = Math.max(0, getMaxSlandererInf() - 2*income); safety2 += Math.max(0, getSmallPoliticianInfluence() - 2*income); return Math.max(safety, safety2); } int getBigPoliInf(){ int safety = getSafetyInf(); int minInf = getMinBigPoliticianInfluence(); //minimum influence to build a big politician if (minInf + safety > rc.getInfluence()) { return 0; } return rc.getInfluence() - safety; } MapLocation lowestContDir(){ Direction bestDir = null; for (Direction dir : directions){ if (!rc.canBuildRobot(RobotType.MUCKRAKER, dir, 1)) continue; if (bestDir == null || buildDirCont[dir.ordinal()] < buildDirCont[bestDir.ordinal()]) bestDir = dir; } if (bestDir != null) return rc.getLocation().add(bestDir); return null; } TypeDescription getTypeStandard(){ boolean[] canBuild = new boolean[typeProportions.length]; if (shouldBuildSlanderer()) canBuild[TypeDescription.SLANDERER.ordinal()] = true; if (shouldBuildBigPoli()) canBuild[TypeDescription.BIG_POLITICIAN.ordinal()] = true; if (shouldBuildPolitician()) canBuild[TypeDescription.POLITICIAN.ordinal()] = true; if (shouldBuildMuckraker()) canBuild[TypeDescription.MUCKRAKER.ordinal()] = true; if (shouldBuildBigMuckraker()) canBuild[TypeDescription.BIG_MUCKRAKER.ordinal()] = true; if (shouldBuildConqueror()) canBuild[TypeDescription.CONQUEROR.ordinal()] = true; if (shouldbuildSmallPoli()) canBuild[TypeDescription.SMALL_POLITICIAN.ordinal()] = true; //System.err.println(canBuild[TypeDescription.CONQUEROR.ordinal()]); TypeDescription ans = null; double minCont = 0; for (int i = 0; i < typeDescriptions.length;++i){ if (!canBuild[i]) continue; //TypeDescription t = typeDescriptions[i]; if (ans == null || minCont > currentProportions[i]){ minCont = currentProportions[i]; ans = typeDescriptions[i]; } } return ans; } boolean shouldbuildSmallPoli(){ return rc.getRoundNum() <= SMALL_POLI_ROUND; } boolean shouldBuildConqueror(){ int conqInf = getInfConqueror(); if (conqInf > 0) return true; return false; } boolean shouldBuildSlanderer(){ if (closestEnemyMuckraker != null || !isSafe()) return false; return true; } boolean shouldBuildBigPoli(){ int bpInf = getBigPoliInf(); if (bpInf <= 0) return false; return true; } boolean shouldBuildMuckraker(){ return true; } boolean shouldBuildPolitician(){ if (rc.getRoundNum() <= SMALL_POLI_ROUND) return false; return true; } boolean shouldBuildBigMuckraker() { int bmInf = getBigMuckInf(); if (bmInf <= 0) return false; return true; } /* Methods to compute the influence of the next politician/muckraker. We use the typical 1 2 1 3 1 2 1 4 1 2 1 3 1 ... order (position of the first 1-bit in n). If the current number (or tier) is t, we build a politician/muckraker with f(t) influence, where f is hardcoded into the arrays below (if t > length of the array we pick the last one). */ int getInfConqueror(){ //TODO: save for slanderer maybe? //int safetyInf = getSafetyInf(); int safetyInf = getSafetyInfRaw(); Communication.RInfo ec = comm.getBestNeutralEC(2*getMaxSlandererInf()); if (ec == null) return 0; if (ec.influence > 2*getMaxSlandererInf()) return 0; int desiredInf = ec.influence + GameConstants.EMPOWER_TAX + 10; if (rc.getInfluence() < desiredInf + safetyInf) return 0; return desiredInf; } int getSlandererInf(int inf){ int msInf = getMaxSlandererInf(); if (inf > msInf) inf = msInf; for (int i = influences.length; i-- > 0;){ if (influences[i] <= inf) return influences[i]; } return 0; } int getSmallPoliticianInfluence(){ int bit = 0; int base = 2; while ((smallPoliticianIndex %base) == 0){ ++bit; base *= 2; } return politicianInf(bit); } final int[] poliTiers = new int[] {16, 24, 36, 54, 81, 121, 181}; int politicianInf(int tier){ int ans = 0; for (int i = 0; i < poliTiers.length; ++i){ if (i > tier) return ans; if (poliTiers[i] > rc.getInfluence()) return ans; ans = poliTiers[i]; } return ans; } int getMinBigPoliticianInfluence(){ return poliTiers[poliTiers.length - 1]; /*Communication.RInfo ec = comm.getBestNeutralEC(); if (ec == null) return 150; //int minInf = (int)((double)(ec.influence + GameConstants.EMPOWER_TAX + 10)/rc.getEmpowerFactor(rc.getTeam(), 30)); if (ec.influence > 2*getMaxSlandererInf()) return 150; return ec.influence + GameConstants.EMPOWER_TAX + 10; //return 150;*/ } int getBigMuckInf(){ int safety = getSafetyInf(); int minInf = getMinBigMuckInf(); //minimum influence to build a big politician if (minInf + safety > rc.getInfluence()) { return 0; } /*int safety = getSafetyInf(); int minInf = getMinBigMuckInf(); //minimum influence to build a big politician if (minInf + safety > rc.getInfluence()) { return 0; }*/ return minInf + (rc.getInfluence() - safety - minInf)/2; } int getMinBigMuckInf(){ return BIG_MUCK_INF; } int getMuckrakerInfluence(){ if (shouldBuild1HPMuck()) return 1; int bit = 0; int base = 2; while ((muckrakerIndex%base) == 0){ ++bit; base *= 2; } return muckrakerInf(bit); } final int[] muckTiers = new int[] {1, 13, 33, 43}; int muckrakerInf(int tier){ int ans = 1; for (int i = 0; i < muckTiers.length; ++i){ if (i > tier) return ans; if (muckTiers[i] > rc.getInfluence()) return ans; ans = muckTiers[i]; } return ans; } double fractionIncome(double r){ if (r < 400) return 0; return Math.min(0.5, (r-400)/2000); } final int MAX_VOTES = 751; final int MIN_TURN_BID = 170; final int MIN_TURN_STRONG_BID = 400; //TODO: improve this void bid(){ try { if (rc.getTeamVotes() >= MAX_VOTES) return; if (rc.getRoundNum() < MIN_TURN_BID) return; int votes = rc.getTeamVotes(); if (votes == rc.getRoundNum() - MIN_TURN_BID){ if (rc.canBid(1)) rc.bid(1); return; } if (rc.getRoundNum() < MIN_TURN_STRONG_BID + votes) return; int bid = 2; bid = Math.max(bid, (int)(fractionIncome(rc.getRoundNum())*income)); if (rc.getInfluence() >= 10000){ bid = Math.max(bid, rc.getInfluence()/100); } //if (rc.getRobotCount() <= 200 && rc.getRoundNum() <= 1000) return; if (rc.canBid(bid)){ rc.bid(bid); } } catch (Exception e){ e.printStackTrace(); } } static class CustomRInfo{ int conviction; MapLocation mLoc; CustomRInfo(int conviction, MapLocation mLoc){ this.conviction = conviction; this.mLoc = mLoc; } CustomRInfo(RobotInfo r){ this.conviction = r.getConviction(); this.mLoc = r.getLocation(); } } }
IvanGeffner/battlecode2021
thirtyone/Enlightment.java
7,519
//income (beginning - end)
line_comment
nl
package thirtyone; import battlecode.common.*; public class Enlightment extends MyRobot { //Util: array of directions static final Direction[] directions = { Direction.NORTH, Direction.NORTHEAST, Direction.EAST, Direction.SOUTHEAST, Direction.SOUTH, Direction.SOUTHWEST, Direction.WEST, Direction.NORTHWEST, }; int[] buildDirCont = new int[directions.length]; enum TypeDescription { SLANDERER, MUCKRAKER, POLITICIAN, BIG_POLITICIAN, BIG_MUCKRAKER, CONQUEROR, SMALL_POLITICIAN } TypeDescription[] typeDescriptions = TypeDescription.values(); double[] typeProportions = new double[TypeDescription.values().length]; double[] currentProportions = new double[TypeDescription.values().length]; //double totalCurrentProportions = 0; //double totalProportions = 0; final double bigMuckrakerOffset = 3; final int SLANDERER_ADVANCE = 2; final int MIN_BIG_POLI_INF = 200; final int BIG_MUCK_INF = 143; final int WAIT_TURNS_CONQUER = 20; final int SMALL_POLITICIAN_INFLUENCE = 16; final int SMALL_POLI_ROUND = 70; final int MAX_ENEMY_M_INFLUENCE = (1 << 7) - 2; final int ADDITIONAL_INF_COUNTER = GameConstants.EMPOWER_TAX + 3; final int INT_BITS = 32; final int POLI_ARRAY_SIZE = 1 + (MAX_ENEMY_M_INFLUENCE + ADDITIONAL_INF_COUNTER + INT_BITS - 1)/INT_BITS; int[] myPolis; void updateTypeProportions(){ //int turnsAlive = rc.getRoundNum() - turnCreation; double turns = rc.getRoundNum(); typeProportions[TypeDescription.SLANDERER.ordinal()] = Math.max(3.0, 3.5 - turns/200); typeProportions[TypeDescription.POLITICIAN.ordinal()] = Math.min(4.5, 2.0 + turns/100); typeProportions[TypeDescription.BIG_POLITICIAN.ordinal()] = Math.min(2.0, 2.0 + turns/100); typeProportions[TypeDescription.MUCKRAKER.ordinal()] = Math.max(2.5, 4.5 - turns/100); typeProportions[TypeDescription.BIG_MUCKRAKER.ordinal()] = Math.max(0.5, 0.5); typeProportions[TypeDescription.CONQUEROR.ordinal()] = Math.max(10000, 10000); typeProportions[TypeDescription.SMALL_POLITICIAN.ordinal()] = Math.min(4.5, 2.0 + turns/100); } void addBigMuckOffset(){ currentProportions[TypeDescription.BIG_MUCKRAKER.ordinal()] += bigMuckrakerOffset; currentProportions[TypeDescription.CONQUEROR.ordinal()] = -10; } //Util: default order (TODO: optimize this, make this adaptive?) /*TypeDescription[] typeOrder = { TypeDescription.SLANDERER, TypeDescription.BIG_POLITICIAN, TypeDescription.MUCKRAKER, TypeDescription.POLITICIAN, //TypeDescription.SLANDERER, //TypeDescription.POLITICIAN, //TypeDescription.MUCKRAKER, //TypeDescription.POLITICIAN, };*/ final int strongMuckrakersIncome = 50; //Bidding info int infBeginning = 0; //influence at the beginning of our turn int infEnd = 0; //influence at the end of our turn int income = 0; //income (beginning<SUF> //We update these at the beginning of each round CustomRInfo closestEnemyMuckraker; CustomRInfo closestEnemyPolitician; int enemyCombinedAttack; int CDTurns; //cooldown turns (depends on passability) //Building info //int currentType = 0; //current type we are trying to build int smallPoliticianIndex = 1; //politician index (this decides the influence given) int muckrakerIndex = 1; //muckraker index (this decides the influence given) boolean safe = false; boolean localSafe = false; int lastTurnEnemy = -100; int turnCreation; final int MIN_TURNS_SAFE = 40; final int MIN_TURNS_WITHOUT_ENEMY = 20; final int SAFE_CONVICTION = 4; public Enlightment(RobotController rc){ super(rc); infEnd = rc.getInfluence(); turnCreation = rc.getRoundNum(); lastTurnEnemy = rc.getRoundNum(); computeInitialSlandIndex(); addBigMuckOffset(); if (rc.getRoundNum() < 10) safe = true; try{ CDTurns = (int) Math.ceil(RobotType.ENLIGHTENMENT_CENTER.actionRadiusSquared/rc.sensePassability(rc.getLocation())); } catch (Exception e){ e.printStackTrace(); } } //necessary slanderer influence to get one more production/turn. final int[] influences = new int[] { 21, 41, 63, 85, 107, 130, 154, 178, 203, 228, 255, 282, 310, 339, 368, 399, 431, 463, 497, 532, 568, 605, 643, 683, 724, 766, 810, 855, 902, 949 }; int currentMaxIndex; //maximum slanderer we ever build final int maxSlandererInf = influences[influences.length - 1]; void increaseMuckrakerIndex(){ if (income > strongMuckrakersIncome) ++muckrakerIndex; } boolean shouldBuild1HPMuck(){ return (income <= strongMuckrakersIncome); } int getMaxSlandererIndex(){ //return Math.min(influences.length - 1, 10 + Math.max(0, income - 50)/5); //return influences.length - 1; return currentMaxIndex; } int getMaxSlandererInf(){ return influences[getMaxSlandererIndex()]; } void computeInitialSlandIndex(){ for (int i = influences.length; i-- > 0; ){ if (influences[i] <= rc.getInfluence()){ currentMaxIndex = i; return; } } } void checkIndex(int inf){ if (inf < getMaxSlandererInf()) return; for (int i = 0; i < influences.length; ++i){ if (influences[i] >= inf){ currentMaxIndex = Math.min(influences.length - 1, i+SLANDERER_ADVANCE); return; } } } boolean isSafe(){ if (safe) return true; if (rc.getRoundNum() - lastTurnEnemy >= MIN_TURNS_WITHOUT_ENEMY) return true; return false; //return true; } public void play(){ //update income info infBeginning = rc.getInfluence(); income = infBeginning - infEnd; //bids (TODO: improve this) bid(); //updates information about environment updateStatus(); //build robots buildNewRobots(); comm.debugNeutralEC(); //update the influence at the end of turn infEnd = rc.getInfluence(); } //Right now this just updates the locations of the closest enemy muckraker and politician (null if none found) void updateStatus(){ if (rc.getRoundNum() - turnCreation >= MIN_TURNS_SAFE) safe = true; updateTypeProportions(); closestEnemyMuckraker = null; closestEnemyPolitician = null; enemyCombinedAttack = 0; myPolis = new int[POLI_ARRAY_SIZE]; MapLocation myLoc = rc.getLocation(); double enemyBuff = rc.getEmpowerFactor(rc.getTeam().opponent(), 0); RobotInfo[] allies = rc.senseNearbyRobots(2, rc.getTeam()); for (RobotInfo r : allies){ if (r.getType() != RobotType.POLITICIAN) continue; int c = r.getConviction(); if (c/INT_BITS >= POLI_ARRAY_SIZE) continue; myPolis[c/INT_BITS] |= (1 << (c%INT_BITS)); } RobotInfo[] enemies = rc.senseNearbyRobots(rc.getType().sensorRadiusSquared, rc.getTeam().opponent()); for (RobotInfo r : enemies){ lastTurnEnemy = rc.getRoundNum(); switch(r.getType()){ case POLITICIAN: int d = myLoc.distanceSquaredTo(r.getLocation()); if (closestEnemyPolitician == null || d < myLoc.distanceSquaredTo(closestEnemyPolitician.mLoc)){ closestEnemyPolitician = new CustomRInfo(r); } enemyCombinedAttack += Math.max(0, (int)(enemyBuff*(r.getConviction() - GameConstants.EMPOWER_TAX))); break; case MUCKRAKER: d = myLoc.distanceSquaredTo(r.getLocation()); if (closestEnemyMuckraker == null || d < myLoc.distanceSquaredTo(closestEnemyMuckraker.mLoc)){ closestEnemyMuckraker = new CustomRInfo(r); } break; } } if (closestEnemyMuckraker != null) return; allies = rc.senseNearbyRobots(rc.getType().sensorRadiusSquared, rc.getTeam()); try { for (RobotInfo r : allies) { CustomRInfo cr = comm.getMuckrakerConvEC(rc.getFlag(r.ID)); if (cr == null) continue; rc.setIndicatorLine(myLoc, cr.mLoc, 255, 0, 0); if (cr.conviction >= MAX_ENEMY_M_INFLUENCE) continue; int c = getConvictionToKillMuckraker(cr.conviction); if ((myPolis[c/INT_BITS] & (1 << (c%INT_BITS))) > 0) continue; int d = myLoc.distanceSquaredTo(cr.mLoc); if (closestEnemyMuckraker == null || d < myLoc.distanceSquaredTo(closestEnemyMuckraker.mLoc)){ closestEnemyMuckraker = cr; } } } catch (Exception e){ e.printStackTrace(); } } //generic method to build robots void buildNewRobots(){ NewRobot r = getNewRobot(closestEnemyPolitician != null, closestEnemyMuckraker != null); build (r); } //class that encodes the next robot we want to build class NewRobot{ RobotType robotType; //type TypeDescription typeDesc; int influence; //influence MapLocation closestLoc = null; //if we want to prioritize building it towards a given location boolean standardBuild = true; //if it comes from the standard build (in this case we must increase the counter after building it) boolean count = false; public NewRobot(RobotType robotType, TypeDescription typeDesc, int influence, boolean standardBuild, boolean count){ this.robotType = robotType; this.typeDesc = typeDesc; this.influence = influence; this.standardBuild = standardBuild; this.count = count; } public NewRobot(RobotType robotType, TypeDescription typeDesc, int influence, MapLocation closestLoc, boolean standardBuild, boolean count){ this.robotType = robotType; this.typeDesc = typeDesc; this.influence = influence; this.closestLoc = closestLoc; this.standardBuild = standardBuild; this.count = count; } } final double eps = 1e-5; //Builds a robot trying to minimize (distanceToObjective)/passability void build(NewRobot r){ try { if (r == null) return; Direction bestSpawnDir = null; double bestSpawnValue = 0; for (Direction dir : directions) { if (!rc.canBuildRobot(r.robotType, dir, r.influence)) continue; double v = getValue(r, dir); if (bestSpawnDir == null || v < bestSpawnValue - eps || (Math.abs(v - bestSpawnValue) < 2*eps && buildDirCont[bestSpawnDir.ordinal()] < buildDirCont[dir.ordinal()])){ bestSpawnDir = dir; bestSpawnValue = v; } } if (bestSpawnDir != null && rc.canBuildRobot(r.robotType, bestSpawnDir, r.influence)){ rc.buildRobot(r.robotType, bestSpawnDir, r.influence); if (r.robotType == RobotType.SLANDERER) checkIndex(r.influence); if (r.standardBuild){ if (r.robotType == RobotType.MUCKRAKER) increaseMuckrakerIndex(); } if (r.count) buildDirCont[bestSpawnDir.ordinal()]++; if (r.typeDesc != null){ double addP = 1.0/typeProportions[r.typeDesc.ordinal()]; currentProportions[r.typeDesc.ordinal()] += addP; //totalCurrentProportions += addP; if (r.typeDesc == TypeDescription.CONQUEROR){ if (r.closestLoc != null) comm.markConqueror(r.closestLoc); } if (r.typeDesc == TypeDescription.SMALL_POLITICIAN){ currentProportions[TypeDescription.POLITICIAN.ordinal()] += addP; } if (r.typeDesc == TypeDescription.POLITICIAN) ++smallPoliticianIndex; } } } catch (Exception e){ e.printStackTrace(); } } //updated current type after building a unit the standard way /*void advanceUnitType(){ currentType = (currentType + 1)%typeOrder.length; }*/ //heuristic to choose position double getValue(NewRobot r, Direction dir) throws GameActionException { double dist = 1; if (r.closestLoc != null){ dist = rc.getLocation().add(dir).distanceSquaredTo(r.closestLoc); } return dist/rc.sensePassability(rc.getLocation().add(dir)); } //Decides which robot to build NewRobot getNewRobot(boolean attacked, boolean nearbyMuckraker){ //Case we are being attacked if (attacked){ NewRobot r = getNewRobot(false, nearbyMuckraker); if (r.influence + enemyCombinedAttack + SAFE_CONVICTION <= rc.getInfluence()) return r; //if we can build whatever we wanted and still resist the attack we are fine if (closestEnemyPolitician == null) return r; //this shouldn't happen... return new NewRobot(RobotType.MUCKRAKER, TypeDescription.MUCKRAKER, 1, closestEnemyPolitician.mLoc, false, true); //build muckrakers to block attack } //Case there is an enemy muckraker trolling around if (nearbyMuckraker){ if (closestEnemyMuckraker == null || !comm.slanderersNearby()){ //TODO: remove nearbyPolitician return getNewRobot(false, false); } //build a politician that kills the muckraker int politicianConviction = getConvictionToKillMuckraker(closestEnemyMuckraker.conviction); if (politicianConviction > rc.getConviction()) return new NewRobot(RobotType.MUCKRAKER, TypeDescription.MUCKRAKER, 1, lowestContDir(), false, true); return new NewRobot(RobotType.POLITICIAN, TypeDescription.POLITICIAN, politicianConviction, closestEnemyMuckraker.mLoc, false, false); } //standard case return getStandardNewRobot(); } //min influence to kill a muckracker with given conviction int getConvictionToKillMuckraker(int muckrakerConviction){ //int ans = (int) ((double)(muckrakerConviction)/rc.getEmpowerFactor(rc.getTeam(), 30)) + ADDITIONAL_INF_COUNTER; int ans = muckrakerConviction + ADDITIONAL_INF_COUNTER; return Math.max(ans, poliTiers[0]); } //checks if there's already a politician that can kill the muckraker efficiently boolean nearbyPolitician(int muckConviction){ RobotInfo[] robots = rc.senseNearbyRobots(2, rc.getTeam()); for (RobotInfo r : robots){ if (r.getType() != RobotType.POLITICIAN) continue; int conv = r.getConviction(); if ((int)(rc.getEmpowerFactor(rc.getTeam(), 25)*conv) <= muckConviction + GameConstants.EMPOWER_TAX) continue; if (1.5*(double)muckConviction + GameConstants.EMPOWER_TAX + 5 < r.getConviction()) continue; return true; } return false; } //this is what we do if there are no emergencies (enemy politicians or muckrakers nearby) NewRobot getStandardNewRobot(){ //System.err.println("Getting standard unit");//while ((closestEnemyMuckraker != null || !isSafe()) && getTypeStandard() == TypeDescription.SLANDERER) advanceUnitType(); TypeDescription type = getTypeStandard(); //we choose the type (right now this just gets typeOrder[currentType]) switch(type){ case MUCKRAKER: return new NewRobot(RobotType.MUCKRAKER, TypeDescription.MUCKRAKER, getMuckrakerInfluence(), lowestContDir(), true, getMuckrakerInfluence() > Util.MUCK_ATTACK_THRESHOLD); //standard muckraker build case SLANDERER: int slandererInf = getSlandererInf(rc.getInfluence() - getSafetyInfRaw()); if (slandererInf > 0) return new NewRobot(RobotType.SLANDERER, TypeDescription.SLANDERER, slandererInf, true, false); //build slanderer with maximal influence break; case POLITICIAN: int politicianInf = getSmallPoliticianInfluence(); if (politicianInf > 0) return new NewRobot(RobotType.POLITICIAN, TypeDescription.POLITICIAN, politicianInf, true, false); //standard politician build break; case BIG_POLITICIAN: int bpInf = getBigPoliInf(); if (bpInf > 0) return new NewRobot(RobotType.POLITICIAN, TypeDescription.BIG_POLITICIAN, bpInf, true, false); //dump all our remaining influence into big poli break; case BIG_MUCKRAKER: int bmInf = getBigMuckInf(); if (bmInf > 0) return new NewRobot(RobotType.MUCKRAKER, TypeDescription.BIG_MUCKRAKER, bmInf, true, false); //dump all our remaining influence into big poli break; case CONQUEROR: int conqInf = getInfConqueror(); Communication.RInfo r = comm.getBestNeutralEC(2*getMaxSlandererInf()); MapLocation loc = null; if (r != null) loc = comm.getBestNeutralEC(2*getMaxSlandererInf()).getMapLocation(); if (loc != null) { if (conqInf > 0) return new NewRobot(RobotType.POLITICIAN, TypeDescription.CONQUEROR, conqInf, loc,true, false); } break; case SMALL_POLITICIAN: int spInf = SMALL_POLITICIAN_INFLUENCE; if (spInf <= rc.getInfluence()){ return new NewRobot(RobotType.POLITICIAN, TypeDescription.SMALL_POLITICIAN, spInf,true, false); } break; } return new NewRobot(RobotType.MUCKRAKER, TypeDescription.MUCKRAKER, 1, lowestContDir(), false, true); //if we couldnt build what we wanted, build a muckraker } int getSafetyInfRaw(){ if (enemyCombinedAttack > 0) return SAFE_CONVICTION + enemyCombinedAttack; return 0; } int getSafetyInf(){ int safety = getSafetyInfRaw(); //check if we have enough to resist attack int safety2 = Math.max(0, getMaxSlandererInf() - 2*income); safety2 += Math.max(0, getSmallPoliticianInfluence() - 2*income); return Math.max(safety, safety2); } int getBigPoliInf(){ int safety = getSafetyInf(); int minInf = getMinBigPoliticianInfluence(); //minimum influence to build a big politician if (minInf + safety > rc.getInfluence()) { return 0; } return rc.getInfluence() - safety; } MapLocation lowestContDir(){ Direction bestDir = null; for (Direction dir : directions){ if (!rc.canBuildRobot(RobotType.MUCKRAKER, dir, 1)) continue; if (bestDir == null || buildDirCont[dir.ordinal()] < buildDirCont[bestDir.ordinal()]) bestDir = dir; } if (bestDir != null) return rc.getLocation().add(bestDir); return null; } TypeDescription getTypeStandard(){ boolean[] canBuild = new boolean[typeProportions.length]; if (shouldBuildSlanderer()) canBuild[TypeDescription.SLANDERER.ordinal()] = true; if (shouldBuildBigPoli()) canBuild[TypeDescription.BIG_POLITICIAN.ordinal()] = true; if (shouldBuildPolitician()) canBuild[TypeDescription.POLITICIAN.ordinal()] = true; if (shouldBuildMuckraker()) canBuild[TypeDescription.MUCKRAKER.ordinal()] = true; if (shouldBuildBigMuckraker()) canBuild[TypeDescription.BIG_MUCKRAKER.ordinal()] = true; if (shouldBuildConqueror()) canBuild[TypeDescription.CONQUEROR.ordinal()] = true; if (shouldbuildSmallPoli()) canBuild[TypeDescription.SMALL_POLITICIAN.ordinal()] = true; //System.err.println(canBuild[TypeDescription.CONQUEROR.ordinal()]); TypeDescription ans = null; double minCont = 0; for (int i = 0; i < typeDescriptions.length;++i){ if (!canBuild[i]) continue; //TypeDescription t = typeDescriptions[i]; if (ans == null || minCont > currentProportions[i]){ minCont = currentProportions[i]; ans = typeDescriptions[i]; } } return ans; } boolean shouldbuildSmallPoli(){ return rc.getRoundNum() <= SMALL_POLI_ROUND; } boolean shouldBuildConqueror(){ int conqInf = getInfConqueror(); if (conqInf > 0) return true; return false; } boolean shouldBuildSlanderer(){ if (closestEnemyMuckraker != null || !isSafe()) return false; return true; } boolean shouldBuildBigPoli(){ int bpInf = getBigPoliInf(); if (bpInf <= 0) return false; return true; } boolean shouldBuildMuckraker(){ return true; } boolean shouldBuildPolitician(){ if (rc.getRoundNum() <= SMALL_POLI_ROUND) return false; return true; } boolean shouldBuildBigMuckraker() { int bmInf = getBigMuckInf(); if (bmInf <= 0) return false; return true; } /* Methods to compute the influence of the next politician/muckraker. We use the typical 1 2 1 3 1 2 1 4 1 2 1 3 1 ... order (position of the first 1-bit in n). If the current number (or tier) is t, we build a politician/muckraker with f(t) influence, where f is hardcoded into the arrays below (if t > length of the array we pick the last one). */ int getInfConqueror(){ //TODO: save for slanderer maybe? //int safetyInf = getSafetyInf(); int safetyInf = getSafetyInfRaw(); Communication.RInfo ec = comm.getBestNeutralEC(2*getMaxSlandererInf()); if (ec == null) return 0; if (ec.influence > 2*getMaxSlandererInf()) return 0; int desiredInf = ec.influence + GameConstants.EMPOWER_TAX + 10; if (rc.getInfluence() < desiredInf + safetyInf) return 0; return desiredInf; } int getSlandererInf(int inf){ int msInf = getMaxSlandererInf(); if (inf > msInf) inf = msInf; for (int i = influences.length; i-- > 0;){ if (influences[i] <= inf) return influences[i]; } return 0; } int getSmallPoliticianInfluence(){ int bit = 0; int base = 2; while ((smallPoliticianIndex %base) == 0){ ++bit; base *= 2; } return politicianInf(bit); } final int[] poliTiers = new int[] {16, 24, 36, 54, 81, 121, 181}; int politicianInf(int tier){ int ans = 0; for (int i = 0; i < poliTiers.length; ++i){ if (i > tier) return ans; if (poliTiers[i] > rc.getInfluence()) return ans; ans = poliTiers[i]; } return ans; } int getMinBigPoliticianInfluence(){ return poliTiers[poliTiers.length - 1]; /*Communication.RInfo ec = comm.getBestNeutralEC(); if (ec == null) return 150; //int minInf = (int)((double)(ec.influence + GameConstants.EMPOWER_TAX + 10)/rc.getEmpowerFactor(rc.getTeam(), 30)); if (ec.influence > 2*getMaxSlandererInf()) return 150; return ec.influence + GameConstants.EMPOWER_TAX + 10; //return 150;*/ } int getBigMuckInf(){ int safety = getSafetyInf(); int minInf = getMinBigMuckInf(); //minimum influence to build a big politician if (minInf + safety > rc.getInfluence()) { return 0; } /*int safety = getSafetyInf(); int minInf = getMinBigMuckInf(); //minimum influence to build a big politician if (minInf + safety > rc.getInfluence()) { return 0; }*/ return minInf + (rc.getInfluence() - safety - minInf)/2; } int getMinBigMuckInf(){ return BIG_MUCK_INF; } int getMuckrakerInfluence(){ if (shouldBuild1HPMuck()) return 1; int bit = 0; int base = 2; while ((muckrakerIndex%base) == 0){ ++bit; base *= 2; } return muckrakerInf(bit); } final int[] muckTiers = new int[] {1, 13, 33, 43}; int muckrakerInf(int tier){ int ans = 1; for (int i = 0; i < muckTiers.length; ++i){ if (i > tier) return ans; if (muckTiers[i] > rc.getInfluence()) return ans; ans = muckTiers[i]; } return ans; } double fractionIncome(double r){ if (r < 400) return 0; return Math.min(0.5, (r-400)/2000); } final int MAX_VOTES = 751; final int MIN_TURN_BID = 170; final int MIN_TURN_STRONG_BID = 400; //TODO: improve this void bid(){ try { if (rc.getTeamVotes() >= MAX_VOTES) return; if (rc.getRoundNum() < MIN_TURN_BID) return; int votes = rc.getTeamVotes(); if (votes == rc.getRoundNum() - MIN_TURN_BID){ if (rc.canBid(1)) rc.bid(1); return; } if (rc.getRoundNum() < MIN_TURN_STRONG_BID + votes) return; int bid = 2; bid = Math.max(bid, (int)(fractionIncome(rc.getRoundNum())*income)); if (rc.getInfluence() >= 10000){ bid = Math.max(bid, rc.getInfluence()/100); } //if (rc.getRobotCount() <= 200 && rc.getRoundNum() <= 1000) return; if (rc.canBid(bid)){ rc.bid(bid); } } catch (Exception e){ e.printStackTrace(); } } static class CustomRInfo{ int conviction; MapLocation mLoc; CustomRInfo(int conviction, MapLocation mLoc){ this.conviction = conviction; this.mLoc = mLoc; } CustomRInfo(RobotInfo r){ this.conviction = r.getConviction(); this.mLoc = r.getLocation(); } } }
44640_7
/** * Create all entity EJBs in the uml model and put them in a hashmap * * @param entityEJBs list with all entity EJBs. * @param simpleModel the uml model. * @return HashMap with all UML Entity classes. */ private HashMap createEntityEJBs(ArrayList entityEJBs, SimpleModel simpleModel) { HashMap map = new HashMap(); for (int i = 0; i < entityEJBs.size(); i++) { Entity e = (Entity) entityEJBs.get(i); String documentation = e.getDescription().toString(); String name = e.getName().toString(); String refName = e.getRefName(); String tableName = e.getTableName(); String displayName = e.getDisplayName().toString(); String entityRootPackage = e.getRootPackage().toString(); simpleModel.addSimpleUmlPackage(entityRootPackage); String isCompositeKey = e.getIsComposite(); String isAssocation = e.getIsAssociationEntity(); // "true" or "false" // Use the refName to put all EntityEJBs in a HashMap. // Add the standard definition for the URLS. SimpleUmlClass umlClass = new SimpleUmlClass(name, SimpleModelElement.PUBLIC); // The e should be a UML Class. // Use the stereoType: simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_CLASS_ENTITY, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_DOCUMENTATION, documentation, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_TABLE_NAME, tableName, umlClass); if (!"".equals(displayName)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_DISPLAY_NAME, displayName, umlClass); } if ("true".equals(isCompositeKey)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_COMPOSITE_PRIMARY_KEY, e.getPrimaryKeyType().toString(), umlClass); } if ("true".equals(isAssocation)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_IS_ASSOCIATION, isAssocation, umlClass); } ArrayList fields = (ArrayList) e.getFields(); for (int j = 0; j < fields.size(); j++) { Field field = (Field) fields.get(j); String fieldType = field.getType(); String fieldName = field.getName().toString(); SimpleUmlClass type = (SimpleUmlClass) typeMappings.get(fieldType); if (type == null) { log("Unknown type: " + type + " for field " + fieldType); type = (SimpleUmlClass) typeMappings.get(this.stringType); } SimpleAttribute theAttribute = new SimpleAttribute(fieldName, SimpleModelElement.PUBLIC, type); umlClass.addSimpleAttribute(theAttribute); String foreignKey = field.getForeignKey().toString(); // "true" or "false" if the current field as a foreign key. if (field.isPrimaryKey()) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_PRIMARY_KEY, theAttribute); } else if (field.isNullable() == false) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_REQUIRED, theAttribute); } if (field.isForeignKey()) { // Niet duidelijk of het plaatsen van 2 stereotypes mogelijk is.... String stereoTypeForeignKey = JagUMLProfile.STEREOTYPE_ATTRIBUTE_FOREIGN_KEY; } String jdbcType = field.getJdbcType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_JDBC_TYPE, jdbcType, theAttribute); String sqlType = field.getSqlType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_SQL_TYPE, sqlType, theAttribute); String columnName = field.getColumnName(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_COLUMN_NAME, columnName, theAttribute); boolean autoGeneratedPrimarykey = field.getHasAutoGenPrimaryKey(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_AUTO_PRIMARY_KEY, "" + autoGeneratedPrimarykey, theAttribute); } SimpleUmlPackage pk = simpleModel.addSimpleUmlPackage(entityRootPackage); pk.addSimpleClassifier(umlClass); map.put(refName, umlClass); } return map; }
D-a-r-e-k/Code-Smells-Detection
Preparation/processed-dataset/god-class_2_942/4.java
1,134
// Niet duidelijk of het plaatsen van 2 stereotypes mogelijk is....
line_comment
nl
/** * Create all entity EJBs in the uml model and put them in a hashmap * * @param entityEJBs list with all entity EJBs. * @param simpleModel the uml model. * @return HashMap with all UML Entity classes. */ private HashMap createEntityEJBs(ArrayList entityEJBs, SimpleModel simpleModel) { HashMap map = new HashMap(); for (int i = 0; i < entityEJBs.size(); i++) { Entity e = (Entity) entityEJBs.get(i); String documentation = e.getDescription().toString(); String name = e.getName().toString(); String refName = e.getRefName(); String tableName = e.getTableName(); String displayName = e.getDisplayName().toString(); String entityRootPackage = e.getRootPackage().toString(); simpleModel.addSimpleUmlPackage(entityRootPackage); String isCompositeKey = e.getIsComposite(); String isAssocation = e.getIsAssociationEntity(); // "true" or "false" // Use the refName to put all EntityEJBs in a HashMap. // Add the standard definition for the URLS. SimpleUmlClass umlClass = new SimpleUmlClass(name, SimpleModelElement.PUBLIC); // The e should be a UML Class. // Use the stereoType: simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_CLASS_ENTITY, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_DOCUMENTATION, documentation, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_TABLE_NAME, tableName, umlClass); if (!"".equals(displayName)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_DISPLAY_NAME, displayName, umlClass); } if ("true".equals(isCompositeKey)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_COMPOSITE_PRIMARY_KEY, e.getPrimaryKeyType().toString(), umlClass); } if ("true".equals(isAssocation)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_IS_ASSOCIATION, isAssocation, umlClass); } ArrayList fields = (ArrayList) e.getFields(); for (int j = 0; j < fields.size(); j++) { Field field = (Field) fields.get(j); String fieldType = field.getType(); String fieldName = field.getName().toString(); SimpleUmlClass type = (SimpleUmlClass) typeMappings.get(fieldType); if (type == null) { log("Unknown type: " + type + " for field " + fieldType); type = (SimpleUmlClass) typeMappings.get(this.stringType); } SimpleAttribute theAttribute = new SimpleAttribute(fieldName, SimpleModelElement.PUBLIC, type); umlClass.addSimpleAttribute(theAttribute); String foreignKey = field.getForeignKey().toString(); // "true" or "false" if the current field as a foreign key. if (field.isPrimaryKey()) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_PRIMARY_KEY, theAttribute); } else if (field.isNullable() == false) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_REQUIRED, theAttribute); } if (field.isForeignKey()) { // Niet duidelijk<SUF> String stereoTypeForeignKey = JagUMLProfile.STEREOTYPE_ATTRIBUTE_FOREIGN_KEY; } String jdbcType = field.getJdbcType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_JDBC_TYPE, jdbcType, theAttribute); String sqlType = field.getSqlType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_SQL_TYPE, sqlType, theAttribute); String columnName = field.getColumnName(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_COLUMN_NAME, columnName, theAttribute); boolean autoGeneratedPrimarykey = field.getHasAutoGenPrimaryKey(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_AUTO_PRIMARY_KEY, "" + autoGeneratedPrimarykey, theAttribute); } SimpleUmlPackage pk = simpleModel.addSimpleUmlPackage(entityRootPackage); pk.addSimpleClassifier(umlClass); map.put(refName, umlClass); } return map; }
83661_21
package uni.sasjonge.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.util.stream.Collectors; import org.jgrapht.Graph; import org.jgrapht.graph.DefaultEdge; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.manchestersyntax.renderer.ManchesterOWLSyntaxOWLObjectRendererImpl; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLAnnotationValue; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLLiteral; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.search.EntitySearcher; import uni.sasjonge.Settings; /** * Create a label for a partition * * @author sascha * */ public class OntologyDescriptor { public static ManchesterOWLSyntaxOWLObjectRendererImpl manchester = new ManchesterOWLSyntaxOWLObjectRendererImpl(); // How many classes are represented through a [ClassLabel] private Map<String, Integer> numberOfRepresentedClasses; static Map<String, String> mapVertexToManchester; private OntologyHierarchy ontHierachy; public OntologyDescriptor(OntologyHierarchy ontHierachy, OWLOntology ontology) { this.ontHierachy = ontHierachy; // mapVertexToManchester = mapVertexToManchester(ontology); numberOfRepresentedClasses = new HashMap<>(); } public static Map<OWLObject, String> owlObjectToString = new HashMap<>(); public static String getCleanNameOWLObj(OWLObject owlOb) { if (!Settings.USE_RDF_LABEL) { String toReturn = owlObjectToString.get(owlOb); if (toReturn == null) { toReturn = getCleanName(owlOb.toString()); owlObjectToString.put(owlOb, toReturn); } return toReturn; } else { return owlObjectToString.get(owlOb); } } public static void initRDFSLabel(OWLOntology ont) { OWLDataFactory df = OWLManager.getOWLDataFactory(); ont.classesInSignature().forEach(c -> { ont.annotationAssertionAxioms(c.getIRI()).forEach(a -> { if (a.getProperty().isLabel()) { if (a.getValue() instanceof OWLLiteral) { OWLLiteral val = (OWLLiteral) a.getValue(); owlObjectToString.put(c, getCleanName(val.getLiteral().toString())); } } }); }); ont.objectPropertiesInSignature().forEach(c -> { ont.annotationAssertionAxioms(c.getIRI()).forEach(a -> { if (a.getProperty().isLabel()) { if (a.getValue() instanceof OWLLiteral) { OWLLiteral val = (OWLLiteral) a.getValue(); owlObjectToString.put(c, val.getLiteral()); } } }); }); ont.dataPropertiesInSignature().forEach(c -> { ont.annotationAssertionAxioms(c.getIRI()).forEach(a -> { if (a.getProperty().isLabel()) { if (a.getValue() instanceof OWLLiteral) { OWLLiteral val = (OWLLiteral) a.getValue(); owlObjectToString.put(c, val.getLiteral()); } } }); }); ont.individualsInSignature().forEach(c -> { ont.annotationAssertionAxioms(c.getIRI()).forEach(a -> { if (a.getProperty().isLabel()) { if (a.getValue() instanceof OWLLiteral) { OWLLiteral val = (OWLLiteral) a.getValue(); owlObjectToString.put(c, val.getLiteral()); } } }); }); // Vertex: SubConcepts ont.logicalAxioms().forEach(a -> { a.nestedClassExpressions().forEach(c -> { if (!owlObjectToString.containsKey(c)) { owlObjectToString.put(c, c.toString()); } }); }); System.out.println("!!!!!!!!!! LAbels: " + owlObjectToString.entrySet().size()); } public static String getCleanName(String owlName) { return owlName.replaceAll("http[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*#|<|>", ""); } public String getManchesterSyntax(OWLObject owlObject) { return manchester.render(owlObject); } /** * Returns a String of all Axioms corresponding to the given connected component * * @param cc Connected Component, List of Vertex Names * @param g Graph * @param edgeToAxiomName A map from edges to axioms * @return A String in form of a list of all axioms */ public String getAxiomString(Set<OWLAxiom> axioms) { if (axioms != null) { // Build the string StringBuilder toReturn = new StringBuilder(); toReturn.append("\n--------\nAxioms:\n"); int i = 0; for (OWLAxiom ax : axioms) { // toReturn.append(OntologyDescriptor.getCleanName(getManchesterSyntax(ax))); String man = manchester.render(ax); String name = OntologyDescriptor.getCleanName(man); toReturn.append(name.length() > 100 ? name.subSequence(0, 100) : name); toReturn.append("\n"); if (i > Settings.AXIOM_COUNT) { break; } i++; } ; return toReturn.toString(); } else { return ""; } } static boolean hasEntities = true; /** * Returns a String of all subConcepts corresponding to the given connected * component * * @param cc Connected Component, List of Vertex Names * @param g Graph * @param edgeToAxiomName A map from edges to sub concepts * @return A String in form of a list of all sub concepts */ public String getSubConceptString(Set<String> cc) { // Build the string StringBuilder toReturn = new StringBuilder(); toReturn.append("Subconcepts:\n"); cc.stream().forEach(vertex -> { toReturn.append(OntologyDescriptor.getCleanName(mapVertexToManchester.get(vertex))); toReturn.append("\n"); }); return toReturn.toString(); } public String getFilteredSubConceptString(Set<String> cc, int maxNumberOfConcepts) { StringBuilder builder = new StringBuilder(); builder.append("--" + cc.size() + " classes--\n"); // Descend into the classes to find classnames int depth = 0; int classesInString = 0; boolean addLastClass = false; boolean foundAnother = false; hasEntities = true; String className = ""; while (hasEntities) { if (ontHierachy.getClassesOfDepth(depth) != null) { for (OWLClass cls : ontHierachy.getClassesOfDepth(depth)) { if (cc.contains(getCleanNameOWLObj(cls))) { className = getCleanNameOWLObj(cls); if (!addLastClass) { builder.append(className); builder.append("\n"); classesInString++; } else { foundAnother = true; } // add dots and the last element if (classesInString > maxNumberOfConcepts - 2) { if (ontHierachy.getClassesOfDepth(depth).size() > maxNumberOfConcepts - 1) { addLastClass = true; } } hasEntities = false; } } ; } else { hasEntities = false; } if (addLastClass && foundAnother) { builder.append("...\n"); builder.append(className); } depth++; } return builder.toString(); } public String getFilteredPropertyString(Set<String> cc, int maxNumberOfConcepts) { StringBuilder builder = new StringBuilder(); // Descend into the classes to find classnames int depth = 0; int classesInString = 0; boolean addLastRoles = false; boolean foundAnother = false; hasEntities = true; String roleName = ""; while (hasEntities && depth <= ontHierachy.getHighestPropertyDepth()) { // System.out.println(depth); if (ontHierachy.getPropertiesOfDepth(depth) != null) { // System.out.println("RoleList: " + cc.toString()); for (OWLObjectProperty cls : ontHierachy.getPropertiesOfDepth(depth)) { // System.out.println("Testing for " + cls); if (cc.contains(getCleanNameOWLObj(cls))) { roleName = getCleanNameOWLObj(cls); if (!addLastRoles) { builder.append(roleName); builder.append("\n"); classesInString++; } else { foundAnother = true; } // add dots and the last element if (classesInString > maxNumberOfConcepts - 2) { if (ontHierachy.getPropertiesOfDepth(depth).size() > maxNumberOfConcepts - 1) { addLastRoles = true; } } hasEntities = false; } } ; } if (addLastRoles && foundAnother) { builder.append("...\n"); builder.append(addLastRoles); } depth++; } return builder.toString(); } public String getLabelForConnectedComponent(int numOfAxioms, Set<String> classesOfCC, Set<String> propertiesOfCC, Set<String> individualsOfCC) { StringBuilder builder = new StringBuilder(); // Header of form AXIOMS / CLASSES / PROPERTIES / INDIVIDUALS builder.append(numOfAxioms + " / " + (classesOfCC != null ? classesOfCC.size() : 0) + " / " + (propertiesOfCC != null ? propertiesOfCC.size() : 0) + " / " + (individualsOfCC != null ? individualsOfCC.size() : 0) + "\n"); // Add classes if (classesOfCC != null) { builder.append("-- Classes --\n"); builder.append(getClassesStringForCC(classesOfCC)); builder.append("\n"); } // Add properties if (propertiesOfCC != null) { builder.append("-- Properties --\n"); builder.append(getPropertiesStringForCC(propertiesOfCC)); builder.append("\n"); } // Add individuals if (individualsOfCC != null) { builder.append("-- Individuals --\n"); builder.append(getIndivStringForCC(individualsOfCC)); builder.append("\n"); } // Return answer // System.out.println("-------------"); // System.out.println("!!:" + classesOfCC); // System.out.println("!!:"+builder.toString()); // System.out.println("-------------"); return builder.toString(); } private String getClassesStringForCC(Set<String> classesOfCC) { Map<String, String> nodeToParent = ontHierachy.getClassToParentString(); Map<String, Set<String>> parentsToCollecteddNodes = ontHierachy.getParentToClassesString(); List<Collection<String>> groupStrings = new ArrayList<Collection<String>>(groupNodesByParents(nodeToParent, filterNodesByLevel(nodeToParent, parentsToCollecteddNodes, classesOfCC))); return createStringForGroupedStrings(sortGroupString(groupStrings), Settings.NUM_OF_CLASS_LABELS_TOPLEVEL, Settings.NUM_OF_CLASS_LABELS_SUBLEVEL); } private Collection<Collection<String>> sortGroupString(List<Collection<String>> groupStrings) { List<List<String>> newGroupCollection = groupStrings.stream().map(e -> new ArrayList<String>(e)) .collect(Collectors.toList()); for (List<String> group : newGroupCollection) { Collections.sort(group, String.CASE_INSENSITIVE_ORDER); Collections.sort(group, new Comparator<String>() { @Override public int compare(String o1, String o2) { if (numberOfRepresentedClasses.containsKey(o1) && numberOfRepresentedClasses.containsKey(o2)) { return numberOfRepresentedClasses.get(o2) - numberOfRepresentedClasses.get(o1); } else if (numberOfRepresentedClasses.containsKey(o1)) { return -1; } else if (numberOfRepresentedClasses.containsKey(o2)) { return 1; } return 0; } }); } Collections.sort(newGroupCollection, new Comparator<Collection<String>>() { @Override public int compare(Collection<String> firstGroup, Collection<String> secondGroup) { int firstGroupValue = 0, secondGroupValue = 0; for (String group : firstGroup) { if (numberOfRepresentedClasses.containsKey(group)) { firstGroupValue = firstGroupValue + numberOfRepresentedClasses.get(group); } else { firstGroupValue++; } } for (String group : secondGroup) { if (numberOfRepresentedClasses.containsKey(group)) { secondGroupValue = secondGroupValue + numberOfRepresentedClasses.get(group); } else { secondGroupValue++; } } if (firstGroupValue == secondGroupValue) { return firstGroup.toString().compareTo(secondGroup.toString()); } return secondGroupValue - firstGroupValue; } }); Collection<Collection<String>> toReturn = new ArrayList<>(newGroupCollection.size()); for (List<String> element : newGroupCollection) { toReturn.add(element); } return toReturn; } private String getIndivStringForCC(Set<String> classesOfCC) { List<String> classesOfCCList = new ArrayList<>(classesOfCC); Collections.sort(classesOfCCList, String.CASE_INSENSITIVE_ORDER); return createStringForGroupedStrings( classesOfCCList.stream().map(e -> Arrays.asList(e)).collect(Collectors.toSet()), Settings.NUM_OF_INDIV_LABELS, Settings.NUM_OF_INDIV_LABELS); } String getPropertiesStringForCC(Set<String> propertiesOfCC) { Map<String, String> nodeToParent = ontHierachy.getPropertyToParentString(); Map<String, Set<String>> parentsToCollecteddNodes = ontHierachy.getParentToPropertiesString(); List<Collection<String>> groupStrings = new ArrayList<Collection<String>>(groupNodesByParents(nodeToParent, filterNodesByLevel(nodeToParent, parentsToCollecteddNodes, propertiesOfCC))); return createStringForGroupedStrings(sortGroupString(groupStrings), Settings.NUM_OF_PROPERTY_LABELS_NODE_TOPLEVEL, Settings.NUM_OF_CLASS_LABELS_SUBLEVEL); } // private String getIndividualsStringForCC(Set<String> individualsOfCC) { // Map<String,String> nodeToParent = ontHierachy.getIndividualToParentString(); // Map<String,Set<String>> parentsToCollecteddNodes = ontHierachy.getParentToIndividualsString(); // // return createStringForGroupedStrings( // groupNodesByParents(nodeToParent, // filterNodesByLevel(nodeToParent, parentsToCollecteddNodes, individualsOfCC)), // Settings.NUM_OF_INDIVIDUAL_LABELS); // } /** * Creates a mapping from all vertexes in our graphs to their corresponding * manchester syntax * * @param ontology The corresponding ontology */ private Map<String, String> mapVertexToManchester(OWLOntology ontology) { Map<String, String> toReturn = new HashMap<>(); // Vertex: ObjectProperties ontology.objectPropertiesInSignature().forEach(objProp -> { if (!objProp.isOWLTopObjectProperty() && !objProp.isTopEntity()) { toReturn.put(objProp.toString() + Settings.PROPERTY_0_DESIGNATOR, manchester.render(objProp) + Settings.PROPERTY_0_DESIGNATOR); toReturn.put(objProp.toString() + Settings.PROPERTY_1_DESIGNATOR, manchester.render(objProp) + Settings.PROPERTY_1_DESIGNATOR); } }); // Vertex: DataProperties ontology.dataPropertiesInSignature().forEach(dataProp -> { if (!dataProp.isOWLTopDataProperty() && !dataProp.isTopEntity()) { toReturn.put(dataProp.toString(), manchester.render(dataProp).toString()); } }); // Vertex: SubConcepts ontology.logicalAxioms().forEach(a -> { a.nestedClassExpressions().forEach(nested -> { if (!nested.isOWLThing()) { toReturn.put(nested.toString(), manchester.render(nested)); } }); }); // Vertex: Individuals ontology.individualsInSignature().forEach(indiv -> { toReturn.put(indiv.toString(), manchester.render(indiv)); }); return toReturn; } public String createStringForGroupedStrings(Collection<Collection<String>> groupedStrings, int numberOfTopLevelGroups, int numberOfValuesPerSubGroup) { if (numberOfValuesPerSubGroup < 1) { throw new IllegalArgumentException("createNameForGroupedStrings needs atleast 1 allowed value per group"); } final String GROUP_OPENER = "{"; final String GROUP_CLOSER = "}"; StringBuilder builder = new StringBuilder(); Iterator<Collection<String>> groupIter = groupedStrings.iterator(); Collection<String> group = null; int addedForTLGroup = 0; while (addedForTLGroup < numberOfTopLevelGroups && groupIter.hasNext()) { addedForTLGroup++; group = groupIter.next(); builder.append(group.size() > 1 ? GROUP_OPENER : ""); int addedForThisSubGroup = 0; Iterator<String> iter = group.iterator(); while (addedForThisSubGroup < numberOfValuesPerSubGroup - 1 && iter.hasNext()) { builder.append(iter.next()); if (iter.hasNext()) { builder.append("\n"); } addedForThisSubGroup++; } if (iter.hasNext()) { builder.append("...\n"); String lastElement = ""; while (iter.hasNext()) { lastElement = iter.next(); } builder.append(lastElement + GROUP_CLOSER + "\n"); } else { builder.append(group.size() > 1 ? GROUP_CLOSER : ""); } if (groupIter.hasNext()) { builder.append("\n"); } } if (groupIter.hasNext()) { builder.append("..."); } return builder.toString(); } public Collection<Collection<String>> groupNodesByParents(Map<String, String> nodeToParent, Set<String> cc) { Map<String, Collection<String>> groupedByParent = new HashMap<>(); // unique index int unique_index = 1; // First decide to which group each String belongs for (String node : cc) { // get the parent name String parent = nodeToParent.get(node.replaceAll("^\\[|\\]$", "")); // If the node has a parent if (parent != null) { // Add node to corresponding Group if (!groupedByParent.containsKey(parent)) { groupedByParent.put(parent, new HashSet<>()); } groupedByParent.get(parent).add(node); } else { // if node has no parent add it with a unique index groupedByParent.put(node + ++unique_index, Arrays.asList(node)); } } return groupedByParent.values(); } public Set<String> filterNodesByLevel(Map<String, String> nodeToParent, Map<String, Set<String>> parentsToCollectedNodes, Set<String> cc) { // System.out.println(cc); Set<String> newCCDescriptor = new HashSet<>(); for (Entry<String, Set<String>> entry : parentsToCollectedNodes.entrySet()) { boolean containsAll = true; // if all childs of the parents are in the cc add the parent for (String subNode : entry.getValue()) { if (!cc.contains(subNode) && !cc.contains("[" + subNode + "]")) { // if(cc.contains("SpecificHeatCapacity") && entry.getKey().contains("Quantity")) { // System.out.println("-----------------------"); // System.out.println(entry.getKey()); // System.out.println(subNode); // System.out.println(cc); // System.out.println("------------------------"); // } containsAll = false; break; } } if (containsAll) { newCCDescriptor.add("[" + entry.getKey() + "]"); numberOfRepresentedClasses.put("[" + entry.getKey() + "]", calculateCurrentValues("[" + entry.getKey() + "]", entry.getValue())); } } for (String elementOfCC : cc) { if (!newCCDescriptor.contains("[" + elementOfCC + "]") && !containsAncestor(nodeToParent, newCCDescriptor, elementOfCC.replaceAll("^\\[|\\]$", "")) && !containsAncestor(nodeToParent, cc, elementOfCC.replaceAll("^\\[|\\]$", ""))) { newCCDescriptor.add(elementOfCC); // System.out.println("!!!!! " + elementOfCC); } } if (newCCDescriptor.equals(cc)) { return newCCDescriptor; } else { return filterNodesByLevel(nodeToParent, parentsToCollectedNodes, newCCDescriptor); } } private Integer calculateCurrentValues(String nameOfRepresentant, Set<String> value) { int toReturn = 0; for (String subClassName : value) { if (numberOfRepresentedClasses.containsKey(subClassName)) { toReturn = toReturn + numberOfRepresentedClasses.get(subClassName); } else { toReturn++; } } if (numberOfRepresentedClasses.containsKey(nameOfRepresentant) && numberOfRepresentedClasses.get(nameOfRepresentant).intValue() > toReturn) { return numberOfRepresentedClasses.get(nameOfRepresentant).intValue(); } return toReturn; } private boolean containsAncestor(Map<String, String> nodeToParent, Set<String> cc, String child) { return cc.contains("[" + nodeToParent.get(child.replaceAll("^\\[|\\]$", "")) + "]"); } // private boolean containsAncestor(Map<String, String> nodeToParent, Set<String> cc, String child) { // String parent = nodeToParent.get(child.replaceAll("^\\[|\\]$", "")); // while(parent != null) { // if (cc.contains("[" + parent + "]")) { // return true; // } // parent = nodeToParent.get(parent.replaceAll("^\\[|\\]$", "")); // } // return false; // } }
mpomarlan/epartition
src/main/java/uni/sasjonge/utils/OntologyDescriptor.java
5,952
// get the parent name
line_comment
nl
package uni.sasjonge.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.util.stream.Collectors; import org.jgrapht.Graph; import org.jgrapht.graph.DefaultEdge; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.manchestersyntax.renderer.ManchesterOWLSyntaxOWLObjectRendererImpl; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLAnnotationValue; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLLiteral; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.search.EntitySearcher; import uni.sasjonge.Settings; /** * Create a label for a partition * * @author sascha * */ public class OntologyDescriptor { public static ManchesterOWLSyntaxOWLObjectRendererImpl manchester = new ManchesterOWLSyntaxOWLObjectRendererImpl(); // How many classes are represented through a [ClassLabel] private Map<String, Integer> numberOfRepresentedClasses; static Map<String, String> mapVertexToManchester; private OntologyHierarchy ontHierachy; public OntologyDescriptor(OntologyHierarchy ontHierachy, OWLOntology ontology) { this.ontHierachy = ontHierachy; // mapVertexToManchester = mapVertexToManchester(ontology); numberOfRepresentedClasses = new HashMap<>(); } public static Map<OWLObject, String> owlObjectToString = new HashMap<>(); public static String getCleanNameOWLObj(OWLObject owlOb) { if (!Settings.USE_RDF_LABEL) { String toReturn = owlObjectToString.get(owlOb); if (toReturn == null) { toReturn = getCleanName(owlOb.toString()); owlObjectToString.put(owlOb, toReturn); } return toReturn; } else { return owlObjectToString.get(owlOb); } } public static void initRDFSLabel(OWLOntology ont) { OWLDataFactory df = OWLManager.getOWLDataFactory(); ont.classesInSignature().forEach(c -> { ont.annotationAssertionAxioms(c.getIRI()).forEach(a -> { if (a.getProperty().isLabel()) { if (a.getValue() instanceof OWLLiteral) { OWLLiteral val = (OWLLiteral) a.getValue(); owlObjectToString.put(c, getCleanName(val.getLiteral().toString())); } } }); }); ont.objectPropertiesInSignature().forEach(c -> { ont.annotationAssertionAxioms(c.getIRI()).forEach(a -> { if (a.getProperty().isLabel()) { if (a.getValue() instanceof OWLLiteral) { OWLLiteral val = (OWLLiteral) a.getValue(); owlObjectToString.put(c, val.getLiteral()); } } }); }); ont.dataPropertiesInSignature().forEach(c -> { ont.annotationAssertionAxioms(c.getIRI()).forEach(a -> { if (a.getProperty().isLabel()) { if (a.getValue() instanceof OWLLiteral) { OWLLiteral val = (OWLLiteral) a.getValue(); owlObjectToString.put(c, val.getLiteral()); } } }); }); ont.individualsInSignature().forEach(c -> { ont.annotationAssertionAxioms(c.getIRI()).forEach(a -> { if (a.getProperty().isLabel()) { if (a.getValue() instanceof OWLLiteral) { OWLLiteral val = (OWLLiteral) a.getValue(); owlObjectToString.put(c, val.getLiteral()); } } }); }); // Vertex: SubConcepts ont.logicalAxioms().forEach(a -> { a.nestedClassExpressions().forEach(c -> { if (!owlObjectToString.containsKey(c)) { owlObjectToString.put(c, c.toString()); } }); }); System.out.println("!!!!!!!!!! LAbels: " + owlObjectToString.entrySet().size()); } public static String getCleanName(String owlName) { return owlName.replaceAll("http[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*#|<|>", ""); } public String getManchesterSyntax(OWLObject owlObject) { return manchester.render(owlObject); } /** * Returns a String of all Axioms corresponding to the given connected component * * @param cc Connected Component, List of Vertex Names * @param g Graph * @param edgeToAxiomName A map from edges to axioms * @return A String in form of a list of all axioms */ public String getAxiomString(Set<OWLAxiom> axioms) { if (axioms != null) { // Build the string StringBuilder toReturn = new StringBuilder(); toReturn.append("\n--------\nAxioms:\n"); int i = 0; for (OWLAxiom ax : axioms) { // toReturn.append(OntologyDescriptor.getCleanName(getManchesterSyntax(ax))); String man = manchester.render(ax); String name = OntologyDescriptor.getCleanName(man); toReturn.append(name.length() > 100 ? name.subSequence(0, 100) : name); toReturn.append("\n"); if (i > Settings.AXIOM_COUNT) { break; } i++; } ; return toReturn.toString(); } else { return ""; } } static boolean hasEntities = true; /** * Returns a String of all subConcepts corresponding to the given connected * component * * @param cc Connected Component, List of Vertex Names * @param g Graph * @param edgeToAxiomName A map from edges to sub concepts * @return A String in form of a list of all sub concepts */ public String getSubConceptString(Set<String> cc) { // Build the string StringBuilder toReturn = new StringBuilder(); toReturn.append("Subconcepts:\n"); cc.stream().forEach(vertex -> { toReturn.append(OntologyDescriptor.getCleanName(mapVertexToManchester.get(vertex))); toReturn.append("\n"); }); return toReturn.toString(); } public String getFilteredSubConceptString(Set<String> cc, int maxNumberOfConcepts) { StringBuilder builder = new StringBuilder(); builder.append("--" + cc.size() + " classes--\n"); // Descend into the classes to find classnames int depth = 0; int classesInString = 0; boolean addLastClass = false; boolean foundAnother = false; hasEntities = true; String className = ""; while (hasEntities) { if (ontHierachy.getClassesOfDepth(depth) != null) { for (OWLClass cls : ontHierachy.getClassesOfDepth(depth)) { if (cc.contains(getCleanNameOWLObj(cls))) { className = getCleanNameOWLObj(cls); if (!addLastClass) { builder.append(className); builder.append("\n"); classesInString++; } else { foundAnother = true; } // add dots and the last element if (classesInString > maxNumberOfConcepts - 2) { if (ontHierachy.getClassesOfDepth(depth).size() > maxNumberOfConcepts - 1) { addLastClass = true; } } hasEntities = false; } } ; } else { hasEntities = false; } if (addLastClass && foundAnother) { builder.append("...\n"); builder.append(className); } depth++; } return builder.toString(); } public String getFilteredPropertyString(Set<String> cc, int maxNumberOfConcepts) { StringBuilder builder = new StringBuilder(); // Descend into the classes to find classnames int depth = 0; int classesInString = 0; boolean addLastRoles = false; boolean foundAnother = false; hasEntities = true; String roleName = ""; while (hasEntities && depth <= ontHierachy.getHighestPropertyDepth()) { // System.out.println(depth); if (ontHierachy.getPropertiesOfDepth(depth) != null) { // System.out.println("RoleList: " + cc.toString()); for (OWLObjectProperty cls : ontHierachy.getPropertiesOfDepth(depth)) { // System.out.println("Testing for " + cls); if (cc.contains(getCleanNameOWLObj(cls))) { roleName = getCleanNameOWLObj(cls); if (!addLastRoles) { builder.append(roleName); builder.append("\n"); classesInString++; } else { foundAnother = true; } // add dots and the last element if (classesInString > maxNumberOfConcepts - 2) { if (ontHierachy.getPropertiesOfDepth(depth).size() > maxNumberOfConcepts - 1) { addLastRoles = true; } } hasEntities = false; } } ; } if (addLastRoles && foundAnother) { builder.append("...\n"); builder.append(addLastRoles); } depth++; } return builder.toString(); } public String getLabelForConnectedComponent(int numOfAxioms, Set<String> classesOfCC, Set<String> propertiesOfCC, Set<String> individualsOfCC) { StringBuilder builder = new StringBuilder(); // Header of form AXIOMS / CLASSES / PROPERTIES / INDIVIDUALS builder.append(numOfAxioms + " / " + (classesOfCC != null ? classesOfCC.size() : 0) + " / " + (propertiesOfCC != null ? propertiesOfCC.size() : 0) + " / " + (individualsOfCC != null ? individualsOfCC.size() : 0) + "\n"); // Add classes if (classesOfCC != null) { builder.append("-- Classes --\n"); builder.append(getClassesStringForCC(classesOfCC)); builder.append("\n"); } // Add properties if (propertiesOfCC != null) { builder.append("-- Properties --\n"); builder.append(getPropertiesStringForCC(propertiesOfCC)); builder.append("\n"); } // Add individuals if (individualsOfCC != null) { builder.append("-- Individuals --\n"); builder.append(getIndivStringForCC(individualsOfCC)); builder.append("\n"); } // Return answer // System.out.println("-------------"); // System.out.println("!!:" + classesOfCC); // System.out.println("!!:"+builder.toString()); // System.out.println("-------------"); return builder.toString(); } private String getClassesStringForCC(Set<String> classesOfCC) { Map<String, String> nodeToParent = ontHierachy.getClassToParentString(); Map<String, Set<String>> parentsToCollecteddNodes = ontHierachy.getParentToClassesString(); List<Collection<String>> groupStrings = new ArrayList<Collection<String>>(groupNodesByParents(nodeToParent, filterNodesByLevel(nodeToParent, parentsToCollecteddNodes, classesOfCC))); return createStringForGroupedStrings(sortGroupString(groupStrings), Settings.NUM_OF_CLASS_LABELS_TOPLEVEL, Settings.NUM_OF_CLASS_LABELS_SUBLEVEL); } private Collection<Collection<String>> sortGroupString(List<Collection<String>> groupStrings) { List<List<String>> newGroupCollection = groupStrings.stream().map(e -> new ArrayList<String>(e)) .collect(Collectors.toList()); for (List<String> group : newGroupCollection) { Collections.sort(group, String.CASE_INSENSITIVE_ORDER); Collections.sort(group, new Comparator<String>() { @Override public int compare(String o1, String o2) { if (numberOfRepresentedClasses.containsKey(o1) && numberOfRepresentedClasses.containsKey(o2)) { return numberOfRepresentedClasses.get(o2) - numberOfRepresentedClasses.get(o1); } else if (numberOfRepresentedClasses.containsKey(o1)) { return -1; } else if (numberOfRepresentedClasses.containsKey(o2)) { return 1; } return 0; } }); } Collections.sort(newGroupCollection, new Comparator<Collection<String>>() { @Override public int compare(Collection<String> firstGroup, Collection<String> secondGroup) { int firstGroupValue = 0, secondGroupValue = 0; for (String group : firstGroup) { if (numberOfRepresentedClasses.containsKey(group)) { firstGroupValue = firstGroupValue + numberOfRepresentedClasses.get(group); } else { firstGroupValue++; } } for (String group : secondGroup) { if (numberOfRepresentedClasses.containsKey(group)) { secondGroupValue = secondGroupValue + numberOfRepresentedClasses.get(group); } else { secondGroupValue++; } } if (firstGroupValue == secondGroupValue) { return firstGroup.toString().compareTo(secondGroup.toString()); } return secondGroupValue - firstGroupValue; } }); Collection<Collection<String>> toReturn = new ArrayList<>(newGroupCollection.size()); for (List<String> element : newGroupCollection) { toReturn.add(element); } return toReturn; } private String getIndivStringForCC(Set<String> classesOfCC) { List<String> classesOfCCList = new ArrayList<>(classesOfCC); Collections.sort(classesOfCCList, String.CASE_INSENSITIVE_ORDER); return createStringForGroupedStrings( classesOfCCList.stream().map(e -> Arrays.asList(e)).collect(Collectors.toSet()), Settings.NUM_OF_INDIV_LABELS, Settings.NUM_OF_INDIV_LABELS); } String getPropertiesStringForCC(Set<String> propertiesOfCC) { Map<String, String> nodeToParent = ontHierachy.getPropertyToParentString(); Map<String, Set<String>> parentsToCollecteddNodes = ontHierachy.getParentToPropertiesString(); List<Collection<String>> groupStrings = new ArrayList<Collection<String>>(groupNodesByParents(nodeToParent, filterNodesByLevel(nodeToParent, parentsToCollecteddNodes, propertiesOfCC))); return createStringForGroupedStrings(sortGroupString(groupStrings), Settings.NUM_OF_PROPERTY_LABELS_NODE_TOPLEVEL, Settings.NUM_OF_CLASS_LABELS_SUBLEVEL); } // private String getIndividualsStringForCC(Set<String> individualsOfCC) { // Map<String,String> nodeToParent = ontHierachy.getIndividualToParentString(); // Map<String,Set<String>> parentsToCollecteddNodes = ontHierachy.getParentToIndividualsString(); // // return createStringForGroupedStrings( // groupNodesByParents(nodeToParent, // filterNodesByLevel(nodeToParent, parentsToCollecteddNodes, individualsOfCC)), // Settings.NUM_OF_INDIVIDUAL_LABELS); // } /** * Creates a mapping from all vertexes in our graphs to their corresponding * manchester syntax * * @param ontology The corresponding ontology */ private Map<String, String> mapVertexToManchester(OWLOntology ontology) { Map<String, String> toReturn = new HashMap<>(); // Vertex: ObjectProperties ontology.objectPropertiesInSignature().forEach(objProp -> { if (!objProp.isOWLTopObjectProperty() && !objProp.isTopEntity()) { toReturn.put(objProp.toString() + Settings.PROPERTY_0_DESIGNATOR, manchester.render(objProp) + Settings.PROPERTY_0_DESIGNATOR); toReturn.put(objProp.toString() + Settings.PROPERTY_1_DESIGNATOR, manchester.render(objProp) + Settings.PROPERTY_1_DESIGNATOR); } }); // Vertex: DataProperties ontology.dataPropertiesInSignature().forEach(dataProp -> { if (!dataProp.isOWLTopDataProperty() && !dataProp.isTopEntity()) { toReturn.put(dataProp.toString(), manchester.render(dataProp).toString()); } }); // Vertex: SubConcepts ontology.logicalAxioms().forEach(a -> { a.nestedClassExpressions().forEach(nested -> { if (!nested.isOWLThing()) { toReturn.put(nested.toString(), manchester.render(nested)); } }); }); // Vertex: Individuals ontology.individualsInSignature().forEach(indiv -> { toReturn.put(indiv.toString(), manchester.render(indiv)); }); return toReturn; } public String createStringForGroupedStrings(Collection<Collection<String>> groupedStrings, int numberOfTopLevelGroups, int numberOfValuesPerSubGroup) { if (numberOfValuesPerSubGroup < 1) { throw new IllegalArgumentException("createNameForGroupedStrings needs atleast 1 allowed value per group"); } final String GROUP_OPENER = "{"; final String GROUP_CLOSER = "}"; StringBuilder builder = new StringBuilder(); Iterator<Collection<String>> groupIter = groupedStrings.iterator(); Collection<String> group = null; int addedForTLGroup = 0; while (addedForTLGroup < numberOfTopLevelGroups && groupIter.hasNext()) { addedForTLGroup++; group = groupIter.next(); builder.append(group.size() > 1 ? GROUP_OPENER : ""); int addedForThisSubGroup = 0; Iterator<String> iter = group.iterator(); while (addedForThisSubGroup < numberOfValuesPerSubGroup - 1 && iter.hasNext()) { builder.append(iter.next()); if (iter.hasNext()) { builder.append("\n"); } addedForThisSubGroup++; } if (iter.hasNext()) { builder.append("...\n"); String lastElement = ""; while (iter.hasNext()) { lastElement = iter.next(); } builder.append(lastElement + GROUP_CLOSER + "\n"); } else { builder.append(group.size() > 1 ? GROUP_CLOSER : ""); } if (groupIter.hasNext()) { builder.append("\n"); } } if (groupIter.hasNext()) { builder.append("..."); } return builder.toString(); } public Collection<Collection<String>> groupNodesByParents(Map<String, String> nodeToParent, Set<String> cc) { Map<String, Collection<String>> groupedByParent = new HashMap<>(); // unique index int unique_index = 1; // First decide to which group each String belongs for (String node : cc) { // get the<SUF> String parent = nodeToParent.get(node.replaceAll("^\\[|\\]$", "")); // If the node has a parent if (parent != null) { // Add node to corresponding Group if (!groupedByParent.containsKey(parent)) { groupedByParent.put(parent, new HashSet<>()); } groupedByParent.get(parent).add(node); } else { // if node has no parent add it with a unique index groupedByParent.put(node + ++unique_index, Arrays.asList(node)); } } return groupedByParent.values(); } public Set<String> filterNodesByLevel(Map<String, String> nodeToParent, Map<String, Set<String>> parentsToCollectedNodes, Set<String> cc) { // System.out.println(cc); Set<String> newCCDescriptor = new HashSet<>(); for (Entry<String, Set<String>> entry : parentsToCollectedNodes.entrySet()) { boolean containsAll = true; // if all childs of the parents are in the cc add the parent for (String subNode : entry.getValue()) { if (!cc.contains(subNode) && !cc.contains("[" + subNode + "]")) { // if(cc.contains("SpecificHeatCapacity") && entry.getKey().contains("Quantity")) { // System.out.println("-----------------------"); // System.out.println(entry.getKey()); // System.out.println(subNode); // System.out.println(cc); // System.out.println("------------------------"); // } containsAll = false; break; } } if (containsAll) { newCCDescriptor.add("[" + entry.getKey() + "]"); numberOfRepresentedClasses.put("[" + entry.getKey() + "]", calculateCurrentValues("[" + entry.getKey() + "]", entry.getValue())); } } for (String elementOfCC : cc) { if (!newCCDescriptor.contains("[" + elementOfCC + "]") && !containsAncestor(nodeToParent, newCCDescriptor, elementOfCC.replaceAll("^\\[|\\]$", "")) && !containsAncestor(nodeToParent, cc, elementOfCC.replaceAll("^\\[|\\]$", ""))) { newCCDescriptor.add(elementOfCC); // System.out.println("!!!!! " + elementOfCC); } } if (newCCDescriptor.equals(cc)) { return newCCDescriptor; } else { return filterNodesByLevel(nodeToParent, parentsToCollectedNodes, newCCDescriptor); } } private Integer calculateCurrentValues(String nameOfRepresentant, Set<String> value) { int toReturn = 0; for (String subClassName : value) { if (numberOfRepresentedClasses.containsKey(subClassName)) { toReturn = toReturn + numberOfRepresentedClasses.get(subClassName); } else { toReturn++; } } if (numberOfRepresentedClasses.containsKey(nameOfRepresentant) && numberOfRepresentedClasses.get(nameOfRepresentant).intValue() > toReturn) { return numberOfRepresentedClasses.get(nameOfRepresentant).intValue(); } return toReturn; } private boolean containsAncestor(Map<String, String> nodeToParent, Set<String> cc, String child) { return cc.contains("[" + nodeToParent.get(child.replaceAll("^\\[|\\]$", "")) + "]"); } // private boolean containsAncestor(Map<String, String> nodeToParent, Set<String> cc, String child) { // String parent = nodeToParent.get(child.replaceAll("^\\[|\\]$", "")); // while(parent != null) { // if (cc.contains("[" + parent + "]")) { // return true; // } // parent = nodeToParent.get(parent.replaceAll("^\\[|\\]$", "")); // } // return false; // } }
178705_24
package Jaybot.YOLOBOT.Util.Planner; import core.game.Observation; import Jaybot.YOLOBOT.Util.Wissensdatenbank.PlayerEvent; import Jaybot.YOLOBOT.Util.Wissensdatenbank.YoloEvent; import Jaybot.YOLOBOT.Util.Wissensdatenbank.YoloKnowledge; import Jaybot.YOLOBOT.YoloState; import ontology.Types; import ontology.Types.ACTIONS; import java.util.*; public class KnowledgeBasedAStar { public static final int MALUS = 40; private List<Observation>[][] grid; public int[][] distance; public int[][] fromAvatarDistance; public byte[][] originDirectionArray; public int[][] ausnahmeID; public boolean[][] interpretedAsWall; public int[] fieldsReachedCount; private boolean stopEarly; private int stopEarlyX, stopEarlyY; private boolean extraIllegalMove; private int extraIllegalMoveX, extraIllegalMoveY, extraIllegalMoveItype; private int oneMoveableIgnoreIType; private byte[] zycleMet; private Collection<Integer> blacklistedObjects; public int[] iTypesFoundCount; public Observation[] nearestITypeObservationFound; public int[] nearestITypeObservationFoundFirstTargetX; public int[] nearestITypeObservationFoundFirstTargetY; private boolean countFoundItypes; private HashSet<Integer> countedObsIds; private int[] possibleMovesX, possibleMovesY; /*** * Direction from where it got reached.<br/> * 0 = Left<br/> * 1 = Right<br/> * 2 = Top<br/> * 3 = Bottom<br/> * 5 = By Portal */ public byte[][] from; public final static byte LEFT = 0; public final static byte RIGHT = 1; public final static byte TOP = 2; public final static byte BOTTOM = 3; private static boolean[] markedItypes; private byte[] inventoryItems; private YoloState state; private boolean moveDirectionInverse; public KnowledgeBasedAStar(YoloState yoloState) { this.state = yoloState; this.grid = yoloState.getObservationGrid(); inventoryItems = yoloState.getInventoryArray(); oneMoveableIgnoreIType = -1; countFoundItypes = false; moveDirectionInverse = false; ArrayList<ACTIONS> actions = yoloState.getAvailableActions(); //TODO use action? int actionsSize = actions.size() - (actions.contains(ACTIONS.ACTION_USE)?1:0); possibleMovesX = new int[actionsSize]; possibleMovesY = new int[actionsSize]; int ignoredActions = 0; for (int i = 0; i < actions.size(); i++) { switch (actions.get(i)) { case ACTION_DOWN: possibleMovesY[i-ignoredActions] = 1; break; case ACTION_UP: possibleMovesY[i-ignoredActions] = -1; break; case ACTION_RIGHT: possibleMovesX[i-ignoredActions] = 1; break; case ACTION_LEFT: possibleMovesX[i-ignoredActions] = -1; break; default: ignoredActions++; break; } } } public void setIllegalMove(int x, int y, int itype){ extraIllegalMove = true; extraIllegalMoveX = x; extraIllegalMoveY = y; extraIllegalMoveItype = itype; } public void disableIllegalMove(){ extraIllegalMove = false; } public void setStopEarly(int x, int y){ stopEarly = true; stopEarlyX = x; stopEarlyY = y; } public void disableStopEarly(){ stopEarly = false; } public void setGrid(List<Observation>[][] grid) { this.grid = grid; } public List<Observation> calculate(int startX, int startY, int agent_itype_start, int[] interestingItypes, boolean ignoreMoveables) { return calculate(startX, startY, agent_itype_start, interestingItypes, ignoreMoveables, false, true); } public List<Observation> calculate(int startX, int startY, int agent_itype_start, int[] interestingItypes, boolean ignoreMoveables, boolean ignoreNPC, boolean ignorePortals) { LinkedList<Observation> retVal = new LinkedList<Observation>(); if(!YoloKnowledge.instance.positionAufSpielfeld(startX, startY)) return null; if(countFoundItypes){ iTypesFoundCount = new int[YoloKnowledge.ITYPE_MAX_COUNT]; nearestITypeObservationFound = new Observation[YoloKnowledge.ITYPE_MAX_COUNT]; nearestITypeObservationFoundFirstTargetX = new int[YoloKnowledge.ITYPE_MAX_COUNT]; nearestITypeObservationFoundFirstTargetY = new int[YoloKnowledge.ITYPE_MAX_COUNT]; countedObsIds = new HashSet<Integer>(); } fieldsReachedCount = new int[4]; zycleMet = new byte[]{0b0001,0b0010,0b0100,0b1000}; markedItypes = new boolean[YoloKnowledge.ITYPE_MAX_COUNT]; for (int i = 0; i < interestingItypes.length; i++) { if(interestingItypes[i] != -1) markedItypes[interestingItypes[i]] = true; } originDirectionArray = new byte[grid.length][grid[0].length]; distance = new int[grid.length][grid[0].length]; ausnahmeID = new int[grid.length][grid[0].length]; distance[startX][startY] = 1; from = new byte[grid.length][grid[0].length]; interpretedAsWall = new boolean[grid.length][grid[0].length]; PriorityQueue<AStarEntry> queue = new PriorityQueue<AStarEntry>(); queue.add(new AStarEntry(startX, startY, agent_itype_start, oneMoveableIgnoreIType, (byte)-1, 1, -1, -1)); if(countFoundItypes){ for (Observation obs : grid[startX][startY]) { if(countedObsIds.contains(obs.obsID)) continue; countedObsIds.add(obs.obsID); int index = YoloKnowledge.instance.itypeToIndex(obs.itype); if(blacklistedObjects != null && blacklistedObjects.contains(obs.obsID)) continue; int oldVal = iTypesFoundCount[index]++; if(oldVal == 0){ //Nearest Observation of this itype: nearestITypeObservationFound[index] = obs; nearestITypeObservationFoundFirstTargetX[index] = startX; nearestITypeObservationFoundFirstTargetY[index] = startY; } } } while (queue.size() > 0) { AStarEntry oldEntry = queue.poll(); int x = oldEntry.getX(); int y = oldEntry.getY(); int agent_itype = oldEntry.getItype(); int itypeAusnahme = oldEntry.getItypeAusnahme(); int oldDistance = oldEntry.getDistance(); byte fromDirectionOld = oldEntry.getOriginAusrichtung(); int changedItypeX = oldEntry.getxFirstItypeChange(); int changedItypeY = oldEntry.getyFirstItypeChange(); for (int i = 0; i < possibleMovesX.length; i++) { int xNew = x + possibleMovesX[i]; int yNew = y + possibleMovesY[i]; int newDistance = oldDistance + 1; byte fromDirection = fromDirectionOld; if (xNew >= 0 && xNew < grid.length && yNew >= 0 && yNew < grid[xNew].length && (xNew == x || yNew == y)){ //First-step-check: if(fromDirection == -1){ //Is first step: if(possibleMovesX[i]>0) fromDirection = RIGHT; else if(possibleMovesX[i] < 0) fromDirection = LEFT; if(possibleMovesY[i]>0) fromDirection = BOTTOM; else if(possibleMovesY[i] < 0) fromDirection = TOP; } //Gueltiges Feld if(distance[xNew][yNew] == 0 || interpretedAsWall[xNew][yNew]){ //Neu gefunden! boolean moveBlocked = false; boolean isPortalEntry = false; int deadlyField = canBeKilledAtByStochasticEnemy(xNew, yNew); int new_itype = agent_itype; int portalIType = -1; boolean[] blockedBy = new boolean[grid[xNew][yNew].size()]; boolean[] useActionEffective = new boolean[grid[xNew][yNew].size()]; int nr = 0; for (Observation obs : grid[xNew][yNew]) { if(ignoreNPC && obs.category == Types.TYPE_NPC){// && (fromAvatarDistance == null || fromAvatarDistance[xNew][yNew] > 5) && (fromAvatarDistance != null || distance[xNew][yNew] > 5)){ continue; } if(obs.category == Types.TYPE_PORTAL){ if(!moveDirectionInverse) portalIType = obs.itype; PlayerEvent pEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, obs.itype, true); YoloEvent event = pEvent.getEvent(inventoryItems); if(!pEvent.willCancel(inventoryItems) && event.getTeleportTo() != -1) isPortalEntry = true; } if(moveDirectionInverse){ int fromTeleport = YoloKnowledge.instance.getPortalExitEntryIType(YoloKnowledge.instance.itypeToIndex(obs.itype)); portalIType = fromTeleport; } if(obs.category != Types.TYPE_AVATAR){ int passiveIndex = YoloKnowledge.instance.itypeToIndex(obs.itype); PlayerEvent event = YoloKnowledge.instance.getPlayerEvent(agent_itype, obs.itype, true); int spawnIndex = YoloKnowledge.instance.getSpawnIndexOfSpawner(obs.itype); boolean isBadSpawner = false; if(spawnIndex != -1){ //Etwas wird gespawnt! PlayerEvent spawnCollisionEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, YoloKnowledge.instance.indexToItype(spawnIndex), true); if(spawnCollisionEvent.getObserveCount() > 0){ YoloEvent yEvent = spawnCollisionEvent.getEvent(inventoryItems); isBadSpawner = yEvent.getKill() || yEvent.getScoreDelta() < 0 || yEvent.getRemoveInventorySlotItem() != -1; } } boolean interactable = YoloKnowledge.instance.canInteractWithUse(agent_itype, obs.itype); useActionEffective[nr] = interactable; boolean deadly = event.getEvent(inventoryItems).getKill() && !YoloKnowledge.instance.hasEverBeenAliveAtFieldWithItypeIndex(YoloKnowledge.instance.itypeToIndex(agent_itype),passiveIndex) && obs.category != Types.TYPE_MOVABLE; if(deadly) deadlyField = 0; blockedBy[nr] = isBadSpawner || (event.getObserveCount() > 0 && (event.willCancel(inventoryItems) || !event.getEvent(inventoryItems).getMove() || (deadly ))) && !interactable; if(!(moveBlocked||blockedBy[nr]) && !ignoreMoveables && event.getObserveCount() > 0){ if(obs.category == Types.TYPE_MOVABLE && !event.getEvent(inventoryItems).getMove()){ //Hier wird wegen eines MOVEABLES geblockt! Teste oneMoveableIgnoreIType if(itypeAusnahme == obs.itype){ //Ausnahme trifft ein, dass ein bestimmter IType ein mal ignoriert werden darf! ausnahmeID[xNew][yNew] = obs.obsID; itypeAusnahme = -1; }else{ //Keine Ausnahme! blockedBy[nr] = true; } } } moveBlocked |= blockedBy[nr]; if(markedItypes[obs.itype]) retVal.add(obs); if(!moveBlocked){ int modType = event.getEvent(inventoryItems).getIType(); if(modType != -1){ new_itype = YoloKnowledge.instance.indexToItype(modType); if(changedItypeX == -1 && changedItypeY == -1){ // not yet changed Itype: changedItypeX = xNew; changedItypeY = yNew; } } } } nr++; } if(deadlyField != Integer.MAX_VALUE) newDistance += 2*MALUS/(deadlyField+1); moveBlocked |= !ignorePortals && isPortalEntry && moveDirectionInverse; if(!moveBlocked && extraIllegalMove && extraIllegalMoveX == xNew && extraIllegalMoveY == yNew){ //Stepping on illegal field PlayerEvent event = YoloKnowledge.instance.getPlayerEvent(agent_itype, extraIllegalMoveItype, false); //Was passiert mit dem passive? YoloEvent triggeredEvent = event.getEvent(inventoryItems); if(triggeredEvent.getMove() || event.getObserveCount() == 0) //Passive bewegt sich? moveBlocked = true; } if(distance[xNew][yNew] == 0 || (interpretedAsWall[xNew][yNew] && !moveBlocked)){ distance[xNew][yNew] = newDistance; from[xNew][yNew] = (byte)((xNew < x?0:(xNew > x?1:(yNew < y?2:3)))); } interpretedAsWall[xNew][yNew] = moveBlocked; //Count appearances: if(countFoundItypes && deadlyField > 1){ nr = -1; for (Observation obs : grid[xNew][yNew]) { nr++; if(countedObsIds.contains(obs.obsID) || (moveBlocked && !blockedBy[nr] && !useActionEffective[nr])) continue; countedObsIds.add(obs.obsID); int index = YoloKnowledge.instance.itypeToIndex(obs.itype); if(blacklistedObjects != null && blacklistedObjects.contains(obs.obsID)) continue; int oldVal = iTypesFoundCount[index]++; if(oldVal == 0){ //Nearest Observation of this itype: nearestITypeObservationFound[index] = obs; if(changedItypeX != -1 && changedItypeY != -1){ //Itype has been changed, so move frist to Itypechange! nearestITypeObservationFoundFirstTargetX[index] = changedItypeX; nearestITypeObservationFoundFirstTargetY[index] = changedItypeY; }else{ //Itype has not been changed, move to object nearestITypeObservationFoundFirstTargetX[index] = xNew; nearestITypeObservationFoundFirstTargetY[index] = yNew; } } } } if(!moveBlocked){ fieldsReachedCount[fromDirection]++; originDirectionArray[xNew][yNew] = fromDirection; //Early Stop if(stopEarly && xNew == stopEarlyX && yNew == stopEarlyY) return retVal; boolean teleported = false; if(portalIType != -1 && !ignorePortals){ int portalExitIType = -1, portalExitIndex; if(!moveDirectionInverse){ PlayerEvent pEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, portalIType, true); YoloEvent event = pEvent.getEvent(inventoryItems); portalExitIndex = event.getTeleportTo(); if(!pEvent.willCancel(inventoryItems) && portalExitIndex != -1) portalExitIType = YoloKnowledge.instance.indexToItype(portalExitIndex); }else{ portalExitIType = portalIType; portalExitIndex = YoloKnowledge.instance.itypeToIndex(portalExitIType); } if(portalExitIType != -1){ int portalExitCategory = YoloKnowledge.instance.getObjectCategory(portalExitIndex, state); if(portalExitCategory != -1){ ArrayList<Observation>[] obs = state.getObservationList(portalExitCategory); if(obs != null){ ArrayList<Observation> portalExits = null; for (ArrayList<Observation> list : obs) { if(!list.isEmpty() && list.get(0).itype == portalExitIType) portalExits = list; } if(portalExits != null){ //Habe Portalausgaenge gefunden! teleported = true; int blockSize = state.getBlockSize(); for (Observation exit : portalExits) { xNew = (int)exit.position.x/blockSize; yNew = (int)exit.position.y/blockSize; if(xNew < 0 || yNew < 0 || xNew >= distance.length ||yNew >= distance[xNew].length) continue; if(distance[xNew][yNew] == 0 || interpretedAsWall[xNew][yNew]){ //Hier war die SUche noch nicht! from[xNew][yNew] = 5; originDirectionArray[xNew][yNew] = fromDirection; distance[xNew][yNew] = newDistance; queue.add(new AStarEntry(xNew, yNew, new_itype, itypeAusnahme, fromDirection, newDistance, changedItypeX, changedItypeY)); }else if(distance[xNew][yNew]>1 && !interpretedAsWall[xNew][yNew]){ //Hier waren wir schon, untersuche zyklus handleZyklus(fromDirection, originDirectionArray[xNew][yNew]); } } } } } } } if(!teleported){ //Standard appending for later loop queue.add(new AStarEntry(xNew, yNew, new_itype, itypeAusnahme, fromDirection, newDistance, changedItypeX, changedItypeY)); } } }else if(distance[xNew][yNew]>1 && !interpretedAsWall[xNew][yNew]){ //Hier waren wir schon, untersuche zyklus handleZyklus(fromDirection, originDirectionArray[xNew][yNew]); } } } } //Postwork - zycles: for (int iteration = 0; iteration < 2; iteration++) { for (int from = 0; from < zycleMet.length; from++) { for (int to = 0; to < 4; to++) { if(to == from) continue; if((zycleMet[from]>>to & 1) == 1){ //from hat zykel zu to byte newMask = (byte) (zycleMet[from] | zycleMet[to]); zycleMet[from] = newMask; zycleMet[to] = newMask; } } } } int[] oldFieldReached = new int[]{fieldsReachedCount[0],fieldsReachedCount[1],fieldsReachedCount[2],fieldsReachedCount[3]}; for (int from = 0; from < zycleMet.length; from++) { fieldsReachedCount[from] = 0; for (int to = 0; to < 4; to++) { if((zycleMet[from]>>to & 1) == 1){ //from hat zykel zu to fieldsReachedCount[from] += oldFieldReached[to]; } } } return retVal; } private int canBeKilledAtByStochasticEnemy(int x, int y){ return state.getStochasticKillMap().getMinDistanceToEnemy(x,y); } public LinkedList<ACTIONS> extractActions(int xTarget, int yTarget) { LinkedList<ACTIONS> actionsToDo = new LinkedList<ACTIONS>(); if (distance[xTarget][yTarget] > 1) { // Weg gefunden(!= 0) und bewegen notwendig(!= 1) int curX = xTarget; int curY = yTarget; while (distance[curX][curY] > 1) { switch (from[curX][curY]) { case KnowledgeBasedAStar.BOTTOM: actionsToDo.addFirst(ACTIONS.ACTION_DOWN); curY--; break; case KnowledgeBasedAStar.TOP: actionsToDo.addFirst(ACTIONS.ACTION_UP); curY++; break; case KnowledgeBasedAStar.LEFT: actionsToDo.addFirst(ACTIONS.ACTION_LEFT); curX++; break; case KnowledgeBasedAStar.RIGHT: actionsToDo.addFirst(ACTIONS.ACTION_RIGHT); curX--; break; default: //TODO: Portal-Case beachten! System.err.println("Portal gefunden, aber 'extractActions' wurde noch nicht passend implementiert!!"); break; } } } return actionsToDo; } public void setIgnoreOneMoveableOfType(int itype) { oneMoveableIgnoreIType = itype; } public void setCountFoundItypes(boolean value) { this.countFoundItypes = value; } public void setMoveDirectionInverse(boolean value) { moveDirectionInverse = value; fromAvatarDistance = distance; } private void handleZyklus(byte direction1, byte direction2){ zycleMet[direction1] |= 1<<direction2; } public void setBlacklistedObjects(Collection<Integer> blacklistedObjects) { this.blacklistedObjects = blacklistedObjects; } }
teaCube/Jaybot
src/main/java/Jaybot/YOLOBOT/Util/Planner/KnowledgeBasedAStar.java
5,528
//TODO: Portal-Case beachten!
line_comment
nl
package Jaybot.YOLOBOT.Util.Planner; import core.game.Observation; import Jaybot.YOLOBOT.Util.Wissensdatenbank.PlayerEvent; import Jaybot.YOLOBOT.Util.Wissensdatenbank.YoloEvent; import Jaybot.YOLOBOT.Util.Wissensdatenbank.YoloKnowledge; import Jaybot.YOLOBOT.YoloState; import ontology.Types; import ontology.Types.ACTIONS; import java.util.*; public class KnowledgeBasedAStar { public static final int MALUS = 40; private List<Observation>[][] grid; public int[][] distance; public int[][] fromAvatarDistance; public byte[][] originDirectionArray; public int[][] ausnahmeID; public boolean[][] interpretedAsWall; public int[] fieldsReachedCount; private boolean stopEarly; private int stopEarlyX, stopEarlyY; private boolean extraIllegalMove; private int extraIllegalMoveX, extraIllegalMoveY, extraIllegalMoveItype; private int oneMoveableIgnoreIType; private byte[] zycleMet; private Collection<Integer> blacklistedObjects; public int[] iTypesFoundCount; public Observation[] nearestITypeObservationFound; public int[] nearestITypeObservationFoundFirstTargetX; public int[] nearestITypeObservationFoundFirstTargetY; private boolean countFoundItypes; private HashSet<Integer> countedObsIds; private int[] possibleMovesX, possibleMovesY; /*** * Direction from where it got reached.<br/> * 0 = Left<br/> * 1 = Right<br/> * 2 = Top<br/> * 3 = Bottom<br/> * 5 = By Portal */ public byte[][] from; public final static byte LEFT = 0; public final static byte RIGHT = 1; public final static byte TOP = 2; public final static byte BOTTOM = 3; private static boolean[] markedItypes; private byte[] inventoryItems; private YoloState state; private boolean moveDirectionInverse; public KnowledgeBasedAStar(YoloState yoloState) { this.state = yoloState; this.grid = yoloState.getObservationGrid(); inventoryItems = yoloState.getInventoryArray(); oneMoveableIgnoreIType = -1; countFoundItypes = false; moveDirectionInverse = false; ArrayList<ACTIONS> actions = yoloState.getAvailableActions(); //TODO use action? int actionsSize = actions.size() - (actions.contains(ACTIONS.ACTION_USE)?1:0); possibleMovesX = new int[actionsSize]; possibleMovesY = new int[actionsSize]; int ignoredActions = 0; for (int i = 0; i < actions.size(); i++) { switch (actions.get(i)) { case ACTION_DOWN: possibleMovesY[i-ignoredActions] = 1; break; case ACTION_UP: possibleMovesY[i-ignoredActions] = -1; break; case ACTION_RIGHT: possibleMovesX[i-ignoredActions] = 1; break; case ACTION_LEFT: possibleMovesX[i-ignoredActions] = -1; break; default: ignoredActions++; break; } } } public void setIllegalMove(int x, int y, int itype){ extraIllegalMove = true; extraIllegalMoveX = x; extraIllegalMoveY = y; extraIllegalMoveItype = itype; } public void disableIllegalMove(){ extraIllegalMove = false; } public void setStopEarly(int x, int y){ stopEarly = true; stopEarlyX = x; stopEarlyY = y; } public void disableStopEarly(){ stopEarly = false; } public void setGrid(List<Observation>[][] grid) { this.grid = grid; } public List<Observation> calculate(int startX, int startY, int agent_itype_start, int[] interestingItypes, boolean ignoreMoveables) { return calculate(startX, startY, agent_itype_start, interestingItypes, ignoreMoveables, false, true); } public List<Observation> calculate(int startX, int startY, int agent_itype_start, int[] interestingItypes, boolean ignoreMoveables, boolean ignoreNPC, boolean ignorePortals) { LinkedList<Observation> retVal = new LinkedList<Observation>(); if(!YoloKnowledge.instance.positionAufSpielfeld(startX, startY)) return null; if(countFoundItypes){ iTypesFoundCount = new int[YoloKnowledge.ITYPE_MAX_COUNT]; nearestITypeObservationFound = new Observation[YoloKnowledge.ITYPE_MAX_COUNT]; nearestITypeObservationFoundFirstTargetX = new int[YoloKnowledge.ITYPE_MAX_COUNT]; nearestITypeObservationFoundFirstTargetY = new int[YoloKnowledge.ITYPE_MAX_COUNT]; countedObsIds = new HashSet<Integer>(); } fieldsReachedCount = new int[4]; zycleMet = new byte[]{0b0001,0b0010,0b0100,0b1000}; markedItypes = new boolean[YoloKnowledge.ITYPE_MAX_COUNT]; for (int i = 0; i < interestingItypes.length; i++) { if(interestingItypes[i] != -1) markedItypes[interestingItypes[i]] = true; } originDirectionArray = new byte[grid.length][grid[0].length]; distance = new int[grid.length][grid[0].length]; ausnahmeID = new int[grid.length][grid[0].length]; distance[startX][startY] = 1; from = new byte[grid.length][grid[0].length]; interpretedAsWall = new boolean[grid.length][grid[0].length]; PriorityQueue<AStarEntry> queue = new PriorityQueue<AStarEntry>(); queue.add(new AStarEntry(startX, startY, agent_itype_start, oneMoveableIgnoreIType, (byte)-1, 1, -1, -1)); if(countFoundItypes){ for (Observation obs : grid[startX][startY]) { if(countedObsIds.contains(obs.obsID)) continue; countedObsIds.add(obs.obsID); int index = YoloKnowledge.instance.itypeToIndex(obs.itype); if(blacklistedObjects != null && blacklistedObjects.contains(obs.obsID)) continue; int oldVal = iTypesFoundCount[index]++; if(oldVal == 0){ //Nearest Observation of this itype: nearestITypeObservationFound[index] = obs; nearestITypeObservationFoundFirstTargetX[index] = startX; nearestITypeObservationFoundFirstTargetY[index] = startY; } } } while (queue.size() > 0) { AStarEntry oldEntry = queue.poll(); int x = oldEntry.getX(); int y = oldEntry.getY(); int agent_itype = oldEntry.getItype(); int itypeAusnahme = oldEntry.getItypeAusnahme(); int oldDistance = oldEntry.getDistance(); byte fromDirectionOld = oldEntry.getOriginAusrichtung(); int changedItypeX = oldEntry.getxFirstItypeChange(); int changedItypeY = oldEntry.getyFirstItypeChange(); for (int i = 0; i < possibleMovesX.length; i++) { int xNew = x + possibleMovesX[i]; int yNew = y + possibleMovesY[i]; int newDistance = oldDistance + 1; byte fromDirection = fromDirectionOld; if (xNew >= 0 && xNew < grid.length && yNew >= 0 && yNew < grid[xNew].length && (xNew == x || yNew == y)){ //First-step-check: if(fromDirection == -1){ //Is first step: if(possibleMovesX[i]>0) fromDirection = RIGHT; else if(possibleMovesX[i] < 0) fromDirection = LEFT; if(possibleMovesY[i]>0) fromDirection = BOTTOM; else if(possibleMovesY[i] < 0) fromDirection = TOP; } //Gueltiges Feld if(distance[xNew][yNew] == 0 || interpretedAsWall[xNew][yNew]){ //Neu gefunden! boolean moveBlocked = false; boolean isPortalEntry = false; int deadlyField = canBeKilledAtByStochasticEnemy(xNew, yNew); int new_itype = agent_itype; int portalIType = -1; boolean[] blockedBy = new boolean[grid[xNew][yNew].size()]; boolean[] useActionEffective = new boolean[grid[xNew][yNew].size()]; int nr = 0; for (Observation obs : grid[xNew][yNew]) { if(ignoreNPC && obs.category == Types.TYPE_NPC){// && (fromAvatarDistance == null || fromAvatarDistance[xNew][yNew] > 5) && (fromAvatarDistance != null || distance[xNew][yNew] > 5)){ continue; } if(obs.category == Types.TYPE_PORTAL){ if(!moveDirectionInverse) portalIType = obs.itype; PlayerEvent pEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, obs.itype, true); YoloEvent event = pEvent.getEvent(inventoryItems); if(!pEvent.willCancel(inventoryItems) && event.getTeleportTo() != -1) isPortalEntry = true; } if(moveDirectionInverse){ int fromTeleport = YoloKnowledge.instance.getPortalExitEntryIType(YoloKnowledge.instance.itypeToIndex(obs.itype)); portalIType = fromTeleport; } if(obs.category != Types.TYPE_AVATAR){ int passiveIndex = YoloKnowledge.instance.itypeToIndex(obs.itype); PlayerEvent event = YoloKnowledge.instance.getPlayerEvent(agent_itype, obs.itype, true); int spawnIndex = YoloKnowledge.instance.getSpawnIndexOfSpawner(obs.itype); boolean isBadSpawner = false; if(spawnIndex != -1){ //Etwas wird gespawnt! PlayerEvent spawnCollisionEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, YoloKnowledge.instance.indexToItype(spawnIndex), true); if(spawnCollisionEvent.getObserveCount() > 0){ YoloEvent yEvent = spawnCollisionEvent.getEvent(inventoryItems); isBadSpawner = yEvent.getKill() || yEvent.getScoreDelta() < 0 || yEvent.getRemoveInventorySlotItem() != -1; } } boolean interactable = YoloKnowledge.instance.canInteractWithUse(agent_itype, obs.itype); useActionEffective[nr] = interactable; boolean deadly = event.getEvent(inventoryItems).getKill() && !YoloKnowledge.instance.hasEverBeenAliveAtFieldWithItypeIndex(YoloKnowledge.instance.itypeToIndex(agent_itype),passiveIndex) && obs.category != Types.TYPE_MOVABLE; if(deadly) deadlyField = 0; blockedBy[nr] = isBadSpawner || (event.getObserveCount() > 0 && (event.willCancel(inventoryItems) || !event.getEvent(inventoryItems).getMove() || (deadly ))) && !interactable; if(!(moveBlocked||blockedBy[nr]) && !ignoreMoveables && event.getObserveCount() > 0){ if(obs.category == Types.TYPE_MOVABLE && !event.getEvent(inventoryItems).getMove()){ //Hier wird wegen eines MOVEABLES geblockt! Teste oneMoveableIgnoreIType if(itypeAusnahme == obs.itype){ //Ausnahme trifft ein, dass ein bestimmter IType ein mal ignoriert werden darf! ausnahmeID[xNew][yNew] = obs.obsID; itypeAusnahme = -1; }else{ //Keine Ausnahme! blockedBy[nr] = true; } } } moveBlocked |= blockedBy[nr]; if(markedItypes[obs.itype]) retVal.add(obs); if(!moveBlocked){ int modType = event.getEvent(inventoryItems).getIType(); if(modType != -1){ new_itype = YoloKnowledge.instance.indexToItype(modType); if(changedItypeX == -1 && changedItypeY == -1){ // not yet changed Itype: changedItypeX = xNew; changedItypeY = yNew; } } } } nr++; } if(deadlyField != Integer.MAX_VALUE) newDistance += 2*MALUS/(deadlyField+1); moveBlocked |= !ignorePortals && isPortalEntry && moveDirectionInverse; if(!moveBlocked && extraIllegalMove && extraIllegalMoveX == xNew && extraIllegalMoveY == yNew){ //Stepping on illegal field PlayerEvent event = YoloKnowledge.instance.getPlayerEvent(agent_itype, extraIllegalMoveItype, false); //Was passiert mit dem passive? YoloEvent triggeredEvent = event.getEvent(inventoryItems); if(triggeredEvent.getMove() || event.getObserveCount() == 0) //Passive bewegt sich? moveBlocked = true; } if(distance[xNew][yNew] == 0 || (interpretedAsWall[xNew][yNew] && !moveBlocked)){ distance[xNew][yNew] = newDistance; from[xNew][yNew] = (byte)((xNew < x?0:(xNew > x?1:(yNew < y?2:3)))); } interpretedAsWall[xNew][yNew] = moveBlocked; //Count appearances: if(countFoundItypes && deadlyField > 1){ nr = -1; for (Observation obs : grid[xNew][yNew]) { nr++; if(countedObsIds.contains(obs.obsID) || (moveBlocked && !blockedBy[nr] && !useActionEffective[nr])) continue; countedObsIds.add(obs.obsID); int index = YoloKnowledge.instance.itypeToIndex(obs.itype); if(blacklistedObjects != null && blacklistedObjects.contains(obs.obsID)) continue; int oldVal = iTypesFoundCount[index]++; if(oldVal == 0){ //Nearest Observation of this itype: nearestITypeObservationFound[index] = obs; if(changedItypeX != -1 && changedItypeY != -1){ //Itype has been changed, so move frist to Itypechange! nearestITypeObservationFoundFirstTargetX[index] = changedItypeX; nearestITypeObservationFoundFirstTargetY[index] = changedItypeY; }else{ //Itype has not been changed, move to object nearestITypeObservationFoundFirstTargetX[index] = xNew; nearestITypeObservationFoundFirstTargetY[index] = yNew; } } } } if(!moveBlocked){ fieldsReachedCount[fromDirection]++; originDirectionArray[xNew][yNew] = fromDirection; //Early Stop if(stopEarly && xNew == stopEarlyX && yNew == stopEarlyY) return retVal; boolean teleported = false; if(portalIType != -1 && !ignorePortals){ int portalExitIType = -1, portalExitIndex; if(!moveDirectionInverse){ PlayerEvent pEvent = YoloKnowledge.instance.getPlayerEvent(agent_itype, portalIType, true); YoloEvent event = pEvent.getEvent(inventoryItems); portalExitIndex = event.getTeleportTo(); if(!pEvent.willCancel(inventoryItems) && portalExitIndex != -1) portalExitIType = YoloKnowledge.instance.indexToItype(portalExitIndex); }else{ portalExitIType = portalIType; portalExitIndex = YoloKnowledge.instance.itypeToIndex(portalExitIType); } if(portalExitIType != -1){ int portalExitCategory = YoloKnowledge.instance.getObjectCategory(portalExitIndex, state); if(portalExitCategory != -1){ ArrayList<Observation>[] obs = state.getObservationList(portalExitCategory); if(obs != null){ ArrayList<Observation> portalExits = null; for (ArrayList<Observation> list : obs) { if(!list.isEmpty() && list.get(0).itype == portalExitIType) portalExits = list; } if(portalExits != null){ //Habe Portalausgaenge gefunden! teleported = true; int blockSize = state.getBlockSize(); for (Observation exit : portalExits) { xNew = (int)exit.position.x/blockSize; yNew = (int)exit.position.y/blockSize; if(xNew < 0 || yNew < 0 || xNew >= distance.length ||yNew >= distance[xNew].length) continue; if(distance[xNew][yNew] == 0 || interpretedAsWall[xNew][yNew]){ //Hier war die SUche noch nicht! from[xNew][yNew] = 5; originDirectionArray[xNew][yNew] = fromDirection; distance[xNew][yNew] = newDistance; queue.add(new AStarEntry(xNew, yNew, new_itype, itypeAusnahme, fromDirection, newDistance, changedItypeX, changedItypeY)); }else if(distance[xNew][yNew]>1 && !interpretedAsWall[xNew][yNew]){ //Hier waren wir schon, untersuche zyklus handleZyklus(fromDirection, originDirectionArray[xNew][yNew]); } } } } } } } if(!teleported){ //Standard appending for later loop queue.add(new AStarEntry(xNew, yNew, new_itype, itypeAusnahme, fromDirection, newDistance, changedItypeX, changedItypeY)); } } }else if(distance[xNew][yNew]>1 && !interpretedAsWall[xNew][yNew]){ //Hier waren wir schon, untersuche zyklus handleZyklus(fromDirection, originDirectionArray[xNew][yNew]); } } } } //Postwork - zycles: for (int iteration = 0; iteration < 2; iteration++) { for (int from = 0; from < zycleMet.length; from++) { for (int to = 0; to < 4; to++) { if(to == from) continue; if((zycleMet[from]>>to & 1) == 1){ //from hat zykel zu to byte newMask = (byte) (zycleMet[from] | zycleMet[to]); zycleMet[from] = newMask; zycleMet[to] = newMask; } } } } int[] oldFieldReached = new int[]{fieldsReachedCount[0],fieldsReachedCount[1],fieldsReachedCount[2],fieldsReachedCount[3]}; for (int from = 0; from < zycleMet.length; from++) { fieldsReachedCount[from] = 0; for (int to = 0; to < 4; to++) { if((zycleMet[from]>>to & 1) == 1){ //from hat zykel zu to fieldsReachedCount[from] += oldFieldReached[to]; } } } return retVal; } private int canBeKilledAtByStochasticEnemy(int x, int y){ return state.getStochasticKillMap().getMinDistanceToEnemy(x,y); } public LinkedList<ACTIONS> extractActions(int xTarget, int yTarget) { LinkedList<ACTIONS> actionsToDo = new LinkedList<ACTIONS>(); if (distance[xTarget][yTarget] > 1) { // Weg gefunden(!= 0) und bewegen notwendig(!= 1) int curX = xTarget; int curY = yTarget; while (distance[curX][curY] > 1) { switch (from[curX][curY]) { case KnowledgeBasedAStar.BOTTOM: actionsToDo.addFirst(ACTIONS.ACTION_DOWN); curY--; break; case KnowledgeBasedAStar.TOP: actionsToDo.addFirst(ACTIONS.ACTION_UP); curY++; break; case KnowledgeBasedAStar.LEFT: actionsToDo.addFirst(ACTIONS.ACTION_LEFT); curX++; break; case KnowledgeBasedAStar.RIGHT: actionsToDo.addFirst(ACTIONS.ACTION_RIGHT); curX--; break; default: //TODO: Portal-Case<SUF> System.err.println("Portal gefunden, aber 'extractActions' wurde noch nicht passend implementiert!!"); break; } } } return actionsToDo; } public void setIgnoreOneMoveableOfType(int itype) { oneMoveableIgnoreIType = itype; } public void setCountFoundItypes(boolean value) { this.countFoundItypes = value; } public void setMoveDirectionInverse(boolean value) { moveDirectionInverse = value; fromAvatarDistance = distance; } private void handleZyklus(byte direction1, byte direction2){ zycleMet[direction1] |= 1<<direction2; } public void setBlacklistedObjects(Collection<Integer> blacklistedObjects) { this.blacklistedObjects = blacklistedObjects; } }
42761_0
package jerseydemo; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureException; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import java.io.IOException; @Provider @Priority(Priorities.AUTHENTICATION) public class SecurityFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { String authheader = requestContext.getHeaderString("Authorization"); if (authheader != null) { authheader = authheader.replace("Bearer ", ""); try{ Jws<Claims> claimswut = Jwts.parser().setSigningKey(KoffieSecurityContext.key).parseClaimsJws(authheader); String subject = claimswut.getBody().getSubject(); requestContext.setSecurityContext(new KoffieSecurityContext(subject)); }catch (Exception ex){ //eeeuh, tsja, lekker niet de security context setten } } } }
TomKemperNL/hu-heroku-demo
src/main/java/jerseydemo/SecurityFilter.java
299
//eeeuh, tsja, lekker niet de security context setten
line_comment
nl
package jerseydemo; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureException; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import java.io.IOException; @Provider @Priority(Priorities.AUTHENTICATION) public class SecurityFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { String authheader = requestContext.getHeaderString("Authorization"); if (authheader != null) { authheader = authheader.replace("Bearer ", ""); try{ Jws<Claims> claimswut = Jwts.parser().setSigningKey(KoffieSecurityContext.key).parseClaimsJws(authheader); String subject = claimswut.getBody().getSubject(); requestContext.setSecurityContext(new KoffieSecurityContext(subject)); }catch (Exception ex){ //eeeuh, tsja,<SUF> } } } }
66574_1
package kalah; /** * Hauptprogramm für KalahMuster. * * @author oliverbittel * @since 29.3.2021 */ public class Kalah { private static final String ANSI_BLUE = "\u001B[34m"; /** * @param args wird nicht verwendet. */ public static void main(String[] args) { //testExample(); //testHHGame(); testMinMaxAlphaBetaWithGivenBoard(); //testMinMaxWithGivenBoard(); //testAlphaBetaWithGivenBoard(); //testHumanMinMax(); //testHumanAlphaBeta(); } /** * Beispiel von https://de.wikipedia.org/wiki/Kalaha */ public static void testExample() { KalahBoard kalahBd = new KalahBoard(new int[]{5, 3, 2, 1, 2, 0, 0, 4, 3, 0, 1, 2, 2, 0}, 'B'); kalahBd.print(); System.out.println("B spielt Mulde 11"); kalahBd.move(11); kalahBd.print(); System.out.println("B darf nochmals ziehen und spielt Mulde 7"); kalahBd.move(7); kalahBd.print(); } /** * Mensch gegen Mensch */ public static void testHHGame() { KalahBoard kalahBd = new KalahBoard(); kalahBd.print(); while (!kalahBd.isFinished()) { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } private static void testMinMaxAlphaBetaWithGivenBoard() { KalahBoard kalahBd = new KalahBoard(new int[]{2, 0, 4, 3, 2, 0, 0, 1, 0, 1, 3, 2, 1, 0}, 'A'); // A ist am Zug und kann aufgrund von Bonuszügen 8-aml hintereinander ziehen! // A muss deutlich gewinnen! kalahBd.print(); KalahBoard kalahBdMinMax = new KalahBoard(kalahBd); KalahBoard kalahBdAlphaBeta = new KalahBoard(kalahBd); for (int i = 0; i < 8; i++) { if (kalahBdMinMax.getCurPlayer() == 'A') { kalahBdMinMax = MinMax.maxAction(kalahBdMinMax); System.out.println(ANSI_BLUE + "A (MinMax) spielt Mulde: " + kalahBdMinMax.getLastPlay()); System.out.println(ANSI_BLUE + MinMax.getTurns() + " Züge in " + MinMax.getTime() + " ms"); kalahBdAlphaBeta = AlphaBeta.alphaBetaPruning(kalahBdAlphaBeta); System.out.println("\n" + ANSI_BLUE + "A (AlphaBeta) spielt Mulde: " + kalahBdAlphaBeta.getLastPlay()); System.out.println(ANSI_BLUE + AlphaBeta.getTurns() + " Züge in " + AlphaBeta.getTime() + " ms"); } kalahBdAlphaBeta.print(); } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } public static void testMinMaxWithGivenBoard() { KalahBoard kalahBd = new KalahBoard(new int[]{2, 0, 4, 3, 2, 0, 0, 1, 0, 1, 3, 2, 1, 0}, 'A'); // A ist am Zug und kann aufgrund von Bonuszügen 8-aml hintereinander ziehen! // A muss deutlich gewinnen! kalahBd.print(); while (!kalahBd.isFinished()) { if (kalahBd.getCurPlayer() == 'A') { kalahBd = MinMax.maxAction(kalahBd); System.out.println(ANSI_BLUE + "A (MinMax) spielt Mulde: " + kalahBd.getLastPlay()); kalahBd.print(); } else { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } public static void testAlphaBetaWithGivenBoard() { KalahBoard kalahBd = new KalahBoard(new int[]{2, 0, 4, 3, 2, 0, 0, 1, 0, 1, 3, 2, 1, 0}, 'A'); // A ist am Zug und kann aufgrund von Bonuszügen 8-aml hintereinander ziehen! // A muss deutlich gewinnen! kalahBd.print(); while (!kalahBd.isFinished()) { if (kalahBd.getCurPlayer() == 'A') { kalahBd = AlphaBeta.alphaBetaPruning(kalahBd); System.out.println(ANSI_BLUE + "A (AlphaBetaPruning) spielt Mulde: " + kalahBd.getLastPlay()); kalahBd.print(); } else { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } public static void testHumanMinMax() { KalahBoard kalahBd = new KalahBoard(); kalahBd.print(); while (!kalahBd.isFinished()) { if (kalahBd.getCurPlayer() == 'A') { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } else { kalahBd = MinMax.maxAction(kalahBd); System.out.println(ANSI_BLUE + "B (MinMax) spielt Mulde: " + kalahBd.getLastPlay()); kalahBd.print(); } } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } public static void testHumanAlphaBeta() { KalahBoard kalahBd = new KalahBoard(); kalahBd.print(); while (!kalahBd.isFinished()) { if (kalahBd.getCurPlayer() == 'A') { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } else { kalahBd = AlphaBeta.alphaBetaPruning(kalahBd); System.out.println(ANSI_BLUE + "B (AlphaBetaPruning) spielt Mulde: " + kalahBd.getLastPlay()); kalahBd.print(); } } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } }
Pxldi/htwg_ai
src/02_kalah/Kalah.java
1,706
/** * @param args wird nicht verwendet. */
block_comment
nl
package kalah; /** * Hauptprogramm für KalahMuster. * * @author oliverbittel * @since 29.3.2021 */ public class Kalah { private static final String ANSI_BLUE = "\u001B[34m"; /** * @param args wird<SUF>*/ public static void main(String[] args) { //testExample(); //testHHGame(); testMinMaxAlphaBetaWithGivenBoard(); //testMinMaxWithGivenBoard(); //testAlphaBetaWithGivenBoard(); //testHumanMinMax(); //testHumanAlphaBeta(); } /** * Beispiel von https://de.wikipedia.org/wiki/Kalaha */ public static void testExample() { KalahBoard kalahBd = new KalahBoard(new int[]{5, 3, 2, 1, 2, 0, 0, 4, 3, 0, 1, 2, 2, 0}, 'B'); kalahBd.print(); System.out.println("B spielt Mulde 11"); kalahBd.move(11); kalahBd.print(); System.out.println("B darf nochmals ziehen und spielt Mulde 7"); kalahBd.move(7); kalahBd.print(); } /** * Mensch gegen Mensch */ public static void testHHGame() { KalahBoard kalahBd = new KalahBoard(); kalahBd.print(); while (!kalahBd.isFinished()) { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } private static void testMinMaxAlphaBetaWithGivenBoard() { KalahBoard kalahBd = new KalahBoard(new int[]{2, 0, 4, 3, 2, 0, 0, 1, 0, 1, 3, 2, 1, 0}, 'A'); // A ist am Zug und kann aufgrund von Bonuszügen 8-aml hintereinander ziehen! // A muss deutlich gewinnen! kalahBd.print(); KalahBoard kalahBdMinMax = new KalahBoard(kalahBd); KalahBoard kalahBdAlphaBeta = new KalahBoard(kalahBd); for (int i = 0; i < 8; i++) { if (kalahBdMinMax.getCurPlayer() == 'A') { kalahBdMinMax = MinMax.maxAction(kalahBdMinMax); System.out.println(ANSI_BLUE + "A (MinMax) spielt Mulde: " + kalahBdMinMax.getLastPlay()); System.out.println(ANSI_BLUE + MinMax.getTurns() + " Züge in " + MinMax.getTime() + " ms"); kalahBdAlphaBeta = AlphaBeta.alphaBetaPruning(kalahBdAlphaBeta); System.out.println("\n" + ANSI_BLUE + "A (AlphaBeta) spielt Mulde: " + kalahBdAlphaBeta.getLastPlay()); System.out.println(ANSI_BLUE + AlphaBeta.getTurns() + " Züge in " + AlphaBeta.getTime() + " ms"); } kalahBdAlphaBeta.print(); } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } public static void testMinMaxWithGivenBoard() { KalahBoard kalahBd = new KalahBoard(new int[]{2, 0, 4, 3, 2, 0, 0, 1, 0, 1, 3, 2, 1, 0}, 'A'); // A ist am Zug und kann aufgrund von Bonuszügen 8-aml hintereinander ziehen! // A muss deutlich gewinnen! kalahBd.print(); while (!kalahBd.isFinished()) { if (kalahBd.getCurPlayer() == 'A') { kalahBd = MinMax.maxAction(kalahBd); System.out.println(ANSI_BLUE + "A (MinMax) spielt Mulde: " + kalahBd.getLastPlay()); kalahBd.print(); } else { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } public static void testAlphaBetaWithGivenBoard() { KalahBoard kalahBd = new KalahBoard(new int[]{2, 0, 4, 3, 2, 0, 0, 1, 0, 1, 3, 2, 1, 0}, 'A'); // A ist am Zug und kann aufgrund von Bonuszügen 8-aml hintereinander ziehen! // A muss deutlich gewinnen! kalahBd.print(); while (!kalahBd.isFinished()) { if (kalahBd.getCurPlayer() == 'A') { kalahBd = AlphaBeta.alphaBetaPruning(kalahBd); System.out.println(ANSI_BLUE + "A (AlphaBetaPruning) spielt Mulde: " + kalahBd.getLastPlay()); kalahBd.print(); } else { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } public static void testHumanMinMax() { KalahBoard kalahBd = new KalahBoard(); kalahBd.print(); while (!kalahBd.isFinished()) { if (kalahBd.getCurPlayer() == 'A') { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } else { kalahBd = MinMax.maxAction(kalahBd); System.out.println(ANSI_BLUE + "B (MinMax) spielt Mulde: " + kalahBd.getLastPlay()); kalahBd.print(); } } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } public static void testHumanAlphaBeta() { KalahBoard kalahBd = new KalahBoard(); kalahBd.print(); while (!kalahBd.isFinished()) { if (kalahBd.getCurPlayer() == 'A') { int action = kalahBd.readAction(); kalahBd.move(action); kalahBd.print(); } else { kalahBd = AlphaBeta.alphaBetaPruning(kalahBd); System.out.println(ANSI_BLUE + "B (AlphaBetaPruning) spielt Mulde: " + kalahBd.getLastPlay()); kalahBd.print(); } } System.out.println("\n" + ANSI_BLUE + "GAME OVER"); } }
53274_2
import java.math.BigDecimal; import java.math.MathContext; /** * * @author Stiaan Uyttersprot */ public class Edge { private Coordinate startPoint; private Coordinate endPoint; private int edgeNumber; private double edgeAngle; private double deltaAngle; // values to be used for bounding box intersection private BigDecimal smallX; private BigDecimal bigX; private BigDecimal smallY; private BigDecimal bigY; private int edgeLabel; //wordt momenteel niet gebruikt private boolean polygonA; private boolean turningPoint; private boolean additional = false; //this edge is additional and is not used for track line trips private int tripSequenceNumber; public static BigDecimal round = new BigDecimal(0); private static MathContext mc = MathContext.DECIMAL128; //values for boundarySearch private boolean positive; private boolean negative; private Coordinate startIntersect; private Coordinate endIntersect; Edge(Coordinate s, Coordinate e, int eN) { startPoint = s; endPoint = e; edgeNumber = eN; calculateRanges(); } public Edge(Edge edge) { startPoint = new Coordinate(edge.getStartPoint()); endPoint = new Coordinate(edge.getEndPoint()); edgeNumber = edge.getEdgeNumber(); edgeAngle =edge.getEdgeAngle(); deltaAngle = edge.getDeltaAngle(); turningPoint = edge.isTurningPoint(); polygonA = edge.isPolygonA(); calculateRanges(); } public Edge(Edge edge, boolean add) { startPoint = new Coordinate(edge.getStartPoint()); endPoint = new Coordinate(edge.getEndPoint()); edgeNumber = edge.getEdgeNumber(); edgeAngle =edge.getEdgeAngle(); deltaAngle = edge.getDeltaAngle(); turningPoint = edge.isTurningPoint(); polygonA = edge.isPolygonA(); additional = add; calculateRanges(); } public Edge(Coordinate s, Coordinate e) { startPoint = s; endPoint = e; edgeNumber = -1; calculateRanges(); } public Coordinate getStartPoint() { return startPoint; } public void setStartPoint(Coordinate startPoint) { this.startPoint = startPoint; } public Coordinate getEndPoint() { return endPoint; } public void setEndPoint(Coordinate endPoint) { this.endPoint = endPoint; } public int getEdgeNumber() { return edgeNumber; } public void setEdgeNumber(int edgeNumber) { this.edgeNumber = edgeNumber; } public void print() { System.out.println(startPoint.toString() + ";" + endPoint.toString()); } public double getEdgeAngle() { return edgeAngle; } public BigDecimal getSmallX() { return smallX; } public void setSmallX(BigDecimal smallX) { this.smallX = smallX; } public BigDecimal getBigX() { return bigX; } public void setBigX(BigDecimal bigX) { this.bigX = bigX; } public BigDecimal getSmallY() { return smallY; } public void setSmallY(BigDecimal smallY) { this.smallY = smallY; } public BigDecimal getBigY() { return bigY; } public void setBigY(BigDecimal bigY) { this.bigY = bigY; } public boolean isPositive() { return positive; } public void setPositive(boolean positive) { this.positive = positive; } public boolean isNegative() { return negative; } public void setNegative(boolean negative) { this.negative = negative; } public Coordinate getStartIntersect() { return startIntersect; } public void setStartIntersect(Coordinate startIntersect) { this.startIntersect = startIntersect; } public Coordinate getEndIntersect() { return endIntersect; } public void setEndIntersect(Coordinate endIntersect) { this.endIntersect = endIntersect; } public void calcEdgeAngle(){ double numerator = endPoint.getyCoord().doubleValue()- startPoint.getyCoord().doubleValue(); double denominator = endPoint.getxCoord().doubleValue()- startPoint.getxCoord().doubleValue(); edgeAngle = Math.atan2(numerator, denominator); } public void calcInverseEdgeAngle() { double numerator = startPoint.getyCoord().doubleValue() - endPoint.getyCoord().doubleValue(); double denominator = startPoint.getxCoord().doubleValue() - endPoint.getxCoord().doubleValue(); edgeAngle = Math.atan2(numerator,denominator); } public Coordinate calcIntersection(Edge testEdge) { /* * the used formula is * x=((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1- * y2)*(x3-x4)); * y=((x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1- * y2)*(x3-x4)); */ BigDecimal x1 = startPoint.getxCoord(); BigDecimal x2 = endPoint.getxCoord(); BigDecimal y1 = startPoint.getyCoord(); BigDecimal y2 = endPoint.getyCoord(); BigDecimal x3 = testEdge.getStartPoint().getxCoord(); BigDecimal x4 = testEdge.getEndPoint().getxCoord(); BigDecimal y3 = testEdge.getStartPoint().getyCoord(); BigDecimal y4 = testEdge.getEndPoint().getyCoord(); // x1 - x2 BigDecimal dx1 = x1.subtract(x2); // x3 - x4 BigDecimal dx2 = x3.subtract(x4); // y1 - y2 BigDecimal dy1 = y1.subtract(y2); // y3 - y4 BigDecimal dy2 = y3.subtract(y4); // (x1*y2-y1*x2) BigDecimal pd1 = x1.multiply(y2).subtract(y1.multiply(x2)); // (x3*y4-y3*x4) BigDecimal pd2 = x3.multiply(y4).subtract(y3.multiply(x4)); // (x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4) BigDecimal xNumerator = pd1.multiply(dx2).subtract(dx1.multiply(pd2)); // (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4) BigDecimal yNumerator = pd1.multiply(dy2).subtract(dy1.multiply(pd2)); // (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) BigDecimal denominator = dx1.multiply(dy2).subtract(dy1.multiply(dx2)); BigDecimal xCoord = xNumerator.divide(denominator, MathContext.DECIMAL128); BigDecimal yCoord = yNumerator.divide(denominator, MathContext.DECIMAL128); return new Coordinate(xCoord, yCoord); } //when a translation is taking place, the values of min and max have to be adjusted public void changeRangeValues(BigDecimal x, BigDecimal y) { smallX = smallX.add(x); bigX = bigX.add(x); smallY = smallY.add(y); bigY = bigY.add(y); } public BigDecimal calcClockwiseValue() { //Sum over the edges, (x2-x1)(y2+y1). If the result is positive the curve is clockwise, if it's negative the curve is counter-clockwise. BigDecimal xDiff = endPoint.getxCoord().subtract(startPoint.getxCoord()); BigDecimal ySum = endPoint.getyCoord().add(startPoint.getyCoord()); return xDiff.multiply(ySum); } public boolean edgesOrientatedRight(Edge preEdge, Edge postEdge) { //the edges are right of or parallel with this edge if(preEdge.getStartPoint().dFunction(startPoint, endPoint).compareTo(round)<=0 && postEdge.getEndPoint().dFunction(startPoint, endPoint).compareTo(round)<=0) return true; return false; } public void setEdgeAngle(double edgeAngle) { this.edgeAngle = edgeAngle; } public int getEdgeLabel() { return edgeLabel; } public void setEdgeLabel(int edgeLabel) { this.edgeLabel = edgeLabel; } public double getDeltaAngle() { return deltaAngle; } public void setDeltaAngle(double deltaAngle) { this.deltaAngle = deltaAngle; } public boolean isTurningPoint() { return turningPoint; } public void setTurningPoint(boolean turningPoint) { this.turningPoint = turningPoint; } @Override public String toString() { return "Edge [startPoint=" + startPoint + ", endPoint=" + endPoint + ", edgeNumber=" + edgeNumber + ", edgeAngle=" + edgeAngle + ", deltaAngle=" + deltaAngle + ", turningPoint=" + turningPoint +", polygon A=" + polygonA + "]"; } public boolean isPolygonA() { return polygonA; } public void setPolygonA(boolean polygonA) { this.polygonA = polygonA; } public void replaceByNegative() { startPoint.replaceByNegative(); endPoint.replaceByNegative(); if(edgeAngle>0){ edgeAngle -= Math.PI; } else{ edgeAngle += Math.PI; } } public void changeEdgeNumber(int direction) { edgeNumber = direction*edgeNumber; } public boolean testIntersect(Edge edge) { Coordinate intersectionCoord; boolean intersection = false; // if the bounding boxes intersect, line intersection // has to be checked if (boundingBoxIntersect(edge)) { if (lineIntersect(edge)) { intersectionCoord = calcIntersection(edge); if(containsIntersectionPoint(intersectionCoord)&&edge.containsIntersectionPoint(intersectionCoord)){ intersection = true; } } } return intersection; } public void calculateRanges() { Coordinate start = getStartPoint(); Coordinate end = getEndPoint(); if (start.getxCoord().compareTo(end.getxCoord())<0) { smallX = start.getxCoord(); bigX = end.getxCoord(); } else { smallX = end.getxCoord(); bigX = start.getxCoord(); } if (start.getyCoord().compareTo(end.getyCoord())<0) { smallY = start.getyCoord(); bigY = end.getyCoord(); } else { smallY = end.getyCoord(); bigY = start.getyCoord(); } } public boolean boundingBoxIntersect(Edge edge) { boolean intersect = true; if (edge.getBigX().compareTo(smallX)<=0|| edge.getSmallX().compareTo(bigX) >= 0 || edge.getBigY().compareTo(smallY)<=0 || edge.getSmallY().compareTo(bigY) >= 0) intersect = false; return intersect; } public boolean lineIntersect(Edge testEdge) { boolean intersect = true; // the lines intersect if the start coordinate and the end coordinate // of one of the edges are not both on the same side //in most cases this will guarantee an intersection, but there are cases where the intersection point will not be part of one of the lines if (testEdge.getStartPoint().dFunction(startPoint, endPoint).compareTo(round)<=0 && testEdge.getEndPoint().dFunction(startPoint, endPoint).compareTo(round)<=0) { intersect = false; } else if (testEdge.getStartPoint().dFunction(startPoint, endPoint).compareTo(round.negate()) >= 0 && testEdge.getEndPoint().dFunction(startPoint, endPoint).compareTo(round.negate()) >=0) { intersect = false; } return intersect; } public boolean containsIntersectionPoint(Coordinate intersectionCoord) { if(intersectionCoord.getxCoord().compareTo(smallX)<0){ return false; } if(intersectionCoord.getxCoord().compareTo(bigX)>0){ return false; } if(intersectionCoord.getyCoord().compareTo(smallY)<0){ return false; } if(intersectionCoord.getyCoord().compareTo(bigY)>0){ return false; } return true; } public boolean containsPoint(Coordinate intersectionCoord) { boolean onLine; onLine = intersectionCoord.dFunctionCheck(startPoint, endPoint); if(onLine == false){ BigDecimal distanceToCoord = intersectionCoord.shortestDistanceToEdge(this); if(distanceToCoord.compareTo(new BigDecimal(0.5))>0)return false; }; if(intersectionCoord.getxCoord().compareTo(smallX)<0){ return false; } if(intersectionCoord.getxCoord().compareTo(bigX)>0){ return false; } if(intersectionCoord.getyCoord().compareTo(smallY)<0){ return false; } if(intersectionCoord.getyCoord().compareTo(bigY)>0){ return false; } return true; } public boolean equals(Edge edge) { if(edgeNumber!=edge.getEdgeNumber())return false; if(polygonA!=edge.isPolygonA())return false; return true; } //we need to check the coordinates here, they have to be the same too, not only the edgeNumber and polygon public boolean equalsComplexPolyEdge(Edge edge) { if(edgeNumber!=edge.getEdgeNumber())return false; if(polygonA!=edge.isPolygonA())return false; if(!startPoint.equals(edge.getStartPoint()))return false; if(!endPoint.equals(edge.getEndPoint()))return false; return true; } public Vector makeFullVector(int eN) { Vector vector; // if the orbiting edge is being used for the vector, it needs to be // inversed // this means startPoint-endPoint in stead of endPoint-startPoint vector = new Vector(endPoint.subtract(startPoint), eN, polygonA); if(eN<0){ vector.setxCoord(vector.getxCoord().negate()); vector.setyCoord(vector.getyCoord().negate()); } return vector; } public boolean equalValuesRounded(Edge edge) { if(!startPoint.equalValuesRounded(edge.getEndPoint()))return false; if(!endPoint.equalValuesRounded(edge.getEndPoint()))return false; return true; } public boolean isAdditional() { return additional; } public void setAdditional(boolean additional) { this.additional = additional; } public int getTripSequenceNumber() { return tripSequenceNumber; } public void setTripSequenceNumber(int tripSequenceNumber) { this.tripSequenceNumber = tripSequenceNumber; } public boolean testIntersectWithoutBorders(Edge edge) { Coordinate intersectionCoord; boolean intersection = false; // if the bounding boxes intersect, line intersection // has to be checked if (boundingBoxIntersect(edge)) { if (lineIntersect(edge)) { intersectionCoord = calcIntersection(edge); if(containsIntersectionPoint(intersectionCoord)&&edge.containsIntersectionPoint(intersectionCoord)){ if(intersectionCoord.equalValuesRounded(edge.getStartPoint())||intersectionCoord.equalValuesRounded(edge.getEndPoint()) ||intersectionCoord.equalValuesRounded(startPoint)||intersectionCoord.equalValuesRounded(endPoint)){ } else intersection = true; } } } return intersection; } }
TonyWauters/JNFP
srcBDMinkowski/Edge.java
4,115
//wordt momenteel niet gebruikt
line_comment
nl
import java.math.BigDecimal; import java.math.MathContext; /** * * @author Stiaan Uyttersprot */ public class Edge { private Coordinate startPoint; private Coordinate endPoint; private int edgeNumber; private double edgeAngle; private double deltaAngle; // values to be used for bounding box intersection private BigDecimal smallX; private BigDecimal bigX; private BigDecimal smallY; private BigDecimal bigY; private int edgeLabel; //wordt momenteel<SUF> private boolean polygonA; private boolean turningPoint; private boolean additional = false; //this edge is additional and is not used for track line trips private int tripSequenceNumber; public static BigDecimal round = new BigDecimal(0); private static MathContext mc = MathContext.DECIMAL128; //values for boundarySearch private boolean positive; private boolean negative; private Coordinate startIntersect; private Coordinate endIntersect; Edge(Coordinate s, Coordinate e, int eN) { startPoint = s; endPoint = e; edgeNumber = eN; calculateRanges(); } public Edge(Edge edge) { startPoint = new Coordinate(edge.getStartPoint()); endPoint = new Coordinate(edge.getEndPoint()); edgeNumber = edge.getEdgeNumber(); edgeAngle =edge.getEdgeAngle(); deltaAngle = edge.getDeltaAngle(); turningPoint = edge.isTurningPoint(); polygonA = edge.isPolygonA(); calculateRanges(); } public Edge(Edge edge, boolean add) { startPoint = new Coordinate(edge.getStartPoint()); endPoint = new Coordinate(edge.getEndPoint()); edgeNumber = edge.getEdgeNumber(); edgeAngle =edge.getEdgeAngle(); deltaAngle = edge.getDeltaAngle(); turningPoint = edge.isTurningPoint(); polygonA = edge.isPolygonA(); additional = add; calculateRanges(); } public Edge(Coordinate s, Coordinate e) { startPoint = s; endPoint = e; edgeNumber = -1; calculateRanges(); } public Coordinate getStartPoint() { return startPoint; } public void setStartPoint(Coordinate startPoint) { this.startPoint = startPoint; } public Coordinate getEndPoint() { return endPoint; } public void setEndPoint(Coordinate endPoint) { this.endPoint = endPoint; } public int getEdgeNumber() { return edgeNumber; } public void setEdgeNumber(int edgeNumber) { this.edgeNumber = edgeNumber; } public void print() { System.out.println(startPoint.toString() + ";" + endPoint.toString()); } public double getEdgeAngle() { return edgeAngle; } public BigDecimal getSmallX() { return smallX; } public void setSmallX(BigDecimal smallX) { this.smallX = smallX; } public BigDecimal getBigX() { return bigX; } public void setBigX(BigDecimal bigX) { this.bigX = bigX; } public BigDecimal getSmallY() { return smallY; } public void setSmallY(BigDecimal smallY) { this.smallY = smallY; } public BigDecimal getBigY() { return bigY; } public void setBigY(BigDecimal bigY) { this.bigY = bigY; } public boolean isPositive() { return positive; } public void setPositive(boolean positive) { this.positive = positive; } public boolean isNegative() { return negative; } public void setNegative(boolean negative) { this.negative = negative; } public Coordinate getStartIntersect() { return startIntersect; } public void setStartIntersect(Coordinate startIntersect) { this.startIntersect = startIntersect; } public Coordinate getEndIntersect() { return endIntersect; } public void setEndIntersect(Coordinate endIntersect) { this.endIntersect = endIntersect; } public void calcEdgeAngle(){ double numerator = endPoint.getyCoord().doubleValue()- startPoint.getyCoord().doubleValue(); double denominator = endPoint.getxCoord().doubleValue()- startPoint.getxCoord().doubleValue(); edgeAngle = Math.atan2(numerator, denominator); } public void calcInverseEdgeAngle() { double numerator = startPoint.getyCoord().doubleValue() - endPoint.getyCoord().doubleValue(); double denominator = startPoint.getxCoord().doubleValue() - endPoint.getxCoord().doubleValue(); edgeAngle = Math.atan2(numerator,denominator); } public Coordinate calcIntersection(Edge testEdge) { /* * the used formula is * x=((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1- * y2)*(x3-x4)); * y=((x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4))/((x1-x2)*(y3-y4)-(y1- * y2)*(x3-x4)); */ BigDecimal x1 = startPoint.getxCoord(); BigDecimal x2 = endPoint.getxCoord(); BigDecimal y1 = startPoint.getyCoord(); BigDecimal y2 = endPoint.getyCoord(); BigDecimal x3 = testEdge.getStartPoint().getxCoord(); BigDecimal x4 = testEdge.getEndPoint().getxCoord(); BigDecimal y3 = testEdge.getStartPoint().getyCoord(); BigDecimal y4 = testEdge.getEndPoint().getyCoord(); // x1 - x2 BigDecimal dx1 = x1.subtract(x2); // x3 - x4 BigDecimal dx2 = x3.subtract(x4); // y1 - y2 BigDecimal dy1 = y1.subtract(y2); // y3 - y4 BigDecimal dy2 = y3.subtract(y4); // (x1*y2-y1*x2) BigDecimal pd1 = x1.multiply(y2).subtract(y1.multiply(x2)); // (x3*y4-y3*x4) BigDecimal pd2 = x3.multiply(y4).subtract(y3.multiply(x4)); // (x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4) BigDecimal xNumerator = pd1.multiply(dx2).subtract(dx1.multiply(pd2)); // (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4) BigDecimal yNumerator = pd1.multiply(dy2).subtract(dy1.multiply(pd2)); // (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) BigDecimal denominator = dx1.multiply(dy2).subtract(dy1.multiply(dx2)); BigDecimal xCoord = xNumerator.divide(denominator, MathContext.DECIMAL128); BigDecimal yCoord = yNumerator.divide(denominator, MathContext.DECIMAL128); return new Coordinate(xCoord, yCoord); } //when a translation is taking place, the values of min and max have to be adjusted public void changeRangeValues(BigDecimal x, BigDecimal y) { smallX = smallX.add(x); bigX = bigX.add(x); smallY = smallY.add(y); bigY = bigY.add(y); } public BigDecimal calcClockwiseValue() { //Sum over the edges, (x2-x1)(y2+y1). If the result is positive the curve is clockwise, if it's negative the curve is counter-clockwise. BigDecimal xDiff = endPoint.getxCoord().subtract(startPoint.getxCoord()); BigDecimal ySum = endPoint.getyCoord().add(startPoint.getyCoord()); return xDiff.multiply(ySum); } public boolean edgesOrientatedRight(Edge preEdge, Edge postEdge) { //the edges are right of or parallel with this edge if(preEdge.getStartPoint().dFunction(startPoint, endPoint).compareTo(round)<=0 && postEdge.getEndPoint().dFunction(startPoint, endPoint).compareTo(round)<=0) return true; return false; } public void setEdgeAngle(double edgeAngle) { this.edgeAngle = edgeAngle; } public int getEdgeLabel() { return edgeLabel; } public void setEdgeLabel(int edgeLabel) { this.edgeLabel = edgeLabel; } public double getDeltaAngle() { return deltaAngle; } public void setDeltaAngle(double deltaAngle) { this.deltaAngle = deltaAngle; } public boolean isTurningPoint() { return turningPoint; } public void setTurningPoint(boolean turningPoint) { this.turningPoint = turningPoint; } @Override public String toString() { return "Edge [startPoint=" + startPoint + ", endPoint=" + endPoint + ", edgeNumber=" + edgeNumber + ", edgeAngle=" + edgeAngle + ", deltaAngle=" + deltaAngle + ", turningPoint=" + turningPoint +", polygon A=" + polygonA + "]"; } public boolean isPolygonA() { return polygonA; } public void setPolygonA(boolean polygonA) { this.polygonA = polygonA; } public void replaceByNegative() { startPoint.replaceByNegative(); endPoint.replaceByNegative(); if(edgeAngle>0){ edgeAngle -= Math.PI; } else{ edgeAngle += Math.PI; } } public void changeEdgeNumber(int direction) { edgeNumber = direction*edgeNumber; } public boolean testIntersect(Edge edge) { Coordinate intersectionCoord; boolean intersection = false; // if the bounding boxes intersect, line intersection // has to be checked if (boundingBoxIntersect(edge)) { if (lineIntersect(edge)) { intersectionCoord = calcIntersection(edge); if(containsIntersectionPoint(intersectionCoord)&&edge.containsIntersectionPoint(intersectionCoord)){ intersection = true; } } } return intersection; } public void calculateRanges() { Coordinate start = getStartPoint(); Coordinate end = getEndPoint(); if (start.getxCoord().compareTo(end.getxCoord())<0) { smallX = start.getxCoord(); bigX = end.getxCoord(); } else { smallX = end.getxCoord(); bigX = start.getxCoord(); } if (start.getyCoord().compareTo(end.getyCoord())<0) { smallY = start.getyCoord(); bigY = end.getyCoord(); } else { smallY = end.getyCoord(); bigY = start.getyCoord(); } } public boolean boundingBoxIntersect(Edge edge) { boolean intersect = true; if (edge.getBigX().compareTo(smallX)<=0|| edge.getSmallX().compareTo(bigX) >= 0 || edge.getBigY().compareTo(smallY)<=0 || edge.getSmallY().compareTo(bigY) >= 0) intersect = false; return intersect; } public boolean lineIntersect(Edge testEdge) { boolean intersect = true; // the lines intersect if the start coordinate and the end coordinate // of one of the edges are not both on the same side //in most cases this will guarantee an intersection, but there are cases where the intersection point will not be part of one of the lines if (testEdge.getStartPoint().dFunction(startPoint, endPoint).compareTo(round)<=0 && testEdge.getEndPoint().dFunction(startPoint, endPoint).compareTo(round)<=0) { intersect = false; } else if (testEdge.getStartPoint().dFunction(startPoint, endPoint).compareTo(round.negate()) >= 0 && testEdge.getEndPoint().dFunction(startPoint, endPoint).compareTo(round.negate()) >=0) { intersect = false; } return intersect; } public boolean containsIntersectionPoint(Coordinate intersectionCoord) { if(intersectionCoord.getxCoord().compareTo(smallX)<0){ return false; } if(intersectionCoord.getxCoord().compareTo(bigX)>0){ return false; } if(intersectionCoord.getyCoord().compareTo(smallY)<0){ return false; } if(intersectionCoord.getyCoord().compareTo(bigY)>0){ return false; } return true; } public boolean containsPoint(Coordinate intersectionCoord) { boolean onLine; onLine = intersectionCoord.dFunctionCheck(startPoint, endPoint); if(onLine == false){ BigDecimal distanceToCoord = intersectionCoord.shortestDistanceToEdge(this); if(distanceToCoord.compareTo(new BigDecimal(0.5))>0)return false; }; if(intersectionCoord.getxCoord().compareTo(smallX)<0){ return false; } if(intersectionCoord.getxCoord().compareTo(bigX)>0){ return false; } if(intersectionCoord.getyCoord().compareTo(smallY)<0){ return false; } if(intersectionCoord.getyCoord().compareTo(bigY)>0){ return false; } return true; } public boolean equals(Edge edge) { if(edgeNumber!=edge.getEdgeNumber())return false; if(polygonA!=edge.isPolygonA())return false; return true; } //we need to check the coordinates here, they have to be the same too, not only the edgeNumber and polygon public boolean equalsComplexPolyEdge(Edge edge) { if(edgeNumber!=edge.getEdgeNumber())return false; if(polygonA!=edge.isPolygonA())return false; if(!startPoint.equals(edge.getStartPoint()))return false; if(!endPoint.equals(edge.getEndPoint()))return false; return true; } public Vector makeFullVector(int eN) { Vector vector; // if the orbiting edge is being used for the vector, it needs to be // inversed // this means startPoint-endPoint in stead of endPoint-startPoint vector = new Vector(endPoint.subtract(startPoint), eN, polygonA); if(eN<0){ vector.setxCoord(vector.getxCoord().negate()); vector.setyCoord(vector.getyCoord().negate()); } return vector; } public boolean equalValuesRounded(Edge edge) { if(!startPoint.equalValuesRounded(edge.getEndPoint()))return false; if(!endPoint.equalValuesRounded(edge.getEndPoint()))return false; return true; } public boolean isAdditional() { return additional; } public void setAdditional(boolean additional) { this.additional = additional; } public int getTripSequenceNumber() { return tripSequenceNumber; } public void setTripSequenceNumber(int tripSequenceNumber) { this.tripSequenceNumber = tripSequenceNumber; } public boolean testIntersectWithoutBorders(Edge edge) { Coordinate intersectionCoord; boolean intersection = false; // if the bounding boxes intersect, line intersection // has to be checked if (boundingBoxIntersect(edge)) { if (lineIntersect(edge)) { intersectionCoord = calcIntersection(edge); if(containsIntersectionPoint(intersectionCoord)&&edge.containsIntersectionPoint(intersectionCoord)){ if(intersectionCoord.equalValuesRounded(edge.getStartPoint())||intersectionCoord.equalValuesRounded(edge.getEndPoint()) ||intersectionCoord.equalValuesRounded(startPoint)||intersectionCoord.equalValuesRounded(endPoint)){ } else intersection = true; } } } return intersection; } }
213906_1
package experiments; import org.scify.jedai.datamodel.EntityProfile; import org.scify.jedai.datamodel.IdDuplicates; import java.util.*; import minhash.LocalitySensitiveHashing; import minhash.MinHash; import minhash.Pair; import minhash.Reader; import minhash.ShinglingModel; import minhash.Utilities; public class schemaAgnostic { static int ITERATIONS = 10; public static void main(String[] args) { boolean[] preprocessed = {false, false, false, true, false, true, false, false, false, false}; int[] bands = {4, 32, 16, 4, 32, 32, 16, 32, 16, 32}; int[] buckets = {64, 8, 8, 128, 16, 8, 16, 16, 16, 8}; int[] k = {2, 2, 2, 2, 2, 5, 2, 2, 2, 2}; String[] mainDirs = {"/home/gap2/Documents/blockingNN/data/schemaAgnostic/", "/home/gap2/Documents/blockingNN/data/preprocessedSA/" }; String[] datasetsD1 = {"restaurant1Profiles", "abtProfiles", "amazonProfiles", "dblpProfiles", "imdbProfilesNEW", "imdbProfilesNEW", "tmdbProfiles", "walmartProfiles", "dblpProfiles2", "imdbProfiles"}; String[] datasetsD2 = {"restaurant2Profiles", "buyProfiles", "gpProfiles", "acmProfiles", "tmdbProfiles", "tvdbProfiles", "tvdbProfiles", "amazonProfiles2", "scholarProfiles", "dbpediaProfiles"}; String[] groundtruthDirs = {"restaurantsIdDuplicates", "abtBuyIdDuplicates", "amazonGpIdDuplicates", "dblpAcmIdDuplicates", "imdbTmdbIdDuplicates", "imdbTvdbIdDuplicates", "tmdbTvdbIdDuplicates", "amazonWalmartIdDuplicates", "dblpScholarIdDuplicates", "moviesIdDuplicates"}; for (int datasetId = 0; datasetId < groundtruthDirs.length; datasetId++) { // read source entities int dirId = preprocessed[datasetId] ? 1 : 0; String sourcePath = mainDirs[dirId] + datasetsD1[datasetId]; List<EntityProfile> sourceEntities = Reader.readSerialized(sourcePath); System.out.println("Source Entities: " + sourceEntities.size()); // read target entities String targetPath = mainDirs[dirId] + datasetsD2[datasetId]; List<EntityProfile> targetEntities = Reader.readSerialized(targetPath); System.out.println("Target Entities: " + targetEntities.size()); // read ground-truth file String groundTruthPath = mainDirs[dirId] + groundtruthDirs[datasetId]; Set<IdDuplicates> gtDuplicates = Reader.readSerializedGT(groundTruthPath, sourceEntities, targetEntities); System.out.println("GT Duplicates Entities: " + gtDuplicates.size()); System.out.println(); double averageIndexingTime = 0; double averageQueryingTime = 0; double averageRecall = 0; double averagePrecision = 0; double averageCandidates = 0; for (int iteration = 0; iteration < ITERATIONS; iteration++) { long time1 = System.currentTimeMillis(); List<String> sourceSTR = Utilities.entities2String(sourceEntities); ShinglingModel model = new ShinglingModel(sourceSTR, k[datasetId]); int[][] sourceVectorsInt = model.vectorization(sourceSTR); float[][] sVectors = new float[sourceVectorsInt.length][]; for (int row = 0; row < sourceVectorsInt.length; row++) { double[] tempArray = Arrays.stream(sourceVectorsInt[row]).asDoubleStream().toArray(); sVectors[row] = new float[tempArray.length]; for (int i = 0; i < tempArray.length; i++) { sVectors[row][i] = (float) tempArray[i]; } } // initialize LSH LocalitySensitiveHashing lsh = new MinHash(sVectors, bands[datasetId], buckets[datasetId], model.getVectorSize()); long time2 = System.currentTimeMillis(); List<String> targetSTR = Utilities.entities2String(targetEntities); int[][] targetVectorsInt = model.vectorization(targetSTR); float[][] tVectors = new float[targetVectorsInt.length][]; for (int row = 0; row < targetVectorsInt.length; row++) { double[] tempArray = Arrays.stream(targetVectorsInt[row]).asDoubleStream().toArray(); tVectors[row] = new float[tempArray.length]; for (int i = 0; i < tempArray.length; i++) { tVectors[row][i] = (float) tempArray[i]; } } // for each target entity, find its candidates (query) // find TP by searching the pairs in GT final List<Pair> candidatePairs = new ArrayList<>(); for (int j = 0; j < targetEntities.size(); j++) { float[] vector = tVectors[j]; Set<Integer> candidates = lsh.query(vector); for (Integer c : candidates) { candidatePairs.add(new Pair(j, c)); } } long time3 = System.currentTimeMillis(); averageIndexingTime += time2 - time1; averageQueryingTime += time3 - time2; // true positive long tp_ = 0; // total verifications long verifications_ = 0; for (int j = 0; j < targetEntities.size(); j++) { float[] vector = tVectors[j]; Set<Integer> candidates = lsh.query(vector); for (Integer c : candidates) { IdDuplicates pair = new IdDuplicates(c, j); if (gtDuplicates.contains(pair)) { tp_ += 1; } verifications_ += 1; } } float recall_ = (float) tp_ / (float) gtDuplicates.size(); float precision_ = (float) tp_ / (float) verifications_; averageRecall += recall_; averagePrecision += precision_; averageCandidates += candidatePairs.size(); } System.out.println("Average indexing time\t:\t" + averageIndexingTime / ITERATIONS); System.out.println("Average querying time\t:\t" + averageQueryingTime / ITERATIONS); System.out.println("Recall\t:\t" + averageRecall / ITERATIONS); System.out.println("Precision\t:\t" + averagePrecision / ITERATIONS); System.out.println("Candidates\t:\t" + averageCandidates / ITERATIONS); } } }
gpapadis/ContinuousFilteringBenchmark
nnmethods/minhashLSH/src/experiments/schemaAgnostic.java
1,687
// read target entities
line_comment
nl
package experiments; import org.scify.jedai.datamodel.EntityProfile; import org.scify.jedai.datamodel.IdDuplicates; import java.util.*; import minhash.LocalitySensitiveHashing; import minhash.MinHash; import minhash.Pair; import minhash.Reader; import minhash.ShinglingModel; import minhash.Utilities; public class schemaAgnostic { static int ITERATIONS = 10; public static void main(String[] args) { boolean[] preprocessed = {false, false, false, true, false, true, false, false, false, false}; int[] bands = {4, 32, 16, 4, 32, 32, 16, 32, 16, 32}; int[] buckets = {64, 8, 8, 128, 16, 8, 16, 16, 16, 8}; int[] k = {2, 2, 2, 2, 2, 5, 2, 2, 2, 2}; String[] mainDirs = {"/home/gap2/Documents/blockingNN/data/schemaAgnostic/", "/home/gap2/Documents/blockingNN/data/preprocessedSA/" }; String[] datasetsD1 = {"restaurant1Profiles", "abtProfiles", "amazonProfiles", "dblpProfiles", "imdbProfilesNEW", "imdbProfilesNEW", "tmdbProfiles", "walmartProfiles", "dblpProfiles2", "imdbProfiles"}; String[] datasetsD2 = {"restaurant2Profiles", "buyProfiles", "gpProfiles", "acmProfiles", "tmdbProfiles", "tvdbProfiles", "tvdbProfiles", "amazonProfiles2", "scholarProfiles", "dbpediaProfiles"}; String[] groundtruthDirs = {"restaurantsIdDuplicates", "abtBuyIdDuplicates", "amazonGpIdDuplicates", "dblpAcmIdDuplicates", "imdbTmdbIdDuplicates", "imdbTvdbIdDuplicates", "tmdbTvdbIdDuplicates", "amazonWalmartIdDuplicates", "dblpScholarIdDuplicates", "moviesIdDuplicates"}; for (int datasetId = 0; datasetId < groundtruthDirs.length; datasetId++) { // read source entities int dirId = preprocessed[datasetId] ? 1 : 0; String sourcePath = mainDirs[dirId] + datasetsD1[datasetId]; List<EntityProfile> sourceEntities = Reader.readSerialized(sourcePath); System.out.println("Source Entities: " + sourceEntities.size()); // read target<SUF> String targetPath = mainDirs[dirId] + datasetsD2[datasetId]; List<EntityProfile> targetEntities = Reader.readSerialized(targetPath); System.out.println("Target Entities: " + targetEntities.size()); // read ground-truth file String groundTruthPath = mainDirs[dirId] + groundtruthDirs[datasetId]; Set<IdDuplicates> gtDuplicates = Reader.readSerializedGT(groundTruthPath, sourceEntities, targetEntities); System.out.println("GT Duplicates Entities: " + gtDuplicates.size()); System.out.println(); double averageIndexingTime = 0; double averageQueryingTime = 0; double averageRecall = 0; double averagePrecision = 0; double averageCandidates = 0; for (int iteration = 0; iteration < ITERATIONS; iteration++) { long time1 = System.currentTimeMillis(); List<String> sourceSTR = Utilities.entities2String(sourceEntities); ShinglingModel model = new ShinglingModel(sourceSTR, k[datasetId]); int[][] sourceVectorsInt = model.vectorization(sourceSTR); float[][] sVectors = new float[sourceVectorsInt.length][]; for (int row = 0; row < sourceVectorsInt.length; row++) { double[] tempArray = Arrays.stream(sourceVectorsInt[row]).asDoubleStream().toArray(); sVectors[row] = new float[tempArray.length]; for (int i = 0; i < tempArray.length; i++) { sVectors[row][i] = (float) tempArray[i]; } } // initialize LSH LocalitySensitiveHashing lsh = new MinHash(sVectors, bands[datasetId], buckets[datasetId], model.getVectorSize()); long time2 = System.currentTimeMillis(); List<String> targetSTR = Utilities.entities2String(targetEntities); int[][] targetVectorsInt = model.vectorization(targetSTR); float[][] tVectors = new float[targetVectorsInt.length][]; for (int row = 0; row < targetVectorsInt.length; row++) { double[] tempArray = Arrays.stream(targetVectorsInt[row]).asDoubleStream().toArray(); tVectors[row] = new float[tempArray.length]; for (int i = 0; i < tempArray.length; i++) { tVectors[row][i] = (float) tempArray[i]; } } // for each target entity, find its candidates (query) // find TP by searching the pairs in GT final List<Pair> candidatePairs = new ArrayList<>(); for (int j = 0; j < targetEntities.size(); j++) { float[] vector = tVectors[j]; Set<Integer> candidates = lsh.query(vector); for (Integer c : candidates) { candidatePairs.add(new Pair(j, c)); } } long time3 = System.currentTimeMillis(); averageIndexingTime += time2 - time1; averageQueryingTime += time3 - time2; // true positive long tp_ = 0; // total verifications long verifications_ = 0; for (int j = 0; j < targetEntities.size(); j++) { float[] vector = tVectors[j]; Set<Integer> candidates = lsh.query(vector); for (Integer c : candidates) { IdDuplicates pair = new IdDuplicates(c, j); if (gtDuplicates.contains(pair)) { tp_ += 1; } verifications_ += 1; } } float recall_ = (float) tp_ / (float) gtDuplicates.size(); float precision_ = (float) tp_ / (float) verifications_; averageRecall += recall_; averagePrecision += precision_; averageCandidates += candidatePairs.size(); } System.out.println("Average indexing time\t:\t" + averageIndexingTime / ITERATIONS); System.out.println("Average querying time\t:\t" + averageQueryingTime / ITERATIONS); System.out.println("Recall\t:\t" + averageRecall / ITERATIONS); System.out.println("Precision\t:\t" + averagePrecision / ITERATIONS); System.out.println("Candidates\t:\t" + averageCandidates / ITERATIONS); } } }
179525_25
// Copyright 2010 - UDS/CNRS // The Aladin program is distributed under the terms // of the GNU General Public License version 3. // //This file is part of Aladin. // // Aladin is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3 of the License. // // Aladin is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // The GNU General Public License is available in COPYING file // along with Aladin. // package cds.aladin; import java.awt.*; import java.awt.event.*; import javax.swing.JComponent; /** * @author Thomas Boch */ /* classe destinee a l'affichage des curseurs pour definir les niveaux des contours */ public class Curseur extends JComponent implements MouseListener, MouseMotionListener { static final int NO = -1; // constante signifiant qu'aucun triangle // n'est le triangle courant int[] niveaux; // tableau des niveaux int currentTriangle; // indice dans niveaux du triangle en cours de selection boolean flagDrag = false; // true si on drag int nbNiveaux = 0; // nb de niveaux couramment utilises Color[] couleurTriangle; // tableau des couleurs pour les triangles private MyListener listener; // pour declencher une action associee aux valeurs du curseur // Les constantes d'affichage final int mX = 10; // Marge en abscisse final int mY = 0; // Marge en ordonnee final int Hp = 0; // Hauteur du graphique final int W = 256+2*mX; // Largeur totale du graphique final int H = Hp+mY+24; // Hauteur totale du graphique /* constructeur */ protected Curseur() { initNiveaux(); initCouleurs(); // setBackground(Aladin.BKGD); enableEvents(AWTEvent.WINDOW_EVENT_MASK); addMouseListener(this); addMouseMotionListener(this); resize(W,H); } protected Curseur(MyListener listener) { this(); this.listener = listener; } /** initCouleurs * initialise le tableau des couleurs * chaque element est initialise a Color.black */ private void initCouleurs() { couleurTriangle = new Color[PlanContour.MAXLEVELS]; for (int i=0;i<PlanContour.MAXLEVELS;i++) { couleurTriangle[i] = Color.black; } } /** initNiveaux * fixe arbitrairement les niveaux initiaux */ private void initNiveaux() { niveaux = new int[PlanContour.MAXLEVELS]; niveaux[0] = 100; nbNiveaux = 1; } public Dimension preferredSize() { return new Dimension(W,H); } public Dimension getPreferredSize() { return preferredSize(); } /** Dessin d'un triangle. * @param g le contexte graphique * @param x l'abcisse du triangle a dessinner * @param i indice dans niveaux du triangle que l'on dessine */ protected void drawTriangle(Graphics g,int x, int i) { int [] tx = new int[4]; int [] ty = new int[4]; tx[0] = tx[3] = x+mX; tx[1] = tx[0]-7; tx[2] = tx[0]+7; ty[0] = ty[3] = Hp+4+mY; ty[1] = ty[2] = ty[0]+10; g.setColor( couleurTriangle[i] ); g.fillPolygon(tx,ty,tx.length); g.setColor(Color.black); g.drawPolygon(tx,ty,tx.length); g.setFont( Aladin.SPLAIN ); g.drawString(""+x,mX+x-7,mY+Hp+24); } /** Reperage du triangle le plus proche de la position de la souris */ public boolean mouseMove(Event e,int x,int y) { x-=mX; if( listener!=null ) listener.fireStateChange(-1); // on demande a avoir le focus pour les evts clavier requestFocus(); // Reperage du triangle le plus proche for( int i=0; i<nbNiveaux; i++ ) { if( x>niveaux[i]-5 && x<niveaux[i]+5 ) { currentTriangle=i; return true; } } currentTriangle = NO; return true; } // implementation de MouseListener /** Reperage du triangle le plus proche du clic souris */ public void mousePressed(MouseEvent e) { int x = e.getX(); x-=mX; // Reperage du triangle le plus proche for( int i=0; i<nbNiveaux; i++ ) { if( x>niveaux[i]-5 && x<niveaux[i]+5 ) { currentTriangle=i; if( listener!=null ) listener.fireStateChange(niveaux[currentTriangle]); return; } } currentTriangle = NO; if( listener!=null ) listener.fireStateChange(null); } /** Fin de deplacement du triangle precedemment selectionne */ public void mouseReleased(MouseEvent e) { if( currentTriangle==NO ) return; int x = e.getX(); x-=mX; if( x<0 ) x=0; else if( x>255 ) x=255; niveaux[currentTriangle] = x; flagDrag=false; repaint(); } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} // implementation de MouseMotionListener /** Deplacement du triangle precedemment selectionne avec mise a jour * d'une portion de l'image */ public void mouseDragged(MouseEvent e) { if( currentTriangle==NO ) return; int x = e.getX(); x-=mX; if( x<0 ) x=0; else if( x>255 ) x=255; niveaux[currentTriangle] = x; if( listener!=null ) listener.fireStateChange(x); flagDrag=true; repaint(); } public void mouseMoved(MouseEvent e) {} public void paint(Graphics g) { int i; g.setColor(Color.black); g.drawLine(mX, Hp+mY+3, mX+255, Hp+mY+3); g.drawLine(mX, Hp+mY, mX, Hp+mY+6); g.drawLine(mX+255, Hp+mY, mX+255, Hp+mY+6); for( i=0; i<nbNiveaux; i++ ) { drawTriangle(g,niveaux[i],i); } } // ajoute un curseur au nivau par defaut 0 protected boolean addCurseur() { if (nbNiveaux>=PlanContour.MAXLEVELS) return false; niveaux[nbNiveaux] = 0; // niveau a la creation du nouveau curseur nbNiveaux++; repaint(); return true; } // ajoute un curseur au niveau specifie protected boolean addCurseur(int level) { if (nbNiveaux>=PlanContour.MAXLEVELS) return false; niveaux[nbNiveaux] = level; // niveau a la creation du nouveau curseur nbNiveaux++; repaint(); return true; } // remet le nb de niveaux a zero protected void reset() { nbNiveaux = 0; repaint(); } // pour Francois Ochsenbein // methode permettant le deplacement des niveaux au clavier public boolean keyDown(Event e,int key) { if(currentTriangle == NO) return true; boolean move = false; if (key == Event.RIGHT) { move = true; if(niveaux[currentTriangle]<255) niveaux[currentTriangle]++; } else if (key == Event.LEFT) { move = true; if(niveaux[currentTriangle]>0) niveaux[currentTriangle]--; } if( move ) { if( listener!=null ) listener.fireStateChange(niveaux[currentTriangle]); repaint(); } return true; } }
jon85p/Aladin
cds/aladin/Curseur.java
2,377
// Marge en ordonnee
line_comment
nl
// Copyright 2010 - UDS/CNRS // The Aladin program is distributed under the terms // of the GNU General Public License version 3. // //This file is part of Aladin. // // Aladin is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3 of the License. // // Aladin is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // The GNU General Public License is available in COPYING file // along with Aladin. // package cds.aladin; import java.awt.*; import java.awt.event.*; import javax.swing.JComponent; /** * @author Thomas Boch */ /* classe destinee a l'affichage des curseurs pour definir les niveaux des contours */ public class Curseur extends JComponent implements MouseListener, MouseMotionListener { static final int NO = -1; // constante signifiant qu'aucun triangle // n'est le triangle courant int[] niveaux; // tableau des niveaux int currentTriangle; // indice dans niveaux du triangle en cours de selection boolean flagDrag = false; // true si on drag int nbNiveaux = 0; // nb de niveaux couramment utilises Color[] couleurTriangle; // tableau des couleurs pour les triangles private MyListener listener; // pour declencher une action associee aux valeurs du curseur // Les constantes d'affichage final int mX = 10; // Marge en abscisse final int mY = 0; // Marge en<SUF> final int Hp = 0; // Hauteur du graphique final int W = 256+2*mX; // Largeur totale du graphique final int H = Hp+mY+24; // Hauteur totale du graphique /* constructeur */ protected Curseur() { initNiveaux(); initCouleurs(); // setBackground(Aladin.BKGD); enableEvents(AWTEvent.WINDOW_EVENT_MASK); addMouseListener(this); addMouseMotionListener(this); resize(W,H); } protected Curseur(MyListener listener) { this(); this.listener = listener; } /** initCouleurs * initialise le tableau des couleurs * chaque element est initialise a Color.black */ private void initCouleurs() { couleurTriangle = new Color[PlanContour.MAXLEVELS]; for (int i=0;i<PlanContour.MAXLEVELS;i++) { couleurTriangle[i] = Color.black; } } /** initNiveaux * fixe arbitrairement les niveaux initiaux */ private void initNiveaux() { niveaux = new int[PlanContour.MAXLEVELS]; niveaux[0] = 100; nbNiveaux = 1; } public Dimension preferredSize() { return new Dimension(W,H); } public Dimension getPreferredSize() { return preferredSize(); } /** Dessin d'un triangle. * @param g le contexte graphique * @param x l'abcisse du triangle a dessinner * @param i indice dans niveaux du triangle que l'on dessine */ protected void drawTriangle(Graphics g,int x, int i) { int [] tx = new int[4]; int [] ty = new int[4]; tx[0] = tx[3] = x+mX; tx[1] = tx[0]-7; tx[2] = tx[0]+7; ty[0] = ty[3] = Hp+4+mY; ty[1] = ty[2] = ty[0]+10; g.setColor( couleurTriangle[i] ); g.fillPolygon(tx,ty,tx.length); g.setColor(Color.black); g.drawPolygon(tx,ty,tx.length); g.setFont( Aladin.SPLAIN ); g.drawString(""+x,mX+x-7,mY+Hp+24); } /** Reperage du triangle le plus proche de la position de la souris */ public boolean mouseMove(Event e,int x,int y) { x-=mX; if( listener!=null ) listener.fireStateChange(-1); // on demande a avoir le focus pour les evts clavier requestFocus(); // Reperage du triangle le plus proche for( int i=0; i<nbNiveaux; i++ ) { if( x>niveaux[i]-5 && x<niveaux[i]+5 ) { currentTriangle=i; return true; } } currentTriangle = NO; return true; } // implementation de MouseListener /** Reperage du triangle le plus proche du clic souris */ public void mousePressed(MouseEvent e) { int x = e.getX(); x-=mX; // Reperage du triangle le plus proche for( int i=0; i<nbNiveaux; i++ ) { if( x>niveaux[i]-5 && x<niveaux[i]+5 ) { currentTriangle=i; if( listener!=null ) listener.fireStateChange(niveaux[currentTriangle]); return; } } currentTriangle = NO; if( listener!=null ) listener.fireStateChange(null); } /** Fin de deplacement du triangle precedemment selectionne */ public void mouseReleased(MouseEvent e) { if( currentTriangle==NO ) return; int x = e.getX(); x-=mX; if( x<0 ) x=0; else if( x>255 ) x=255; niveaux[currentTriangle] = x; flagDrag=false; repaint(); } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} // implementation de MouseMotionListener /** Deplacement du triangle precedemment selectionne avec mise a jour * d'une portion de l'image */ public void mouseDragged(MouseEvent e) { if( currentTriangle==NO ) return; int x = e.getX(); x-=mX; if( x<0 ) x=0; else if( x>255 ) x=255; niveaux[currentTriangle] = x; if( listener!=null ) listener.fireStateChange(x); flagDrag=true; repaint(); } public void mouseMoved(MouseEvent e) {} public void paint(Graphics g) { int i; g.setColor(Color.black); g.drawLine(mX, Hp+mY+3, mX+255, Hp+mY+3); g.drawLine(mX, Hp+mY, mX, Hp+mY+6); g.drawLine(mX+255, Hp+mY, mX+255, Hp+mY+6); for( i=0; i<nbNiveaux; i++ ) { drawTriangle(g,niveaux[i],i); } } // ajoute un curseur au nivau par defaut 0 protected boolean addCurseur() { if (nbNiveaux>=PlanContour.MAXLEVELS) return false; niveaux[nbNiveaux] = 0; // niveau a la creation du nouveau curseur nbNiveaux++; repaint(); return true; } // ajoute un curseur au niveau specifie protected boolean addCurseur(int level) { if (nbNiveaux>=PlanContour.MAXLEVELS) return false; niveaux[nbNiveaux] = level; // niveau a la creation du nouveau curseur nbNiveaux++; repaint(); return true; } // remet le nb de niveaux a zero protected void reset() { nbNiveaux = 0; repaint(); } // pour Francois Ochsenbein // methode permettant le deplacement des niveaux au clavier public boolean keyDown(Event e,int key) { if(currentTriangle == NO) return true; boolean move = false; if (key == Event.RIGHT) { move = true; if(niveaux[currentTriangle]<255) niveaux[currentTriangle]++; } else if (key == Event.LEFT) { move = true; if(niveaux[currentTriangle]>0) niveaux[currentTriangle]--; } if( move ) { if( listener!=null ) listener.fireStateChange(niveaux[currentTriangle]); repaint(); } return true; } }
11797_4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko; import java.util.List; import java.util.ArrayList; import android.content.Context; import android.content.ComponentName; import android.content.Intent; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class GeckoMenu extends LinearLayout implements Menu, GeckoMenuItem.OnShowAsActionChangedListener { private static final String LOGTAG = "GeckoMenu"; private Context mContext; public static interface ActionItemBarPresenter { public void addActionItem(View actionItem); public void removeActionItem(int index); public int getActionItemsCount(); } private static final int NO_ID = 0; // Default list of items. private List<GeckoMenuItem> mItems; // List of items in action-bar. private List<GeckoMenuItem> mActionItems; // Reference to action-items bar in action-bar. private ActionItemBarPresenter mActionItemBarPresenter; public GeckoMenu(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); setOrientation(VERTICAL); mItems = new ArrayList<GeckoMenuItem>(); mActionItems = new ArrayList<GeckoMenuItem>(); } @Override public MenuItem add(CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID); menuItem.setTitle(title); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order); menuItem.setTitle(titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID); menuItem.setTitle(titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order); menuItem.setTitle(title); addItem(menuItem); return menuItem; } private void addItem(GeckoMenuItem menuItem) { menuItem.setOnShowAsActionChangedListener(this); // Insert it in proper order. int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() > menuItem.getOrder()) { mItems.add(index, menuItem); // Account for the items in the action-bar. if (mActionItemBarPresenter != null) addView(menuItem.getLayout(), index - mActionItemBarPresenter.getActionItemsCount()); else addView(menuItem.getLayout(), index); return; } else { index++; } } // Add the menuItem at the end. mItems.add(menuItem); addView(menuItem.getLayout()); } private void addActionItem(GeckoMenuItem menuItem) { menuItem.setOnShowAsActionChangedListener(this); int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() <= menuItem.getOrder()) index++; else break; } mActionItems.add(menuItem); mItems.add(index, menuItem); mActionItemBarPresenter.addActionItem(menuItem.getLayout()); } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { return 0; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { return null; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { return null; } @Override public SubMenu addSubMenu(CharSequence title) { return null; } @Override public SubMenu addSubMenu(int titleRes) { return null; } @Override public void clear() { } @Override public void close() { } @Override public MenuItem findItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) return menuItem; } return null; } @Override public MenuItem getItem(int index) { if (index < mItems.size()) return mItems.get(index); return null; } @Override public boolean hasVisibleItems() { for (GeckoMenuItem menuItem : mItems) { if (menuItem.isVisible()) return true; } return false; } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return true; } @Override public boolean performIdentifierAction(int id, int flags) { return false; } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return false; } @Override public void removeGroup(int groupId) { } @Override public void removeItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) { if (mActionItems.contains(menuItem)) { if (mActionItemBarPresenter != null) mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(menuItem)); mActionItems.remove(menuItem); } else { removeView(findViewById(id)); } mItems.remove(menuItem); return; } } } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { } @Override public void setGroupEnabled(int group, boolean enabled) { } @Override public void setGroupVisible(int group, boolean visible) { } @Override public void setQwertyMode(boolean isQwerty) { } @Override public int size() { return mItems.size(); } @Override public boolean hasActionItemBar() { return (mActionItemBarPresenter != null); } @Override public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) { removeItem(item.getItemId()); if (isActionItem) addActionItem(item); else addItem(item); } public void setActionItemBarPresenter(ActionItemBarPresenter presenter) { mActionItemBarPresenter = presenter; } }
l-hedgehog/gecko-dev
mobile/android/base/GeckoMenu.java
1,779
// Insert it in proper order.
line_comment
nl
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko; import java.util.List; import java.util.ArrayList; import android.content.Context; import android.content.ComponentName; import android.content.Intent; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class GeckoMenu extends LinearLayout implements Menu, GeckoMenuItem.OnShowAsActionChangedListener { private static final String LOGTAG = "GeckoMenu"; private Context mContext; public static interface ActionItemBarPresenter { public void addActionItem(View actionItem); public void removeActionItem(int index); public int getActionItemsCount(); } private static final int NO_ID = 0; // Default list of items. private List<GeckoMenuItem> mItems; // List of items in action-bar. private List<GeckoMenuItem> mActionItems; // Reference to action-items bar in action-bar. private ActionItemBarPresenter mActionItemBarPresenter; public GeckoMenu(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); setOrientation(VERTICAL); mItems = new ArrayList<GeckoMenuItem>(); mActionItems = new ArrayList<GeckoMenuItem>(); } @Override public MenuItem add(CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID); menuItem.setTitle(title); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order); menuItem.setTitle(titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID); menuItem.setTitle(titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order); menuItem.setTitle(title); addItem(menuItem); return menuItem; } private void addItem(GeckoMenuItem menuItem) { menuItem.setOnShowAsActionChangedListener(this); // Insert it<SUF> int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() > menuItem.getOrder()) { mItems.add(index, menuItem); // Account for the items in the action-bar. if (mActionItemBarPresenter != null) addView(menuItem.getLayout(), index - mActionItemBarPresenter.getActionItemsCount()); else addView(menuItem.getLayout(), index); return; } else { index++; } } // Add the menuItem at the end. mItems.add(menuItem); addView(menuItem.getLayout()); } private void addActionItem(GeckoMenuItem menuItem) { menuItem.setOnShowAsActionChangedListener(this); int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() <= menuItem.getOrder()) index++; else break; } mActionItems.add(menuItem); mItems.add(index, menuItem); mActionItemBarPresenter.addActionItem(menuItem.getLayout()); } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { return 0; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { return null; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { return null; } @Override public SubMenu addSubMenu(CharSequence title) { return null; } @Override public SubMenu addSubMenu(int titleRes) { return null; } @Override public void clear() { } @Override public void close() { } @Override public MenuItem findItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) return menuItem; } return null; } @Override public MenuItem getItem(int index) { if (index < mItems.size()) return mItems.get(index); return null; } @Override public boolean hasVisibleItems() { for (GeckoMenuItem menuItem : mItems) { if (menuItem.isVisible()) return true; } return false; } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return true; } @Override public boolean performIdentifierAction(int id, int flags) { return false; } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return false; } @Override public void removeGroup(int groupId) { } @Override public void removeItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) { if (mActionItems.contains(menuItem)) { if (mActionItemBarPresenter != null) mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(menuItem)); mActionItems.remove(menuItem); } else { removeView(findViewById(id)); } mItems.remove(menuItem); return; } } } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { } @Override public void setGroupEnabled(int group, boolean enabled) { } @Override public void setGroupVisible(int group, boolean visible) { } @Override public void setQwertyMode(boolean isQwerty) { } @Override public int size() { return mItems.size(); } @Override public boolean hasActionItemBar() { return (mActionItemBarPresenter != null); } @Override public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) { removeItem(item.getItemId()); if (isActionItem) addActionItem(item); else addItem(item); } public void setActionItemBarPresenter(ActionItemBarPresenter presenter) { mActionItemBarPresenter = presenter; } }
16527_3
/* * Copyright (c) 2023, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. * * https://opensource.org/licenses/BSD-3-Clause */ package org.jline.nativ; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; /** * Provides OS name and architecture name. * * @author leo */ public class OSInfo { public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; public static final String ARM64 = "arm64"; private static final Logger logger = Logger.getLogger("org.jline"); private static final HashMap<String, String> archMapping = new HashMap<>(); static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac // Itenium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itenium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); archMapping.put("aarch64", ARM64); } public static void main(String[] args) { if (args.length >= 1) { if ("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if ("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName() + "/" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static boolean isAndroid() { return System.getProperty("java.runtime.name", "").toLowerCase().contains("android"); } @SuppressWarnings("unused") public static boolean isAlpine() { try { Process p = Runtime.getRuntime().exec(new String[] {"cat", "/etc/os-release", "|", "grep", "^ID"}); p.waitFor(); try (InputStream in = p.getInputStream()) { return readFully(in).toLowerCase().contains("alpine"); } } catch (Throwable e) { return false; } } static String getHardwareName() { try { Process p = Runtime.getRuntime().exec(new String[] {"uname", "-m"}); p.waitFor(); try (InputStream in = p.getInputStream()) { return readFully(in); } } catch (Throwable e) { log(Level.WARNING, "Error while running uname -m", e); return "unknown"; } } private static String readFully(InputStream in) throws IOException { int readLen = 0; ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[32]; while ((readLen = in.read(buf, 0, buf.length)) >= 0) { b.write(buf, 0, readLen); } return b.toString(); } static String resolveArmArchType() { if (System.getProperty("os.name").contains("Linux")) { String armType = getHardwareName(); // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l, aarch64, i686 if (armType.startsWith("armv6")) { // Raspberry PI return "armv6"; } else if (armType.startsWith("armv7")) { // Generic return "armv7"; } else if (armType.startsWith("armv5")) { // Use armv5, soft-float ABI return "arm"; } else if (armType.equals("aarch64")) { // Use arm64 return "arm64"; } // Java 1.8 introduces a system property to determine armel or armhf // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545 String abi = System.getProperty("sun.arch.abi"); if (abi != null && abi.startsWith("gnueabihf")) { return "armv7"; } } // Use armv5, soft-float ABI return "arm"; } public static String getArchName() { String osArch = System.getProperty("os.arch"); // For Android if (isAndroid()) { return "android-arm"; } if (osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if (archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if (osName.contains("Windows")) { return "Windows"; } else if (osName.contains("Mac") || osName.contains("Darwin")) { return "Mac"; // } else if (isAlpine()) { // return "Linux-Alpine"; } else if (osName.contains("Linux")) { return "Linux"; } else if (osName.contains("AIX")) { return "AIX"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } private static void log(Level level, String message, Throwable t) { if (logger.isLoggable(level)) { if (logger.isLoggable(Level.FINE)) { logger.log(level, message, t); } else { logger.log(level, message + " (caused by: " + t + ", enable debug logging for stacktrace)"); } } } }
jline/jline3
native/src/main/java/org/jline/nativ/OSInfo.java
2,225
// Needed for openjdk7 in Mac
line_comment
nl
/* * Copyright (c) 2023, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. * * https://opensource.org/licenses/BSD-3-Clause */ package org.jline.nativ; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; /** * Provides OS name and architecture name. * * @author leo */ public class OSInfo { public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; public static final String ARM64 = "arm64"; private static final Logger logger = Logger.getLogger("org.jline"); private static final HashMap<String, String> archMapping = new HashMap<>(); static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for<SUF> // Itenium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itenium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); archMapping.put("aarch64", ARM64); } public static void main(String[] args) { if (args.length >= 1) { if ("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if ("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName() + "/" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static boolean isAndroid() { return System.getProperty("java.runtime.name", "").toLowerCase().contains("android"); } @SuppressWarnings("unused") public static boolean isAlpine() { try { Process p = Runtime.getRuntime().exec(new String[] {"cat", "/etc/os-release", "|", "grep", "^ID"}); p.waitFor(); try (InputStream in = p.getInputStream()) { return readFully(in).toLowerCase().contains("alpine"); } } catch (Throwable e) { return false; } } static String getHardwareName() { try { Process p = Runtime.getRuntime().exec(new String[] {"uname", "-m"}); p.waitFor(); try (InputStream in = p.getInputStream()) { return readFully(in); } } catch (Throwable e) { log(Level.WARNING, "Error while running uname -m", e); return "unknown"; } } private static String readFully(InputStream in) throws IOException { int readLen = 0; ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[32]; while ((readLen = in.read(buf, 0, buf.length)) >= 0) { b.write(buf, 0, readLen); } return b.toString(); } static String resolveArmArchType() { if (System.getProperty("os.name").contains("Linux")) { String armType = getHardwareName(); // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l, aarch64, i686 if (armType.startsWith("armv6")) { // Raspberry PI return "armv6"; } else if (armType.startsWith("armv7")) { // Generic return "armv7"; } else if (armType.startsWith("armv5")) { // Use armv5, soft-float ABI return "arm"; } else if (armType.equals("aarch64")) { // Use arm64 return "arm64"; } // Java 1.8 introduces a system property to determine armel or armhf // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545 String abi = System.getProperty("sun.arch.abi"); if (abi != null && abi.startsWith("gnueabihf")) { return "armv7"; } } // Use armv5, soft-float ABI return "arm"; } public static String getArchName() { String osArch = System.getProperty("os.arch"); // For Android if (isAndroid()) { return "android-arm"; } if (osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if (archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if (osName.contains("Windows")) { return "Windows"; } else if (osName.contains("Mac") || osName.contains("Darwin")) { return "Mac"; // } else if (isAlpine()) { // return "Linux-Alpine"; } else if (osName.contains("Linux")) { return "Linux"; } else if (osName.contains("AIX")) { return "AIX"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } private static void log(Level level, String message, Throwable t) { if (logger.isLoggable(level)) { if (logger.isLoggable(Level.FINE)) { logger.log(level, message, t); } else { logger.log(level, message + " (caused by: " + t + ", enable debug logging for stacktrace)"); } } } }
200999_4
/* @author Nick @version 0607 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; public class Datenbank { int zug = 0; Connection connection = null; public void datenbankErstellen() { try { // Pfad zur SQLite-Datenbankdatei angeben String dbFile = "datenbank.db"; // Verbindung zur Datenbank herstellen connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile); } catch (SQLException e) { e.printStackTrace(); } } Statement statement = null; ResultSet resultSet = null; public void tabelleErstellen(){ try { statement = connection.createStatement(); // Tabelle erstellen String createTableQuery = "CREATE TABLE IF NOT EXISTS zuege (Zugnummer INT, Zug TEXT)"; statement.executeUpdate(createTableQuery); } catch (SQLException e) { e.printStackTrace(); } } public void insertDataIntoTable(Connection connection, String text) throws SQLException { // SQL-Abfrage zum Einfügen von Daten String insertQuery = "INSERT INTO zuege (Zugnummer, Zug) VALUES (?, ?)"; // Prepared Statement vorbereiten PreparedStatement statement = connection.prepareStatement(insertQuery); // Werte für die Parameter festlegen statement.setInt(1, zug); statement.setString(2, text); // Einfügen der Daten ausführen statement.executeUpdate(); // Prepared Statement schließen statement.close(); } public static void clearTable(Connection connection) throws SQLException { //leert die komplette Tabelle String deleteQuery = "DELETE FROM zuege"; Statement statement = connection.createStatement(); statement.executeUpdate(deleteQuery); statement.close(); } }
wulusub/Schach
Schach-main/Datenbank.java
509
// Prepared Statement vorbereiten
line_comment
nl
/* @author Nick @version 0607 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; public class Datenbank { int zug = 0; Connection connection = null; public void datenbankErstellen() { try { // Pfad zur SQLite-Datenbankdatei angeben String dbFile = "datenbank.db"; // Verbindung zur Datenbank herstellen connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile); } catch (SQLException e) { e.printStackTrace(); } } Statement statement = null; ResultSet resultSet = null; public void tabelleErstellen(){ try { statement = connection.createStatement(); // Tabelle erstellen String createTableQuery = "CREATE TABLE IF NOT EXISTS zuege (Zugnummer INT, Zug TEXT)"; statement.executeUpdate(createTableQuery); } catch (SQLException e) { e.printStackTrace(); } } public void insertDataIntoTable(Connection connection, String text) throws SQLException { // SQL-Abfrage zum Einfügen von Daten String insertQuery = "INSERT INTO zuege (Zugnummer, Zug) VALUES (?, ?)"; // Prepared Statement<SUF> PreparedStatement statement = connection.prepareStatement(insertQuery); // Werte für die Parameter festlegen statement.setInt(1, zug); statement.setString(2, text); // Einfügen der Daten ausführen statement.executeUpdate(); // Prepared Statement schließen statement.close(); } public static void clearTable(Connection connection) throws SQLException { //leert die komplette Tabelle String deleteQuery = "DELETE FROM zuege"; Statement statement = connection.createStatement(); statement.executeUpdate(deleteQuery); statement.close(); } }
154463_9
// CashDispenser.java // Represents the cash dispenser of the ATM public class CashDispenser { // the default initial number of bills in the cash dispenser private final static int INITIAL_COUNT = 500; private int count; // number of $20 bills remaining // no-argument CashDispenser constructor initializes count to default public CashDispenser() { count = INITIAL_COUNT; // set count attribute to default } // end CashDispenser constructor // simulates dispensing of specified amount of cash public void dispenseCash(int amount) { int billsRequired = amount / 20; // number of $20 bills required count -= billsRequired; // update the count of bills } // end method dispenseCash // indicates whether cash dispenser can dispense desired amount public boolean isSufficientCashAvailable(int amount) { int billsRequired = amount / 20; // number of $20 bills required if (count >= billsRequired ) return true; // enough bills available else return false; // not enough bills available } // end method isSufficientCashAvailable } // end class CashDispenser /************************************************************************** * (C) Copyright 1992-2014 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
DanH957/ATM-Machine
CashDispenser.java
510
// end method dispenseCash
line_comment
nl
// CashDispenser.java // Represents the cash dispenser of the ATM public class CashDispenser { // the default initial number of bills in the cash dispenser private final static int INITIAL_COUNT = 500; private int count; // number of $20 bills remaining // no-argument CashDispenser constructor initializes count to default public CashDispenser() { count = INITIAL_COUNT; // set count attribute to default } // end CashDispenser constructor // simulates dispensing of specified amount of cash public void dispenseCash(int amount) { int billsRequired = amount / 20; // number of $20 bills required count -= billsRequired; // update the count of bills } // end method<SUF> // indicates whether cash dispenser can dispense desired amount public boolean isSufficientCashAvailable(int amount) { int billsRequired = amount / 20; // number of $20 bills required if (count >= billsRequired ) return true; // enough bills available else return false; // not enough bills available } // end method isSufficientCashAvailable } // end class CashDispenser /************************************************************************** * (C) Copyright 1992-2014 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
6614_13
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; /** * {@code StepGeneration} is a utility class containing the step generation utility functions used * in autoregressive search. */ public final class StepGeneration { private StepGeneration() {} /** * Generate the output token id and selecting indices used in contrastive search. * * @param topKIds the topk candidate token ids * @param logits the logits from the language model * @param contextHiddenStates the embedding of the past generated token ids * @param topkHiddenStates the embedding of the topk candidate token ids * @param offSets the offsets * @param alpha the repetition penalty * @return the output token ids and selecting indices */ public static NDList constrastiveStepGeneration( NDArray topKIds, NDArray logits, NDArray contextHiddenStates, NDArray topkHiddenStates, NDArray offSets, float alpha) { /* topKIds: [batch, topK] attentionMask: [batch, past_seq] logits: [batch, vocabSize] contextHiddenStates: [batch, past_seq, dim] topkHiddenStates: [batch*topK, seq=1, dim] attentionMaskSlice: [batch, 2]: (startPosition, endPosition) */ long batch = topKIds.getShape().get(0); long topK = topKIds.getShape().get(1); long hiddenDim = topkHiddenStates.getShape().getLastDimension(); // [batch*topK, seq=1, dim] -> [batch, topK, dim] topkHiddenStates = topkHiddenStates.reshape(batch, topK, hiddenDim); // [batch, topK, dim] * [batch, past_seq, dim] -> [batch, topK, past_seq] topkHiddenStates = topkHiddenStates.normalize(2, 2); contextHiddenStates = contextHiddenStates.normalize(2, 2); NDArray cosSimilarity = topkHiddenStates.batchMatMul(contextHiddenStates.transpose(0, 2, 1)); // Deactivate entries (batch_idx, :, zero_attention_idx_slice) in max{cosSim} step long[] offSetsArray = offSets.toLongArray(); for (int i = 0; i < offSetsArray.length; i++) { cosSimilarity.set(new NDIndex("{}, :, {}:{}", i, 0, offSetsArray[i]), -1); } // [batch, topK, past_seq] -> [batch, topK] NDArray topkScorePart1 = cosSimilarity.max(new int[] {2}); assert topkScorePart1.getShape().getShape().length == 2 : "Wrong output size"; // [batch, logitDim].gather([batch, topK) -> [batch, topK] NDArray topkScorePart2 = logits.softmax(1).gather(topKIds, 1); NDArray topkScore = topkScorePart2.muli(1 - alpha).subi(topkScorePart1.muli(alpha)); // [batch, topK] => [batch, 1] NDArray select = topkScore.argMax(1); NDIndex selectIndex = new NDIndex( "{}, {}, ...", logits.getManager().arange(0, topKIds.getShape().get(0), 1, DataType.INT64), select); NDArray outputIds = topKIds.get(selectIndex).reshape(-1, 1); return new NDList(outputIds, select); } // TODO: add support of Einstein summation: // a = torch.randn(batch, past_seq, dim) // b = torch.randn(batch, topK, dim) // result = torch.einsum('bik,bjk->bij', a, b) /** * Generates the output token id for greedy search. * * @param logits the logits from the language model * @return the output token ids */ public static NDArray greedyStepGen(NDArray logits) { // logits: [batch, seq, probDim] assert logits.getShape().getShape().length == 3 : "unexpected input"; logits = logits.get(":, -1, :"); return logits.argMax(-1).expandDims(1); // [batch, vacDim] } /** * Generates the output token id and selecting indices used in beam search. * * @param lastProbs the probabilities of the past prefix sequences * @param logits the logits * @param numBatch number of batch * @param numBeam number of beam * @return the output token ids and selecting indices */ public static NDList beamStepGeneration( NDArray lastProbs, NDArray logits, long numBatch, long numBeam) { // [batch * beamSource, seq, probDim] -> [batch, beamSource, probDim] NDArray allProbs = logits.get(":, -1, :").softmax(1).reshape(numBatch, numBeam, -1); // Argmax over the probs in the prob dimension. // [batch, beamSource, probDim] -> [batch, beamSource, beamChild] NDList topK = allProbs.topK(Math.toIntExact(numBeam), -1, true, false); NDArray outputIs = topK.get(1); NDArray stepProbs = topK.get(0); // Chain the probability // [batch, beamSource] -> [batch, beamSource, 1] lastProbs = lastProbs.reshape(numBatch, numBeam, 1); // [batch, beamSource, beamChild] NDArray newProbs = stepProbs.muli(lastProbs); // Argmax over the (beamSource * beamChild) dimension topK = newProbs.reshape(numBatch, numBeam * numBeam) .topK(Math.toIntExact(numBeam), -1, true, false); // The select indices act on (beamSource, beamChild) dimension. Decides how the new // generated tokenIds correspond to the past tokenIds. // [batch, beamNew]. NDArray select = topK.get(1); // Act on [batch, beam, ...] dimension and the output will be [batch, beam, ...] NDIndex selectIndex = new NDIndex( "{}, {}, ...", logits.getManager() .arange(0, numBatch, 1, DataType.INT64) .expandDims(1) .repeat(1, numBeam), select); // [batch, beamNew] outputIs = outputIs.reshape(numBatch, numBeam * numBeam).get(selectIndex).expandDims(2); // [batch, beamNew] newProbs = newProbs.reshape(numBatch, numBeam * numBeam).get(selectIndex).normalize(1, 1); /* During the beam selection process, some source beams are selected several times while some source beams are not selected even once. The pastOutputs should be reselected to have the right correspondence to the newInputIds. */ // [batch, beamNew] assert select.getDataType() == DataType.INT64 : "Wrong output! Expect integer division"; assert select.getShape().getShape().length == 2 : "Wrong size. Expect [batch, beamNew]"; // For each batch, convert the index1 in beamSource*beamChild dimension to its index2 in // beamSource dimension: index2 = index1 / numBeam. long[] index = select.toLongArray(); for (int i = 0; i < index.length; i++) { index[i] = Math.floorDiv(index[i], numBeam); } NDArray sourceBeamSelected = logits.getManager().create(index, new Shape(numBatch, numBeam)); return new NDList(outputIs, newProbs, sourceBeamSelected); } // TODO: implement pytorch floor_divide. }
deepjavalibrary/djl
api/src/main/java/ai/djl/modality/nlp/generate/StepGeneration.java
2,182
// result = torch.einsum('bik,bjk->bij', a, b)
line_comment
nl
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; /** * {@code StepGeneration} is a utility class containing the step generation utility functions used * in autoregressive search. */ public final class StepGeneration { private StepGeneration() {} /** * Generate the output token id and selecting indices used in contrastive search. * * @param topKIds the topk candidate token ids * @param logits the logits from the language model * @param contextHiddenStates the embedding of the past generated token ids * @param topkHiddenStates the embedding of the topk candidate token ids * @param offSets the offsets * @param alpha the repetition penalty * @return the output token ids and selecting indices */ public static NDList constrastiveStepGeneration( NDArray topKIds, NDArray logits, NDArray contextHiddenStates, NDArray topkHiddenStates, NDArray offSets, float alpha) { /* topKIds: [batch, topK] attentionMask: [batch, past_seq] logits: [batch, vocabSize] contextHiddenStates: [batch, past_seq, dim] topkHiddenStates: [batch*topK, seq=1, dim] attentionMaskSlice: [batch, 2]: (startPosition, endPosition) */ long batch = topKIds.getShape().get(0); long topK = topKIds.getShape().get(1); long hiddenDim = topkHiddenStates.getShape().getLastDimension(); // [batch*topK, seq=1, dim] -> [batch, topK, dim] topkHiddenStates = topkHiddenStates.reshape(batch, topK, hiddenDim); // [batch, topK, dim] * [batch, past_seq, dim] -> [batch, topK, past_seq] topkHiddenStates = topkHiddenStates.normalize(2, 2); contextHiddenStates = contextHiddenStates.normalize(2, 2); NDArray cosSimilarity = topkHiddenStates.batchMatMul(contextHiddenStates.transpose(0, 2, 1)); // Deactivate entries (batch_idx, :, zero_attention_idx_slice) in max{cosSim} step long[] offSetsArray = offSets.toLongArray(); for (int i = 0; i < offSetsArray.length; i++) { cosSimilarity.set(new NDIndex("{}, :, {}:{}", i, 0, offSetsArray[i]), -1); } // [batch, topK, past_seq] -> [batch, topK] NDArray topkScorePart1 = cosSimilarity.max(new int[] {2}); assert topkScorePart1.getShape().getShape().length == 2 : "Wrong output size"; // [batch, logitDim].gather([batch, topK) -> [batch, topK] NDArray topkScorePart2 = logits.softmax(1).gather(topKIds, 1); NDArray topkScore = topkScorePart2.muli(1 - alpha).subi(topkScorePart1.muli(alpha)); // [batch, topK] => [batch, 1] NDArray select = topkScore.argMax(1); NDIndex selectIndex = new NDIndex( "{}, {}, ...", logits.getManager().arange(0, topKIds.getShape().get(0), 1, DataType.INT64), select); NDArray outputIds = topKIds.get(selectIndex).reshape(-1, 1); return new NDList(outputIds, select); } // TODO: add support of Einstein summation: // a = torch.randn(batch, past_seq, dim) // b = torch.randn(batch, topK, dim) // result =<SUF> /** * Generates the output token id for greedy search. * * @param logits the logits from the language model * @return the output token ids */ public static NDArray greedyStepGen(NDArray logits) { // logits: [batch, seq, probDim] assert logits.getShape().getShape().length == 3 : "unexpected input"; logits = logits.get(":, -1, :"); return logits.argMax(-1).expandDims(1); // [batch, vacDim] } /** * Generates the output token id and selecting indices used in beam search. * * @param lastProbs the probabilities of the past prefix sequences * @param logits the logits * @param numBatch number of batch * @param numBeam number of beam * @return the output token ids and selecting indices */ public static NDList beamStepGeneration( NDArray lastProbs, NDArray logits, long numBatch, long numBeam) { // [batch * beamSource, seq, probDim] -> [batch, beamSource, probDim] NDArray allProbs = logits.get(":, -1, :").softmax(1).reshape(numBatch, numBeam, -1); // Argmax over the probs in the prob dimension. // [batch, beamSource, probDim] -> [batch, beamSource, beamChild] NDList topK = allProbs.topK(Math.toIntExact(numBeam), -1, true, false); NDArray outputIs = topK.get(1); NDArray stepProbs = topK.get(0); // Chain the probability // [batch, beamSource] -> [batch, beamSource, 1] lastProbs = lastProbs.reshape(numBatch, numBeam, 1); // [batch, beamSource, beamChild] NDArray newProbs = stepProbs.muli(lastProbs); // Argmax over the (beamSource * beamChild) dimension topK = newProbs.reshape(numBatch, numBeam * numBeam) .topK(Math.toIntExact(numBeam), -1, true, false); // The select indices act on (beamSource, beamChild) dimension. Decides how the new // generated tokenIds correspond to the past tokenIds. // [batch, beamNew]. NDArray select = topK.get(1); // Act on [batch, beam, ...] dimension and the output will be [batch, beam, ...] NDIndex selectIndex = new NDIndex( "{}, {}, ...", logits.getManager() .arange(0, numBatch, 1, DataType.INT64) .expandDims(1) .repeat(1, numBeam), select); // [batch, beamNew] outputIs = outputIs.reshape(numBatch, numBeam * numBeam).get(selectIndex).expandDims(2); // [batch, beamNew] newProbs = newProbs.reshape(numBatch, numBeam * numBeam).get(selectIndex).normalize(1, 1); /* During the beam selection process, some source beams are selected several times while some source beams are not selected even once. The pastOutputs should be reselected to have the right correspondence to the newInputIds. */ // [batch, beamNew] assert select.getDataType() == DataType.INT64 : "Wrong output! Expect integer division"; assert select.getShape().getShape().length == 2 : "Wrong size. Expect [batch, beamNew]"; // For each batch, convert the index1 in beamSource*beamChild dimension to its index2 in // beamSource dimension: index2 = index1 / numBeam. long[] index = select.toLongArray(); for (int i = 0; i < index.length; i++) { index[i] = Math.floorDiv(index[i], numBeam); } NDArray sourceBeamSelected = logits.getManager().create(index, new Shape(numBatch, numBeam)); return new NDList(outputIs, newProbs, sourceBeamSelected); } // TODO: implement pytorch floor_divide. }
204415_45
/* * Copyright (c) 2016 Martin Davis. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html * and the Eclipse Distribution License is available at * * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.locationtech.jts.operation.buffer; import org.locationtech.jts.algorithm.Angle; import org.locationtech.jts.algorithm.Intersection; import org.locationtech.jts.algorithm.LineIntersector; import org.locationtech.jts.algorithm.Orientation; import org.locationtech.jts.algorithm.RobustLineIntersector; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.LineSegment; import org.locationtech.jts.geom.Position; import org.locationtech.jts.geom.PrecisionModel; /** * Generates segments which form an offset curve. * Supports all end cap and join options * provided for buffering. * This algorithm implements various heuristics to * produce smoother, simpler curves which are * still within a reasonable tolerance of the * true curve. * * @author Martin Davis * */ class OffsetSegmentGenerator { /** * Factor which controls how close offset segments can be to * skip adding a filler or mitre. */ private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices on inside turns can be to be snapped */ private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices can be to be snapped */ private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6; /** * Factor which determines how short closing segs can be for round buffers */ private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80; /** * the max error of approximation (distance) between a quad segment and the true fillet curve */ private double maxCurveSegmentError = 0.0; /** * The angle quantum with which to approximate a fillet curve * (based on the input # of quadrant segments) */ private double filletAngleQuantum; /** * The Closing Segment Length Factor controls how long * "closing segments" are. Closing segments are added * at the middle of inside corners to ensure a smoother * boundary for the buffer offset curve. * In some cases (particularly for round joins with default-or-better * quantization) the closing segments can be made quite short. * This substantially improves performance (due to fewer intersections being created). * * A closingSegFactor of 0 results in lines to the corner vertex * A closingSegFactor of 1 results in lines halfway to the corner vertex * A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex * (this option is reasonable for the very common default situation of round joins * and quadrantSegs >= 8) */ private int closingSegLengthFactor = 1; private OffsetSegmentString segList; private double distance = 0.0; private PrecisionModel precisionModel; private BufferParameters bufParams; private LineIntersector li; private Coordinate s0, s1, s2; private LineSegment seg0 = new LineSegment(); private LineSegment seg1 = new LineSegment(); private LineSegment offset0 = new LineSegment(); private LineSegment offset1 = new LineSegment(); private int side = 0; private boolean hasNarrowConcaveAngle = false; public OffsetSegmentGenerator(PrecisionModel precisionModel, BufferParameters bufParams, double distance) { this.precisionModel = precisionModel; this.bufParams = bufParams; // compute intersections in full precision, to provide accuracy // the points are rounded as they are inserted into the curve line li = new RobustLineIntersector(); filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments(); /** * Non-round joins cause issues with short closing segments, so don't use * them. In any case, non-round joins only really make sense for relatively * small buffer distances. */ if (bufParams.getQuadrantSegments() >= 8 && bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR; init(distance); } /** * Tests whether the input has a narrow concave angle * (relative to the offset distance). * In this case the generated offset curve will contain self-intersections * and heuristic closing segments. * This is expected behaviour in the case of Buffer curves. * For pure Offset Curves, * the output needs to be further treated * before it can be used. * * @return true if the input has a narrow concave angle */ public boolean hasNarrowConcaveAngle() { return hasNarrowConcaveAngle; } private void init(double distance) { this.distance = distance; maxCurveSegmentError = distance * (1 - Math.cos(filletAngleQuantum / 2.0)); segList = new OffsetSegmentString(); segList.setPrecisionModel(precisionModel); /** * Choose the min vertex separation as a small fraction of the offset distance. */ segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR); } public void initSideSegments(Coordinate s1, Coordinate s2, int side) { this.s1 = s1; this.s2 = s2; this.side = side; seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); } public Coordinate[] getCoordinates() { Coordinate[] pts = segList.getCoordinates(); return pts; } public void closeRing() { segList.closeRing(); } public void addSegments(Coordinate[] pt, boolean isForward) { segList.addPts(pt, isForward); } public void addFirstSegment() { segList.addPt(offset1.p0); } /** * Add last offset point */ public void addLastSegment() { segList.addPt(offset1.p1); } //private static double MAX_CLOSING_SEG_LEN = 3.0; public void addNextSegment(Coordinate p, boolean addStartPoint) { // s0-s1-s2 are the coordinates of the previous segment and the current one s0 = s1; s1 = s2; s2 = p; seg0.setCoordinates(s0, s1); computeOffsetSegment(seg0, side, distance, offset0); seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); // do nothing if points are equal if (s1.equals(s2)) return; int orientation = Orientation.index(s0, s1, s2); boolean outsideTurn = (orientation == Orientation.CLOCKWISE && side == Position.LEFT) || (orientation == Orientation.COUNTERCLOCKWISE && side == Position.RIGHT); if (orientation == 0) { // lines are collinear addCollinear(addStartPoint); } else if (outsideTurn) { addOutsideTurn(orientation, addStartPoint); } else { // inside turn addInsideTurn(orientation, addStartPoint); } } private void addCollinear(boolean addStartPoint) { /** * This test could probably be done more efficiently, * but the situation of exact collinearity should be fairly rare. */ li.computeIntersection(s0, s1, s1, s2); int numInt = li.getIntersectionNum(); /** * if numInt is < 2, the lines are parallel and in the same direction. In * this case the point can be ignored, since the offset lines will also be * parallel. */ if (numInt >= 2) { /** * segments are collinear but reversing. * Add an "end-cap" fillet * all the way around to other direction This case should ONLY happen * for LineStrings, so the orientation is always CW. (Polygons can never * have two consecutive segments which are parallel but reversed, * because that would be a self intersection. * */ if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL || bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { if (addStartPoint) segList.addPt(offset0.p1); segList.addPt(offset1.p0); } else { addCornerFillet(s1, offset0.p1, offset1.p0, Orientation.CLOCKWISE, distance); } } } /** * Adds the offset points for an outside (convex) turn * * @param orientation * @param addStartPoint */ private void addOutsideTurn(int orientation, boolean addStartPoint) { /** * Heuristic: If offset endpoints are very close together, * just use one of them as the corner vertex. * This avoids problems with computing mitre corners in the case * where the two segments are almost parallel * (which is hard to compute a robust intersection for). */ if (offset0.p1.distance(offset1.p0) < distance * OFFSET_SEGMENT_SEPARATION_FACTOR) { segList.addPt(offset0.p1); return; } if (bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { addMitreJoin(s1, offset0, offset1, distance); } else if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL){ addBevelJoin(offset0, offset1); } else { // add a circular fillet connecting the endpoints of the offset segments if (addStartPoint) segList.addPt(offset0.p1); // TESTING - comment out to produce beveled joins addCornerFillet(s1, offset0.p1, offset1.p0, orientation, distance); segList.addPt(offset1.p0); } } /** * Adds the offset points for an inside (concave) turn. * * @param orientation * @param addStartPoint */ private void addInsideTurn(int orientation, boolean addStartPoint) { /** * add intersection point of offset segments (if any) */ li.computeIntersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (li.hasIntersection()) { segList.addPt(li.getIntersection(0)); } else { /** * If no intersection is detected, * it means the angle is so small and/or the offset so * large that the offsets segments don't intersect. * In this case we must * add a "closing segment" to make sure the buffer curve is continuous, * fairly smooth (e.g. no sharp reversals in direction) * and tracks the buffer correctly around the corner. The curve connects * the endpoints of the segment offsets to points * which lie toward the centre point of the corner. * The joining curve will not appear in the final buffer outline, since it * is completely internal to the buffer polygon. * * In complex buffer cases the closing segment may cut across many other * segments in the generated offset curve. In order to improve the * performance of the noding, the closing segment should be kept as short as possible. * (But not too short, since that would defeat its purpose). * This is the purpose of the closingSegFactor heuristic value. */ /** * The intersection test above is vulnerable to robustness errors; i.e. it * may be that the offsets should intersect very close to their endpoints, * but aren't reported as such due to rounding. To handle this situation * appropriately, we use the following test: If the offset points are very * close, don't add closing segments but simply use one of the offset * points */ hasNarrowConcaveAngle = true; //System.out.println("NARROW ANGLE - distance = " + distance); if (offset0.p1.distance(offset1.p0) < distance * INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) { segList.addPt(offset0.p1); } else { // add endpoint of this segment offset segList.addPt(offset0.p1); /** * Add "closing segment" of required length. */ if (closingSegLengthFactor > 0) { Coordinate mid0 = new Coordinate((closingSegLengthFactor * offset0.p1.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset0.p1.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid0); Coordinate mid1 = new Coordinate((closingSegLengthFactor*offset1.p0.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset1.p0.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid1); } else { /** * This branch is not expected to be used except for testing purposes. * It is equivalent to the JTS 1.9 logic for closing segments * (which results in very poor performance for large buffer distances) */ segList.addPt(s1); } //*/ // add start point of next segment offset segList.addPt(offset1.p0); } } } /** * Compute an offset segment for an input segment on a given side and at a given distance. * The offset points are computed in full double precision, for accuracy. * * @param seg the segment to offset * @param side the side of the segment ({@link Position}) the offset lies on * @param distance the offset distance * @param offset the points computed for the offset segment */ private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) { int sideSign = side == Position.LEFT ? 1 : -1; double dx = seg.p1.x - seg.p0.x; double dy = seg.p1.y - seg.p0.y; double len = Math.sqrt(dx * dx + dy * dy); // u is the vector that is the length of the offset, in the direction of the segment double ux = sideSign * distance * dx / len; double uy = sideSign * distance * dy / len; offset.p0.x = seg.p0.x - uy; offset.p0.y = seg.p0.y + ux; offset.p1.x = seg.p1.x - uy; offset.p1.y = seg.p1.y + ux; } /** * Add an end cap around point p1, terminating a line segment coming from p0 */ public void addLineEndCap(Coordinate p0, Coordinate p1) { LineSegment seg = new LineSegment(p0, p1); LineSegment offsetL = new LineSegment(); computeOffsetSegment(seg, Position.LEFT, distance, offsetL); LineSegment offsetR = new LineSegment(); computeOffsetSegment(seg, Position.RIGHT, distance, offsetR); double dx = p1.x - p0.x; double dy = p1.y - p0.y; double angle = Math.atan2(dy, dx); switch (bufParams.getEndCapStyle()) { case BufferParameters.CAP_ROUND: // add offset seg points with a fillet between them segList.addPt(offsetL.p1); addDirectedFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, Orientation.CLOCKWISE, distance); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_FLAT: // only offset segment points are added segList.addPt(offsetL.p1); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_SQUARE: // add a square defined by extensions of the offset segment endpoints Coordinate squareCapSideOffset = new Coordinate(); squareCapSideOffset.x = Math.abs(distance) * Math.cos(angle); squareCapSideOffset.y = Math.abs(distance) * Math.sin(angle); Coordinate squareCapLOffset = new Coordinate( offsetL.p1.x + squareCapSideOffset.x, offsetL.p1.y + squareCapSideOffset.y); Coordinate squareCapROffset = new Coordinate( offsetR.p1.x + squareCapSideOffset.x, offsetR.p1.y + squareCapSideOffset.y); segList.addPt(squareCapLOffset); segList.addPt(squareCapROffset); break; } } /** * Adds a mitre join connecting the two reflex offset segments. * The mitre will be beveled if it exceeds the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance */ private void addMitreJoin(Coordinate p, LineSegment offset0, LineSegment offset1, double distance) { /** * This computation is unstable if the offset segments are nearly collinear. * However, this situation should have been eliminated earlier by the check * for whether the offset segment endpoints are almost coincident */ Coordinate intPt = Intersection.intersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (intPt != null) { double mitreRatio = distance <= 0.0 ? 1.0 : intPt.distance(p) / Math.abs(distance); if (mitreRatio <= bufParams.getMitreLimit()) { segList.addPt(intPt); return; } } // at this point either intersection failed or mitre limit was exceeded addLimitedMitreJoin(offset0, offset1, distance, bufParams.getMitreLimit()); // addBevelJoin(offset0, offset1); } /** * Adds a limited mitre join connecting the two reflex offset segments. * A limited mitre is a mitre which is beveled at the distance * determined by the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance * @param mitreLimit the mitre limit ratio */ private void addLimitedMitreJoin( LineSegment offset0, LineSegment offset1, double distance, double mitreLimit) { Coordinate basePt = seg0.p1; double ang0 = Angle.angle(basePt, seg0.p0); // oriented angle between segments double angDiff = Angle.angleBetweenOriented(seg0.p0, basePt, seg1.p1); // half of the interior angle double angDiffHalf = angDiff / 2; // angle for bisector of the interior angle between the segments double midAng = Angle.normalize(ang0 + angDiffHalf); // rotating this by PI gives the bisector of the reflex angle double mitreMidAng = Angle.normalize(midAng + Math.PI); // the miterLimit determines the distance to the mitre bevel double mitreDist = mitreLimit * distance; // the bevel delta is the difference between the buffer distance // and half of the length of the bevel segment double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf)); double bevelHalfLen = distance - bevelDelta; // compute the midpoint of the bevel segment double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng); double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng); Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY); // compute the mitre midline segment from the corner point to the bevel segment midpoint LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt); // finally the bevel segment endpoints are computed as offsets from // the mitre midline Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen); Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen); if (side == Position.LEFT) { segList.addPt(bevelEndLeft); segList.addPt(bevelEndRight); } else { segList.addPt(bevelEndRight); segList.addPt(bevelEndLeft); } } /** * Adds a bevel join connecting the two offset segments * around a reflex corner. * * @param offset0 the first offset segment * @param offset1 the second offset segment */ private void addBevelJoin( LineSegment offset0, LineSegment offset1) { segList.addPt(offset0.p1); segList.addPt(offset1.p0); } /** * Add points for a circular fillet around a reflex corner. * Adds the start and end points * * @param p base point of curve * @param p0 start point of fillet curve * @param p1 endpoint of fillet curve * @param direction the orientation of the fillet * @param radius the radius of the fillet */ private void addCornerFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) { double dx0 = p0.x - p.x; double dy0 = p0.y - p.y; double startAngle = Math.atan2(dy0, dx0); double dx1 = p1.x - p.x; double dy1 = p1.y - p.y; double endAngle = Math.atan2(dy1, dx1); if (direction == Orientation.CLOCKWISE) { if (startAngle <= endAngle) startAngle += 2.0 * Math.PI; } else { // direction == COUNTERCLOCKWISE if (startAngle >= endAngle) startAngle -= 2.0 * Math.PI; } segList.addPt(p0); addDirectedFillet(p, startAngle, endAngle, direction, radius); segList.addPt(p1); } /** * Adds points for a circular fillet arc * between two specified angles. * The start and end point for the fillet are not added - * the caller must add them if required. * * @param direction is -1 for a CW angle, 1 for a CCW angle * @param radius the radius of the fillet */ private void addDirectedFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) { int directionFactor = direction == Orientation.CLOCKWISE ? -1 : 1; double totalAngle = Math.abs(startAngle - endAngle); int nSegs = (int) (totalAngle / filletAngleQuantum + 0.5); if (nSegs < 1) return; // no segments because angle is less than increment - nothing to do! // choose angle increment so that each segment has equal length double angleInc = totalAngle / nSegs; Coordinate pt = new Coordinate(); for (int i = 0; i < nSegs; i++) { double angle = startAngle + directionFactor * i * angleInc; pt.x = p.x + radius * Math.cos(angle); pt.y = p.y + radius * Math.sin(angle); segList.addPt(pt); } } /** * Creates a CW circle around a point */ public void createCircle(Coordinate p) { // add start point Coordinate pt = new Coordinate(p.x + distance, p.y); segList.addPt(pt); addDirectedFillet(p, 0.0, 2.0 * Math.PI, -1, distance); segList.closeRing(); } /** * Creates a CW square around a point */ public void createSquare(Coordinate p) { segList.addPt(new Coordinate(p.x + distance, p.y + distance)); segList.addPt(new Coordinate(p.x + distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y + distance)); segList.closeRing(); } }
deepin-community/jts
modules/core/src/main/java/org/locationtech/jts/operation/buffer/OffsetSegmentGenerator.java
6,434
// oriented angle between segments
line_comment
nl
/* * Copyright (c) 2016 Martin Davis. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html * and the Eclipse Distribution License is available at * * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.locationtech.jts.operation.buffer; import org.locationtech.jts.algorithm.Angle; import org.locationtech.jts.algorithm.Intersection; import org.locationtech.jts.algorithm.LineIntersector; import org.locationtech.jts.algorithm.Orientation; import org.locationtech.jts.algorithm.RobustLineIntersector; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.LineSegment; import org.locationtech.jts.geom.Position; import org.locationtech.jts.geom.PrecisionModel; /** * Generates segments which form an offset curve. * Supports all end cap and join options * provided for buffering. * This algorithm implements various heuristics to * produce smoother, simpler curves which are * still within a reasonable tolerance of the * true curve. * * @author Martin Davis * */ class OffsetSegmentGenerator { /** * Factor which controls how close offset segments can be to * skip adding a filler or mitre. */ private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices on inside turns can be to be snapped */ private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices can be to be snapped */ private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6; /** * Factor which determines how short closing segs can be for round buffers */ private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80; /** * the max error of approximation (distance) between a quad segment and the true fillet curve */ private double maxCurveSegmentError = 0.0; /** * The angle quantum with which to approximate a fillet curve * (based on the input # of quadrant segments) */ private double filletAngleQuantum; /** * The Closing Segment Length Factor controls how long * "closing segments" are. Closing segments are added * at the middle of inside corners to ensure a smoother * boundary for the buffer offset curve. * In some cases (particularly for round joins with default-or-better * quantization) the closing segments can be made quite short. * This substantially improves performance (due to fewer intersections being created). * * A closingSegFactor of 0 results in lines to the corner vertex * A closingSegFactor of 1 results in lines halfway to the corner vertex * A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex * (this option is reasonable for the very common default situation of round joins * and quadrantSegs >= 8) */ private int closingSegLengthFactor = 1; private OffsetSegmentString segList; private double distance = 0.0; private PrecisionModel precisionModel; private BufferParameters bufParams; private LineIntersector li; private Coordinate s0, s1, s2; private LineSegment seg0 = new LineSegment(); private LineSegment seg1 = new LineSegment(); private LineSegment offset0 = new LineSegment(); private LineSegment offset1 = new LineSegment(); private int side = 0; private boolean hasNarrowConcaveAngle = false; public OffsetSegmentGenerator(PrecisionModel precisionModel, BufferParameters bufParams, double distance) { this.precisionModel = precisionModel; this.bufParams = bufParams; // compute intersections in full precision, to provide accuracy // the points are rounded as they are inserted into the curve line li = new RobustLineIntersector(); filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments(); /** * Non-round joins cause issues with short closing segments, so don't use * them. In any case, non-round joins only really make sense for relatively * small buffer distances. */ if (bufParams.getQuadrantSegments() >= 8 && bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR; init(distance); } /** * Tests whether the input has a narrow concave angle * (relative to the offset distance). * In this case the generated offset curve will contain self-intersections * and heuristic closing segments. * This is expected behaviour in the case of Buffer curves. * For pure Offset Curves, * the output needs to be further treated * before it can be used. * * @return true if the input has a narrow concave angle */ public boolean hasNarrowConcaveAngle() { return hasNarrowConcaveAngle; } private void init(double distance) { this.distance = distance; maxCurveSegmentError = distance * (1 - Math.cos(filletAngleQuantum / 2.0)); segList = new OffsetSegmentString(); segList.setPrecisionModel(precisionModel); /** * Choose the min vertex separation as a small fraction of the offset distance. */ segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR); } public void initSideSegments(Coordinate s1, Coordinate s2, int side) { this.s1 = s1; this.s2 = s2; this.side = side; seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); } public Coordinate[] getCoordinates() { Coordinate[] pts = segList.getCoordinates(); return pts; } public void closeRing() { segList.closeRing(); } public void addSegments(Coordinate[] pt, boolean isForward) { segList.addPts(pt, isForward); } public void addFirstSegment() { segList.addPt(offset1.p0); } /** * Add last offset point */ public void addLastSegment() { segList.addPt(offset1.p1); } //private static double MAX_CLOSING_SEG_LEN = 3.0; public void addNextSegment(Coordinate p, boolean addStartPoint) { // s0-s1-s2 are the coordinates of the previous segment and the current one s0 = s1; s1 = s2; s2 = p; seg0.setCoordinates(s0, s1); computeOffsetSegment(seg0, side, distance, offset0); seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); // do nothing if points are equal if (s1.equals(s2)) return; int orientation = Orientation.index(s0, s1, s2); boolean outsideTurn = (orientation == Orientation.CLOCKWISE && side == Position.LEFT) || (orientation == Orientation.COUNTERCLOCKWISE && side == Position.RIGHT); if (orientation == 0) { // lines are collinear addCollinear(addStartPoint); } else if (outsideTurn) { addOutsideTurn(orientation, addStartPoint); } else { // inside turn addInsideTurn(orientation, addStartPoint); } } private void addCollinear(boolean addStartPoint) { /** * This test could probably be done more efficiently, * but the situation of exact collinearity should be fairly rare. */ li.computeIntersection(s0, s1, s1, s2); int numInt = li.getIntersectionNum(); /** * if numInt is < 2, the lines are parallel and in the same direction. In * this case the point can be ignored, since the offset lines will also be * parallel. */ if (numInt >= 2) { /** * segments are collinear but reversing. * Add an "end-cap" fillet * all the way around to other direction This case should ONLY happen * for LineStrings, so the orientation is always CW. (Polygons can never * have two consecutive segments which are parallel but reversed, * because that would be a self intersection. * */ if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL || bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { if (addStartPoint) segList.addPt(offset0.p1); segList.addPt(offset1.p0); } else { addCornerFillet(s1, offset0.p1, offset1.p0, Orientation.CLOCKWISE, distance); } } } /** * Adds the offset points for an outside (convex) turn * * @param orientation * @param addStartPoint */ private void addOutsideTurn(int orientation, boolean addStartPoint) { /** * Heuristic: If offset endpoints are very close together, * just use one of them as the corner vertex. * This avoids problems with computing mitre corners in the case * where the two segments are almost parallel * (which is hard to compute a robust intersection for). */ if (offset0.p1.distance(offset1.p0) < distance * OFFSET_SEGMENT_SEPARATION_FACTOR) { segList.addPt(offset0.p1); return; } if (bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { addMitreJoin(s1, offset0, offset1, distance); } else if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL){ addBevelJoin(offset0, offset1); } else { // add a circular fillet connecting the endpoints of the offset segments if (addStartPoint) segList.addPt(offset0.p1); // TESTING - comment out to produce beveled joins addCornerFillet(s1, offset0.p1, offset1.p0, orientation, distance); segList.addPt(offset1.p0); } } /** * Adds the offset points for an inside (concave) turn. * * @param orientation * @param addStartPoint */ private void addInsideTurn(int orientation, boolean addStartPoint) { /** * add intersection point of offset segments (if any) */ li.computeIntersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (li.hasIntersection()) { segList.addPt(li.getIntersection(0)); } else { /** * If no intersection is detected, * it means the angle is so small and/or the offset so * large that the offsets segments don't intersect. * In this case we must * add a "closing segment" to make sure the buffer curve is continuous, * fairly smooth (e.g. no sharp reversals in direction) * and tracks the buffer correctly around the corner. The curve connects * the endpoints of the segment offsets to points * which lie toward the centre point of the corner. * The joining curve will not appear in the final buffer outline, since it * is completely internal to the buffer polygon. * * In complex buffer cases the closing segment may cut across many other * segments in the generated offset curve. In order to improve the * performance of the noding, the closing segment should be kept as short as possible. * (But not too short, since that would defeat its purpose). * This is the purpose of the closingSegFactor heuristic value. */ /** * The intersection test above is vulnerable to robustness errors; i.e. it * may be that the offsets should intersect very close to their endpoints, * but aren't reported as such due to rounding. To handle this situation * appropriately, we use the following test: If the offset points are very * close, don't add closing segments but simply use one of the offset * points */ hasNarrowConcaveAngle = true; //System.out.println("NARROW ANGLE - distance = " + distance); if (offset0.p1.distance(offset1.p0) < distance * INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) { segList.addPt(offset0.p1); } else { // add endpoint of this segment offset segList.addPt(offset0.p1); /** * Add "closing segment" of required length. */ if (closingSegLengthFactor > 0) { Coordinate mid0 = new Coordinate((closingSegLengthFactor * offset0.p1.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset0.p1.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid0); Coordinate mid1 = new Coordinate((closingSegLengthFactor*offset1.p0.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset1.p0.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid1); } else { /** * This branch is not expected to be used except for testing purposes. * It is equivalent to the JTS 1.9 logic for closing segments * (which results in very poor performance for large buffer distances) */ segList.addPt(s1); } //*/ // add start point of next segment offset segList.addPt(offset1.p0); } } } /** * Compute an offset segment for an input segment on a given side and at a given distance. * The offset points are computed in full double precision, for accuracy. * * @param seg the segment to offset * @param side the side of the segment ({@link Position}) the offset lies on * @param distance the offset distance * @param offset the points computed for the offset segment */ private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) { int sideSign = side == Position.LEFT ? 1 : -1; double dx = seg.p1.x - seg.p0.x; double dy = seg.p1.y - seg.p0.y; double len = Math.sqrt(dx * dx + dy * dy); // u is the vector that is the length of the offset, in the direction of the segment double ux = sideSign * distance * dx / len; double uy = sideSign * distance * dy / len; offset.p0.x = seg.p0.x - uy; offset.p0.y = seg.p0.y + ux; offset.p1.x = seg.p1.x - uy; offset.p1.y = seg.p1.y + ux; } /** * Add an end cap around point p1, terminating a line segment coming from p0 */ public void addLineEndCap(Coordinate p0, Coordinate p1) { LineSegment seg = new LineSegment(p0, p1); LineSegment offsetL = new LineSegment(); computeOffsetSegment(seg, Position.LEFT, distance, offsetL); LineSegment offsetR = new LineSegment(); computeOffsetSegment(seg, Position.RIGHT, distance, offsetR); double dx = p1.x - p0.x; double dy = p1.y - p0.y; double angle = Math.atan2(dy, dx); switch (bufParams.getEndCapStyle()) { case BufferParameters.CAP_ROUND: // add offset seg points with a fillet between them segList.addPt(offsetL.p1); addDirectedFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, Orientation.CLOCKWISE, distance); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_FLAT: // only offset segment points are added segList.addPt(offsetL.p1); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_SQUARE: // add a square defined by extensions of the offset segment endpoints Coordinate squareCapSideOffset = new Coordinate(); squareCapSideOffset.x = Math.abs(distance) * Math.cos(angle); squareCapSideOffset.y = Math.abs(distance) * Math.sin(angle); Coordinate squareCapLOffset = new Coordinate( offsetL.p1.x + squareCapSideOffset.x, offsetL.p1.y + squareCapSideOffset.y); Coordinate squareCapROffset = new Coordinate( offsetR.p1.x + squareCapSideOffset.x, offsetR.p1.y + squareCapSideOffset.y); segList.addPt(squareCapLOffset); segList.addPt(squareCapROffset); break; } } /** * Adds a mitre join connecting the two reflex offset segments. * The mitre will be beveled if it exceeds the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance */ private void addMitreJoin(Coordinate p, LineSegment offset0, LineSegment offset1, double distance) { /** * This computation is unstable if the offset segments are nearly collinear. * However, this situation should have been eliminated earlier by the check * for whether the offset segment endpoints are almost coincident */ Coordinate intPt = Intersection.intersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (intPt != null) { double mitreRatio = distance <= 0.0 ? 1.0 : intPt.distance(p) / Math.abs(distance); if (mitreRatio <= bufParams.getMitreLimit()) { segList.addPt(intPt); return; } } // at this point either intersection failed or mitre limit was exceeded addLimitedMitreJoin(offset0, offset1, distance, bufParams.getMitreLimit()); // addBevelJoin(offset0, offset1); } /** * Adds a limited mitre join connecting the two reflex offset segments. * A limited mitre is a mitre which is beveled at the distance * determined by the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance * @param mitreLimit the mitre limit ratio */ private void addLimitedMitreJoin( LineSegment offset0, LineSegment offset1, double distance, double mitreLimit) { Coordinate basePt = seg0.p1; double ang0 = Angle.angle(basePt, seg0.p0); // oriented angle<SUF> double angDiff = Angle.angleBetweenOriented(seg0.p0, basePt, seg1.p1); // half of the interior angle double angDiffHalf = angDiff / 2; // angle for bisector of the interior angle between the segments double midAng = Angle.normalize(ang0 + angDiffHalf); // rotating this by PI gives the bisector of the reflex angle double mitreMidAng = Angle.normalize(midAng + Math.PI); // the miterLimit determines the distance to the mitre bevel double mitreDist = mitreLimit * distance; // the bevel delta is the difference between the buffer distance // and half of the length of the bevel segment double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf)); double bevelHalfLen = distance - bevelDelta; // compute the midpoint of the bevel segment double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng); double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng); Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY); // compute the mitre midline segment from the corner point to the bevel segment midpoint LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt); // finally the bevel segment endpoints are computed as offsets from // the mitre midline Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen); Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen); if (side == Position.LEFT) { segList.addPt(bevelEndLeft); segList.addPt(bevelEndRight); } else { segList.addPt(bevelEndRight); segList.addPt(bevelEndLeft); } } /** * Adds a bevel join connecting the two offset segments * around a reflex corner. * * @param offset0 the first offset segment * @param offset1 the second offset segment */ private void addBevelJoin( LineSegment offset0, LineSegment offset1) { segList.addPt(offset0.p1); segList.addPt(offset1.p0); } /** * Add points for a circular fillet around a reflex corner. * Adds the start and end points * * @param p base point of curve * @param p0 start point of fillet curve * @param p1 endpoint of fillet curve * @param direction the orientation of the fillet * @param radius the radius of the fillet */ private void addCornerFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) { double dx0 = p0.x - p.x; double dy0 = p0.y - p.y; double startAngle = Math.atan2(dy0, dx0); double dx1 = p1.x - p.x; double dy1 = p1.y - p.y; double endAngle = Math.atan2(dy1, dx1); if (direction == Orientation.CLOCKWISE) { if (startAngle <= endAngle) startAngle += 2.0 * Math.PI; } else { // direction == COUNTERCLOCKWISE if (startAngle >= endAngle) startAngle -= 2.0 * Math.PI; } segList.addPt(p0); addDirectedFillet(p, startAngle, endAngle, direction, radius); segList.addPt(p1); } /** * Adds points for a circular fillet arc * between two specified angles. * The start and end point for the fillet are not added - * the caller must add them if required. * * @param direction is -1 for a CW angle, 1 for a CCW angle * @param radius the radius of the fillet */ private void addDirectedFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) { int directionFactor = direction == Orientation.CLOCKWISE ? -1 : 1; double totalAngle = Math.abs(startAngle - endAngle); int nSegs = (int) (totalAngle / filletAngleQuantum + 0.5); if (nSegs < 1) return; // no segments because angle is less than increment - nothing to do! // choose angle increment so that each segment has equal length double angleInc = totalAngle / nSegs; Coordinate pt = new Coordinate(); for (int i = 0; i < nSegs; i++) { double angle = startAngle + directionFactor * i * angleInc; pt.x = p.x + radius * Math.cos(angle); pt.y = p.y + radius * Math.sin(angle); segList.addPt(pt); } } /** * Creates a CW circle around a point */ public void createCircle(Coordinate p) { // add start point Coordinate pt = new Coordinate(p.x + distance, p.y); segList.addPt(pt); addDirectedFillet(p, 0.0, 2.0 * Math.PI, -1, distance); segList.closeRing(); } /** * Creates a CW square around a point */ public void createSquare(Coordinate p) { segList.addPt(new Coordinate(p.x + distance, p.y + distance)); segList.addPt(new Coordinate(p.x + distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y + distance)); segList.closeRing(); } }
26580_1
/* * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.hosted.image; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.graalvm.compiler.core.common.NumUtil; import org.graalvm.nativeimage.c.function.CFunctionPointer; import org.graalvm.nativeimage.c.function.RelocatedPointer; import com.oracle.objectfile.ObjectFile; import com.oracle.svm.hosted.meta.HostedMethod; import com.oracle.svm.hosted.meta.MethodPointer; public final class RelocatableBuffer { public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) { return new RelocatableBuffer(name, size, byteOrder); } /* * Map methods. */ public RelocatableBuffer.Info getInfo(final int key) { return getMap().get(key); } // The only place is is used is to add the ObjectHeader bits to a DynamicHub, // which is otherwise just a reference to a class. // In the future, this could be used for any offset from a relocated object reference. public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public int mapSize() { return getMap().size(); } // TODO: Replace with a visitor pattern rather than exposing the entrySet. public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() { return getMap().entrySet(); } /** Raw map access. */ private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) { return getMap().put(key, value); } /** Raw map access. */ protected Map<Integer, RelocatableBuffer.Info> getMap() { return map; } /* * ByteBuffer methods. */ public byte getByte(final int index) { return getBuffer().get(index); } public RelocatableBuffer putByte(final byte value) { getBuffer().put(value); return this; } public RelocatableBuffer putByte(final int index, final byte value) { getBuffer().put(index, value); return this; } public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) { getBuffer().put(source, offset, length); return this; } public RelocatableBuffer putInt(final int index, final int value) { getBuffer().putInt(index, value); return this; } public int getPosition() { return getBuffer().position(); } public RelocatableBuffer setPosition(final int newPosition) { getBuffer().position(newPosition); return this; } // TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer. protected byte[] getBytes() { return getBuffer().array(); } // TODO: This should become a private method. protected ByteBuffer getBuffer() { return buffer; } /* * Info factory. */ private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { return new Info(kind, relocationSize, explicitAddend, targetObject); } /* * Debugging. */ public String getName() { return name; } protected static String targetObjectClassification(final Object targetObject) { final StringBuilder result = new StringBuilder(); if (targetObject == null) { result.append("null"); } else { if (targetObject instanceof CFunctionPointer) { result.append("pointer to function"); if (targetObject instanceof MethodPointer) { final MethodPointer mp = (MethodPointer) targetObject; final HostedMethod hm = mp.getMethod(); result.append(" name: "); result.append(hm.getName()); } } else { result.append("pointer to data"); } } return result.toString(); } /** Constructor. */ private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) { this.name = name; this.size = size; final int intSize = NumUtil.safeToInt(size); this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder); this.map = new TreeMap<>(); } // Immutable fields. /** For debugging. */ protected final String name; /** The size of the ByteBuffer. */ protected final long size; /** The ByteBuffer itself. */ protected final ByteBuffer buffer; /** The map itself. */ private final TreeMap<Integer, RelocatableBuffer.Info> map; // Constants. static final long serialVersionUID = 0; static final int WORD_SIZE = 8; // HACK: hard-code for now // Note: A non-static inner class. // Note: To keep the RelocatableBuffer from getting separated from this Info. public class Info { /* * Access methods. */ public int getRelocationSize() { return relocationSize; } public ObjectFile.RelocationKind getRelocationKind() { return relocationKind; } public boolean hasExplicitAddend() { return (explicitAddend != null); } // May return null. public Long getExplicitAddend() { return explicitAddend; } public Object getTargetObject() { return targetObject; } // Protected constructor called only from RelocatableBuffer.infoFactory method. protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { this.relocationKind = kind; this.relocationSize = relocationSize; this.explicitAddend = explicitAddend; this.targetObject = targetObject; } // Immutable state. private final int relocationSize; private final ObjectFile.RelocationKind relocationKind; private final Long explicitAddend; /** * The referenced object on the heap. If this is an instance of a {@link RelocatedPointer}, * than the relocation is not treated as a data relocation but has a special meaning, e.g. a * code (text section) or constants (rodata section) relocation. */ private final Object targetObject; } }
nezihyigitbasi/graal
substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/image/RelocatableBuffer.java
2,169
/* * Map methods. */
block_comment
nl
/* * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.hosted.image; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.graalvm.compiler.core.common.NumUtil; import org.graalvm.nativeimage.c.function.CFunctionPointer; import org.graalvm.nativeimage.c.function.RelocatedPointer; import com.oracle.objectfile.ObjectFile; import com.oracle.svm.hosted.meta.HostedMethod; import com.oracle.svm.hosted.meta.MethodPointer; public final class RelocatableBuffer { public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) { return new RelocatableBuffer(name, size, byteOrder); } /* * Map methods. <SUF>*/ public RelocatableBuffer.Info getInfo(final int key) { return getMap().get(key); } // The only place is is used is to add the ObjectHeader bits to a DynamicHub, // which is otherwise just a reference to a class. // In the future, this could be used for any offset from a relocated object reference. public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public int mapSize() { return getMap().size(); } // TODO: Replace with a visitor pattern rather than exposing the entrySet. public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() { return getMap().entrySet(); } /** Raw map access. */ private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) { return getMap().put(key, value); } /** Raw map access. */ protected Map<Integer, RelocatableBuffer.Info> getMap() { return map; } /* * ByteBuffer methods. */ public byte getByte(final int index) { return getBuffer().get(index); } public RelocatableBuffer putByte(final byte value) { getBuffer().put(value); return this; } public RelocatableBuffer putByte(final int index, final byte value) { getBuffer().put(index, value); return this; } public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) { getBuffer().put(source, offset, length); return this; } public RelocatableBuffer putInt(final int index, final int value) { getBuffer().putInt(index, value); return this; } public int getPosition() { return getBuffer().position(); } public RelocatableBuffer setPosition(final int newPosition) { getBuffer().position(newPosition); return this; } // TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer. protected byte[] getBytes() { return getBuffer().array(); } // TODO: This should become a private method. protected ByteBuffer getBuffer() { return buffer; } /* * Info factory. */ private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { return new Info(kind, relocationSize, explicitAddend, targetObject); } /* * Debugging. */ public String getName() { return name; } protected static String targetObjectClassification(final Object targetObject) { final StringBuilder result = new StringBuilder(); if (targetObject == null) { result.append("null"); } else { if (targetObject instanceof CFunctionPointer) { result.append("pointer to function"); if (targetObject instanceof MethodPointer) { final MethodPointer mp = (MethodPointer) targetObject; final HostedMethod hm = mp.getMethod(); result.append(" name: "); result.append(hm.getName()); } } else { result.append("pointer to data"); } } return result.toString(); } /** Constructor. */ private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) { this.name = name; this.size = size; final int intSize = NumUtil.safeToInt(size); this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder); this.map = new TreeMap<>(); } // Immutable fields. /** For debugging. */ protected final String name; /** The size of the ByteBuffer. */ protected final long size; /** The ByteBuffer itself. */ protected final ByteBuffer buffer; /** The map itself. */ private final TreeMap<Integer, RelocatableBuffer.Info> map; // Constants. static final long serialVersionUID = 0; static final int WORD_SIZE = 8; // HACK: hard-code for now // Note: A non-static inner class. // Note: To keep the RelocatableBuffer from getting separated from this Info. public class Info { /* * Access methods. */ public int getRelocationSize() { return relocationSize; } public ObjectFile.RelocationKind getRelocationKind() { return relocationKind; } public boolean hasExplicitAddend() { return (explicitAddend != null); } // May return null. public Long getExplicitAddend() { return explicitAddend; } public Object getTargetObject() { return targetObject; } // Protected constructor called only from RelocatableBuffer.infoFactory method. protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { this.relocationKind = kind; this.relocationSize = relocationSize; this.explicitAddend = explicitAddend; this.targetObject = targetObject; } // Immutable state. private final int relocationSize; private final ObjectFile.RelocationKind relocationKind; private final Long explicitAddend; /** * The referenced object on the heap. If this is an instance of a {@link RelocatedPointer}, * than the relocation is not treated as a data relocation but has a special meaning, e.g. a * code (text section) or constants (rodata section) relocation. */ private final Object targetObject; } }
64507_13
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ambari.server.controller.metrics.ganglia; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.codehaus.jackson.annotate.JsonIgnoreProperties; /** * Data structure for temporal data returned from Ganglia Web. */ @JsonIgnoreProperties(ignoreUnknown = true) public class GangliaMetric { // Note that the member names correspond to the names in the JSON returned from Ganglia Web. /** * The name. */ private String ds_name; /** * The ganglia cluster name. */ private String cluster_name; /** * The graph type. */ private String graph_type; /** * The host name. */ private String host_name; /** * The metric name. */ private String metric_name; /** * The temporal data points. */ private Number[][] datapoints; private static final Set<String> PERCENTAGE_METRIC; //BUG-3386 Cluster CPU Chart is off the charts // Here can be added other percentage metrics static { Set<String> temp = new HashSet<>(); temp.add("cpu_wio"); temp.add("cpu_idle"); temp.add("cpu_nice"); temp.add("cpu_aidle"); temp.add("cpu_system"); temp.add("cpu_user"); PERCENTAGE_METRIC = Collections.unmodifiableSet(temp); } // ----- GangliaMetric ----------------------------------------------------- public String getDs_name() { return ds_name; } public void setDs_name(String ds_name) { this.ds_name = ds_name; } public String getCluster_name() { return cluster_name; } public void setCluster_name(String cluster_name) { this.cluster_name = cluster_name; } public String getGraph_type() { return graph_type; } public void setGraph_type(String graph_type) { this.graph_type = graph_type; } public String getHost_name() { return host_name; } public void setHost_name(String host_name) { this.host_name = host_name; } public String getMetric_name() { return metric_name; } public void setMetric_name(String metric_name) { this.metric_name = metric_name; } public Number[][] getDatapoints() { return datapoints; } public void setDatapoints(Number[][] datapoints) { this.datapoints = datapoints; } public void setDatapointsFromList(List<GangliaMetric.TemporalMetric> listTemporalMetrics) { //this.datapoints = datapoints; Number[][] datapointsArray = new Number[listTemporalMetrics.size()][2]; int cnt = 0; if (PERCENTAGE_METRIC.contains(metric_name)) { int firstIndex = 0; int lastIndex = listTemporalMetrics.size() - 1; for (int i = firstIndex; i <= lastIndex; ++i) { GangliaMetric.TemporalMetric m = listTemporalMetrics.get(i); Number val = m.getValue(); if (100.0 >= val.doubleValue()) { datapointsArray[cnt][0] = val; datapointsArray[cnt][1] = m.getTime(); cnt++; } } } else { int firstIndex = 0; int lastIndex = listTemporalMetrics.size() - 1; for (int i = firstIndex; i <= lastIndex; ++i) { GangliaMetric.TemporalMetric m = listTemporalMetrics.get(i); datapointsArray[i][0] = m.getValue(); datapointsArray[i][1] = m.getTime(); cnt++; } } this.datapoints = new Number[cnt][2]; for (int i = 0; i < this.datapoints.length; i++) { this.datapoints[i][0] = datapointsArray[i][0]; this.datapoints[i][1] = datapointsArray[i][1]; } } // ----- Object overrides -------------------------------------------------- @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("\n"); stringBuilder.append("name="); stringBuilder.append(ds_name); stringBuilder.append("\n"); stringBuilder.append("cluster name="); stringBuilder.append(cluster_name); stringBuilder.append("\n"); stringBuilder.append("graph type="); stringBuilder.append(graph_type); stringBuilder.append("\n"); stringBuilder.append("host name="); stringBuilder.append(host_name); stringBuilder.append("\n"); stringBuilder.append("api name="); stringBuilder.append(metric_name); stringBuilder.append("\n"); stringBuilder.append("datapoints (value/timestamp):"); stringBuilder.append("\n"); boolean first = true; stringBuilder.append("["); for (Number[] m : datapoints) { if (!first) { stringBuilder.append(","); } stringBuilder.append("["); stringBuilder.append(m[0]); stringBuilder.append(","); stringBuilder.append(m[1].longValue()); stringBuilder.append("]"); first = false; } stringBuilder.append("]"); return stringBuilder.toString(); } public static class TemporalMetric { private Number m_value; private Number m_time; private boolean valid; public boolean isValid() { return valid; } public TemporalMetric(String value, Number time) { valid = true; try{ m_value = convertToNumber(value); } catch (NumberFormatException e) { valid = false; } m_time = time; } public Number getValue() { return m_value; } public Number getTime() { return m_time; } private Number convertToNumber(String s) throws NumberFormatException { Number res; if(s.contains(".")){ Double d = Double.parseDouble(s); if(d.isNaN() || d.isInfinite()){ throw new NumberFormatException(s); } else { res = d; } } else { res = Long.parseLong(s); } return res; } } }
apache/ambari
ambari-server/src/main/java/org/apache/ambari/server/controller/metrics/ganglia/GangliaMetric.java
1,827
// ----- Object overrides --------------------------------------------------
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ambari.server.controller.metrics.ganglia; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.codehaus.jackson.annotate.JsonIgnoreProperties; /** * Data structure for temporal data returned from Ganglia Web. */ @JsonIgnoreProperties(ignoreUnknown = true) public class GangliaMetric { // Note that the member names correspond to the names in the JSON returned from Ganglia Web. /** * The name. */ private String ds_name; /** * The ganglia cluster name. */ private String cluster_name; /** * The graph type. */ private String graph_type; /** * The host name. */ private String host_name; /** * The metric name. */ private String metric_name; /** * The temporal data points. */ private Number[][] datapoints; private static final Set<String> PERCENTAGE_METRIC; //BUG-3386 Cluster CPU Chart is off the charts // Here can be added other percentage metrics static { Set<String> temp = new HashSet<>(); temp.add("cpu_wio"); temp.add("cpu_idle"); temp.add("cpu_nice"); temp.add("cpu_aidle"); temp.add("cpu_system"); temp.add("cpu_user"); PERCENTAGE_METRIC = Collections.unmodifiableSet(temp); } // ----- GangliaMetric ----------------------------------------------------- public String getDs_name() { return ds_name; } public void setDs_name(String ds_name) { this.ds_name = ds_name; } public String getCluster_name() { return cluster_name; } public void setCluster_name(String cluster_name) { this.cluster_name = cluster_name; } public String getGraph_type() { return graph_type; } public void setGraph_type(String graph_type) { this.graph_type = graph_type; } public String getHost_name() { return host_name; } public void setHost_name(String host_name) { this.host_name = host_name; } public String getMetric_name() { return metric_name; } public void setMetric_name(String metric_name) { this.metric_name = metric_name; } public Number[][] getDatapoints() { return datapoints; } public void setDatapoints(Number[][] datapoints) { this.datapoints = datapoints; } public void setDatapointsFromList(List<GangliaMetric.TemporalMetric> listTemporalMetrics) { //this.datapoints = datapoints; Number[][] datapointsArray = new Number[listTemporalMetrics.size()][2]; int cnt = 0; if (PERCENTAGE_METRIC.contains(metric_name)) { int firstIndex = 0; int lastIndex = listTemporalMetrics.size() - 1; for (int i = firstIndex; i <= lastIndex; ++i) { GangliaMetric.TemporalMetric m = listTemporalMetrics.get(i); Number val = m.getValue(); if (100.0 >= val.doubleValue()) { datapointsArray[cnt][0] = val; datapointsArray[cnt][1] = m.getTime(); cnt++; } } } else { int firstIndex = 0; int lastIndex = listTemporalMetrics.size() - 1; for (int i = firstIndex; i <= lastIndex; ++i) { GangliaMetric.TemporalMetric m = listTemporalMetrics.get(i); datapointsArray[i][0] = m.getValue(); datapointsArray[i][1] = m.getTime(); cnt++; } } this.datapoints = new Number[cnt][2]; for (int i = 0; i < this.datapoints.length; i++) { this.datapoints[i][0] = datapointsArray[i][0]; this.datapoints[i][1] = datapointsArray[i][1]; } } // ----- Object<SUF> @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("\n"); stringBuilder.append("name="); stringBuilder.append(ds_name); stringBuilder.append("\n"); stringBuilder.append("cluster name="); stringBuilder.append(cluster_name); stringBuilder.append("\n"); stringBuilder.append("graph type="); stringBuilder.append(graph_type); stringBuilder.append("\n"); stringBuilder.append("host name="); stringBuilder.append(host_name); stringBuilder.append("\n"); stringBuilder.append("api name="); stringBuilder.append(metric_name); stringBuilder.append("\n"); stringBuilder.append("datapoints (value/timestamp):"); stringBuilder.append("\n"); boolean first = true; stringBuilder.append("["); for (Number[] m : datapoints) { if (!first) { stringBuilder.append(","); } stringBuilder.append("["); stringBuilder.append(m[0]); stringBuilder.append(","); stringBuilder.append(m[1].longValue()); stringBuilder.append("]"); first = false; } stringBuilder.append("]"); return stringBuilder.toString(); } public static class TemporalMetric { private Number m_value; private Number m_time; private boolean valid; public boolean isValid() { return valid; } public TemporalMetric(String value, Number time) { valid = true; try{ m_value = convertToNumber(value); } catch (NumberFormatException e) { valid = false; } m_time = time; } public Number getValue() { return m_value; } public Number getTime() { return m_time; } private Number convertToNumber(String s) throws NumberFormatException { Number res; if(s.contains(".")){ Double d = Double.parseDouble(s); if(d.isNaN() || d.isInfinite()){ throw new NumberFormatException(s); } else { res = d; } } else { res = Long.parseLong(s); } return res; } } }
137722_0
package io.dagger.client; import static io.smallrye.graphql.client.core.Document.document; import static io.smallrye.graphql.client.core.Field.field; import static io.smallrye.graphql.client.core.Operation.operation; import com.jayway.jsonpath.JsonPath; import io.smallrye.graphql.client.GraphQLError; import io.smallrye.graphql.client.Response; import io.smallrye.graphql.client.core.Document; import io.smallrye.graphql.client.core.Field; import io.smallrye.graphql.client.core.FieldOrFragment; import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.bind.Jsonb; import jakarta.json.bind.JsonbBuilder; import jakarta.json.bind.JsonbConfig; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.apache.commons.lang3.reflect.TypeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class QueryBuilder { static final Logger LOG = LoggerFactory.getLogger(QueryBuilder.class); private final DynamicGraphQLClient client; private final Deque<QueryPart> parts; private final List<QueryPart> leaves; QueryBuilder(DynamicGraphQLClient client) { this(client, new LinkedList<>()); } private QueryBuilder(DynamicGraphQLClient client, Deque<QueryPart> parts) { this(client, parts, new ArrayList<>()); } private QueryBuilder( DynamicGraphQLClient client, Deque<QueryPart> parts, List<String> finalFields) { this.client = client; this.parts = parts; this.leaves = finalFields.stream().map(QueryPart::new).toList(); } QueryBuilder chain(String operation) { return chain(operation, Arguments.noArgs()); } QueryBuilder chain(String operation, Arguments arguments) { if (leaves != null && !leaves.isEmpty()) { throw new IllegalStateException("A new field cannot be chained"); } Deque<QueryPart> list = new LinkedList<>(); list.addAll(this.parts); list.push(new QueryPart(operation, arguments)); return new QueryBuilder(client, list); } QueryBuilder chain(String operation, List<String> leaves) { if (!this.leaves.isEmpty()) { throw new IllegalStateException("A new field cannot be chained"); } Deque<QueryPart> list = new LinkedList<>(); list.addAll(this.parts); list.push(new QueryPart(operation)); return new QueryBuilder(client, list, leaves); } QueryBuilder chain(List<String> leaves) { if (!this.leaves.isEmpty()) { throw new IllegalStateException("A new field cannot be chained"); } Deque<QueryPart> list = new LinkedList<>(); list.addAll(this.parts); return new QueryBuilder(client, list, leaves); } private void handleErrors(Response response) throws DaggerQueryException { if (!response.hasError()) { return; } LOG.debug( String.format( "Query execution failed: %s", response.getErrors().stream() .map(GraphQLError::toString) .collect(Collectors.joining(", ")))); if (response.getErrors().isEmpty()) { throw new DaggerQueryException(); } // GraphQLError error = response.getErrors().get(0); // error.getExtensions().get("_type"); throw new DaggerQueryException(response.getErrors().toArray(new GraphQLError[0])); } Document buildDocument() throws ExecutionException, InterruptedException, DaggerQueryException { Field leafField = parts.pop().toField(); leafField.setFields( leaves.stream().<FieldOrFragment>map(qp -> field(qp.getOperation())).toList()); List<Field> fields = new ArrayList<>(); for (QueryPart qp : parts) { fields.add(qp.toField()); } Field operation = fields.stream() .reduce( leafField, (acc, field) -> { field.setFields(List.of(acc)); return field; }); Document query = document(operation(operation)); return query; } Response executeQuery(Document document) throws ExecutionException, InterruptedException, DaggerQueryException { LOG.debug("Executing query: {}", document.build()); Response response = client.executeSync(document); handleErrors(response); LOG.debug("Received response: {}", response.getData()); return response; } /** * Execute a query and discord the response. * * @throws ExecutionException * @throws InterruptedException * @throws DaggerQueryException */ void executeQuery() throws ExecutionException, InterruptedException, DaggerQueryException { Document query = buildDocument(); executeQuery(query); } <T> T executeQuery(Class<T> klass) throws ExecutionException, InterruptedException, DaggerQueryException { String path = StreamSupport.stream( Spliterators.spliteratorUnknownSize(parts.descendingIterator(), 0), false) .map(QueryPart::getOperation) .collect(Collectors.joining(".")); Document query = buildDocument(); Response response = executeQuery(query); if (Scalar.class.isAssignableFrom(klass)) { // FIXME scalar could be other types than String in the future String value = JsonPath.parse(response.getData().toString()).read(path, String.class); try { return klass.getDeclaredConstructor(String.class).newInstance(value); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException nsme) { // FIXME - This may not happen throw new RuntimeException(nsme); } } else { return JsonPath.parse(response.getData().toString()).read(path, klass); } } <T> List<T> executeListQuery(Class<T> klass) throws ExecutionException, InterruptedException, DaggerQueryException { List<String> pathElts = StreamSupport.stream( Spliterators.spliteratorUnknownSize(parts.descendingIterator(), 0), false) .map(QueryPart::getOperation) .toList(); Document document = buildDocument(); Response response = executeQuery(document); JsonObject obj = response.getData(); for (int i = 0; i < pathElts.size() - 1; i++) { obj = obj.getJsonObject(pathElts.get(i)); } JsonArray array = obj.getJsonArray(pathElts.get(pathElts.size() - 1)); JsonbConfig config = new JsonbConfig().withPropertyVisibilityStrategy(new PrivateVisibilityStrategy()); Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build(); List<T> rv = jsonb.fromJson(array.toString(), TypeUtils.parameterize(List.class, klass)); return rv; } <T> List<QueryBuilder> executeObjectListQuery(Class<T> klass) throws ExecutionException, InterruptedException, DaggerQueryException { List<String> pathElts = StreamSupport.stream( Spliterators.spliteratorUnknownSize(parts.descendingIterator(), 0), false) .map(QueryPart::getOperation) .toList(); Document document = buildDocument(); Response response = executeQuery(document); JsonObject obj = response.getData(); for (int i = 0; i < pathElts.size() - 1; i++) { obj = obj.getJsonObject(pathElts.get(i)); } JsonArray array = obj.getJsonArray(pathElts.get(pathElts.size() - 1)); List<QueryBuilder> rv = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { String id = array.getJsonObject(i).getString("id"); QueryBuilder qb = new QueryBuilder(this.client) .chain( String.format("load%sFromID", klass.getSimpleName()), Arguments.newBuilder().add("id", id).build()); rv.add(qb); } return rv; } }
dagger/dagger
sdk/java/dagger-java-sdk/src/main/java/io/dagger/client/QueryBuilder.java
2,075
// GraphQLError error = response.getErrors().get(0);
line_comment
nl
package io.dagger.client; import static io.smallrye.graphql.client.core.Document.document; import static io.smallrye.graphql.client.core.Field.field; import static io.smallrye.graphql.client.core.Operation.operation; import com.jayway.jsonpath.JsonPath; import io.smallrye.graphql.client.GraphQLError; import io.smallrye.graphql.client.Response; import io.smallrye.graphql.client.core.Document; import io.smallrye.graphql.client.core.Field; import io.smallrye.graphql.client.core.FieldOrFragment; import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient; import jakarta.json.JsonArray; import jakarta.json.JsonObject; import jakarta.json.bind.Jsonb; import jakarta.json.bind.JsonbBuilder; import jakarta.json.bind.JsonbConfig; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.apache.commons.lang3.reflect.TypeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class QueryBuilder { static final Logger LOG = LoggerFactory.getLogger(QueryBuilder.class); private final DynamicGraphQLClient client; private final Deque<QueryPart> parts; private final List<QueryPart> leaves; QueryBuilder(DynamicGraphQLClient client) { this(client, new LinkedList<>()); } private QueryBuilder(DynamicGraphQLClient client, Deque<QueryPart> parts) { this(client, parts, new ArrayList<>()); } private QueryBuilder( DynamicGraphQLClient client, Deque<QueryPart> parts, List<String> finalFields) { this.client = client; this.parts = parts; this.leaves = finalFields.stream().map(QueryPart::new).toList(); } QueryBuilder chain(String operation) { return chain(operation, Arguments.noArgs()); } QueryBuilder chain(String operation, Arguments arguments) { if (leaves != null && !leaves.isEmpty()) { throw new IllegalStateException("A new field cannot be chained"); } Deque<QueryPart> list = new LinkedList<>(); list.addAll(this.parts); list.push(new QueryPart(operation, arguments)); return new QueryBuilder(client, list); } QueryBuilder chain(String operation, List<String> leaves) { if (!this.leaves.isEmpty()) { throw new IllegalStateException("A new field cannot be chained"); } Deque<QueryPart> list = new LinkedList<>(); list.addAll(this.parts); list.push(new QueryPart(operation)); return new QueryBuilder(client, list, leaves); } QueryBuilder chain(List<String> leaves) { if (!this.leaves.isEmpty()) { throw new IllegalStateException("A new field cannot be chained"); } Deque<QueryPart> list = new LinkedList<>(); list.addAll(this.parts); return new QueryBuilder(client, list, leaves); } private void handleErrors(Response response) throws DaggerQueryException { if (!response.hasError()) { return; } LOG.debug( String.format( "Query execution failed: %s", response.getErrors().stream() .map(GraphQLError::toString) .collect(Collectors.joining(", ")))); if (response.getErrors().isEmpty()) { throw new DaggerQueryException(); } // GraphQLError error<SUF> // error.getExtensions().get("_type"); throw new DaggerQueryException(response.getErrors().toArray(new GraphQLError[0])); } Document buildDocument() throws ExecutionException, InterruptedException, DaggerQueryException { Field leafField = parts.pop().toField(); leafField.setFields( leaves.stream().<FieldOrFragment>map(qp -> field(qp.getOperation())).toList()); List<Field> fields = new ArrayList<>(); for (QueryPart qp : parts) { fields.add(qp.toField()); } Field operation = fields.stream() .reduce( leafField, (acc, field) -> { field.setFields(List.of(acc)); return field; }); Document query = document(operation(operation)); return query; } Response executeQuery(Document document) throws ExecutionException, InterruptedException, DaggerQueryException { LOG.debug("Executing query: {}", document.build()); Response response = client.executeSync(document); handleErrors(response); LOG.debug("Received response: {}", response.getData()); return response; } /** * Execute a query and discord the response. * * @throws ExecutionException * @throws InterruptedException * @throws DaggerQueryException */ void executeQuery() throws ExecutionException, InterruptedException, DaggerQueryException { Document query = buildDocument(); executeQuery(query); } <T> T executeQuery(Class<T> klass) throws ExecutionException, InterruptedException, DaggerQueryException { String path = StreamSupport.stream( Spliterators.spliteratorUnknownSize(parts.descendingIterator(), 0), false) .map(QueryPart::getOperation) .collect(Collectors.joining(".")); Document query = buildDocument(); Response response = executeQuery(query); if (Scalar.class.isAssignableFrom(klass)) { // FIXME scalar could be other types than String in the future String value = JsonPath.parse(response.getData().toString()).read(path, String.class); try { return klass.getDeclaredConstructor(String.class).newInstance(value); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException nsme) { // FIXME - This may not happen throw new RuntimeException(nsme); } } else { return JsonPath.parse(response.getData().toString()).read(path, klass); } } <T> List<T> executeListQuery(Class<T> klass) throws ExecutionException, InterruptedException, DaggerQueryException { List<String> pathElts = StreamSupport.stream( Spliterators.spliteratorUnknownSize(parts.descendingIterator(), 0), false) .map(QueryPart::getOperation) .toList(); Document document = buildDocument(); Response response = executeQuery(document); JsonObject obj = response.getData(); for (int i = 0; i < pathElts.size() - 1; i++) { obj = obj.getJsonObject(pathElts.get(i)); } JsonArray array = obj.getJsonArray(pathElts.get(pathElts.size() - 1)); JsonbConfig config = new JsonbConfig().withPropertyVisibilityStrategy(new PrivateVisibilityStrategy()); Jsonb jsonb = JsonbBuilder.newBuilder().withConfig(config).build(); List<T> rv = jsonb.fromJson(array.toString(), TypeUtils.parameterize(List.class, klass)); return rv; } <T> List<QueryBuilder> executeObjectListQuery(Class<T> klass) throws ExecutionException, InterruptedException, DaggerQueryException { List<String> pathElts = StreamSupport.stream( Spliterators.spliteratorUnknownSize(parts.descendingIterator(), 0), false) .map(QueryPart::getOperation) .toList(); Document document = buildDocument(); Response response = executeQuery(document); JsonObject obj = response.getData(); for (int i = 0; i < pathElts.size() - 1; i++) { obj = obj.getJsonObject(pathElts.get(i)); } JsonArray array = obj.getJsonArray(pathElts.get(pathElts.size() - 1)); List<QueryBuilder> rv = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { String id = array.getJsonObject(i).getString("id"); QueryBuilder qb = new QueryBuilder(this.client) .chain( String.format("load%sFromID", klass.getSimpleName()), Arguments.newBuilder().add("id", id).build()); rv.add(qb); } return rv; } }
74582_1
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ // Contributors: Georg Lundesgaard package ch.qos.logback.core.joran.util; import ch.qos.logback.core.Context; import ch.qos.logback.core.joran.spi.DefaultNestedComponentRegistry; import ch.qos.logback.core.joran.util.beans.BeanDescription; import ch.qos.logback.core.joran.util.beans.BeanDescriptionCache; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.AggregationType; import ch.qos.logback.core.util.PropertySetterException; import ch.qos.logback.core.util.StringUtil; import java.lang.reflect.Method; /** * General purpose Object property setter. Clients repeatedly invokes * {@link #setProperty setProperty(name,value)} in order to invoke setters on * the Object specified in the constructor. This class relies on reflection to * analyze the given Object Class. * * <p> * Usage: * * <pre> * PropertySetter ps = new PropertySetter(anObject); * ps.set(&quot;name&quot;, &quot;Joe&quot;); * ps.set(&quot;age&quot;, &quot;32&quot;); * ps.set(&quot;isMale&quot;, &quot;true&quot;); * </pre> * * will cause the invocations anObject.setName("Joe"), anObject.setAge(32), and * setMale(true) if such methods exist with those signatures. Otherwise an * {@link PropertySetterException} is thrown. * * @author Anders Kristensen * @author Ceki Gulcu */ public class PropertySetter extends ContextAwareBase { protected final Object obj; protected final Class<?> objClass; protected final BeanDescription beanDescription; protected final AggregationAssessor aggregationAssessor; /** * Create a new PropertySetter for the specified Object. This is done in * preparation for invoking {@link #setProperty} one or more times. * * @param obj the object for which to set properties */ public PropertySetter(BeanDescriptionCache beanDescriptionCache, Object obj) { this.obj = obj; this.objClass = obj.getClass(); this.beanDescription = beanDescriptionCache.getBeanDescription(objClass); this.aggregationAssessor = new AggregationAssessor(beanDescriptionCache, this.objClass); } @Override public void setContext(Context context) { super.setContext(context); aggregationAssessor.setContext(context); } /** * Set a property on this PropertySetter's Object. If successful, this method * will invoke a setter method on the underlying Object. The setter is the one * for the specified property name and the value is determined partly from the * setter argument type and partly from the value specified in the call to this * method. * * <p> * If the setter expects a String no conversion is necessary. If it expects an * int, then an attempt is made to convert 'value' to an int using new * Integer(value). If the setter expects a boolean, the conversion is by new * Boolean(value). * * @param name name of the property * @param value String value of the property */ public void setProperty(String name, String value) { if (value == null) { return; } Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("No setter for property [" + name + "] in " + objClass.getName() + "."); } else { try { setProperty(setter, value); } catch (PropertySetterException ex) { addWarn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex); } } } /** * Set the named property using a {@link Method setter}. * * @param setter A Method describing the characteristics of the * property to set. * @param value The value of the property. */ private void setProperty(Method setter, String value) throws PropertySetterException { Class<?>[] paramTypes = setter.getParameterTypes(); Object arg; try { arg = StringToObjectConverter.convertArg(this, value, paramTypes[0]); } catch (Throwable t) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed. ", t); } if (arg == null) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed."); } try { setter.invoke(obj, arg); } catch (Exception ex) { throw new PropertySetterException(ex); } } public AggregationType computeAggregationType(String name) { return this.aggregationAssessor.computeAggregationType(name); } // private Method findAdderMethod(String name) { // String propertyName = BeanUtil.toLowerCamelCase(name); // return beanDescription.getAdder(propertyName); // } // // private Method findSetterMethod(String name) { // String propertyName = BeanUtil.toLowerCamelCase(name); // return beanDescription.getSetter(propertyName); // } // private Class<?> getParameterClassForMethod(Method method) { // if (method == null) { // return null; // } // Class<?>[] classArray = method.getParameterTypes(); // if (classArray.length != 1) { // return null; // } else { // return classArray[0]; // } // } // private AggregationType computeRawAggregationType(Method method) { // Class<?> parameterClass = getParameterClassForMethod(method); // if (parameterClass == null) { // return AggregationType.NOT_FOUND; // } // if (StringToObjectConverter.canBeBuiltFromSimpleString(parameterClass)) { // return AggregationType.AS_BASIC_PROPERTY; // } else { // return AggregationType.AS_COMPLEX_PROPERTY; // } // } public Class<?> getObjClass() { return objClass; } public void addComplexProperty(String name, Object complexProperty) { Method adderMethod = aggregationAssessor.findAdderMethod(name); // first let us use the addXXX method if (adderMethod != null) { Class<?>[] paramTypes = adderMethod.getParameterTypes(); if (!isSanityCheckSuccessful(name, adderMethod, paramTypes, complexProperty)) { return; } invokeMethodWithSingleParameterOnThisObject(adderMethod, complexProperty); } else { addError("Could not find method [" + "add" + name + "] in class [" + objClass.getName() + "]."); } } void invokeMethodWithSingleParameterOnThisObject(Method method, Object parameter) { Class<?> ccc = parameter.getClass(); try { method.invoke(this.obj, parameter); } catch (Exception e) { addError("Could not invoke method " + method.getName() + " in class " + obj.getClass().getName() + " with parameter of type " + ccc.getName(), e); } } public void addBasicProperty(String name, String strValue) { if (strValue == null) { return; } name = StringUtil.capitalizeFirstLetter(name); Method adderMethod =aggregationAssessor.findAdderMethod(name); if (adderMethod == null) { addError("No adder for property [" + name + "]."); return; } Class<?>[] paramTypes = adderMethod.getParameterTypes(); isSanityCheckSuccessful(name, adderMethod, paramTypes, strValue); Object arg; try { arg = StringToObjectConverter.convertArg(this, strValue, paramTypes[0]); } catch (Throwable t) { addError("Conversion to type [" + paramTypes[0] + "] failed. ", t); return; } if (arg != null) { invokeMethodWithSingleParameterOnThisObject(adderMethod, arg); } } public void setComplexProperty(String name, Object complexProperty) { Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("Not setter method for property [" + name + "] in " + obj.getClass().getName()); return; } Class<?>[] paramTypes = setter.getParameterTypes(); if (!isSanityCheckSuccessful(name, setter, paramTypes, complexProperty)) { return; } try { invokeMethodWithSingleParameterOnThisObject(setter, complexProperty); } catch (Exception e) { addError("Could not set component " + obj + " for parent component " + obj, e); } } private boolean isSanityCheckSuccessful(String name, Method method, Class<?>[] params, Object complexProperty) { Class<?> ccc = complexProperty.getClass(); if (params.length != 1) { addError("Wrong number of parameters in setter method for property [" + name + "] in " + obj.getClass().getName()); return false; } if (!params[0].isAssignableFrom(complexProperty.getClass())) { addError("A \"" + ccc.getName() + "\" object is not assignable to a \"" + params[0].getName() + "\" variable."); addError("The class \"" + params[0].getName() + "\" was loaded by "); addError("[" + params[0].getClassLoader() + "] whereas object of type "); addError("\"" + ccc.getName() + "\" was loaded by [" + ccc.getClassLoader() + "]."); return false; } return true; } public Object getObj() { return obj; } public Class<?> getClassNameViaImplicitRules(String name, AggregationType aggregationType, DefaultNestedComponentRegistry registry) { return aggregationAssessor.getClassNameViaImplicitRules(name, aggregationType, registry); } }
qos-ch/logback
logback-core/src/main/java/ch/qos/logback/core/joran/util/PropertySetter.java
2,579
// Contributors: Georg Lundesgaard
line_comment
nl
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ // Contributors: <SUF> package ch.qos.logback.core.joran.util; import ch.qos.logback.core.Context; import ch.qos.logback.core.joran.spi.DefaultNestedComponentRegistry; import ch.qos.logback.core.joran.util.beans.BeanDescription; import ch.qos.logback.core.joran.util.beans.BeanDescriptionCache; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.AggregationType; import ch.qos.logback.core.util.PropertySetterException; import ch.qos.logback.core.util.StringUtil; import java.lang.reflect.Method; /** * General purpose Object property setter. Clients repeatedly invokes * {@link #setProperty setProperty(name,value)} in order to invoke setters on * the Object specified in the constructor. This class relies on reflection to * analyze the given Object Class. * * <p> * Usage: * * <pre> * PropertySetter ps = new PropertySetter(anObject); * ps.set(&quot;name&quot;, &quot;Joe&quot;); * ps.set(&quot;age&quot;, &quot;32&quot;); * ps.set(&quot;isMale&quot;, &quot;true&quot;); * </pre> * * will cause the invocations anObject.setName("Joe"), anObject.setAge(32), and * setMale(true) if such methods exist with those signatures. Otherwise an * {@link PropertySetterException} is thrown. * * @author Anders Kristensen * @author Ceki Gulcu */ public class PropertySetter extends ContextAwareBase { protected final Object obj; protected final Class<?> objClass; protected final BeanDescription beanDescription; protected final AggregationAssessor aggregationAssessor; /** * Create a new PropertySetter for the specified Object. This is done in * preparation for invoking {@link #setProperty} one or more times. * * @param obj the object for which to set properties */ public PropertySetter(BeanDescriptionCache beanDescriptionCache, Object obj) { this.obj = obj; this.objClass = obj.getClass(); this.beanDescription = beanDescriptionCache.getBeanDescription(objClass); this.aggregationAssessor = new AggregationAssessor(beanDescriptionCache, this.objClass); } @Override public void setContext(Context context) { super.setContext(context); aggregationAssessor.setContext(context); } /** * Set a property on this PropertySetter's Object. If successful, this method * will invoke a setter method on the underlying Object. The setter is the one * for the specified property name and the value is determined partly from the * setter argument type and partly from the value specified in the call to this * method. * * <p> * If the setter expects a String no conversion is necessary. If it expects an * int, then an attempt is made to convert 'value' to an int using new * Integer(value). If the setter expects a boolean, the conversion is by new * Boolean(value). * * @param name name of the property * @param value String value of the property */ public void setProperty(String name, String value) { if (value == null) { return; } Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("No setter for property [" + name + "] in " + objClass.getName() + "."); } else { try { setProperty(setter, value); } catch (PropertySetterException ex) { addWarn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex); } } } /** * Set the named property using a {@link Method setter}. * * @param setter A Method describing the characteristics of the * property to set. * @param value The value of the property. */ private void setProperty(Method setter, String value) throws PropertySetterException { Class<?>[] paramTypes = setter.getParameterTypes(); Object arg; try { arg = StringToObjectConverter.convertArg(this, value, paramTypes[0]); } catch (Throwable t) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed. ", t); } if (arg == null) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed."); } try { setter.invoke(obj, arg); } catch (Exception ex) { throw new PropertySetterException(ex); } } public AggregationType computeAggregationType(String name) { return this.aggregationAssessor.computeAggregationType(name); } // private Method findAdderMethod(String name) { // String propertyName = BeanUtil.toLowerCamelCase(name); // return beanDescription.getAdder(propertyName); // } // // private Method findSetterMethod(String name) { // String propertyName = BeanUtil.toLowerCamelCase(name); // return beanDescription.getSetter(propertyName); // } // private Class<?> getParameterClassForMethod(Method method) { // if (method == null) { // return null; // } // Class<?>[] classArray = method.getParameterTypes(); // if (classArray.length != 1) { // return null; // } else { // return classArray[0]; // } // } // private AggregationType computeRawAggregationType(Method method) { // Class<?> parameterClass = getParameterClassForMethod(method); // if (parameterClass == null) { // return AggregationType.NOT_FOUND; // } // if (StringToObjectConverter.canBeBuiltFromSimpleString(parameterClass)) { // return AggregationType.AS_BASIC_PROPERTY; // } else { // return AggregationType.AS_COMPLEX_PROPERTY; // } // } public Class<?> getObjClass() { return objClass; } public void addComplexProperty(String name, Object complexProperty) { Method adderMethod = aggregationAssessor.findAdderMethod(name); // first let us use the addXXX method if (adderMethod != null) { Class<?>[] paramTypes = adderMethod.getParameterTypes(); if (!isSanityCheckSuccessful(name, adderMethod, paramTypes, complexProperty)) { return; } invokeMethodWithSingleParameterOnThisObject(adderMethod, complexProperty); } else { addError("Could not find method [" + "add" + name + "] in class [" + objClass.getName() + "]."); } } void invokeMethodWithSingleParameterOnThisObject(Method method, Object parameter) { Class<?> ccc = parameter.getClass(); try { method.invoke(this.obj, parameter); } catch (Exception e) { addError("Could not invoke method " + method.getName() + " in class " + obj.getClass().getName() + " with parameter of type " + ccc.getName(), e); } } public void addBasicProperty(String name, String strValue) { if (strValue == null) { return; } name = StringUtil.capitalizeFirstLetter(name); Method adderMethod =aggregationAssessor.findAdderMethod(name); if (adderMethod == null) { addError("No adder for property [" + name + "]."); return; } Class<?>[] paramTypes = adderMethod.getParameterTypes(); isSanityCheckSuccessful(name, adderMethod, paramTypes, strValue); Object arg; try { arg = StringToObjectConverter.convertArg(this, strValue, paramTypes[0]); } catch (Throwable t) { addError("Conversion to type [" + paramTypes[0] + "] failed. ", t); return; } if (arg != null) { invokeMethodWithSingleParameterOnThisObject(adderMethod, arg); } } public void setComplexProperty(String name, Object complexProperty) { Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("Not setter method for property [" + name + "] in " + obj.getClass().getName()); return; } Class<?>[] paramTypes = setter.getParameterTypes(); if (!isSanityCheckSuccessful(name, setter, paramTypes, complexProperty)) { return; } try { invokeMethodWithSingleParameterOnThisObject(setter, complexProperty); } catch (Exception e) { addError("Could not set component " + obj + " for parent component " + obj, e); } } private boolean isSanityCheckSuccessful(String name, Method method, Class<?>[] params, Object complexProperty) { Class<?> ccc = complexProperty.getClass(); if (params.length != 1) { addError("Wrong number of parameters in setter method for property [" + name + "] in " + obj.getClass().getName()); return false; } if (!params[0].isAssignableFrom(complexProperty.getClass())) { addError("A \"" + ccc.getName() + "\" object is not assignable to a \"" + params[0].getName() + "\" variable."); addError("The class \"" + params[0].getName() + "\" was loaded by "); addError("[" + params[0].getClassLoader() + "] whereas object of type "); addError("\"" + ccc.getName() + "\" was loaded by [" + ccc.getClassLoader() + "]."); return false; } return true; } public Object getObj() { return obj; } public Class<?> getClassNameViaImplicitRules(String name, AggregationType aggregationType, DefaultNestedComponentRegistry registry) { return aggregationAssessor.getClassNameViaImplicitRules(name, aggregationType, registry); } }
187427_1
class RingBuffer { int size; int[] smg; int start; int end; // returns a rb of the size RingBuffer(int size) { this.size = size; this.smg = new int[size]; this.start = 0; this.end = 0; } // insert : int -> public RingBuffer insert( int elem ) { this.smg[ this.end ] = elem; this.end = (this.end + 1) % this.size; return this; } // read : int -> int // REQUIRES: insert() has been called at least idx times // idx < size // returns the element inserted idx times in the past // EXAMPLE // (new RingBuffer(2)).insert(1).insert(2).insert(3).read(1) // = 2 public int read ( int idx ) { return this.smg[ (this.end - idx + this.size - 1) % this.size ]; } // BEFORE: start = 0, end = 0, size = 2, smg = { ? , ? } // insert(1) // AFTER: smg = { 1 , ? }, end = 1 // insert(2) // AFTER: smg = { 1 , 2 }, end = 0 // insert(3) // AFTER: smg = { 3 , 2 }, end = 1 // read(1) } class Box { boolean d; Box() { this.d = true; } // observe : -> bool // EFFECTS: this // IMPL: flips the booleanosity of this.d // CLIENT: cycles between false and true // CLIENT: the next call to observe will return the opposite of what this one does; the first call returns false // BIG DEAL: Specs are for clients, not implementers public boolean observe() { this.d = ! this.d; return this.d; } } class C7 { // returns three more than the input // REQUIRES: x be even static int f ( int x ) { return x + 3; } // g : -> // REQUIRES: amanda_before is even // EFFECTS: amanda // amanda_after is amanda_before + 3 static int amanda = 0; static void g ( ) { amanda = amanda + 3; } static class Store { public int amanda; Store ( int amanda ) { this.amanda = amanda; } } // XXXg : Store -> Store // REQUIRES: the store contain an even amanda // produces a new store that contains an amanda three degrees // cooler static Store XXXg ( Store st ) { return new Store ( st.amanda + 3 ); } static int isabella = 0; // hm : int -> int // REQUIRES: y can't be zero // EFFECTS: isabella // isabella_after is one more than isabella_before // returns isabella_before divided by y static int hm ( int y ) { int r = isabella / y; isabella = isabella + 1; return r; } static class HMStore { public int isabella; HMStore ( int isabella ) { this.isabella = isabella; } } static class IntAndHMStore { int r; HMStore st; IntAndHMStore( int r, HMStore st ) { this.r = r; this.st = st; } } // XXXh : Store int -> int x Store // REQUIRES: y can't be zero // returns st.isabella divided by y and a store where isabella is // one more than st.isabella static IntAndHMStore XXXhm ( HMStore st, int y ) { int r = st.isabella / y; HMStore stp = new HMStore( st.isabella + 1 ); return new IntAndHMStore( r, stp ); } // The transformation is called "Store-Passing Style" public static void main(String[] args) { System.out.println("Yo! Raps!"); System.out.println(f(4) + " should be " + 7); int x = 4; System.out.println(f(x) + " should be " + 7); System.out.println((x + 3) + " should be " + 7); System.out.println((4 + 3) + " should be " + 7); x = x / 2; System.out.println(f(x) + " should be " + 5); System.out.println((x + 3) + " should be " + 5); System.out.println((2 + 3) + " should be " + 5); amanda = 4; // BEFORE amanda = 4 g(); // AFTER amanda = 7 System.out.println(amanda + " should be " + 7); g(); System.out.println(amanda + " should be " + 10); // From here Store st_0 = new Store( 4 ); Store st_1 = XXXg( st_0 ); System.out.println(st_1.amanda + " should be " + 7); Store st_2 = XXXg( st_1 ); System.out.println(st_2.amanda + " should be " + 10); // to here // st_x is used "linearly" System.out.println(st_0.amanda + " should be " + 4); Box sb = new Box(); System.out.println("The box says, " + sb.observe()); System.out.println("The box says, " + sb.observe()); System.out.println("The box says, " + sb.observe()); System.out.println("The fox says, ?"); RingBuffer rb = (new RingBuffer(2)); rb.insert(1); System.out.println(rb.read(0) + " should be " + 1 ); rb.insert(2); System.out.println(rb.read(0) + " should be " + 2 ); System.out.println(rb.read(1) + " should be " + 1 ); rb.insert(3); System.out.println(rb.read(0) + " should be " + 3 ); System.out.println(rb.read(1) + " should be " + 2 ); rb.insert(4); System.out.println(rb.read(0) + " should be " + 4 ); System.out.println(rb.read(1) + " should be " + 3 ); } }
jeapostrophe/jeapostrophe.github.com
courses/2014/fall/203/notes/7.java
1,744
// insert : int ->
line_comment
nl
class RingBuffer { int size; int[] smg; int start; int end; // returns a rb of the size RingBuffer(int size) { this.size = size; this.smg = new int[size]; this.start = 0; this.end = 0; } // insert :<SUF> public RingBuffer insert( int elem ) { this.smg[ this.end ] = elem; this.end = (this.end + 1) % this.size; return this; } // read : int -> int // REQUIRES: insert() has been called at least idx times // idx < size // returns the element inserted idx times in the past // EXAMPLE // (new RingBuffer(2)).insert(1).insert(2).insert(3).read(1) // = 2 public int read ( int idx ) { return this.smg[ (this.end - idx + this.size - 1) % this.size ]; } // BEFORE: start = 0, end = 0, size = 2, smg = { ? , ? } // insert(1) // AFTER: smg = { 1 , ? }, end = 1 // insert(2) // AFTER: smg = { 1 , 2 }, end = 0 // insert(3) // AFTER: smg = { 3 , 2 }, end = 1 // read(1) } class Box { boolean d; Box() { this.d = true; } // observe : -> bool // EFFECTS: this // IMPL: flips the booleanosity of this.d // CLIENT: cycles between false and true // CLIENT: the next call to observe will return the opposite of what this one does; the first call returns false // BIG DEAL: Specs are for clients, not implementers public boolean observe() { this.d = ! this.d; return this.d; } } class C7 { // returns three more than the input // REQUIRES: x be even static int f ( int x ) { return x + 3; } // g : -> // REQUIRES: amanda_before is even // EFFECTS: amanda // amanda_after is amanda_before + 3 static int amanda = 0; static void g ( ) { amanda = amanda + 3; } static class Store { public int amanda; Store ( int amanda ) { this.amanda = amanda; } } // XXXg : Store -> Store // REQUIRES: the store contain an even amanda // produces a new store that contains an amanda three degrees // cooler static Store XXXg ( Store st ) { return new Store ( st.amanda + 3 ); } static int isabella = 0; // hm : int -> int // REQUIRES: y can't be zero // EFFECTS: isabella // isabella_after is one more than isabella_before // returns isabella_before divided by y static int hm ( int y ) { int r = isabella / y; isabella = isabella + 1; return r; } static class HMStore { public int isabella; HMStore ( int isabella ) { this.isabella = isabella; } } static class IntAndHMStore { int r; HMStore st; IntAndHMStore( int r, HMStore st ) { this.r = r; this.st = st; } } // XXXh : Store int -> int x Store // REQUIRES: y can't be zero // returns st.isabella divided by y and a store where isabella is // one more than st.isabella static IntAndHMStore XXXhm ( HMStore st, int y ) { int r = st.isabella / y; HMStore stp = new HMStore( st.isabella + 1 ); return new IntAndHMStore( r, stp ); } // The transformation is called "Store-Passing Style" public static void main(String[] args) { System.out.println("Yo! Raps!"); System.out.println(f(4) + " should be " + 7); int x = 4; System.out.println(f(x) + " should be " + 7); System.out.println((x + 3) + " should be " + 7); System.out.println((4 + 3) + " should be " + 7); x = x / 2; System.out.println(f(x) + " should be " + 5); System.out.println((x + 3) + " should be " + 5); System.out.println((2 + 3) + " should be " + 5); amanda = 4; // BEFORE amanda = 4 g(); // AFTER amanda = 7 System.out.println(amanda + " should be " + 7); g(); System.out.println(amanda + " should be " + 10); // From here Store st_0 = new Store( 4 ); Store st_1 = XXXg( st_0 ); System.out.println(st_1.amanda + " should be " + 7); Store st_2 = XXXg( st_1 ); System.out.println(st_2.amanda + " should be " + 10); // to here // st_x is used "linearly" System.out.println(st_0.amanda + " should be " + 4); Box sb = new Box(); System.out.println("The box says, " + sb.observe()); System.out.println("The box says, " + sb.observe()); System.out.println("The box says, " + sb.observe()); System.out.println("The fox says, ?"); RingBuffer rb = (new RingBuffer(2)); rb.insert(1); System.out.println(rb.read(0) + " should be " + 1 ); rb.insert(2); System.out.println(rb.read(0) + " should be " + 2 ); System.out.println(rb.read(1) + " should be " + 1 ); rb.insert(3); System.out.println(rb.read(0) + " should be " + 3 ); System.out.println(rb.read(1) + " should be " + 2 ); rb.insert(4); System.out.println(rb.read(0) + " should be " + 4 ); System.out.println(rb.read(1) + " should be " + 3 ); } }
5145_1
/* * Copyright (c) 2020, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.feature.describe; import boofcv.alg.misc.GImageMiscOps; import boofcv.core.image.GeneralizedImageOps; import boofcv.struct.image.ImageGray; import boofcv.struct.image.ImageType; import boofcv.struct.sparse.GradientValue; import boofcv.struct.sparse.SparseScaleGradient; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.util.Random; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @Warmup(iterations = 2) @Measurement(iterations = 5) @State(Scope.Benchmark) @Fork(value = 1) public class BenchmarkSurfDescribeOps<T extends ImageGray<T>> { @Param({"SB_S32", "SB_F32"}) String imageTypeName; Class<T> imageType; T input; // parameters for region gradient double tl_x = 100.0; double tl_y = 120.3; double period = 1.2; int regionSize = 20; double kernelWidth = 5; double[] derivX = new double[ regionSize*regionSize ]; double[] derivY = new double[ regionSize*regionSize ]; @Setup public void setup() { int width = 640, height = 480; var rand = new Random(234234); imageType = ImageType.stringToType(imageTypeName, 3).getImageClass(); input = GeneralizedImageOps.createSingleBand(imageType,width,height); GImageMiscOps.fillUniform(input, rand, 0, 1); } @Benchmark public void Not_Haar() { SurfDescribeOps.gradient(input, tl_x, tl_y, period, regionSize, kernelWidth, false, derivX, derivY); } @Benchmark public void Haar() { SurfDescribeOps.gradient(input, tl_x , tl_y , period, regionSize, kernelWidth,true,derivX,derivY); } @Benchmark public void Not_Haar_Border() { SparseScaleGradient<T,?> g = SurfDescribeOps.createGradient(false,imageType); g.setWidth(kernelWidth); g.setImage(input); sampleBorder(g); } @Benchmark public void Haar_Border() { SparseScaleGradient<T,?> g = SurfDescribeOps.createGradient(true,imageType); g.setWidth(kernelWidth); g.setImage(input); sampleBorder(g); } /** * Sample the gradient using SparseImageGradient instead of the completely * unrolled code */ public void sampleBorder(SparseScaleGradient<T,?> g) { for (int iter = 0; iter < 500; iter++) { double tl_x = this.tl_x + 0.5; double tl_y = this.tl_y + 0.5; int j = 0; for( int y = 0; y < regionSize; y++ ) { for( int x = 0; x < regionSize; x++ , j++) { int xx = (int)(tl_x + x * period); int yy = (int)(tl_y + y * period); GradientValue deriv = g.compute(xx,yy); derivX[j] = deriv.getX(); derivY[j] = deriv.getY(); } } } } public static void main( String[] args ) throws RunnerException { Options opt = new OptionsBuilder() .include(BenchmarkSurfDescribeOps.class.getSimpleName()) .warmupTime(TimeValue.seconds(1)) .measurementTime(TimeValue.seconds(1)) .build(); new Runner(opt).run(); } }
lessthanoptimal/BoofCV
main/boofcv-feature/src/benchmark/java/boofcv/alg/feature/describe/BenchmarkSurfDescribeOps.java
1,229
// parameters for region gradient
line_comment
nl
/* * Copyright (c) 2020, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.feature.describe; import boofcv.alg.misc.GImageMiscOps; import boofcv.core.image.GeneralizedImageOps; import boofcv.struct.image.ImageGray; import boofcv.struct.image.ImageType; import boofcv.struct.sparse.GradientValue; import boofcv.struct.sparse.SparseScaleGradient; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.util.Random; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @Warmup(iterations = 2) @Measurement(iterations = 5) @State(Scope.Benchmark) @Fork(value = 1) public class BenchmarkSurfDescribeOps<T extends ImageGray<T>> { @Param({"SB_S32", "SB_F32"}) String imageTypeName; Class<T> imageType; T input; // parameters for<SUF> double tl_x = 100.0; double tl_y = 120.3; double period = 1.2; int regionSize = 20; double kernelWidth = 5; double[] derivX = new double[ regionSize*regionSize ]; double[] derivY = new double[ regionSize*regionSize ]; @Setup public void setup() { int width = 640, height = 480; var rand = new Random(234234); imageType = ImageType.stringToType(imageTypeName, 3).getImageClass(); input = GeneralizedImageOps.createSingleBand(imageType,width,height); GImageMiscOps.fillUniform(input, rand, 0, 1); } @Benchmark public void Not_Haar() { SurfDescribeOps.gradient(input, tl_x, tl_y, period, regionSize, kernelWidth, false, derivX, derivY); } @Benchmark public void Haar() { SurfDescribeOps.gradient(input, tl_x , tl_y , period, regionSize, kernelWidth,true,derivX,derivY); } @Benchmark public void Not_Haar_Border() { SparseScaleGradient<T,?> g = SurfDescribeOps.createGradient(false,imageType); g.setWidth(kernelWidth); g.setImage(input); sampleBorder(g); } @Benchmark public void Haar_Border() { SparseScaleGradient<T,?> g = SurfDescribeOps.createGradient(true,imageType); g.setWidth(kernelWidth); g.setImage(input); sampleBorder(g); } /** * Sample the gradient using SparseImageGradient instead of the completely * unrolled code */ public void sampleBorder(SparseScaleGradient<T,?> g) { for (int iter = 0; iter < 500; iter++) { double tl_x = this.tl_x + 0.5; double tl_y = this.tl_y + 0.5; int j = 0; for( int y = 0; y < regionSize; y++ ) { for( int x = 0; x < regionSize; x++ , j++) { int xx = (int)(tl_x + x * period); int yy = (int)(tl_y + y * period); GradientValue deriv = g.compute(xx,yy); derivX[j] = deriv.getX(); derivY[j] = deriv.getY(); } } } } public static void main( String[] args ) throws RunnerException { Options opt = new OptionsBuilder() .include(BenchmarkSurfDescribeOps.class.getSimpleName()) .warmupTime(TimeValue.seconds(1)) .measurementTime(TimeValue.seconds(1)) .build(); new Runner(opt).run(); } }
87567_3
import java.awt.geom.Point2D; import java.io.*; import java.net.Socket; import java.util.Arrays; import java.util.stream.Collectors; public class HandleASession implements Runnable, Connect4Constants { private Socket player1; private Socket player2; // Create and initialize cells private char[][] cell = new char[6][7]; private ObjectInputStream fromPlayer1; private ObjectOutputStream toPlayer1; private ObjectInputStream fromPlayer2; private ObjectOutputStream toPlayer2; // Continue to play private boolean continueToPlay = true; /** Construct a thread */ public HandleASession(Socket player1, Socket player2) { this.player1 = player1; this.player2 = player2; // Initialize cells for (int i = 0; i < 6; i++) for (int j = 0; j < 7; j++) cell[i][j] = ' '; printBoard(); // System.out.println(isRowFull(0)); wordt ook gecontroleerd in client -> als hij vol zit dan wordt hij niet gestuurd naar de server } private void printBoard(){ String result = Arrays .stream(cell) .map(Arrays::toString) .collect(Collectors.joining(System.lineSeparator())); System.out.println(result); } /** Implement the run() method for the thread */ public void run() { try { // Create data input and output streams fromPlayer1 = new ObjectInputStream( player1.getInputStream()); toPlayer1 = new ObjectOutputStream( player1.getOutputStream()); fromPlayer2 = new ObjectInputStream( player2.getInputStream()); toPlayer2 = new ObjectOutputStream( player2.getOutputStream()); boolean isValid; System.out.println("run() in HandleASession"); toPlayer1.writeInt(PLAYER1); System.out.println("Send to player 1"); toPlayer1.flush(); toPlayer2.writeInt(PLAYER2); toPlayer2.flush(); System.out.println("Send to player 2"); // Continuously serve the players and determine and report // the game status to the players while (true) { // Receive a move from player 1 Point2D point = (Point2D) fromPlayer1.readObject(); System.out.println("Reading point object from player 1"); if(cell[(int) point.getY()][(int)(point.getX())] == ' ') { cell[(int) point.getY()][(int) point.getX()] = 'R'; isValid = true; } else { toPlayer1.writeInt(INVALID_MOVE); isValid = false; } // Check if Player 1 wins if (isWon('R')) { System.out.println("PLAYER 1 WINS"); toPlayer1.writeInt(PLAYER1_WON); toPlayer2.writeInt(PLAYER1_WON); toPlayer1.writeObject(point); toPlayer2.writeObject(point); break; // Break the loop } else if (isFull()) { // Check if all cells are filled System.out.println("NOBODY WINS, ITS A DRAW"); toPlayer1.writeInt(DRAW); toPlayer2.writeInt(DRAW); toPlayer2.writeObject(point); break; } else if(isValid){ // Notify player 2 to take the turn System.out.println("Notify player 2 to take the turn"); toPlayer2.writeInt(CONTINUE); // Send player 1's selected row and column to player 2 System.out.println("send move"); toPlayer2.writeObject(point); isValid = false; } // Receive a move from Player 2 point = (Point2D) fromPlayer2.readObject(); System.out.println("Reading point object from player 1"); if(cell[(int) point.getY()][(int)(point.getX())] == ' ') { cell[(int) point.getY()][(int) (point.getX())] = 'G'; isValid = true; } else { toPlayer2.writeInt(INVALID_MOVE); isValid = false; } // Check if Player 2 wins if (isWon('G')) { System.out.println("PLAYER 2 WINS"); toPlayer1.writeInt(PLAYER2_WON); toPlayer2.writeInt(PLAYER2_WON); toPlayer1.writeObject(point); toPlayer2.writeObject(point); break; } else if(isValid){ System.out.println("Notify player 1 to take the turn"); toPlayer1.writeInt(CONTINUE); // Send player 2's selected row and column to player 1 System.out.println("send move"); toPlayer1.writeObject(point); isValid = false; } printBoard(); } }catch (IOException ioEx){ // ioEx.printStackTrace(); System.out.println("Player left."); }catch (ClassNotFoundException classEx){ classEx.printStackTrace(); } } /** Determine if the cells are all occupied */ private boolean isFull() { for (int i = 0; i < 6; i++) for (int j = 0; j < 7; j++) if (cell[i][j] == ' ') { return false; // At least one cell is not filled } // All cells are filled return true; } private boolean isRowFull(int row){ return cell[5][row] != ' '; } /** Determine if the player with the specified token wins */ private boolean isWon(char token) { // TEST BOARD VALUES for (int x = 0; x < 5; x++) { for (int y = 0; y < 6; y++) { System.out.print(cell[x][y]); } System.out.println(); } // Check all rows for (int x = 0; x < 6; x++) { for (int y = 0; y < 3; y++) { if (cell[x][y] == token && cell[x][y+1] == token && cell[x][y+2] == token && cell[x][y+3] == token) { return true; } } } ///Vert for (int x = 0; x < 3; x++) { for (int y = 0; y < 7; y++) { if (cell[x][y] == token && cell[x+1][y] == token && cell[x+2][y] == token && cell[x+3][y] == token) { return true; } } } //Diagonal wins //0 to 1 //0 to 3 for (int x = 0; x < 3; x++) { for (int y = 0; y < 6; y++) { if (cell[x][y] == token && cell[x+1][y+1] == token && cell[x+2][y+2] == token && cell[x+3][y+3] == token) { return true; } } } //Other diagonal wins for (int x = 0; x < 3; x++) { for (int y = 3; y < 7; y++) { if (cell[x][y] == token && cell[x+1][y-1] == token && cell[x+2][y-2] == token && cell[x+3][y-3] == token) { return true; } } } return false; } }
kuriye/connect-4
server/src/HandleASession.java
2,025
// System.out.println(isRowFull(0)); wordt ook gecontroleerd in client -> als hij vol zit dan wordt hij niet gestuurd naar de server
line_comment
nl
import java.awt.geom.Point2D; import java.io.*; import java.net.Socket; import java.util.Arrays; import java.util.stream.Collectors; public class HandleASession implements Runnable, Connect4Constants { private Socket player1; private Socket player2; // Create and initialize cells private char[][] cell = new char[6][7]; private ObjectInputStream fromPlayer1; private ObjectOutputStream toPlayer1; private ObjectInputStream fromPlayer2; private ObjectOutputStream toPlayer2; // Continue to play private boolean continueToPlay = true; /** Construct a thread */ public HandleASession(Socket player1, Socket player2) { this.player1 = player1; this.player2 = player2; // Initialize cells for (int i = 0; i < 6; i++) for (int j = 0; j < 7; j++) cell[i][j] = ' '; printBoard(); // System.out.println(isRowFull(0)); wordt<SUF> } private void printBoard(){ String result = Arrays .stream(cell) .map(Arrays::toString) .collect(Collectors.joining(System.lineSeparator())); System.out.println(result); } /** Implement the run() method for the thread */ public void run() { try { // Create data input and output streams fromPlayer1 = new ObjectInputStream( player1.getInputStream()); toPlayer1 = new ObjectOutputStream( player1.getOutputStream()); fromPlayer2 = new ObjectInputStream( player2.getInputStream()); toPlayer2 = new ObjectOutputStream( player2.getOutputStream()); boolean isValid; System.out.println("run() in HandleASession"); toPlayer1.writeInt(PLAYER1); System.out.println("Send to player 1"); toPlayer1.flush(); toPlayer2.writeInt(PLAYER2); toPlayer2.flush(); System.out.println("Send to player 2"); // Continuously serve the players and determine and report // the game status to the players while (true) { // Receive a move from player 1 Point2D point = (Point2D) fromPlayer1.readObject(); System.out.println("Reading point object from player 1"); if(cell[(int) point.getY()][(int)(point.getX())] == ' ') { cell[(int) point.getY()][(int) point.getX()] = 'R'; isValid = true; } else { toPlayer1.writeInt(INVALID_MOVE); isValid = false; } // Check if Player 1 wins if (isWon('R')) { System.out.println("PLAYER 1 WINS"); toPlayer1.writeInt(PLAYER1_WON); toPlayer2.writeInt(PLAYER1_WON); toPlayer1.writeObject(point); toPlayer2.writeObject(point); break; // Break the loop } else if (isFull()) { // Check if all cells are filled System.out.println("NOBODY WINS, ITS A DRAW"); toPlayer1.writeInt(DRAW); toPlayer2.writeInt(DRAW); toPlayer2.writeObject(point); break; } else if(isValid){ // Notify player 2 to take the turn System.out.println("Notify player 2 to take the turn"); toPlayer2.writeInt(CONTINUE); // Send player 1's selected row and column to player 2 System.out.println("send move"); toPlayer2.writeObject(point); isValid = false; } // Receive a move from Player 2 point = (Point2D) fromPlayer2.readObject(); System.out.println("Reading point object from player 1"); if(cell[(int) point.getY()][(int)(point.getX())] == ' ') { cell[(int) point.getY()][(int) (point.getX())] = 'G'; isValid = true; } else { toPlayer2.writeInt(INVALID_MOVE); isValid = false; } // Check if Player 2 wins if (isWon('G')) { System.out.println("PLAYER 2 WINS"); toPlayer1.writeInt(PLAYER2_WON); toPlayer2.writeInt(PLAYER2_WON); toPlayer1.writeObject(point); toPlayer2.writeObject(point); break; } else if(isValid){ System.out.println("Notify player 1 to take the turn"); toPlayer1.writeInt(CONTINUE); // Send player 2's selected row and column to player 1 System.out.println("send move"); toPlayer1.writeObject(point); isValid = false; } printBoard(); } }catch (IOException ioEx){ // ioEx.printStackTrace(); System.out.println("Player left."); }catch (ClassNotFoundException classEx){ classEx.printStackTrace(); } } /** Determine if the cells are all occupied */ private boolean isFull() { for (int i = 0; i < 6; i++) for (int j = 0; j < 7; j++) if (cell[i][j] == ' ') { return false; // At least one cell is not filled } // All cells are filled return true; } private boolean isRowFull(int row){ return cell[5][row] != ' '; } /** Determine if the player with the specified token wins */ private boolean isWon(char token) { // TEST BOARD VALUES for (int x = 0; x < 5; x++) { for (int y = 0; y < 6; y++) { System.out.print(cell[x][y]); } System.out.println(); } // Check all rows for (int x = 0; x < 6; x++) { for (int y = 0; y < 3; y++) { if (cell[x][y] == token && cell[x][y+1] == token && cell[x][y+2] == token && cell[x][y+3] == token) { return true; } } } ///Vert for (int x = 0; x < 3; x++) { for (int y = 0; y < 7; y++) { if (cell[x][y] == token && cell[x+1][y] == token && cell[x+2][y] == token && cell[x+3][y] == token) { return true; } } } //Diagonal wins //0 to 1 //0 to 3 for (int x = 0; x < 3; x++) { for (int y = 0; y < 6; y++) { if (cell[x][y] == token && cell[x+1][y+1] == token && cell[x+2][y+2] == token && cell[x+3][y+3] == token) { return true; } } } //Other diagonal wins for (int x = 0; x < 3; x++) { for (int y = 3; y < 7; y++) { if (cell[x][y] == token && cell[x+1][y-1] == token && cell[x+2][y-2] == token && cell[x+3][y-3] == token) { return true; } } } return false; } }
25115_3
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.ArrayList; /** * Write a description of class Hud here. * * @author (your name) * @version (a version number or a date) */ public class Hud extends Actor { public static char type; static ArrayList<Munt> munten = new ArrayList(); public void update(){ // HUD interface. // Heart if(Hero.levens > StartScherm.hudLevens){ getWorld().removeObjects(getWorld().getObjects(Heart.class)); StartScherm.hudLevens = 0; for(int i = 0; StartScherm.hudLevens < Hero.levens; i++){ getWorld().addObject(new Heart(),(50+(60*StartScherm.hudLevens)), 50); StartScherm.hudLevens++; } } // Munten /*if(Hero.munten > Startscherm.hudMunten){ for(int i = 0; Startscherm.hudMunten < Hero.munten; i++){ if(munten.get(munten.size()-1).type == 'g'){ getWorld().addObject(new Munt('g'), (950-(10*Startscherm.hudMunten)), 50); } else if(munten.get(munten.size()-1).type == 'z'){ getWorld().addObject(new Munt('z'), (950-(10*Startscherm.hudMunten)), 50); } Startscherm.hudMunten++; } }*/ if(Hero.munten > StartScherm.hudMunten){ getWorld().removeObjects(getWorld().getObjects(Munt.class)); StartScherm.hudMunten = 0; for(int i = 0; i < munten.size(); i++){ getWorld().addObject(munten.get(i), (950-(10*i)), 50); } } // Reset munten in HUD wanneer er 40 muntjes zijn verzameld. if(Hero.muntWaarde >= 20){ Hero.muntWaarde -= 20; munten.clear(); getWorld().removeObjects(getWorld().getObjects(Munt.class)); Hero.levens++; } //Diamanten //addObject(new Diamanten(), 50, 110); } public static void reset(){ StartScherm.hudLevens = 0; StartScherm.hudMunten = 0; munten.clear(); } public void act() { update(); } }
ROCMondriaanTIN/project-greenfoot-game-KiranKaria
Hud.java
674
// Reset munten in HUD wanneer er 40 muntjes zijn verzameld.
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.ArrayList; /** * Write a description of class Hud here. * * @author (your name) * @version (a version number or a date) */ public class Hud extends Actor { public static char type; static ArrayList<Munt> munten = new ArrayList(); public void update(){ // HUD interface. // Heart if(Hero.levens > StartScherm.hudLevens){ getWorld().removeObjects(getWorld().getObjects(Heart.class)); StartScherm.hudLevens = 0; for(int i = 0; StartScherm.hudLevens < Hero.levens; i++){ getWorld().addObject(new Heart(),(50+(60*StartScherm.hudLevens)), 50); StartScherm.hudLevens++; } } // Munten /*if(Hero.munten > Startscherm.hudMunten){ for(int i = 0; Startscherm.hudMunten < Hero.munten; i++){ if(munten.get(munten.size()-1).type == 'g'){ getWorld().addObject(new Munt('g'), (950-(10*Startscherm.hudMunten)), 50); } else if(munten.get(munten.size()-1).type == 'z'){ getWorld().addObject(new Munt('z'), (950-(10*Startscherm.hudMunten)), 50); } Startscherm.hudMunten++; } }*/ if(Hero.munten > StartScherm.hudMunten){ getWorld().removeObjects(getWorld().getObjects(Munt.class)); StartScherm.hudMunten = 0; for(int i = 0; i < munten.size(); i++){ getWorld().addObject(munten.get(i), (950-(10*i)), 50); } } // Reset munten<SUF> if(Hero.muntWaarde >= 20){ Hero.muntWaarde -= 20; munten.clear(); getWorld().removeObjects(getWorld().getObjects(Munt.class)); Hero.levens++; } //Diamanten //addObject(new Diamanten(), 50, 110); } public static void reset(){ StartScherm.hudLevens = 0; StartScherm.hudMunten = 0; munten.clear(); } public void act() { update(); } }
141653_8
/*************************************************************************** * (C) Copyright 2003-2023 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.core.rp.achievement.factory; import java.util.Collection; import java.util.LinkedList; import games.stendhal.common.parser.Sentence; import games.stendhal.server.core.rp.achievement.Achievement; import games.stendhal.server.core.rp.achievement.Category; import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.npc.ChatCondition; import games.stendhal.server.entity.npc.condition.AndCondition; import games.stendhal.server.entity.npc.condition.QuestActiveCondition; import games.stendhal.server.entity.npc.condition.QuestCompletedCondition; import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition; import games.stendhal.server.entity.npc.condition.QuestStartedCondition; import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition; import games.stendhal.server.entity.player.Player; import games.stendhal.server.maps.quests.AGrandfathersWish; /** * Factory for quest achievements * * @author kymara */ public class FriendAchievementFactory extends AbstractAchievementFactory { public static final String ID_CHILD_FRIEND = "friend.quests.children"; public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find"; public static final String ID_GOOD_SAMARITAN = "friend.karma.250"; public static final String ID_STILL_BELIEVING = "friend.meet.seasonal"; @Override protected Category getCategory() { return Category.FRIEND; } @Override public Collection<Achievement> createAchievements() { final LinkedList<Achievement> achievements = new LinkedList<Achievement>(); // Befriend Susi and complete quests for all children achievements.add(createAchievement( ID_CHILD_FRIEND, "Childrens' Friend", "Complete quests for all children", Achievement.MEDIUM_BASE_SCORE, true, new AndCondition( // Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java) new QuestStartedCondition("susi"), // Help Tad, Semos Town Hall (Medicine for Tad) new QuestCompletedCondition("introduce_players"), // Plink, Semos Plains North new QuestCompletedCondition("plinks_toy"), // Anna, in Ados new QuestCompletedCondition("toys_collector"), // Sally, Orril River new QuestCompletedCondition("campfire"), // Annie, Kalavan city gardens new QuestStateStartsWithCondition("icecream_for_annie","eating;"), // Elisabeth, Kirdneh new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"), // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom"), // Hughie, Ados farmhouse new AndCondition( new QuestActiveCondition("fishsoup_for_hughie"), new QuestNotInStateCondition("fishsoup_for_hughie", "start")), // Finn Farmer, George new QuestCompletedCondition("coded_message"), // Marianne, Deniran City S new QuestCompletedCondition("eggs_for_marianne") ))); // quests about finding people achievements.add(createAchievement( ID_PRIVATE_DETECTIVE, "Private Detective", "Find all lost and hidden people", Achievement.HARD_BASE_SCORE, true, new AndCondition( // Rat Children (Agnus) new QuestCompletedCondition("find_rat_kids"), // Find Ghosts (Carena) new QuestCompletedCondition("find_ghosts"), // Meet Angels (any of the cherubs) new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { if (!player.hasQuest("seven_cherubs")) { return false; } final String npcDoneText = player.getQuest("seven_cherubs"); final String[] done = npcDoneText.split(";"); final int left = 7 - done.length; return left < 0; } }, // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom"), // Elias Breland, Deniran new QuestCompletedCondition(AGrandfathersWish.QUEST_SLOT) ))); // earn over 250 karma achievements.add(createAchievement( ID_GOOD_SAMARITAN, "Good Samaritan", "Earn a very good karma", Achievement.MEDIUM_BASE_SCORE, true, new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { return player.getKarma() > 250; } })); // meet Santa Claus and Easter Bunny achievements.add(createAchievement( ID_STILL_BELIEVING, "Still Believing", "Meet Santa Claus and Easter Bunny", Achievement.EASY_BASE_SCORE, true, new AndCondition( new QuestWithPrefixCompletedCondition("meet_santa_"), new QuestWithPrefixCompletedCondition("meet_bunny_")))); return achievements; } }
AntumDeluge/arianne-stendhal
src/games/stendhal/server/core/rp/achievement/factory/FriendAchievementFactory.java
1,437
// Annie, Kalavan city gardens
line_comment
nl
/*************************************************************************** * (C) Copyright 2003-2023 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.core.rp.achievement.factory; import java.util.Collection; import java.util.LinkedList; import games.stendhal.common.parser.Sentence; import games.stendhal.server.core.rp.achievement.Achievement; import games.stendhal.server.core.rp.achievement.Category; import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.npc.ChatCondition; import games.stendhal.server.entity.npc.condition.AndCondition; import games.stendhal.server.entity.npc.condition.QuestActiveCondition; import games.stendhal.server.entity.npc.condition.QuestCompletedCondition; import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition; import games.stendhal.server.entity.npc.condition.QuestStartedCondition; import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition; import games.stendhal.server.entity.player.Player; import games.stendhal.server.maps.quests.AGrandfathersWish; /** * Factory for quest achievements * * @author kymara */ public class FriendAchievementFactory extends AbstractAchievementFactory { public static final String ID_CHILD_FRIEND = "friend.quests.children"; public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find"; public static final String ID_GOOD_SAMARITAN = "friend.karma.250"; public static final String ID_STILL_BELIEVING = "friend.meet.seasonal"; @Override protected Category getCategory() { return Category.FRIEND; } @Override public Collection<Achievement> createAchievements() { final LinkedList<Achievement> achievements = new LinkedList<Achievement>(); // Befriend Susi and complete quests for all children achievements.add(createAchievement( ID_CHILD_FRIEND, "Childrens' Friend", "Complete quests for all children", Achievement.MEDIUM_BASE_SCORE, true, new AndCondition( // Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java) new QuestStartedCondition("susi"), // Help Tad, Semos Town Hall (Medicine for Tad) new QuestCompletedCondition("introduce_players"), // Plink, Semos Plains North new QuestCompletedCondition("plinks_toy"), // Anna, in Ados new QuestCompletedCondition("toys_collector"), // Sally, Orril River new QuestCompletedCondition("campfire"), // Annie, Kalavan<SUF> new QuestStateStartsWithCondition("icecream_for_annie","eating;"), // Elisabeth, Kirdneh new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"), // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom"), // Hughie, Ados farmhouse new AndCondition( new QuestActiveCondition("fishsoup_for_hughie"), new QuestNotInStateCondition("fishsoup_for_hughie", "start")), // Finn Farmer, George new QuestCompletedCondition("coded_message"), // Marianne, Deniran City S new QuestCompletedCondition("eggs_for_marianne") ))); // quests about finding people achievements.add(createAchievement( ID_PRIVATE_DETECTIVE, "Private Detective", "Find all lost and hidden people", Achievement.HARD_BASE_SCORE, true, new AndCondition( // Rat Children (Agnus) new QuestCompletedCondition("find_rat_kids"), // Find Ghosts (Carena) new QuestCompletedCondition("find_ghosts"), // Meet Angels (any of the cherubs) new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { if (!player.hasQuest("seven_cherubs")) { return false; } final String npcDoneText = player.getQuest("seven_cherubs"); final String[] done = npcDoneText.split(";"); final int left = 7 - done.length; return left < 0; } }, // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom"), // Elias Breland, Deniran new QuestCompletedCondition(AGrandfathersWish.QUEST_SLOT) ))); // earn over 250 karma achievements.add(createAchievement( ID_GOOD_SAMARITAN, "Good Samaritan", "Earn a very good karma", Achievement.MEDIUM_BASE_SCORE, true, new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { return player.getKarma() > 250; } })); // meet Santa Claus and Easter Bunny achievements.add(createAchievement( ID_STILL_BELIEVING, "Still Believing", "Meet Santa Claus and Easter Bunny", Achievement.EASY_BASE_SCORE, true, new AndCondition( new QuestWithPrefixCompletedCondition("meet_santa_"), new QuestWithPrefixCompletedCondition("meet_bunny_")))); return achievements; } }
207261_0
package laura; import net.xqhs.flash.FlashBoot; /** * Deployment testing. */ public class Boot { /** * Performs test. * * @param args * - not used. */ public static void main(String[] args) { String test_args = ""; // test_args += " -package laura"; // test_args += " -node main"; // test_args += " -support ros classpath:net.xqhs.flash.ros.RosSupport connect-to:ws://localhost:9090"; // test_args += " -agent AgentA classpath:AgentPingPong sendTo:AgentB"; // test_args += " -agent AgentB classpath:AgentPingPong"; test_args += " -package laura"; test_args += " -node nodeA"; test_args += " -support ros classpath:net.xqhs.flash.ros.RosSupport connect-to:ws://localhost:9090"; test_args += " -agent agentA1 classpath:AgentPingPong sendTo:agentA2 sendTo:agentB2"; test_args += " -agent agentA2 classpath:AgentPingPong"; test_args += " -node nodeB"; test_args += " -support ros classpath:net.xqhs.flash.ros.RosSupport connect-to:ws://localhost:9090"; test_args += " -agent agentB1 classpath:AgentPingPong sendTo:agentB2"; test_args += " -agent agentB2 classpath:AgentPingPong"; FlashBoot.main(test_args.split(" ")); } }
andreiolaru-ro/FLASH-MAS
src-experiments/laura/Boot.java
417
/** * Deployment testing. */
block_comment
nl
package laura; import net.xqhs.flash.FlashBoot; /** * Deployment testing. <SUF>*/ public class Boot { /** * Performs test. * * @param args * - not used. */ public static void main(String[] args) { String test_args = ""; // test_args += " -package laura"; // test_args += " -node main"; // test_args += " -support ros classpath:net.xqhs.flash.ros.RosSupport connect-to:ws://localhost:9090"; // test_args += " -agent AgentA classpath:AgentPingPong sendTo:AgentB"; // test_args += " -agent AgentB classpath:AgentPingPong"; test_args += " -package laura"; test_args += " -node nodeA"; test_args += " -support ros classpath:net.xqhs.flash.ros.RosSupport connect-to:ws://localhost:9090"; test_args += " -agent agentA1 classpath:AgentPingPong sendTo:agentA2 sendTo:agentB2"; test_args += " -agent agentA2 classpath:AgentPingPong"; test_args += " -node nodeB"; test_args += " -support ros classpath:net.xqhs.flash.ros.RosSupport connect-to:ws://localhost:9090"; test_args += " -agent agentB1 classpath:AgentPingPong sendTo:agentB2"; test_args += " -agent agentB2 classpath:AgentPingPong"; FlashBoot.main(test_args.split(" ")); } }
214306_0
package com.magictool.web.util; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.Map; /** * 用于生成和验证 token 的工具类 * @author lijf */ public class JwtUtils { /** * token 过期时间 */ public static final long TOKEN_EXPIRED_TIME = 1000 * 60 * 60 * 24L; /** * 签发ID */ public static final String ISSUE_ID = "admin"; /** * userId 标识 */ public static final String USER_ID = "userId"; /** * 加密/解密 密钥 */ private static final String JWT_SECRET = "HS256/MD5"; /** * 创建token * @param claims 载荷 * @param time token时长 * @return String */ public static String createJwt(Map<String, Object> claims, Long time) { // 指定签名的时候使用的签名算法 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; Date now = new Date(System.currentTimeMillis()); long nowMillis = System.currentTimeMillis(); JwtBuilder builder = Jwts.builder() .setClaims(claims) .setId(ISSUE_ID) .setIssuedAt(now) .signWith(signatureAlgorithm, JWT_SECRET); if (time >= 0) { long expMillis = nowMillis + time; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); } /** * 通过 token 获取 userId * * @param token token * @return userId */ public static String getUserId(String token){ Claims claims = verifyJwt(token); return claims.get(USER_ID) + ""; } /** * 验证Token,如果返回null说明token无效或过期 * * @param token token令牌 * @return Claims */ public static Claims verifyJwt(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(JWT_SECRET) .parseClaimsJws(token).getBody(); } catch (Exception e) { claims = null; } return claims; } /** * 生成token * * @param data 载荷 * @return String */ public static String generateToken(Map<String, Object> data) { return createJwt(data, TOKEN_EXPIRED_TIME); } }
james-ljf/magic-tool
src/main/java/com/magictool/web/util/JwtUtils.java
678
/** * 用于生成和验证 token 的工具类 * @author lijf */
block_comment
nl
package com.magictool.web.util; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.Map; /** * 用于生成和验证 token 的工具类<SUF>*/ public class JwtUtils { /** * token 过期时间 */ public static final long TOKEN_EXPIRED_TIME = 1000 * 60 * 60 * 24L; /** * 签发ID */ public static final String ISSUE_ID = "admin"; /** * userId 标识 */ public static final String USER_ID = "userId"; /** * 加密/解密 密钥 */ private static final String JWT_SECRET = "HS256/MD5"; /** * 创建token * @param claims 载荷 * @param time token时长 * @return String */ public static String createJwt(Map<String, Object> claims, Long time) { // 指定签名的时候使用的签名算法 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; Date now = new Date(System.currentTimeMillis()); long nowMillis = System.currentTimeMillis(); JwtBuilder builder = Jwts.builder() .setClaims(claims) .setId(ISSUE_ID) .setIssuedAt(now) .signWith(signatureAlgorithm, JWT_SECRET); if (time >= 0) { long expMillis = nowMillis + time; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); } /** * 通过 token 获取 userId * * @param token token * @return userId */ public static String getUserId(String token){ Claims claims = verifyJwt(token); return claims.get(USER_ID) + ""; } /** * 验证Token,如果返回null说明token无效或过期 * * @param token token令牌 * @return Claims */ public static Claims verifyJwt(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(JWT_SECRET) .parseClaimsJws(token).getBody(); } catch (Exception e) { claims = null; } return claims; } /** * 生成token * * @param data 载荷 * @return String */ public static String generateToken(Map<String, Object> data) { return createJwt(data, TOKEN_EXPIRED_TIME); } }
134888_0
// Chapter 7 version. package sparc; class InFrame extends frame.Access { int offset; InFrame(int o) {offset=o;} // Here the base pointer will be the frame pointer. public tree.Exp exp(tree.Exp basePtr) { return new tree.MEM( new tree.BINOP(tree.BINOP.PLUS, basePtr, new tree.CONST(offset))); } } class InReg extends frame.Access { temp.Temp temp; InReg(temp.Temp t) {temp=t;} public tree.Exp exp(tree.Exp basePtr) { return new tree.TEMP(temp); } } public class SparcFrame extends frame.Frame { // Incoming argument registers static final temp.Temp [] incomingArgs = new temp.Temp[6]; // A static initializer static { for (int i = 0; i < 6; i++) { incomingArgs[i] = new temp.Temp(); } } // Return value public temp.Temp RVCallee() {return incomingArgs[0];} // Frame pointer static final temp.Temp fp = new temp.Temp(); public temp.Temp FP() {return fp;} // Define the "color" of precolored temps (pp. 198, 251). public String tempMap(temp.Temp temp) { // This code could be made more efficient... for (int i = 0; i < 6; i++) if (temp == incomingArgs[i]) return "%i" + i; if (temp == fp) return "%fp"; return null; } public int wordSize() {return 4;} public tree.Exp externalCall(String s, tree.ExpList args) { return new tree.CALL(new tree.NAME(new temp.Label(s)), args); } public frame.Frame newFrame(temp.Label name, util.BoolList formals) { sparc.SparcFrame frame = new SparcFrame(); frame.formals = frame.argsAccesses(0, formals); frame.name = name; return (frame.Frame) frame; } // mover holds the code needed to move register arguments from the // registers where they arrive (i.e. %i0 through %i5) to the place where // they will be accessed by the function body. (Since MiniJava doesn't // have escaping variables, mover will typically be null.) tree.Stm mover = null; // Returns a Frame.Access for each argument of the function, taking note // of whether the argument escapes or not. As a side effect, updates // mover. See pp. 126-130, 155-158, 251. frame.AccessList argsAccesses(int i, util.BoolList formals) { // i is the number of the argument currently being processed. if (formals == null) return null; else if (i >= 6) // The argument will arrive on the stack. return new frame.AccessList(new InFrame(68+4*i), argsAccesses(i+1, formals.tail)); else if (formals.head) { // The argument escapes, and hence needs to be accessed from the stack. // But it initially arrives in a register, and so we have to generate // code to move it onto the stack. tree.Exp src = new tree.TEMP(incomingArgs[i]); frame.Access arg = new InFrame(68+4*i); if (mover == null) mover = new tree.MOVE(arg.exp(new tree.TEMP(FP())), src); else mover = new tree.SEQ(mover, new tree.MOVE(arg.exp(new tree.TEMP(FP())), src)); return new frame.AccessList(arg, argsAccesses(i+1, formals.tail)); } else // The argument does not escape, and can be gotten from a register. // Since the SPARC's register windows prevent the kind of interference // described by Appel on page 129, I allow the argument to be accessed // from the register in which it arrives. // [But note that if we had a good register allocator, it might be // better to move the argument to a fresh register anyway, since // this would enable the register allocator to optimize the use // of the registers. For instance, if the argument arriving in an // input register is not used much, it might be better to move it to // the stack, thereby freeing up the input register for other uses.] return new frame.AccessList(new InReg(incomingArgs[i]), argsAccesses(i+1, formals.tail)); } // How many locals have been allocated on the stack in this frame? int localsCount = 0; public frame.Access allocLocal(boolean escape) { if (escape) return new InFrame(-wordSize()*(++localsCount)); else return new InReg(new temp.Temp()); } public tree.Stm procEntryExit1(tree.Stm body) { // pp. 156-157, 251 // If we generated code here to save and restore callee-save registers, // we could make use of 7 more registers: %g2 -- %g7 and %i7. if (mover == null) return body; else return new tree.SEQ(mover, body); } }
jrivera777/Compiler-Project
minijava/chap7/sparc/SparcFrame.java
1,371
// Chapter 7 version.
line_comment
nl
// Chapter 7<SUF> package sparc; class InFrame extends frame.Access { int offset; InFrame(int o) {offset=o;} // Here the base pointer will be the frame pointer. public tree.Exp exp(tree.Exp basePtr) { return new tree.MEM( new tree.BINOP(tree.BINOP.PLUS, basePtr, new tree.CONST(offset))); } } class InReg extends frame.Access { temp.Temp temp; InReg(temp.Temp t) {temp=t;} public tree.Exp exp(tree.Exp basePtr) { return new tree.TEMP(temp); } } public class SparcFrame extends frame.Frame { // Incoming argument registers static final temp.Temp [] incomingArgs = new temp.Temp[6]; // A static initializer static { for (int i = 0; i < 6; i++) { incomingArgs[i] = new temp.Temp(); } } // Return value public temp.Temp RVCallee() {return incomingArgs[0];} // Frame pointer static final temp.Temp fp = new temp.Temp(); public temp.Temp FP() {return fp;} // Define the "color" of precolored temps (pp. 198, 251). public String tempMap(temp.Temp temp) { // This code could be made more efficient... for (int i = 0; i < 6; i++) if (temp == incomingArgs[i]) return "%i" + i; if (temp == fp) return "%fp"; return null; } public int wordSize() {return 4;} public tree.Exp externalCall(String s, tree.ExpList args) { return new tree.CALL(new tree.NAME(new temp.Label(s)), args); } public frame.Frame newFrame(temp.Label name, util.BoolList formals) { sparc.SparcFrame frame = new SparcFrame(); frame.formals = frame.argsAccesses(0, formals); frame.name = name; return (frame.Frame) frame; } // mover holds the code needed to move register arguments from the // registers where they arrive (i.e. %i0 through %i5) to the place where // they will be accessed by the function body. (Since MiniJava doesn't // have escaping variables, mover will typically be null.) tree.Stm mover = null; // Returns a Frame.Access for each argument of the function, taking note // of whether the argument escapes or not. As a side effect, updates // mover. See pp. 126-130, 155-158, 251. frame.AccessList argsAccesses(int i, util.BoolList formals) { // i is the number of the argument currently being processed. if (formals == null) return null; else if (i >= 6) // The argument will arrive on the stack. return new frame.AccessList(new InFrame(68+4*i), argsAccesses(i+1, formals.tail)); else if (formals.head) { // The argument escapes, and hence needs to be accessed from the stack. // But it initially arrives in a register, and so we have to generate // code to move it onto the stack. tree.Exp src = new tree.TEMP(incomingArgs[i]); frame.Access arg = new InFrame(68+4*i); if (mover == null) mover = new tree.MOVE(arg.exp(new tree.TEMP(FP())), src); else mover = new tree.SEQ(mover, new tree.MOVE(arg.exp(new tree.TEMP(FP())), src)); return new frame.AccessList(arg, argsAccesses(i+1, formals.tail)); } else // The argument does not escape, and can be gotten from a register. // Since the SPARC's register windows prevent the kind of interference // described by Appel on page 129, I allow the argument to be accessed // from the register in which it arrives. // [But note that if we had a good register allocator, it might be // better to move the argument to a fresh register anyway, since // this would enable the register allocator to optimize the use // of the registers. For instance, if the argument arriving in an // input register is not used much, it might be better to move it to // the stack, thereby freeing up the input register for other uses.] return new frame.AccessList(new InReg(incomingArgs[i]), argsAccesses(i+1, formals.tail)); } // How many locals have been allocated on the stack in this frame? int localsCount = 0; public frame.Access allocLocal(boolean escape) { if (escape) return new InFrame(-wordSize()*(++localsCount)); else return new InReg(new temp.Temp()); } public tree.Stm procEntryExit1(tree.Stm body) { // pp. 156-157, 251 // If we generated code here to save and restore callee-save registers, // we could make use of 7 more registers: %g2 -- %g7 and %i7. if (mover == null) return body; else return new tree.SEQ(mover, body); } }
48083_1
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.core.config; import java.util.Locale; import net.minecraftforge.oredict.OreDictionary; public class Defaults { // System public static final String MOD = "Forestry"; public static final String ID = MOD.toLowerCase(Locale.ENGLISH); public static final String URL = "http://forestry.sengir.net/"; public static final int WILDCARD = OreDictionary.WILDCARD_VALUE; public static final int WORLD_HEIGHT = 256; public static final int FLAG_BLOCK_UPDATE = 1; public static final int FLAG_BLOCK_SYNCH = 2; public static final int NET_MAX_UPDATE_DISTANCE = 50; public static final String DEFAULT_POWER_FRAMEWORK = "forestry.energy.BioPowerFramework"; public static final int BUCKET_VOLUME = 1000; public static final int[] FACINGS = { 0, 1, 2, 3, 4, 5 }; public static final int FACING_UP = 1; public static final int FACING_DOWN = 0; public static final int FACING_NORTH = 2; public static final int FACING_SOUTH = 3; public static final int FACING_WEST = 4; public static final int FACING_EAST = 5; public static final int[] FACING_SIDES = { FACING_NORTH, FACING_SOUTH, FACING_WEST, FACING_EAST }; public static final int[] FACING_NORTHSOUTH = { FACING_NORTH, FACING_SOUTH }; public static final int[] FACING_WESTEAST = { FACING_WEST, FACING_EAST }; public static final int[] FACINGS_NONE = new int[0]; public static final String LIQUID_WATER = "water"; public static final String LIQUID_LAVA = "lava"; public static final String LIQUID_MILK = "milk"; public static final String LIQUID_BIOMASS = "biomass"; public static final String LIQUID_ETHANOL = "bioethanol"; public static final String LIQUID_SEEDOIL = "seedoil"; public static final String LIQUID_HONEY = "honey"; public static final String LIQUID_JUICE = "juice"; public static final String LIQUID_ICE = "ice"; public static final String LIQUID_MEAD = "short.mead"; public static final String LIQUID_GLASS = "glass"; public static final String LIQUID_OIL = "oil"; public static final String LIQUID_FUEL = "fuel"; // Textures public static final String TEXTURE_PATH_GUI = "textures/gui"; public static final String TEXTURE_PATH_BLOCKS = "textures/blocks"; public static final String TEXTURE_PATH_ITEMS = "textures/items"; public static final String TEXTURE_PATH_ENTITIES = "textures/entity"; public static final String TEXTURE_BLOCKS = TEXTURE_PATH_BLOCKS + "/blocks.png"; public static final String TEXTURE_ARBORICULTURE = TEXTURE_PATH_BLOCKS + "/arboriculture.png"; public static final String TEXTURE_PODS = TEXTURE_PATH_BLOCKS + "/pods.png"; public static final String TEXTURE_FARM = TEXTURE_PATH_BLOCKS + "/farm.png"; public static final String TEXTURE_APIARIST_ARMOR_PRIMARY = TEXTURE_PATH_ITEMS + "/apiarist_armor_1.png"; public static final String TEXTURE_APIARIST_ARMOR_SECONDARY = TEXTURE_PATH_ITEMS + "/apiarist_armor_2.png"; public static final String TEXTURE_NATURALIST_ARMOR_PRIMARY = TEXTURE_PATH_ITEMS + "/naturalist_armor_1.png"; public static final String TEXTURE_SKIN_BEEKPEEPER = TEXTURE_PATH_ENTITIES + "/beekeeper.png"; public static final String TEXTURE_SKIN_LUMBERJACK = TEXTURE_PATH_ENTITIES + "/lumberjack.png"; public static final String TEXTURE_ICONS_MINECRAFT = "/gui/items.png"; public static final String TEXTURE_BLOCKS_MINECRAFT = "/terrain.png"; // Villagers public static final int ID_VILLAGER_BEEKEEPER = 80; public static final int ID_VILLAGER_LUMBERJACK = 81; // Village Chest Gen hook public static final String CHEST_GEN_HOOK_NATURALIST_CHEST = "naturalistChest"; // Definition IDs public static final int DEFINITION_ANALYZER_META = 0; public static final int DEFINITION_ESCRITOIRE_META = 1; public static final int DEFINITION_APIARY_META = 0; public static final int DEFINITION_APIARISTCHEST_META = 1; public static final int DEFINITION_BEEHOUSE_META = 2; public static final int DEFINITION_ENGINETIN_META = 0; public static final int DEFINITION_ENGINECOPPER_META = 1; public static final int DEFINITION_ENGINEBRONZE_META = 2; public static final int DEFINITION_GENERATOR_META = 3; public static final int DEFINITION_ENGINECLOCKWORK_META = 4; public static final int DEFINITION_MAILBOX_META = 0; public static final int DEFINITION_TRADESTATION_META = 1; public static final int DEFINITION_PHILATELIST_META = 2; public static final int DEFINITION_BOTTLER_META = 0; public static final int DEFINITION_CARPENTER_META = 1; public static final int DEFINITION_CENTRIFUGE_META = 2; public static final int DEFINITION_FERMENTER_META = 3; public static final int DEFINITION_MOISTENER_META = 4; public static final int DEFINITION_SQUEEZER_META = 5; public static final int DEFINITION_STILL_META = 6; public static final int DEFINITION_RAINMAKER_META = 7; public static final int DEFINITION_FABRICATOR_META = 0; public static final int DEFINITION_RAINTANK_META = 1; public static final int DEFINITION_WORKTABLE_META = 2; public static final int DEFINITION_LEPICHEST_META = 0; public static final int DEFINITION_ARBCHEST_META = 0; // Package Ids public static final int ID_PACKAGE_MACHINE_FERMENTER = 0; public static final int ID_PACKAGE_MACHINE_STILL = 1; public static final int ID_PACKAGE_MACHINE_BOTTLER = 2; public static final int ID_PACKAGE_MACHINE_RAINTANK = 3; public static final int ID_PACKAGE_MACHINE_CARPENTER = 5; public static final int ID_PACKAGE_MACHINE_MOISTENER = 6; public static final int ID_PACKAGE_MACHINE_APIARY = 7; public static final int ID_PACKAGE_MACHINE_CENTRIFUGE = 8; public static final int ID_PACKAGE_MACHINE_SQUEEZER = 9; public static final int ID_PACKAGE_MACHINE_ALVEARY = 10; public static final int ID_PACKAGE_MACHINE_FABRICATOR = 11; public static final int ID_PACKAGE_MILL_RAINMAKER = 1; public static final int ID_PACKAGE_MILL_APIARIST_CHEST = 3; public static final int ID_PACKAGE_MILL_ANALYZER = 4; public static final int ID_PACKAGE_MILL_MAILBOX = 5; public static final int ID_PACKAGE_MILL_TRADER = 6; public static final int ID_PACKAGE_MILL_PHILATELIST = 7; // Item Ids public static final int SLOTS_BACKPACK_DEFAULT = 15; public static final int SLOTS_BACKPACK_T2 = 45; public static final int SLOTS_BACKPACK_APIARIST = 125; // Bee ids public static final int ID_BEE_SPECIES_REDDENED = 31; public static final int ID_BEE_SPECIES_DARKENED = 32; public static final int ID_BEE_SPECIES_OMEGA = 33; // Food stuff public static final int FOOD_AMBROSIA_HEAL = 8; public static final int FOOD_JUICE_HEAL = 2; public static final float FOOD_JUICE_SATURATION = 0.2f; public static final int FOOD_HONEY_HEAL = 2; public static final float FOOD_HONEY_SATURATION = 0.2f; // IndustrialCraft 2 public static final int ID_IC2_FUELCAN_DAMAGE = 6480; // BuildCraft public static final int BUILDCRAFT_BLOCKID_ENGINE = 161; public static final int BUILDCRAFT_BLOCKID_PIPE = 166; public static final int APIARY_MIN_LEVEL_LIGHT = 11; public static final int APIARY_BREEDING_TIME = 100; // Energy public static final int ENGINE_TANK_CAPACITY = 10 * BUCKET_VOLUME; public static final int ENGINE_CYCLE_DURATION_WATER = 1000; public static final int ENGINE_CYCLE_DURATION_JUICE = 2500; public static final int ENGINE_CYCLE_DURATION_HONEY = 2500; public static final int ENGINE_CYCLE_DURATION_MILK = 10000; public static final int ENGINE_CYCLE_DURATION_SEED_OIL = 2500; public static final int ENGINE_CYCLE_DURATION_BIOMASS = 2500; public static final int ENGINE_CYCLE_DURATION_ETHANOL = 15000; public static final int ENGINE_FUEL_VALUE_WATER = 1; public static final int ENGINE_FUEL_VALUE_JUICE = 1; public static final int ENGINE_FUEL_VALUE_HONEY = 2; public static final int ENGINE_FUEL_VALUE_MILK = 1; public static final int ENGINE_FUEL_VALUE_SEED_OIL = 3; public static final int ENGINE_FUEL_VALUE_BIOMASS = 5; public static final int ENGINE_HEAT_VALUE_LAVA = 20; public static final float ENGINE_PISTON_SPEED_MAX = 0.08f; public static final int ENGINE_BRONZE_HEAT_MAX = 10000; public static final int ENGINE_BRONZE_HEAT_LOSS_COOL = 2; public static final int ENGINE_BRONZE_HEAT_LOSS_OPERATING = 1; public static final int ENGINE_BRONZE_HEAT_LOSS_OVERHEATING = 5; public static final int ENGINE_BRONZE_HEAT_GENERATION_ENERGY = 1; public static final int ENGINE_COPPER_CYCLE_DURATION_PEAT = 5000; public static final int ENGINE_COPPER_FUEL_VALUE_PEAT = 1; public static final int ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT = 6000; public static final int ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT = 2; public static final int ENGINE_COPPER_HEAT_MAX = 10000; public static final int ENGINE_COPPER_ASH_FOR_ITEM = 7500; public static final int ENGINE_TIN_HEAT_MAX = 3000; public static final int ENGINE_TIN_EU_FOR_CYCLE = 6; public static final int ENGINE_TIN_ENERGY_PER_CYCLE = 2; public static final int ENGINE_TIN_MAX_EU_STORED = 2 * ENGINE_TIN_EU_FOR_CYCLE; public static final int ENGINE_TIN_MAX_EU_BATTERY = 100; // Factory public static final int PROCESSOR_TANK_CAPACITY = 10 * BUCKET_VOLUME; public static final int MACHINE_LATENCY = 1000; public static final int MACHINE_MIN_ENERGY_RECEIVED = 5; public static final int MACHINE_MAX_ENERGY_RECEIVED = 40; public static final int MACHINE_MIN_ACTIVATION_ENERGY = 15; public static final int MACHINE_MAX_ENERGY = 500; public static final int RAINMAKER_RAIN_DURATION_IODINE = 10000; public static final int STILL_DESTILLATION_DURATION = 100; public static final int STILL_DESTILLATION_INPUT = 10; public static final int STILL_DESTILLATION_OUTPUT = 3; public static final int BOTTLER_FILLING_TIME = 20; public static final int BOTTLER_FUELCAN_VOLUME = 2000; // Storage public static final int RAINTANK_TANK_CAPACITY = 30 * BUCKET_VOLUME; public static final int RAINTANK_AMOUNT_PER_UPDATE = 10; public static final int RAINTANK_FILLING_TIME = 12; public static final int CARPENTER_CRATING_CYCLES = 5; public static final int CARPENTER_UNCRATING_CYCLES = 5; public static final int CARPENTER_CRATING_LIQUID_QUANTITY = 100; // SMP gui ids public static final int ID_GUI_ARBORETUM = 90; public static final int ID_GUI_BOTTLER = 91; public static final int ID_GUI_ENGINE_BRONZE = 92; public static final int ID_GUI_FARM = 93; public static final int ID_GUI_FERMENTER = 94; public static final int ID_GUI_FORESTER = 95; public static final int ID_GUI_PLANTATION = 96; public static final int ID_GUI_PUMPKIN_FARM = 97; public static final int ID_GUI_PEAT_BOG = 98; public static final int ID_GUI_STILL = 99; public static final int ID_GUI_ENGINE_COPPER = 89; public static final int ID_GUI_RAINTANK = 88; public static final int ID_GUI_GENERATOR = 87; public static final int ID_GUI_CARPENTER = 86; public static final int ID_GUI_MOISTENER = 85; public static final int ID_GUI_MUSHROOM_FARM = 84; public static final int ID_GUI_APIARY = 83; public static final int ID_GUI_CENTRIFUGE = 82; public static final int ID_GUI_APIARIST_INVENTORY = 81; public static final int ID_GUI_BACKPACK = 80; public static final int ID_GUI_SQUEEZER = 79; public static final int ID_GUI_NETHER_FARM = 78; public static final int ID_GUI_BEEALYZER = 100; public static final int ID_GUI_BACKPACK_T2 = 101; public static final int ID_GUI_BIOME_FINDER = 102; // ID 100 used by bucket filler. }
jvantuyl/ForestryMC
forestry_common/core/forestry/core/config/Defaults.java
3,837
// Village Chest Gen hook
line_comment
nl
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.core.config; import java.util.Locale; import net.minecraftforge.oredict.OreDictionary; public class Defaults { // System public static final String MOD = "Forestry"; public static final String ID = MOD.toLowerCase(Locale.ENGLISH); public static final String URL = "http://forestry.sengir.net/"; public static final int WILDCARD = OreDictionary.WILDCARD_VALUE; public static final int WORLD_HEIGHT = 256; public static final int FLAG_BLOCK_UPDATE = 1; public static final int FLAG_BLOCK_SYNCH = 2; public static final int NET_MAX_UPDATE_DISTANCE = 50; public static final String DEFAULT_POWER_FRAMEWORK = "forestry.energy.BioPowerFramework"; public static final int BUCKET_VOLUME = 1000; public static final int[] FACINGS = { 0, 1, 2, 3, 4, 5 }; public static final int FACING_UP = 1; public static final int FACING_DOWN = 0; public static final int FACING_NORTH = 2; public static final int FACING_SOUTH = 3; public static final int FACING_WEST = 4; public static final int FACING_EAST = 5; public static final int[] FACING_SIDES = { FACING_NORTH, FACING_SOUTH, FACING_WEST, FACING_EAST }; public static final int[] FACING_NORTHSOUTH = { FACING_NORTH, FACING_SOUTH }; public static final int[] FACING_WESTEAST = { FACING_WEST, FACING_EAST }; public static final int[] FACINGS_NONE = new int[0]; public static final String LIQUID_WATER = "water"; public static final String LIQUID_LAVA = "lava"; public static final String LIQUID_MILK = "milk"; public static final String LIQUID_BIOMASS = "biomass"; public static final String LIQUID_ETHANOL = "bioethanol"; public static final String LIQUID_SEEDOIL = "seedoil"; public static final String LIQUID_HONEY = "honey"; public static final String LIQUID_JUICE = "juice"; public static final String LIQUID_ICE = "ice"; public static final String LIQUID_MEAD = "short.mead"; public static final String LIQUID_GLASS = "glass"; public static final String LIQUID_OIL = "oil"; public static final String LIQUID_FUEL = "fuel"; // Textures public static final String TEXTURE_PATH_GUI = "textures/gui"; public static final String TEXTURE_PATH_BLOCKS = "textures/blocks"; public static final String TEXTURE_PATH_ITEMS = "textures/items"; public static final String TEXTURE_PATH_ENTITIES = "textures/entity"; public static final String TEXTURE_BLOCKS = TEXTURE_PATH_BLOCKS + "/blocks.png"; public static final String TEXTURE_ARBORICULTURE = TEXTURE_PATH_BLOCKS + "/arboriculture.png"; public static final String TEXTURE_PODS = TEXTURE_PATH_BLOCKS + "/pods.png"; public static final String TEXTURE_FARM = TEXTURE_PATH_BLOCKS + "/farm.png"; public static final String TEXTURE_APIARIST_ARMOR_PRIMARY = TEXTURE_PATH_ITEMS + "/apiarist_armor_1.png"; public static final String TEXTURE_APIARIST_ARMOR_SECONDARY = TEXTURE_PATH_ITEMS + "/apiarist_armor_2.png"; public static final String TEXTURE_NATURALIST_ARMOR_PRIMARY = TEXTURE_PATH_ITEMS + "/naturalist_armor_1.png"; public static final String TEXTURE_SKIN_BEEKPEEPER = TEXTURE_PATH_ENTITIES + "/beekeeper.png"; public static final String TEXTURE_SKIN_LUMBERJACK = TEXTURE_PATH_ENTITIES + "/lumberjack.png"; public static final String TEXTURE_ICONS_MINECRAFT = "/gui/items.png"; public static final String TEXTURE_BLOCKS_MINECRAFT = "/terrain.png"; // Villagers public static final int ID_VILLAGER_BEEKEEPER = 80; public static final int ID_VILLAGER_LUMBERJACK = 81; // Village Chest<SUF> public static final String CHEST_GEN_HOOK_NATURALIST_CHEST = "naturalistChest"; // Definition IDs public static final int DEFINITION_ANALYZER_META = 0; public static final int DEFINITION_ESCRITOIRE_META = 1; public static final int DEFINITION_APIARY_META = 0; public static final int DEFINITION_APIARISTCHEST_META = 1; public static final int DEFINITION_BEEHOUSE_META = 2; public static final int DEFINITION_ENGINETIN_META = 0; public static final int DEFINITION_ENGINECOPPER_META = 1; public static final int DEFINITION_ENGINEBRONZE_META = 2; public static final int DEFINITION_GENERATOR_META = 3; public static final int DEFINITION_ENGINECLOCKWORK_META = 4; public static final int DEFINITION_MAILBOX_META = 0; public static final int DEFINITION_TRADESTATION_META = 1; public static final int DEFINITION_PHILATELIST_META = 2; public static final int DEFINITION_BOTTLER_META = 0; public static final int DEFINITION_CARPENTER_META = 1; public static final int DEFINITION_CENTRIFUGE_META = 2; public static final int DEFINITION_FERMENTER_META = 3; public static final int DEFINITION_MOISTENER_META = 4; public static final int DEFINITION_SQUEEZER_META = 5; public static final int DEFINITION_STILL_META = 6; public static final int DEFINITION_RAINMAKER_META = 7; public static final int DEFINITION_FABRICATOR_META = 0; public static final int DEFINITION_RAINTANK_META = 1; public static final int DEFINITION_WORKTABLE_META = 2; public static final int DEFINITION_LEPICHEST_META = 0; public static final int DEFINITION_ARBCHEST_META = 0; // Package Ids public static final int ID_PACKAGE_MACHINE_FERMENTER = 0; public static final int ID_PACKAGE_MACHINE_STILL = 1; public static final int ID_PACKAGE_MACHINE_BOTTLER = 2; public static final int ID_PACKAGE_MACHINE_RAINTANK = 3; public static final int ID_PACKAGE_MACHINE_CARPENTER = 5; public static final int ID_PACKAGE_MACHINE_MOISTENER = 6; public static final int ID_PACKAGE_MACHINE_APIARY = 7; public static final int ID_PACKAGE_MACHINE_CENTRIFUGE = 8; public static final int ID_PACKAGE_MACHINE_SQUEEZER = 9; public static final int ID_PACKAGE_MACHINE_ALVEARY = 10; public static final int ID_PACKAGE_MACHINE_FABRICATOR = 11; public static final int ID_PACKAGE_MILL_RAINMAKER = 1; public static final int ID_PACKAGE_MILL_APIARIST_CHEST = 3; public static final int ID_PACKAGE_MILL_ANALYZER = 4; public static final int ID_PACKAGE_MILL_MAILBOX = 5; public static final int ID_PACKAGE_MILL_TRADER = 6; public static final int ID_PACKAGE_MILL_PHILATELIST = 7; // Item Ids public static final int SLOTS_BACKPACK_DEFAULT = 15; public static final int SLOTS_BACKPACK_T2 = 45; public static final int SLOTS_BACKPACK_APIARIST = 125; // Bee ids public static final int ID_BEE_SPECIES_REDDENED = 31; public static final int ID_BEE_SPECIES_DARKENED = 32; public static final int ID_BEE_SPECIES_OMEGA = 33; // Food stuff public static final int FOOD_AMBROSIA_HEAL = 8; public static final int FOOD_JUICE_HEAL = 2; public static final float FOOD_JUICE_SATURATION = 0.2f; public static final int FOOD_HONEY_HEAL = 2; public static final float FOOD_HONEY_SATURATION = 0.2f; // IndustrialCraft 2 public static final int ID_IC2_FUELCAN_DAMAGE = 6480; // BuildCraft public static final int BUILDCRAFT_BLOCKID_ENGINE = 161; public static final int BUILDCRAFT_BLOCKID_PIPE = 166; public static final int APIARY_MIN_LEVEL_LIGHT = 11; public static final int APIARY_BREEDING_TIME = 100; // Energy public static final int ENGINE_TANK_CAPACITY = 10 * BUCKET_VOLUME; public static final int ENGINE_CYCLE_DURATION_WATER = 1000; public static final int ENGINE_CYCLE_DURATION_JUICE = 2500; public static final int ENGINE_CYCLE_DURATION_HONEY = 2500; public static final int ENGINE_CYCLE_DURATION_MILK = 10000; public static final int ENGINE_CYCLE_DURATION_SEED_OIL = 2500; public static final int ENGINE_CYCLE_DURATION_BIOMASS = 2500; public static final int ENGINE_CYCLE_DURATION_ETHANOL = 15000; public static final int ENGINE_FUEL_VALUE_WATER = 1; public static final int ENGINE_FUEL_VALUE_JUICE = 1; public static final int ENGINE_FUEL_VALUE_HONEY = 2; public static final int ENGINE_FUEL_VALUE_MILK = 1; public static final int ENGINE_FUEL_VALUE_SEED_OIL = 3; public static final int ENGINE_FUEL_VALUE_BIOMASS = 5; public static final int ENGINE_HEAT_VALUE_LAVA = 20; public static final float ENGINE_PISTON_SPEED_MAX = 0.08f; public static final int ENGINE_BRONZE_HEAT_MAX = 10000; public static final int ENGINE_BRONZE_HEAT_LOSS_COOL = 2; public static final int ENGINE_BRONZE_HEAT_LOSS_OPERATING = 1; public static final int ENGINE_BRONZE_HEAT_LOSS_OVERHEATING = 5; public static final int ENGINE_BRONZE_HEAT_GENERATION_ENERGY = 1; public static final int ENGINE_COPPER_CYCLE_DURATION_PEAT = 5000; public static final int ENGINE_COPPER_FUEL_VALUE_PEAT = 1; public static final int ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT = 6000; public static final int ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT = 2; public static final int ENGINE_COPPER_HEAT_MAX = 10000; public static final int ENGINE_COPPER_ASH_FOR_ITEM = 7500; public static final int ENGINE_TIN_HEAT_MAX = 3000; public static final int ENGINE_TIN_EU_FOR_CYCLE = 6; public static final int ENGINE_TIN_ENERGY_PER_CYCLE = 2; public static final int ENGINE_TIN_MAX_EU_STORED = 2 * ENGINE_TIN_EU_FOR_CYCLE; public static final int ENGINE_TIN_MAX_EU_BATTERY = 100; // Factory public static final int PROCESSOR_TANK_CAPACITY = 10 * BUCKET_VOLUME; public static final int MACHINE_LATENCY = 1000; public static final int MACHINE_MIN_ENERGY_RECEIVED = 5; public static final int MACHINE_MAX_ENERGY_RECEIVED = 40; public static final int MACHINE_MIN_ACTIVATION_ENERGY = 15; public static final int MACHINE_MAX_ENERGY = 500; public static final int RAINMAKER_RAIN_DURATION_IODINE = 10000; public static final int STILL_DESTILLATION_DURATION = 100; public static final int STILL_DESTILLATION_INPUT = 10; public static final int STILL_DESTILLATION_OUTPUT = 3; public static final int BOTTLER_FILLING_TIME = 20; public static final int BOTTLER_FUELCAN_VOLUME = 2000; // Storage public static final int RAINTANK_TANK_CAPACITY = 30 * BUCKET_VOLUME; public static final int RAINTANK_AMOUNT_PER_UPDATE = 10; public static final int RAINTANK_FILLING_TIME = 12; public static final int CARPENTER_CRATING_CYCLES = 5; public static final int CARPENTER_UNCRATING_CYCLES = 5; public static final int CARPENTER_CRATING_LIQUID_QUANTITY = 100; // SMP gui ids public static final int ID_GUI_ARBORETUM = 90; public static final int ID_GUI_BOTTLER = 91; public static final int ID_GUI_ENGINE_BRONZE = 92; public static final int ID_GUI_FARM = 93; public static final int ID_GUI_FERMENTER = 94; public static final int ID_GUI_FORESTER = 95; public static final int ID_GUI_PLANTATION = 96; public static final int ID_GUI_PUMPKIN_FARM = 97; public static final int ID_GUI_PEAT_BOG = 98; public static final int ID_GUI_STILL = 99; public static final int ID_GUI_ENGINE_COPPER = 89; public static final int ID_GUI_RAINTANK = 88; public static final int ID_GUI_GENERATOR = 87; public static final int ID_GUI_CARPENTER = 86; public static final int ID_GUI_MOISTENER = 85; public static final int ID_GUI_MUSHROOM_FARM = 84; public static final int ID_GUI_APIARY = 83; public static final int ID_GUI_CENTRIFUGE = 82; public static final int ID_GUI_APIARIST_INVENTORY = 81; public static final int ID_GUI_BACKPACK = 80; public static final int ID_GUI_SQUEEZER = 79; public static final int ID_GUI_NETHER_FARM = 78; public static final int ID_GUI_BEEALYZER = 100; public static final int ID_GUI_BACKPACK_T2 = 101; public static final int ID_GUI_BIOME_FINDER = 102; // ID 100 used by bucket filler. }
122450_31
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.IDN; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.validator.routines.DomainValidator.ArrayType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests for the DomainValidator. */ public class DomainValidatorTest { private static void closeQuietly(final Closeable in) { if (in != null) { try { in.close(); } catch (final IOException e) { } } } /* * Download a file if it is more recent than our cached copy. Unfortunately the server does not seem to honor If-Modified-Since for the Html page, so we * check if it is newer than the txt file and skip download if so */ private static long download(final File file, final String tldUrl, final long timestamp) throws IOException { final int HOUR = 60 * 60 * 1000; // an hour in ms final long modTime; // For testing purposes, don't download files more than once an hour if (file.canRead()) { modTime = file.lastModified(); if (modTime > System.currentTimeMillis() - HOUR) { System.out.println("Skipping download - found recent " + file); return modTime; } } else { modTime = 0; } final HttpURLConnection hc = (HttpURLConnection) new URL(tldUrl).openConnection(); if (modTime > 0) { final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");// Sun, 06 Nov 1994 08:49:37 GMT final String since = sdf.format(new Date(modTime)); hc.addRequestProperty("If-Modified-Since", since); System.out.println("Found " + file + " with date " + since); } if (hc.getResponseCode() == 304) { System.out.println("Already have most recent " + tldUrl); } else { System.out.println("Downloading " + tldUrl); try (InputStream is = hc.getInputStream()) { Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING); } System.out.println("Done"); } return file.lastModified(); } private static Map<String, String[]> getHtmlInfo(final File f) throws IOException { final Map<String, String[]> info = new HashMap<>(); // <td><span class="domain tld"><a href="/domains/root/db/ax.html">.ax</a></span></td> final Pattern domain = Pattern.compile(".*<a href=\"/domains/root/db/([^.]+)\\.html"); // <td>country-code</td> final Pattern type = Pattern.compile("\\s+<td>([^<]+)</td>"); // <!-- <td>Åland Islands<br/><span class="tld-table-so">Ålands landskapsregering</span></td> </td> --> // <td>Ålands landskapsregering</td> final Pattern comment = Pattern.compile("\\s+<td>([^<]+)</td>"); try (BufferedReader br = new BufferedReader(new FileReader(f))) { String line; while ((line = br.readLine()) != null) { final Matcher m = domain.matcher(line); if (m.lookingAt()) { final String dom = m.group(1); String typ = "??"; String com = "??"; line = br.readLine(); while (line.matches("^\\s*$")) { // extra blank lines introduced line = br.readLine(); } final Matcher t = type.matcher(line); if (t.lookingAt()) { typ = t.group(1); line = br.readLine(); if (line.matches("\\s+<!--.*")) { while (!line.matches(".*-->.*")) { line = br.readLine(); } line = br.readLine(); } // Should have comment; is it wrapped? while (!line.matches(".*</td>.*")) { line += " " + br.readLine(); } final Matcher n = comment.matcher(line); if (n.lookingAt()) { com = n.group(1); } // Don't save unused entries if (com.contains("Not assigned") || com.contains("Retired") || typ.equals("test")) { // System.out.println("Ignored: " + typ + " " + dom + " " +com); } else { info.put(dom.toLowerCase(Locale.ENGLISH), new String[] { typ, com }); // System.out.println("Storing: " + typ + " " + dom + " " +com); } } else { System.err.println("Unexpected type: " + line); } } } } return info; } // isInIanaList and isSorted are split into two methods. // If/when access to the arrays is possible without reflection, the intermediate // methods can be dropped private static boolean isInIanaList(final String arrayName, final Set<String> ianaTlds) throws Exception { final Field f = DomainValidator.class.getDeclaredField(arrayName); final boolean isPrivate = Modifier.isPrivate(f.getModifiers()); if (isPrivate) { f.setAccessible(true); } final String[] array = (String[]) f.get(null); try { return isInIanaList(arrayName, array, ianaTlds); } finally { if (isPrivate) { f.setAccessible(false); } } } private static boolean isInIanaList(final String name, final String[] array, final Set<String> ianaTlds) { for (final String element : array) { if (!ianaTlds.contains(element)) { System.out.println(name + " contains unexpected value: " + element); } } return true; } private static boolean isLowerCase(final String string) { return string.equals(string.toLowerCase(Locale.ENGLISH)); } /** * Check whether the domain is in the root zone currently. Reads the URL http://www.iana.org/domains/root/db/*domain*.html (using a local disk cache) and * checks for the string "This domain is not present in the root zone at this time." * * @param domain the domain to check * @return true if the string is found */ private static boolean isNotInRootZone(final String domain) { final String tldUrl = "http://www.iana.org/domains/root/db/" + domain + ".html"; final File rootCheck = new File("target", "tld_" + domain + ".html"); BufferedReader in = null; try { download(rootCheck, tldUrl, 0L); in = new BufferedReader(new FileReader(rootCheck)); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("This domain is not present in the root zone at this time.")) { return true; } } in.close(); } catch (final IOException e) { } finally { closeQuietly(in); } return false; } private static boolean isSortedLowerCase(final String arrayName) throws Exception { final Field f = DomainValidator.class.getDeclaredField(arrayName); final boolean isPrivate = Modifier.isPrivate(f.getModifiers()); if (isPrivate) { f.setAccessible(true); } final String[] array = (String[]) f.get(null); try { return isSortedLowerCase(arrayName, array); } finally { if (isPrivate) { f.setAccessible(false); } } } // Check if an array is strictly sorted - and lowerCase private static boolean isSortedLowerCase(final String name, final String[] array) { boolean sorted = true; boolean strictlySorted = true; final int length = array.length; boolean lowerCase = isLowerCase(array[length - 1]); // Check the last entry for (int i = 0; i < length - 1; i++) { // compare all but last entry with next final String entry = array[i]; final String nextEntry = array[i + 1]; final int cmp = entry.compareTo(nextEntry); if (cmp > 0) { // out of order System.out.println("Out of order entry: " + entry + " < " + nextEntry + " in " + name); sorted = false; } else if (cmp == 0) { strictlySorted = false; System.out.println("Duplicated entry: " + entry + " in " + name); } if (!isLowerCase(entry)) { System.out.println("Non lowerCase entry: " + entry + " in " + name); lowerCase = false; } } return sorted && strictlySorted && lowerCase; } // Download and process local copy of https://data.iana.org/TLD/tlds-alpha-by-domain.txt // Check if the internal TLD table is up to date // Check if the internal TLD tables have any spurious entries public static void main(final String a[]) throws Exception { // Check the arrays first as this affects later checks // Doing this here makes it easier when updating the lists boolean OK = true; for (final String list : new String[] { "INFRASTRUCTURE_TLDS", "COUNTRY_CODE_TLDS", "GENERIC_TLDS", "LOCAL_TLDS" }) { OK &= isSortedLowerCase(list); } if (!OK) { System.out.println("Fix arrays before retrying; cannot continue"); return; } final Set<String> ianaTlds = new HashSet<>(); // keep for comparison with array contents final DomainValidator dv = DomainValidator.getInstance(); final File txtFile = new File("target/tlds-alpha-by-domain.txt"); final long timestamp = download(txtFile, "https://data.iana.org/TLD/tlds-alpha-by-domain.txt", 0L); final File htmlFile = new File("target/tlds-alpha-by-domain.html"); // N.B. sometimes the html file may be updated a day or so after the txt file // if the txt file contains entries not found in the html file, try again in a day or two download(htmlFile, "https://www.iana.org/domains/root/db", timestamp); final BufferedReader br = new BufferedReader(new FileReader(txtFile)); String line; final String header; line = br.readLine(); // header if (!line.startsWith("# Version ")) { br.close(); throw new IOException("File does not have expected Version header"); } header = line.substring(2); final boolean generateUnicodeTlds = false; // Change this to generate Unicode TLDs as well // Parse html page to get entries final Map<String, String[]> htmlInfo = getHtmlInfo(htmlFile); final Map<String, String> missingTLD = new TreeMap<>(); // stores entry and comments as String[] final Map<String, String> missingCC = new TreeMap<>(); while ((line = br.readLine()) != null) { if (!line.startsWith("#")) { final String unicodeTld; // only different from asciiTld if that was punycode final String asciiTld = line.toLowerCase(Locale.ENGLISH); if (line.startsWith("XN--")) { unicodeTld = IDN.toUnicode(line); } else { unicodeTld = asciiTld; } if (!dv.isValidTld(asciiTld)) { final String[] info = htmlInfo.get(asciiTld); if (info != null) { final String type = info[0]; final String comment = info[1]; if ("country-code".equals(type)) { // Which list to use? missingCC.put(asciiTld, unicodeTld + " " + comment); if (generateUnicodeTlds) { missingCC.put(unicodeTld, asciiTld + " " + comment); } } else { missingTLD.put(asciiTld, unicodeTld + " " + comment); if (generateUnicodeTlds) { missingTLD.put(unicodeTld, asciiTld + " " + comment); } } } else { System.err.println("Expected to find HTML info for " + asciiTld); } } ianaTlds.add(asciiTld); // Don't merge these conditions; generateUnicodeTlds is final so needs to be separate to avoid a warning if (generateUnicodeTlds && !unicodeTld.equals(asciiTld)) { ianaTlds.add(unicodeTld); } } } br.close(); // List html entries not in TLD text list for (final String key : new TreeMap<>(htmlInfo).keySet()) { if (!ianaTlds.contains(key)) { if (isNotInRootZone(key)) { System.out.println("INFO: HTML entry not yet in root zone: " + key); } else { System.err.println("WARN: Expected to find text entry for html: " + key); } } } if (!missingTLD.isEmpty()) { printMap(header, missingTLD, "GENERIC_TLDS"); } if (!missingCC.isEmpty()) { printMap(header, missingCC, "COUNTRY_CODE_TLDS"); } // Check if internal tables contain any additional entries isInIanaList("INFRASTRUCTURE_TLDS", ianaTlds); isInIanaList("COUNTRY_CODE_TLDS", ianaTlds); isInIanaList("GENERIC_TLDS", ianaTlds); // Don't check local TLDS isInIanaList("LOCAL_TLDS", ianaTlds); System.out.println("Finished checks"); } private static void printMap(final String header, final Map<String, String> map, final String string) { System.out.println("Entries missing from " + string + " List\n"); if (header != null) { System.out.println(" // Taken from " + header); } for (final Entry<String, String> me : map.entrySet()) { System.out.println(" \"" + me.getKey() + "\", // " + me.getValue()); } System.out.println("\nDone"); } private DomainValidator validator; @BeforeEach public void setUp() { validator = DomainValidator.getInstance(); } // Check array is sorted and is lower-case @Test public void test_COUNTRY_CODE_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("COUNTRY_CODE_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case @Test public void test_GENERIC_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("GENERIC_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case @Test public void test_INFRASTRUCTURE_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("INFRASTRUCTURE_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case @Test public void test_LOCAL_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("LOCAL_TLDS"); assertTrue(sorted); } @Test public void testAllowLocal() { final DomainValidator noLocal = DomainValidator.getInstance(false); final DomainValidator allowLocal = DomainValidator.getInstance(true); // Default is false, and should use singletons assertEquals(noLocal, validator); // Default won't allow local assertFalse(noLocal.isValid("localhost.localdomain"), "localhost.localdomain should validate"); assertFalse(noLocal.isValid("localhost"), "localhost should validate"); // But it may be requested assertTrue(allowLocal.isValid("localhost.localdomain"), "localhost.localdomain should validate"); assertTrue(allowLocal.isValid("localhost"), "localhost should validate"); assertTrue(allowLocal.isValid("hostname"), "hostname should validate"); assertTrue(allowLocal.isValid("machinename"), "machinename should validate"); // Check the localhost one with a few others assertTrue(allowLocal.isValid("apache.org"), "apache.org should validate"); assertFalse(allowLocal.isValid(" apache.org "), "domain name with spaces shouldn't validate"); } @Test public void testDomainNoDots() {// rfc1123 assertTrue(validator.isValidDomainSyntax("a"), "a (alpha) should validate"); assertTrue(validator.isValidDomainSyntax("9"), "9 (alphanum) should validate"); assertTrue(validator.isValidDomainSyntax("c-z"), "c-z (alpha - alpha) should validate"); assertFalse(validator.isValidDomainSyntax("c-"), "c- (alpha -) should fail"); assertFalse(validator.isValidDomainSyntax("-c"), "-c (- alpha) should fail"); assertFalse(validator.isValidDomainSyntax("-"), "- (-) should fail"); } @Test public void testEnumIsPublic() { assertTrue(Modifier.isPublic(DomainValidator.ArrayType.class.getModifiers())); } @Test public void testGetArray() { assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_MINUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_PLUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_MINUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_PLUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_MINUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_PLUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_RO)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_RO)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.INFRASTRUCTURE_RO)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_RO)); } @Test public void testIDN() { assertTrue(validator.isValid("www.xn--bcher-kva.ch"), "b\u00fccher.ch in IDN should validate"); } @Test public void testIDNJava6OrLater() { final String version = System.getProperty("java.version"); if (version.compareTo("1.6") < 0) { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } // xn--d1abbgf6aiiy.xn--p1ai http://президент.рф assertTrue(validator.isValid("www.b\u00fccher.ch"), "b\u00fccher.ch should validate"); assertTrue(validator.isValid("xn--d1abbgf6aiiy.xn--p1ai"), "xn--d1abbgf6aiiy.xn--p1ai should validate"); assertTrue(validator.isValid("президент.рф"), "президент.рф should validate"); assertFalse(validator.isValid("www.\uFFFD.ch"), "www.\uFFFD.ch FFFD should fail"); } @Test public void testInvalidDomains() { assertFalse(validator.isValid(".org"), "bare TLD .org shouldn't validate"); assertFalse(validator.isValid(" apache.org "), "domain name with spaces shouldn't validate"); assertFalse(validator.isValid("apa che.org"), "domain name containing spaces shouldn't validate"); assertFalse(validator.isValid("-testdomain.name"), "domain name starting with dash shouldn't validate"); assertFalse(validator.isValid("testdomain-.name"), "domain name ending with dash shouldn't validate"); assertFalse(validator.isValid("---c.com"), "domain name starting with multiple dashes shouldn't validate"); assertFalse(validator.isValid("c--.com"), "domain name ending with multiple dashes shouldn't validate"); assertFalse(validator.isValid("apache.rog"), "domain name with invalid TLD shouldn't validate"); assertFalse(validator.isValid("http://www.apache.org"), "URL shouldn't validate"); assertFalse(validator.isValid(" "), "Empty string shouldn't validate as domain name"); assertFalse(validator.isValid(null), "Null shouldn't validate as domain name"); } // Check if IDN.toASCII is broken or not @Test public void testIsIDNtoASCIIBroken() { System.out.println(">>DomainValidatorTest.testIsIDNtoASCIIBroken()"); final String input = "."; final boolean ok = input.equals(IDN.toASCII(input)); System.out.println("IDN.toASCII is " + (ok ? "OK" : "BROKEN")); final String[] props = { "java.version", // Java Runtime Environment version "java.vendor", // Java Runtime Environment vendor "java.vm.specification.version", // Java Virtual Machine specification version "java.vm.specification.vendor", // Java Virtual Machine specification vendor "java.vm.specification.name", // Java Virtual Machine specification name "java.vm.version", // Java Virtual Machine implementation version "java.vm.vendor", // Java Virtual Machine implementation vendor "java.vm.name", // Java Virtual Machine implementation name "java.specification.version", // Java Runtime Environment specification version "java.specification.vendor", // Java Runtime Environment specification vendor "java.specification.name", // Java Runtime Environment specification name "java.class.version", // Java class format version number }; for (final String t : props) { System.out.println(t + "=" + System.getProperty(t)); } System.out.println("<<DomainValidatorTest.testIsIDNtoASCIIBroken()"); assertTrue(true); // dummy assertion to satisfy lint } // RFC2396: domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum @Test public void testRFC2396domainlabel() { // use fixed valid TLD assertTrue(validator.isValid("a.ch"), "a.ch should validate"); assertTrue(validator.isValid("9.ch"), "9.ch should validate"); assertTrue(validator.isValid("az.ch"), "az.ch should validate"); assertTrue(validator.isValid("09.ch"), "09.ch should validate"); assertTrue(validator.isValid("9-1.ch"), "9-1.ch should validate"); assertFalse(validator.isValid("91-.ch"), "91-.ch should not validate"); assertFalse(validator.isValid("-.ch"), "-.ch should not validate"); } // RFC2396 toplabel = alpha | alpha *( alphanum | "-" ) alphanum @Test public void testRFC2396toplabel() { // These tests use non-existent TLDs so currently need to use a package protected method assertTrue(validator.isValidDomainSyntax("a.c"), "a.c (alpha) should validate"); assertTrue(validator.isValidDomainSyntax("a.cc"), "a.cc (alpha alpha) should validate"); assertTrue(validator.isValidDomainSyntax("a.c9"), "a.c9 (alpha alphanum) should validate"); assertTrue(validator.isValidDomainSyntax("a.c-9"), "a.c-9 (alpha - alphanum) should validate"); assertTrue(validator.isValidDomainSyntax("a.c-z"), "a.c-z (alpha - alpha) should validate"); assertFalse(validator.isValidDomainSyntax("a.9c"), "a.9c (alphanum alpha) should fail"); assertFalse(validator.isValidDomainSyntax("a.c-"), "a.c- (alpha -) should fail"); assertFalse(validator.isValidDomainSyntax("a.-"), "a.- (-) should fail"); assertFalse(validator.isValidDomainSyntax("a.-9"), "a.-9 (- alphanum) should fail"); } @Test public void testTopLevelDomains() { // infrastructure TLDs assertTrue(validator.isValidInfrastructureTld(".arpa"), ".arpa should validate as iTLD"); assertFalse(validator.isValidInfrastructureTld(".com"), ".com shouldn't validate as iTLD"); // generic TLDs assertTrue(validator.isValidGenericTld(".name"), ".name should validate as gTLD"); assertFalse(validator.isValidGenericTld(".us"), ".us shouldn't validate as gTLD"); // country code TLDs assertTrue(validator.isValidCountryCodeTld(".uk"), ".uk should validate as ccTLD"); assertFalse(validator.isValidCountryCodeTld(".org"), ".org shouldn't validate as ccTLD"); // case-insensitive assertTrue(validator.isValidTld(".COM"), ".COM should validate as TLD"); assertTrue(validator.isValidTld(".BiZ"), ".BiZ should validate as TLD"); // corner cases assertFalse(validator.isValid(".nope"), "invalid TLD shouldn't validate"); // TODO this is not guaranteed invalid forever assertFalse(validator.isValid(""), "empty string shouldn't validate as TLD"); assertFalse(validator.isValid(null), "null shouldn't validate as TLD"); } // Check that IDN.toASCII behaves as it should (when wrapped by DomainValidator.unicodeToASCII) // Tests show that method incorrectly trims a trailing "." character @Test public void testUnicodeToASCII() { final String[] asciidots = { "", ",", ".", // fails IDN.toASCII, but should pass wrapped version "a.", // ditto "a.b", "a..b", "a...b", ".a", "..a", }; for (final String s : asciidots) { assertEquals(s, DomainValidator.unicodeToASCII(s)); } // RFC3490 3.1. 1) // Whenever dots are used as label separators, the following // characters MUST be recognized as dots: U+002E (full stop), U+3002 // (ideographic full stop), U+FF0E (fullwidth full stop), U+FF61 // (halfwidth ideographic full stop). final String otherDots[][] = { { "b\u3002", "b.", }, { "b\uFF0E", "b.", }, { "b\uFF61", "b.", }, { "\u3002", ".", }, { "\uFF0E", ".", }, { "\uFF61", ".", }, }; for (final String s[] : otherDots) { assertEquals(s[1], DomainValidator.unicodeToASCII(s[0])); } } @Test public void testValidator297() { assertTrue(validator.isValid("xn--d1abbgf6aiiy.xn--p1ai"), "xn--d1abbgf6aiiy.xn--p1ai should validate"); // This uses a valid TLD } // labels are a max of 63 chars and domains 253 @Test public void testValidator306() { final String longString = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789A"; assertEquals(63, longString.length()); // 26 * 2 + 11 assertTrue(validator.isValidDomainSyntax(longString + ".com"), "63 chars label should validate"); assertFalse(validator.isValidDomainSyntax(longString + "x.com"), "64 chars label should fail"); assertTrue(validator.isValidDomainSyntax("test." + longString), "63 chars TLD should validate"); assertFalse(validator.isValidDomainSyntax("test.x" + longString), "64 chars TLD should fail"); final String longDomain = longString + "." + longString + "." + longString + "." + longString.substring(0, 61); assertEquals(253, longDomain.length()); assertTrue(validator.isValidDomainSyntax(longDomain), "253 chars domain should validate"); assertFalse(validator.isValidDomainSyntax(longDomain + "x"), "254 chars domain should fail"); } @Test public void testValidDomains() { assertTrue(validator.isValid("apache.org"), "apache.org should validate"); assertTrue(validator.isValid("www.google.com"), "www.google.com should validate"); assertTrue(validator.isValid("test-domain.com"), "test-domain.com should validate"); assertTrue(validator.isValid("test---domain.com"), "test---domain.com should validate"); assertTrue(validator.isValid("test-d-o-m-ain.com"), "test-d-o-m-ain.com should validate"); assertTrue(validator.isValid("as.uk"), "two-letter domain label should validate"); assertTrue(validator.isValid("ApAchE.Org"), "case-insensitive ApAchE.Org should validate"); assertTrue(validator.isValid("z.com"), "single-character domain label should validate"); assertTrue(validator.isValid("i.have.an-example.domain.name"), "i.have.an-example.domain.name should validate"); } }
nhojpatrick/apache_commons-validator
src/test/java/org/apache/commons/validator/routines/DomainValidatorTest.java
7,637
// Parse html page to get entries
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.IDN; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.validator.routines.DomainValidator.ArrayType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests for the DomainValidator. */ public class DomainValidatorTest { private static void closeQuietly(final Closeable in) { if (in != null) { try { in.close(); } catch (final IOException e) { } } } /* * Download a file if it is more recent than our cached copy. Unfortunately the server does not seem to honor If-Modified-Since for the Html page, so we * check if it is newer than the txt file and skip download if so */ private static long download(final File file, final String tldUrl, final long timestamp) throws IOException { final int HOUR = 60 * 60 * 1000; // an hour in ms final long modTime; // For testing purposes, don't download files more than once an hour if (file.canRead()) { modTime = file.lastModified(); if (modTime > System.currentTimeMillis() - HOUR) { System.out.println("Skipping download - found recent " + file); return modTime; } } else { modTime = 0; } final HttpURLConnection hc = (HttpURLConnection) new URL(tldUrl).openConnection(); if (modTime > 0) { final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");// Sun, 06 Nov 1994 08:49:37 GMT final String since = sdf.format(new Date(modTime)); hc.addRequestProperty("If-Modified-Since", since); System.out.println("Found " + file + " with date " + since); } if (hc.getResponseCode() == 304) { System.out.println("Already have most recent " + tldUrl); } else { System.out.println("Downloading " + tldUrl); try (InputStream is = hc.getInputStream()) { Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING); } System.out.println("Done"); } return file.lastModified(); } private static Map<String, String[]> getHtmlInfo(final File f) throws IOException { final Map<String, String[]> info = new HashMap<>(); // <td><span class="domain tld"><a href="/domains/root/db/ax.html">.ax</a></span></td> final Pattern domain = Pattern.compile(".*<a href=\"/domains/root/db/([^.]+)\\.html"); // <td>country-code</td> final Pattern type = Pattern.compile("\\s+<td>([^<]+)</td>"); // <!-- <td>Åland Islands<br/><span class="tld-table-so">Ålands landskapsregering</span></td> </td> --> // <td>Ålands landskapsregering</td> final Pattern comment = Pattern.compile("\\s+<td>([^<]+)</td>"); try (BufferedReader br = new BufferedReader(new FileReader(f))) { String line; while ((line = br.readLine()) != null) { final Matcher m = domain.matcher(line); if (m.lookingAt()) { final String dom = m.group(1); String typ = "??"; String com = "??"; line = br.readLine(); while (line.matches("^\\s*$")) { // extra blank lines introduced line = br.readLine(); } final Matcher t = type.matcher(line); if (t.lookingAt()) { typ = t.group(1); line = br.readLine(); if (line.matches("\\s+<!--.*")) { while (!line.matches(".*-->.*")) { line = br.readLine(); } line = br.readLine(); } // Should have comment; is it wrapped? while (!line.matches(".*</td>.*")) { line += " " + br.readLine(); } final Matcher n = comment.matcher(line); if (n.lookingAt()) { com = n.group(1); } // Don't save unused entries if (com.contains("Not assigned") || com.contains("Retired") || typ.equals("test")) { // System.out.println("Ignored: " + typ + " " + dom + " " +com); } else { info.put(dom.toLowerCase(Locale.ENGLISH), new String[] { typ, com }); // System.out.println("Storing: " + typ + " " + dom + " " +com); } } else { System.err.println("Unexpected type: " + line); } } } } return info; } // isInIanaList and isSorted are split into two methods. // If/when access to the arrays is possible without reflection, the intermediate // methods can be dropped private static boolean isInIanaList(final String arrayName, final Set<String> ianaTlds) throws Exception { final Field f = DomainValidator.class.getDeclaredField(arrayName); final boolean isPrivate = Modifier.isPrivate(f.getModifiers()); if (isPrivate) { f.setAccessible(true); } final String[] array = (String[]) f.get(null); try { return isInIanaList(arrayName, array, ianaTlds); } finally { if (isPrivate) { f.setAccessible(false); } } } private static boolean isInIanaList(final String name, final String[] array, final Set<String> ianaTlds) { for (final String element : array) { if (!ianaTlds.contains(element)) { System.out.println(name + " contains unexpected value: " + element); } } return true; } private static boolean isLowerCase(final String string) { return string.equals(string.toLowerCase(Locale.ENGLISH)); } /** * Check whether the domain is in the root zone currently. Reads the URL http://www.iana.org/domains/root/db/*domain*.html (using a local disk cache) and * checks for the string "This domain is not present in the root zone at this time." * * @param domain the domain to check * @return true if the string is found */ private static boolean isNotInRootZone(final String domain) { final String tldUrl = "http://www.iana.org/domains/root/db/" + domain + ".html"; final File rootCheck = new File("target", "tld_" + domain + ".html"); BufferedReader in = null; try { download(rootCheck, tldUrl, 0L); in = new BufferedReader(new FileReader(rootCheck)); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("This domain is not present in the root zone at this time.")) { return true; } } in.close(); } catch (final IOException e) { } finally { closeQuietly(in); } return false; } private static boolean isSortedLowerCase(final String arrayName) throws Exception { final Field f = DomainValidator.class.getDeclaredField(arrayName); final boolean isPrivate = Modifier.isPrivate(f.getModifiers()); if (isPrivate) { f.setAccessible(true); } final String[] array = (String[]) f.get(null); try { return isSortedLowerCase(arrayName, array); } finally { if (isPrivate) { f.setAccessible(false); } } } // Check if an array is strictly sorted - and lowerCase private static boolean isSortedLowerCase(final String name, final String[] array) { boolean sorted = true; boolean strictlySorted = true; final int length = array.length; boolean lowerCase = isLowerCase(array[length - 1]); // Check the last entry for (int i = 0; i < length - 1; i++) { // compare all but last entry with next final String entry = array[i]; final String nextEntry = array[i + 1]; final int cmp = entry.compareTo(nextEntry); if (cmp > 0) { // out of order System.out.println("Out of order entry: " + entry + " < " + nextEntry + " in " + name); sorted = false; } else if (cmp == 0) { strictlySorted = false; System.out.println("Duplicated entry: " + entry + " in " + name); } if (!isLowerCase(entry)) { System.out.println("Non lowerCase entry: " + entry + " in " + name); lowerCase = false; } } return sorted && strictlySorted && lowerCase; } // Download and process local copy of https://data.iana.org/TLD/tlds-alpha-by-domain.txt // Check if the internal TLD table is up to date // Check if the internal TLD tables have any spurious entries public static void main(final String a[]) throws Exception { // Check the arrays first as this affects later checks // Doing this here makes it easier when updating the lists boolean OK = true; for (final String list : new String[] { "INFRASTRUCTURE_TLDS", "COUNTRY_CODE_TLDS", "GENERIC_TLDS", "LOCAL_TLDS" }) { OK &= isSortedLowerCase(list); } if (!OK) { System.out.println("Fix arrays before retrying; cannot continue"); return; } final Set<String> ianaTlds = new HashSet<>(); // keep for comparison with array contents final DomainValidator dv = DomainValidator.getInstance(); final File txtFile = new File("target/tlds-alpha-by-domain.txt"); final long timestamp = download(txtFile, "https://data.iana.org/TLD/tlds-alpha-by-domain.txt", 0L); final File htmlFile = new File("target/tlds-alpha-by-domain.html"); // N.B. sometimes the html file may be updated a day or so after the txt file // if the txt file contains entries not found in the html file, try again in a day or two download(htmlFile, "https://www.iana.org/domains/root/db", timestamp); final BufferedReader br = new BufferedReader(new FileReader(txtFile)); String line; final String header; line = br.readLine(); // header if (!line.startsWith("# Version ")) { br.close(); throw new IOException("File does not have expected Version header"); } header = line.substring(2); final boolean generateUnicodeTlds = false; // Change this to generate Unicode TLDs as well // Parse html<SUF> final Map<String, String[]> htmlInfo = getHtmlInfo(htmlFile); final Map<String, String> missingTLD = new TreeMap<>(); // stores entry and comments as String[] final Map<String, String> missingCC = new TreeMap<>(); while ((line = br.readLine()) != null) { if (!line.startsWith("#")) { final String unicodeTld; // only different from asciiTld if that was punycode final String asciiTld = line.toLowerCase(Locale.ENGLISH); if (line.startsWith("XN--")) { unicodeTld = IDN.toUnicode(line); } else { unicodeTld = asciiTld; } if (!dv.isValidTld(asciiTld)) { final String[] info = htmlInfo.get(asciiTld); if (info != null) { final String type = info[0]; final String comment = info[1]; if ("country-code".equals(type)) { // Which list to use? missingCC.put(asciiTld, unicodeTld + " " + comment); if (generateUnicodeTlds) { missingCC.put(unicodeTld, asciiTld + " " + comment); } } else { missingTLD.put(asciiTld, unicodeTld + " " + comment); if (generateUnicodeTlds) { missingTLD.put(unicodeTld, asciiTld + " " + comment); } } } else { System.err.println("Expected to find HTML info for " + asciiTld); } } ianaTlds.add(asciiTld); // Don't merge these conditions; generateUnicodeTlds is final so needs to be separate to avoid a warning if (generateUnicodeTlds && !unicodeTld.equals(asciiTld)) { ianaTlds.add(unicodeTld); } } } br.close(); // List html entries not in TLD text list for (final String key : new TreeMap<>(htmlInfo).keySet()) { if (!ianaTlds.contains(key)) { if (isNotInRootZone(key)) { System.out.println("INFO: HTML entry not yet in root zone: " + key); } else { System.err.println("WARN: Expected to find text entry for html: " + key); } } } if (!missingTLD.isEmpty()) { printMap(header, missingTLD, "GENERIC_TLDS"); } if (!missingCC.isEmpty()) { printMap(header, missingCC, "COUNTRY_CODE_TLDS"); } // Check if internal tables contain any additional entries isInIanaList("INFRASTRUCTURE_TLDS", ianaTlds); isInIanaList("COUNTRY_CODE_TLDS", ianaTlds); isInIanaList("GENERIC_TLDS", ianaTlds); // Don't check local TLDS isInIanaList("LOCAL_TLDS", ianaTlds); System.out.println("Finished checks"); } private static void printMap(final String header, final Map<String, String> map, final String string) { System.out.println("Entries missing from " + string + " List\n"); if (header != null) { System.out.println(" // Taken from " + header); } for (final Entry<String, String> me : map.entrySet()) { System.out.println(" \"" + me.getKey() + "\", // " + me.getValue()); } System.out.println("\nDone"); } private DomainValidator validator; @BeforeEach public void setUp() { validator = DomainValidator.getInstance(); } // Check array is sorted and is lower-case @Test public void test_COUNTRY_CODE_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("COUNTRY_CODE_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case @Test public void test_GENERIC_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("GENERIC_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case @Test public void test_INFRASTRUCTURE_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("INFRASTRUCTURE_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case @Test public void test_LOCAL_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("LOCAL_TLDS"); assertTrue(sorted); } @Test public void testAllowLocal() { final DomainValidator noLocal = DomainValidator.getInstance(false); final DomainValidator allowLocal = DomainValidator.getInstance(true); // Default is false, and should use singletons assertEquals(noLocal, validator); // Default won't allow local assertFalse(noLocal.isValid("localhost.localdomain"), "localhost.localdomain should validate"); assertFalse(noLocal.isValid("localhost"), "localhost should validate"); // But it may be requested assertTrue(allowLocal.isValid("localhost.localdomain"), "localhost.localdomain should validate"); assertTrue(allowLocal.isValid("localhost"), "localhost should validate"); assertTrue(allowLocal.isValid("hostname"), "hostname should validate"); assertTrue(allowLocal.isValid("machinename"), "machinename should validate"); // Check the localhost one with a few others assertTrue(allowLocal.isValid("apache.org"), "apache.org should validate"); assertFalse(allowLocal.isValid(" apache.org "), "domain name with spaces shouldn't validate"); } @Test public void testDomainNoDots() {// rfc1123 assertTrue(validator.isValidDomainSyntax("a"), "a (alpha) should validate"); assertTrue(validator.isValidDomainSyntax("9"), "9 (alphanum) should validate"); assertTrue(validator.isValidDomainSyntax("c-z"), "c-z (alpha - alpha) should validate"); assertFalse(validator.isValidDomainSyntax("c-"), "c- (alpha -) should fail"); assertFalse(validator.isValidDomainSyntax("-c"), "-c (- alpha) should fail"); assertFalse(validator.isValidDomainSyntax("-"), "- (-) should fail"); } @Test public void testEnumIsPublic() { assertTrue(Modifier.isPublic(DomainValidator.ArrayType.class.getModifiers())); } @Test public void testGetArray() { assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_MINUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_PLUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_MINUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_PLUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_MINUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_PLUS)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.COUNTRY_CODE_RO)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.GENERIC_RO)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.INFRASTRUCTURE_RO)); assertNotNull(DomainValidator.getTLDEntries(ArrayType.LOCAL_RO)); } @Test public void testIDN() { assertTrue(validator.isValid("www.xn--bcher-kva.ch"), "b\u00fccher.ch in IDN should validate"); } @Test public void testIDNJava6OrLater() { final String version = System.getProperty("java.version"); if (version.compareTo("1.6") < 0) { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } // xn--d1abbgf6aiiy.xn--p1ai http://президент.рф assertTrue(validator.isValid("www.b\u00fccher.ch"), "b\u00fccher.ch should validate"); assertTrue(validator.isValid("xn--d1abbgf6aiiy.xn--p1ai"), "xn--d1abbgf6aiiy.xn--p1ai should validate"); assertTrue(validator.isValid("президент.рф"), "президент.рф should validate"); assertFalse(validator.isValid("www.\uFFFD.ch"), "www.\uFFFD.ch FFFD should fail"); } @Test public void testInvalidDomains() { assertFalse(validator.isValid(".org"), "bare TLD .org shouldn't validate"); assertFalse(validator.isValid(" apache.org "), "domain name with spaces shouldn't validate"); assertFalse(validator.isValid("apa che.org"), "domain name containing spaces shouldn't validate"); assertFalse(validator.isValid("-testdomain.name"), "domain name starting with dash shouldn't validate"); assertFalse(validator.isValid("testdomain-.name"), "domain name ending with dash shouldn't validate"); assertFalse(validator.isValid("---c.com"), "domain name starting with multiple dashes shouldn't validate"); assertFalse(validator.isValid("c--.com"), "domain name ending with multiple dashes shouldn't validate"); assertFalse(validator.isValid("apache.rog"), "domain name with invalid TLD shouldn't validate"); assertFalse(validator.isValid("http://www.apache.org"), "URL shouldn't validate"); assertFalse(validator.isValid(" "), "Empty string shouldn't validate as domain name"); assertFalse(validator.isValid(null), "Null shouldn't validate as domain name"); } // Check if IDN.toASCII is broken or not @Test public void testIsIDNtoASCIIBroken() { System.out.println(">>DomainValidatorTest.testIsIDNtoASCIIBroken()"); final String input = "."; final boolean ok = input.equals(IDN.toASCII(input)); System.out.println("IDN.toASCII is " + (ok ? "OK" : "BROKEN")); final String[] props = { "java.version", // Java Runtime Environment version "java.vendor", // Java Runtime Environment vendor "java.vm.specification.version", // Java Virtual Machine specification version "java.vm.specification.vendor", // Java Virtual Machine specification vendor "java.vm.specification.name", // Java Virtual Machine specification name "java.vm.version", // Java Virtual Machine implementation version "java.vm.vendor", // Java Virtual Machine implementation vendor "java.vm.name", // Java Virtual Machine implementation name "java.specification.version", // Java Runtime Environment specification version "java.specification.vendor", // Java Runtime Environment specification vendor "java.specification.name", // Java Runtime Environment specification name "java.class.version", // Java class format version number }; for (final String t : props) { System.out.println(t + "=" + System.getProperty(t)); } System.out.println("<<DomainValidatorTest.testIsIDNtoASCIIBroken()"); assertTrue(true); // dummy assertion to satisfy lint } // RFC2396: domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum @Test public void testRFC2396domainlabel() { // use fixed valid TLD assertTrue(validator.isValid("a.ch"), "a.ch should validate"); assertTrue(validator.isValid("9.ch"), "9.ch should validate"); assertTrue(validator.isValid("az.ch"), "az.ch should validate"); assertTrue(validator.isValid("09.ch"), "09.ch should validate"); assertTrue(validator.isValid("9-1.ch"), "9-1.ch should validate"); assertFalse(validator.isValid("91-.ch"), "91-.ch should not validate"); assertFalse(validator.isValid("-.ch"), "-.ch should not validate"); } // RFC2396 toplabel = alpha | alpha *( alphanum | "-" ) alphanum @Test public void testRFC2396toplabel() { // These tests use non-existent TLDs so currently need to use a package protected method assertTrue(validator.isValidDomainSyntax("a.c"), "a.c (alpha) should validate"); assertTrue(validator.isValidDomainSyntax("a.cc"), "a.cc (alpha alpha) should validate"); assertTrue(validator.isValidDomainSyntax("a.c9"), "a.c9 (alpha alphanum) should validate"); assertTrue(validator.isValidDomainSyntax("a.c-9"), "a.c-9 (alpha - alphanum) should validate"); assertTrue(validator.isValidDomainSyntax("a.c-z"), "a.c-z (alpha - alpha) should validate"); assertFalse(validator.isValidDomainSyntax("a.9c"), "a.9c (alphanum alpha) should fail"); assertFalse(validator.isValidDomainSyntax("a.c-"), "a.c- (alpha -) should fail"); assertFalse(validator.isValidDomainSyntax("a.-"), "a.- (-) should fail"); assertFalse(validator.isValidDomainSyntax("a.-9"), "a.-9 (- alphanum) should fail"); } @Test public void testTopLevelDomains() { // infrastructure TLDs assertTrue(validator.isValidInfrastructureTld(".arpa"), ".arpa should validate as iTLD"); assertFalse(validator.isValidInfrastructureTld(".com"), ".com shouldn't validate as iTLD"); // generic TLDs assertTrue(validator.isValidGenericTld(".name"), ".name should validate as gTLD"); assertFalse(validator.isValidGenericTld(".us"), ".us shouldn't validate as gTLD"); // country code TLDs assertTrue(validator.isValidCountryCodeTld(".uk"), ".uk should validate as ccTLD"); assertFalse(validator.isValidCountryCodeTld(".org"), ".org shouldn't validate as ccTLD"); // case-insensitive assertTrue(validator.isValidTld(".COM"), ".COM should validate as TLD"); assertTrue(validator.isValidTld(".BiZ"), ".BiZ should validate as TLD"); // corner cases assertFalse(validator.isValid(".nope"), "invalid TLD shouldn't validate"); // TODO this is not guaranteed invalid forever assertFalse(validator.isValid(""), "empty string shouldn't validate as TLD"); assertFalse(validator.isValid(null), "null shouldn't validate as TLD"); } // Check that IDN.toASCII behaves as it should (when wrapped by DomainValidator.unicodeToASCII) // Tests show that method incorrectly trims a trailing "." character @Test public void testUnicodeToASCII() { final String[] asciidots = { "", ",", ".", // fails IDN.toASCII, but should pass wrapped version "a.", // ditto "a.b", "a..b", "a...b", ".a", "..a", }; for (final String s : asciidots) { assertEquals(s, DomainValidator.unicodeToASCII(s)); } // RFC3490 3.1. 1) // Whenever dots are used as label separators, the following // characters MUST be recognized as dots: U+002E (full stop), U+3002 // (ideographic full stop), U+FF0E (fullwidth full stop), U+FF61 // (halfwidth ideographic full stop). final String otherDots[][] = { { "b\u3002", "b.", }, { "b\uFF0E", "b.", }, { "b\uFF61", "b.", }, { "\u3002", ".", }, { "\uFF0E", ".", }, { "\uFF61", ".", }, }; for (final String s[] : otherDots) { assertEquals(s[1], DomainValidator.unicodeToASCII(s[0])); } } @Test public void testValidator297() { assertTrue(validator.isValid("xn--d1abbgf6aiiy.xn--p1ai"), "xn--d1abbgf6aiiy.xn--p1ai should validate"); // This uses a valid TLD } // labels are a max of 63 chars and domains 253 @Test public void testValidator306() { final String longString = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789A"; assertEquals(63, longString.length()); // 26 * 2 + 11 assertTrue(validator.isValidDomainSyntax(longString + ".com"), "63 chars label should validate"); assertFalse(validator.isValidDomainSyntax(longString + "x.com"), "64 chars label should fail"); assertTrue(validator.isValidDomainSyntax("test." + longString), "63 chars TLD should validate"); assertFalse(validator.isValidDomainSyntax("test.x" + longString), "64 chars TLD should fail"); final String longDomain = longString + "." + longString + "." + longString + "." + longString.substring(0, 61); assertEquals(253, longDomain.length()); assertTrue(validator.isValidDomainSyntax(longDomain), "253 chars domain should validate"); assertFalse(validator.isValidDomainSyntax(longDomain + "x"), "254 chars domain should fail"); } @Test public void testValidDomains() { assertTrue(validator.isValid("apache.org"), "apache.org should validate"); assertTrue(validator.isValid("www.google.com"), "www.google.com should validate"); assertTrue(validator.isValid("test-domain.com"), "test-domain.com should validate"); assertTrue(validator.isValid("test---domain.com"), "test---domain.com should validate"); assertTrue(validator.isValid("test-d-o-m-ain.com"), "test-d-o-m-ain.com should validate"); assertTrue(validator.isValid("as.uk"), "two-letter domain label should validate"); assertTrue(validator.isValid("ApAchE.Org"), "case-insensitive ApAchE.Org should validate"); assertTrue(validator.isValid("z.com"), "single-character domain label should validate"); assertTrue(validator.isValid("i.have.an-example.domain.name"), "i.have.an-example.domain.name should validate"); } }
11787_52
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.menu; import org.mozilla.gecko.AppConstants; import org.mozilla.gecko.R; import org.mozilla.gecko.util.ThreadUtils; import org.mozilla.gecko.util.ThreadUtils.AssertBehavior; import org.mozilla.gecko.widget.GeckoActionProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GeckoMenu extends ListView implements Menu, AdapterView.OnItemClickListener, GeckoMenuItem.OnShowAsActionChangedListener { private static final String LOGTAG = "GeckoMenu"; /** * Controls whether off-UI-thread method calls in this class cause an * exception or just logging. */ private static final AssertBehavior THREAD_ASSERT_BEHAVIOR = AppConstants.RELEASE_BUILD ? AssertBehavior.NONE : AssertBehavior.THROW; /* * A callback for a menu item click/long click event. */ public static interface Callback { // Called when a menu item is clicked, with the actual menu item as the argument. public boolean onMenuItemClick(MenuItem item); // Called when a menu item is long-clicked, with the actual menu item as the argument. public boolean onMenuItemLongClick(MenuItem item); } /* * An interface for a presenter to show the menu. * Either an Activity or a View can be a presenter, that can watch for events * and show/hide menu. */ public static interface MenuPresenter { // Open the menu. public void openMenu(); // Show the actual view containing the menu items. This can either be a parent or sub-menu. public void showMenu(View menu); // Close the menu. public void closeMenu(); } /* * An interface for a presenter of action-items. * Either an Activity or a View can be a presenter, that can watch for events * and add/remove action-items. If not ActionItemBarPresenter, the menu uses a * DefaultActionItemBar, that shows the action-items as a header over list-view. */ public static interface ActionItemBarPresenter { // Add an action-item. public boolean addActionItem(View actionItem); // Remove an action-item. public void removeActionItem(View actionItem); } protected static final int NO_ID = 0; // List of all menu items. private List<GeckoMenuItem> mItems; // Map of "always" action-items in action-bar and their views. private Map<GeckoMenuItem, View> mPrimaryActionItems; // Map of "ifRoom" action-items in action-bar and their views. private Map<GeckoMenuItem, View> mSecondaryActionItems; // Reference to a callback for menu events. private Callback mCallback; // Reference to menu presenter. private MenuPresenter mMenuPresenter; // Reference to "always" action-items bar in action-bar. private ActionItemBarPresenter mPrimaryActionItemBar; // Reference to "ifRoom" action-items bar in action-bar. private final ActionItemBarPresenter mSecondaryActionItemBar; // Adapter to hold the list of menu items. private MenuItemsAdapter mAdapter; // Show/hide icons in the list. boolean mShowIcons; public GeckoMenu(Context context) { this(context, null); } public GeckoMenu(Context context, AttributeSet attrs) { this(context, attrs, R.attr.geckoMenuListViewStyle); } public GeckoMenu(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // Attach an adapter. mAdapter = new MenuItemsAdapter(); setAdapter(mAdapter); setOnItemClickListener(this); mItems = new ArrayList<GeckoMenuItem>(); mPrimaryActionItems = new HashMap<GeckoMenuItem, View>(); mSecondaryActionItems = new HashMap<GeckoMenuItem, View>(); mPrimaryActionItemBar = (DefaultActionItemBar) LayoutInflater.from(context).inflate(R.layout.menu_action_bar, null); mSecondaryActionItemBar = (DefaultActionItemBar) LayoutInflater.from(context).inflate(R.layout.menu_secondary_action_bar, null); } private static void assertOnUiThread() { ThreadUtils.assertOnUiThread(THREAD_ASSERT_BEHAVIOR); } @Override public MenuItem add(CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(this, NO_ID, 0, title); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(this, itemId, order, titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(this, NO_ID, 0, titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(this, itemId, order, title); addItem(menuItem); return menuItem; } private void addItem(GeckoMenuItem menuItem) { assertOnUiThread(); menuItem.setOnShowAsActionChangedListener(this); mAdapter.addMenuItem(menuItem); mItems.add(menuItem); } private boolean addActionItem(final GeckoMenuItem menuItem) { assertOnUiThread(); menuItem.setOnShowAsActionChangedListener(this); final View actionView = menuItem.getActionView(); final int actionEnum = menuItem.getActionEnum(); boolean added = false; if (actionEnum == GeckoMenuItem.SHOW_AS_ACTION_ALWAYS) { if (mPrimaryActionItems.size() == 0 && mPrimaryActionItemBar instanceof DefaultActionItemBar) { // Reset the adapter before adding the header view to a list. setAdapter(null); addHeaderView((DefaultActionItemBar) mPrimaryActionItemBar); setAdapter(mAdapter); } if (added = mPrimaryActionItemBar.addActionItem(actionView)) { mPrimaryActionItems.put(menuItem, actionView); mItems.add(menuItem); } } else if (actionEnum == GeckoMenuItem.SHOW_AS_ACTION_IF_ROOM) { if (mSecondaryActionItems.size() == 0) { // Reset the adapter before adding the header view to a list. setAdapter(null); addHeaderView((DefaultActionItemBar) mSecondaryActionItemBar); setAdapter(mAdapter); } if (added = mSecondaryActionItemBar.addActionItem(actionView)) { mSecondaryActionItems.put(menuItem, actionView); mItems.add(menuItem); } } // Set the listeners. if (actionView instanceof MenuItemActionBar) { ((MenuItemActionBar) actionView).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleMenuItemClick(menuItem); } }); ((MenuItemActionBar) actionView).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { handleMenuItemLongClick(menuItem); return true; } }); } else if (actionView instanceof MenuItemActionView) { ((MenuItemActionView) actionView).setMenuItemClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleMenuItemClick(menuItem); } }); ((MenuItemActionView) actionView).setMenuItemLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { handleMenuItemLongClick(menuItem); return true; } }); } return added; } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { return 0; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { MenuItem menuItem = add(groupId, itemId, order, title); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { MenuItem menuItem = add(groupId, itemId, order, titleRes); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(CharSequence title) { MenuItem menuItem = add(title); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(int titleRes) { MenuItem menuItem = add(titleRes); return addSubMenu(menuItem); } private SubMenu addSubMenu(MenuItem menuItem) { GeckoSubMenu subMenu = new GeckoSubMenu(getContext()); subMenu.setMenuItem(menuItem); subMenu.setCallback(mCallback); subMenu.setMenuPresenter(mMenuPresenter); ((GeckoMenuItem) menuItem).setSubMenu(subMenu); return subMenu; } private void removePrimaryActionBarView() { // Reset the adapter before removing the header view from a list. setAdapter(null); removeHeaderView((DefaultActionItemBar) mPrimaryActionItemBar); setAdapter(mAdapter); } private void removeSecondaryActionBarView() { // Reset the adapter before removing the header view from a list. setAdapter(null); removeHeaderView((DefaultActionItemBar) mSecondaryActionItemBar); setAdapter(mAdapter); } @Override public void clear() { assertOnUiThread(); for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { SubMenu sub = menuItem.getSubMenu(); if (sub == null) { continue; } try { sub.clear(); } catch (Exception ex) { Log.e(LOGTAG, "Couldn't clear submenu.", ex); } } } mAdapter.clear(); mItems.clear(); /* * Reinflating the menu will re-add any action items to the toolbar, so * remove the old ones. This also ensures that any text associated with * these is switched to the correct locale. */ if (mPrimaryActionItemBar != null) { for (View item : mPrimaryActionItems.values()) { mPrimaryActionItemBar.removeActionItem(item); } } mPrimaryActionItems.clear(); if (mSecondaryActionItemBar != null) { for (View item : mSecondaryActionItems.values()) { mSecondaryActionItemBar.removeActionItem(item); } } mSecondaryActionItems.clear(); // Remove the view, too -- the first addActionItem will re-add it, // and this is simpler than changing that logic. if (mPrimaryActionItemBar instanceof DefaultActionItemBar) { removePrimaryActionBarView(); } removeSecondaryActionBarView(); } @Override public void close() { if (mMenuPresenter != null) mMenuPresenter.closeMenu(); } private void showMenu(View viewForMenu) { if (mMenuPresenter != null) mMenuPresenter.showMenu(viewForMenu); } @Override public MenuItem findItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) { return menuItem; } else if (menuItem.hasSubMenu()) { if (!menuItem.hasActionProvider()) { SubMenu subMenu = menuItem.getSubMenu(); MenuItem item = subMenu.findItem(id); if (item != null) return item; } } } return null; } @Override public MenuItem getItem(int index) { if (index < mItems.size()) return mItems.get(index); return null; } @Override public boolean hasVisibleItems() { assertOnUiThread(); for (GeckoMenuItem menuItem : mItems) { if (menuItem.isVisible() && !mPrimaryActionItems.containsKey(menuItem) && !mSecondaryActionItems.containsKey(menuItem)) return true; } return false; } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return true; } @Override public boolean performIdentifierAction(int id, int flags) { return false; } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return false; } @Override public void removeGroup(int groupId) { } @Override public void removeItem(int id) { assertOnUiThread(); GeckoMenuItem item = (GeckoMenuItem) findItem(id); if (item == null) return; // Remove it from any sub-menu. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { SubMenu subMenu = menuItem.getSubMenu(); if (subMenu != null && subMenu.findItem(id) != null) { subMenu.removeItem(id); return; } } } // Remove it from own menu. if (mPrimaryActionItems.containsKey(item)) { if (mPrimaryActionItemBar != null) mPrimaryActionItemBar.removeActionItem(mPrimaryActionItems.get(item)); mPrimaryActionItems.remove(item); mItems.remove(item); if (mPrimaryActionItems.size() == 0 && mPrimaryActionItemBar instanceof DefaultActionItemBar) { removePrimaryActionBarView(); } return; } if (mSecondaryActionItems.containsKey(item)) { if (mSecondaryActionItemBar != null) mSecondaryActionItemBar.removeActionItem(mSecondaryActionItems.get(item)); mSecondaryActionItems.remove(item); mItems.remove(item); if (mSecondaryActionItems.size() == 0) { removeSecondaryActionBarView(); } return; } mAdapter.removeMenuItem(item); mItems.remove(item); } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { } @Override public void setGroupEnabled(int group, boolean enabled) { } @Override public void setGroupVisible(int group, boolean visible) { } @Override public void setQwertyMode(boolean isQwerty) { } @Override public int size() { return mItems.size(); } @Override public boolean hasActionItemBar() { return (mPrimaryActionItemBar != null) && (mSecondaryActionItemBar != null); } @Override public void onShowAsActionChanged(GeckoMenuItem item) { removeItem(item.getItemId()); if (item.isActionItem() && addActionItem(item)) { return; } addItem(item); } public void onItemChanged(GeckoMenuItem item) { assertOnUiThread(); if (item.isActionItem()) { final View actionView; if (item.getActionEnum() == GeckoMenuItem.SHOW_AS_ACTION_ALWAYS) { actionView = mPrimaryActionItems.get(item); } else { actionView = mSecondaryActionItems.get(item); } if (actionView != null) { // The update could be coming from the background thread. // Post a runnable on the UI thread of the view for it to update. final GeckoMenuItem menuItem = item; actionView.post(new Runnable() { @Override public void run() { if (menuItem.isVisible()) { actionView.setVisibility(View.VISIBLE); if (actionView instanceof MenuItemActionBar) { ((MenuItemActionBar) actionView).initialize(menuItem); } else { ((MenuItemActionView) actionView).initialize(menuItem); } } else { actionView.setVisibility(View.GONE); } } }); } } else { mAdapter.notifyDataSetChanged(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // We might be showing headers. Account them while using the position. position -= getHeaderViewsCount(); GeckoMenuItem item = mAdapter.getItem(position); handleMenuItemClick(item); } void handleMenuItemClick(GeckoMenuItem item) { if (!item.isEnabled()) return; if (item.invoke()) { close(); } else if (item.hasSubMenu()) { // Refresh the submenu for the provider. GeckoActionProvider provider = item.getGeckoActionProvider(); if (provider != null) { GeckoSubMenu subMenu = new GeckoSubMenu(getContext()); subMenu.setShowIcons(true); provider.onPrepareSubMenu(subMenu); item.setSubMenu(subMenu); } // Show the submenu. GeckoSubMenu subMenu = (GeckoSubMenu) item.getSubMenu(); showMenu(subMenu); } else { close(); mCallback.onMenuItemClick(item); } } void handleMenuItemLongClick(GeckoMenuItem item) { if(!item.isEnabled()) { return; } if(mCallback != null) { mCallback.onMenuItemLongClick(item); } } public Callback getCallback() { return mCallback; } public MenuPresenter getMenuPresenter() { return mMenuPresenter; } public void setCallback(Callback callback) { mCallback = callback; // Update the submenus just in case this changes on the fly. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu(); subMenu.setCallback(mCallback); } } } public void setMenuPresenter(MenuPresenter presenter) { mMenuPresenter = presenter; // Update the submenus just in case this changes on the fly. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu(); subMenu.setMenuPresenter(mMenuPresenter); } } } public void setActionItemBarPresenter(ActionItemBarPresenter presenter) { mPrimaryActionItemBar = presenter; } public void setShowIcons(boolean show) { if (mShowIcons != show) { mShowIcons = show; mAdapter.notifyDataSetChanged(); } } // Action Items are added to the header view by default. // URL bar can register itself as a presenter, in case it has a different place to show them. public static class DefaultActionItemBar extends LinearLayout implements ActionItemBarPresenter { private final int mRowHeight; private float mWeightSum; public DefaultActionItemBar(Context context) { this(context, null); } public DefaultActionItemBar(Context context, AttributeSet attrs) { super(context, attrs); mRowHeight = getResources().getDimensionPixelSize(R.dimen.menu_item_row_height); } @Override public boolean addActionItem(View actionItem) { ViewGroup.LayoutParams actualParams = actionItem.getLayoutParams(); LinearLayout.LayoutParams params; if (actualParams != null) { params = new LinearLayout.LayoutParams(actionItem.getLayoutParams()); params.width = 0; } else { params = new LinearLayout.LayoutParams(0, mRowHeight); } if (actionItem instanceof MenuItemActionView) { params.weight = ((MenuItemActionView) actionItem).getChildCount(); } else { params.weight = 1.0f; } mWeightSum += params.weight; actionItem.setLayoutParams(params); addView(actionItem); setWeightSum(mWeightSum); return true; } @Override public void removeActionItem(View actionItem) { if (indexOfChild(actionItem) != -1) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) actionItem.getLayoutParams(); mWeightSum -= params.weight; removeView(actionItem); } } } // Adapter to bind menu items to the list. private class MenuItemsAdapter extends BaseAdapter { private static final int VIEW_TYPE_DEFAULT = 0; private static final int VIEW_TYPE_ACTION_MODE = 1; private List<GeckoMenuItem> mItems; public MenuItemsAdapter() { mItems = new ArrayList<GeckoMenuItem>(); } @Override public int getCount() { if (mItems == null) return 0; int visibleCount = 0; for (GeckoMenuItem item : mItems) { if (item.isVisible()) visibleCount++; } return visibleCount; } @Override public GeckoMenuItem getItem(int position) { for (GeckoMenuItem item : mItems) { if (item.isVisible()) { position--; if (position < 0) return item; } } return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { GeckoMenuItem item = getItem(position); GeckoMenuItem.Layout view = null; // Try to re-use the view. if (convertView == null && getItemViewType(position) == VIEW_TYPE_DEFAULT) { view = new MenuItemDefault(parent.getContext(), null); } else { view = (GeckoMenuItem.Layout) convertView; } if (view == null || view instanceof MenuItemActionView) { // Always get from the menu item. // This will ensure that the default activity is refreshed. view = (MenuItemActionView) item.getActionView(); // ListView will not perform an item click if the row has a focusable view in it. // Hence, forward the click event on the menu item in the action-view to the ListView. final View actionView = (View) view; final int pos = position; final long id = getItemId(position); ((MenuItemActionView) view).setMenuItemClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GeckoMenu listView = GeckoMenu.this; listView.performItemClick(actionView, pos + listView.getHeaderViewsCount(), id); } }); } // Initialize the view. view.setShowIcon(mShowIcons); view.initialize(item); return (View) view; } @Override public int getItemViewType(int position) { return getItem(position).getGeckoActionProvider() == null ? VIEW_TYPE_DEFAULT : VIEW_TYPE_ACTION_MODE; } @Override public int getViewTypeCount() { return 2; } @Override public boolean hasStableIds() { return false; } @Override public boolean areAllItemsEnabled() { // Setting this to true is a workaround to fix disappearing // dividers in the menu (bug 963249). return true; } @Override public boolean isEnabled(int position) { // Setting this to true is a workaround to fix disappearing // dividers in the menu in L (bug 1050780). return true; } public void addMenuItem(GeckoMenuItem menuItem) { if (mItems.contains(menuItem)) return; // Insert it in proper order. int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() > menuItem.getOrder()) { mItems.add(index, menuItem); notifyDataSetChanged(); return; } else { index++; } } // Add the menuItem at the end. mItems.add(menuItem); notifyDataSetChanged(); } public void removeMenuItem(GeckoMenuItem menuItem) { // Remove it from the list. mItems.remove(menuItem); notifyDataSetChanged(); } public void clear() { mItems.clear(); notifyDataSetChanged(); } public GeckoMenuItem getMenuItem(int id) { for (GeckoMenuItem item : mItems) { if (item.getItemId() == id) return item; } return null; } } }
jrmuizel/gecko-cinnabar
mobile/android/base/menu/GeckoMenu.java
6,260
// Insert it in proper order.
line_comment
nl
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.menu; import org.mozilla.gecko.AppConstants; import org.mozilla.gecko.R; import org.mozilla.gecko.util.ThreadUtils; import org.mozilla.gecko.util.ThreadUtils.AssertBehavior; import org.mozilla.gecko.widget.GeckoActionProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GeckoMenu extends ListView implements Menu, AdapterView.OnItemClickListener, GeckoMenuItem.OnShowAsActionChangedListener { private static final String LOGTAG = "GeckoMenu"; /** * Controls whether off-UI-thread method calls in this class cause an * exception or just logging. */ private static final AssertBehavior THREAD_ASSERT_BEHAVIOR = AppConstants.RELEASE_BUILD ? AssertBehavior.NONE : AssertBehavior.THROW; /* * A callback for a menu item click/long click event. */ public static interface Callback { // Called when a menu item is clicked, with the actual menu item as the argument. public boolean onMenuItemClick(MenuItem item); // Called when a menu item is long-clicked, with the actual menu item as the argument. public boolean onMenuItemLongClick(MenuItem item); } /* * An interface for a presenter to show the menu. * Either an Activity or a View can be a presenter, that can watch for events * and show/hide menu. */ public static interface MenuPresenter { // Open the menu. public void openMenu(); // Show the actual view containing the menu items. This can either be a parent or sub-menu. public void showMenu(View menu); // Close the menu. public void closeMenu(); } /* * An interface for a presenter of action-items. * Either an Activity or a View can be a presenter, that can watch for events * and add/remove action-items. If not ActionItemBarPresenter, the menu uses a * DefaultActionItemBar, that shows the action-items as a header over list-view. */ public static interface ActionItemBarPresenter { // Add an action-item. public boolean addActionItem(View actionItem); // Remove an action-item. public void removeActionItem(View actionItem); } protected static final int NO_ID = 0; // List of all menu items. private List<GeckoMenuItem> mItems; // Map of "always" action-items in action-bar and their views. private Map<GeckoMenuItem, View> mPrimaryActionItems; // Map of "ifRoom" action-items in action-bar and their views. private Map<GeckoMenuItem, View> mSecondaryActionItems; // Reference to a callback for menu events. private Callback mCallback; // Reference to menu presenter. private MenuPresenter mMenuPresenter; // Reference to "always" action-items bar in action-bar. private ActionItemBarPresenter mPrimaryActionItemBar; // Reference to "ifRoom" action-items bar in action-bar. private final ActionItemBarPresenter mSecondaryActionItemBar; // Adapter to hold the list of menu items. private MenuItemsAdapter mAdapter; // Show/hide icons in the list. boolean mShowIcons; public GeckoMenu(Context context) { this(context, null); } public GeckoMenu(Context context, AttributeSet attrs) { this(context, attrs, R.attr.geckoMenuListViewStyle); } public GeckoMenu(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // Attach an adapter. mAdapter = new MenuItemsAdapter(); setAdapter(mAdapter); setOnItemClickListener(this); mItems = new ArrayList<GeckoMenuItem>(); mPrimaryActionItems = new HashMap<GeckoMenuItem, View>(); mSecondaryActionItems = new HashMap<GeckoMenuItem, View>(); mPrimaryActionItemBar = (DefaultActionItemBar) LayoutInflater.from(context).inflate(R.layout.menu_action_bar, null); mSecondaryActionItemBar = (DefaultActionItemBar) LayoutInflater.from(context).inflate(R.layout.menu_secondary_action_bar, null); } private static void assertOnUiThread() { ThreadUtils.assertOnUiThread(THREAD_ASSERT_BEHAVIOR); } @Override public MenuItem add(CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(this, NO_ID, 0, title); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(this, itemId, order, titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(this, NO_ID, 0, titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(this, itemId, order, title); addItem(menuItem); return menuItem; } private void addItem(GeckoMenuItem menuItem) { assertOnUiThread(); menuItem.setOnShowAsActionChangedListener(this); mAdapter.addMenuItem(menuItem); mItems.add(menuItem); } private boolean addActionItem(final GeckoMenuItem menuItem) { assertOnUiThread(); menuItem.setOnShowAsActionChangedListener(this); final View actionView = menuItem.getActionView(); final int actionEnum = menuItem.getActionEnum(); boolean added = false; if (actionEnum == GeckoMenuItem.SHOW_AS_ACTION_ALWAYS) { if (mPrimaryActionItems.size() == 0 && mPrimaryActionItemBar instanceof DefaultActionItemBar) { // Reset the adapter before adding the header view to a list. setAdapter(null); addHeaderView((DefaultActionItemBar) mPrimaryActionItemBar); setAdapter(mAdapter); } if (added = mPrimaryActionItemBar.addActionItem(actionView)) { mPrimaryActionItems.put(menuItem, actionView); mItems.add(menuItem); } } else if (actionEnum == GeckoMenuItem.SHOW_AS_ACTION_IF_ROOM) { if (mSecondaryActionItems.size() == 0) { // Reset the adapter before adding the header view to a list. setAdapter(null); addHeaderView((DefaultActionItemBar) mSecondaryActionItemBar); setAdapter(mAdapter); } if (added = mSecondaryActionItemBar.addActionItem(actionView)) { mSecondaryActionItems.put(menuItem, actionView); mItems.add(menuItem); } } // Set the listeners. if (actionView instanceof MenuItemActionBar) { ((MenuItemActionBar) actionView).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleMenuItemClick(menuItem); } }); ((MenuItemActionBar) actionView).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { handleMenuItemLongClick(menuItem); return true; } }); } else if (actionView instanceof MenuItemActionView) { ((MenuItemActionView) actionView).setMenuItemClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleMenuItemClick(menuItem); } }); ((MenuItemActionView) actionView).setMenuItemLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { handleMenuItemLongClick(menuItem); return true; } }); } return added; } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { return 0; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { MenuItem menuItem = add(groupId, itemId, order, title); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { MenuItem menuItem = add(groupId, itemId, order, titleRes); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(CharSequence title) { MenuItem menuItem = add(title); return addSubMenu(menuItem); } @Override public SubMenu addSubMenu(int titleRes) { MenuItem menuItem = add(titleRes); return addSubMenu(menuItem); } private SubMenu addSubMenu(MenuItem menuItem) { GeckoSubMenu subMenu = new GeckoSubMenu(getContext()); subMenu.setMenuItem(menuItem); subMenu.setCallback(mCallback); subMenu.setMenuPresenter(mMenuPresenter); ((GeckoMenuItem) menuItem).setSubMenu(subMenu); return subMenu; } private void removePrimaryActionBarView() { // Reset the adapter before removing the header view from a list. setAdapter(null); removeHeaderView((DefaultActionItemBar) mPrimaryActionItemBar); setAdapter(mAdapter); } private void removeSecondaryActionBarView() { // Reset the adapter before removing the header view from a list. setAdapter(null); removeHeaderView((DefaultActionItemBar) mSecondaryActionItemBar); setAdapter(mAdapter); } @Override public void clear() { assertOnUiThread(); for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { SubMenu sub = menuItem.getSubMenu(); if (sub == null) { continue; } try { sub.clear(); } catch (Exception ex) { Log.e(LOGTAG, "Couldn't clear submenu.", ex); } } } mAdapter.clear(); mItems.clear(); /* * Reinflating the menu will re-add any action items to the toolbar, so * remove the old ones. This also ensures that any text associated with * these is switched to the correct locale. */ if (mPrimaryActionItemBar != null) { for (View item : mPrimaryActionItems.values()) { mPrimaryActionItemBar.removeActionItem(item); } } mPrimaryActionItems.clear(); if (mSecondaryActionItemBar != null) { for (View item : mSecondaryActionItems.values()) { mSecondaryActionItemBar.removeActionItem(item); } } mSecondaryActionItems.clear(); // Remove the view, too -- the first addActionItem will re-add it, // and this is simpler than changing that logic. if (mPrimaryActionItemBar instanceof DefaultActionItemBar) { removePrimaryActionBarView(); } removeSecondaryActionBarView(); } @Override public void close() { if (mMenuPresenter != null) mMenuPresenter.closeMenu(); } private void showMenu(View viewForMenu) { if (mMenuPresenter != null) mMenuPresenter.showMenu(viewForMenu); } @Override public MenuItem findItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) { return menuItem; } else if (menuItem.hasSubMenu()) { if (!menuItem.hasActionProvider()) { SubMenu subMenu = menuItem.getSubMenu(); MenuItem item = subMenu.findItem(id); if (item != null) return item; } } } return null; } @Override public MenuItem getItem(int index) { if (index < mItems.size()) return mItems.get(index); return null; } @Override public boolean hasVisibleItems() { assertOnUiThread(); for (GeckoMenuItem menuItem : mItems) { if (menuItem.isVisible() && !mPrimaryActionItems.containsKey(menuItem) && !mSecondaryActionItems.containsKey(menuItem)) return true; } return false; } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return true; } @Override public boolean performIdentifierAction(int id, int flags) { return false; } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return false; } @Override public void removeGroup(int groupId) { } @Override public void removeItem(int id) { assertOnUiThread(); GeckoMenuItem item = (GeckoMenuItem) findItem(id); if (item == null) return; // Remove it from any sub-menu. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { SubMenu subMenu = menuItem.getSubMenu(); if (subMenu != null && subMenu.findItem(id) != null) { subMenu.removeItem(id); return; } } } // Remove it from own menu. if (mPrimaryActionItems.containsKey(item)) { if (mPrimaryActionItemBar != null) mPrimaryActionItemBar.removeActionItem(mPrimaryActionItems.get(item)); mPrimaryActionItems.remove(item); mItems.remove(item); if (mPrimaryActionItems.size() == 0 && mPrimaryActionItemBar instanceof DefaultActionItemBar) { removePrimaryActionBarView(); } return; } if (mSecondaryActionItems.containsKey(item)) { if (mSecondaryActionItemBar != null) mSecondaryActionItemBar.removeActionItem(mSecondaryActionItems.get(item)); mSecondaryActionItems.remove(item); mItems.remove(item); if (mSecondaryActionItems.size() == 0) { removeSecondaryActionBarView(); } return; } mAdapter.removeMenuItem(item); mItems.remove(item); } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { } @Override public void setGroupEnabled(int group, boolean enabled) { } @Override public void setGroupVisible(int group, boolean visible) { } @Override public void setQwertyMode(boolean isQwerty) { } @Override public int size() { return mItems.size(); } @Override public boolean hasActionItemBar() { return (mPrimaryActionItemBar != null) && (mSecondaryActionItemBar != null); } @Override public void onShowAsActionChanged(GeckoMenuItem item) { removeItem(item.getItemId()); if (item.isActionItem() && addActionItem(item)) { return; } addItem(item); } public void onItemChanged(GeckoMenuItem item) { assertOnUiThread(); if (item.isActionItem()) { final View actionView; if (item.getActionEnum() == GeckoMenuItem.SHOW_AS_ACTION_ALWAYS) { actionView = mPrimaryActionItems.get(item); } else { actionView = mSecondaryActionItems.get(item); } if (actionView != null) { // The update could be coming from the background thread. // Post a runnable on the UI thread of the view for it to update. final GeckoMenuItem menuItem = item; actionView.post(new Runnable() { @Override public void run() { if (menuItem.isVisible()) { actionView.setVisibility(View.VISIBLE); if (actionView instanceof MenuItemActionBar) { ((MenuItemActionBar) actionView).initialize(menuItem); } else { ((MenuItemActionView) actionView).initialize(menuItem); } } else { actionView.setVisibility(View.GONE); } } }); } } else { mAdapter.notifyDataSetChanged(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // We might be showing headers. Account them while using the position. position -= getHeaderViewsCount(); GeckoMenuItem item = mAdapter.getItem(position); handleMenuItemClick(item); } void handleMenuItemClick(GeckoMenuItem item) { if (!item.isEnabled()) return; if (item.invoke()) { close(); } else if (item.hasSubMenu()) { // Refresh the submenu for the provider. GeckoActionProvider provider = item.getGeckoActionProvider(); if (provider != null) { GeckoSubMenu subMenu = new GeckoSubMenu(getContext()); subMenu.setShowIcons(true); provider.onPrepareSubMenu(subMenu); item.setSubMenu(subMenu); } // Show the submenu. GeckoSubMenu subMenu = (GeckoSubMenu) item.getSubMenu(); showMenu(subMenu); } else { close(); mCallback.onMenuItemClick(item); } } void handleMenuItemLongClick(GeckoMenuItem item) { if(!item.isEnabled()) { return; } if(mCallback != null) { mCallback.onMenuItemLongClick(item); } } public Callback getCallback() { return mCallback; } public MenuPresenter getMenuPresenter() { return mMenuPresenter; } public void setCallback(Callback callback) { mCallback = callback; // Update the submenus just in case this changes on the fly. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu(); subMenu.setCallback(mCallback); } } } public void setMenuPresenter(MenuPresenter presenter) { mMenuPresenter = presenter; // Update the submenus just in case this changes on the fly. for (GeckoMenuItem menuItem : mItems) { if (menuItem.hasSubMenu()) { GeckoSubMenu subMenu = (GeckoSubMenu) menuItem.getSubMenu(); subMenu.setMenuPresenter(mMenuPresenter); } } } public void setActionItemBarPresenter(ActionItemBarPresenter presenter) { mPrimaryActionItemBar = presenter; } public void setShowIcons(boolean show) { if (mShowIcons != show) { mShowIcons = show; mAdapter.notifyDataSetChanged(); } } // Action Items are added to the header view by default. // URL bar can register itself as a presenter, in case it has a different place to show them. public static class DefaultActionItemBar extends LinearLayout implements ActionItemBarPresenter { private final int mRowHeight; private float mWeightSum; public DefaultActionItemBar(Context context) { this(context, null); } public DefaultActionItemBar(Context context, AttributeSet attrs) { super(context, attrs); mRowHeight = getResources().getDimensionPixelSize(R.dimen.menu_item_row_height); } @Override public boolean addActionItem(View actionItem) { ViewGroup.LayoutParams actualParams = actionItem.getLayoutParams(); LinearLayout.LayoutParams params; if (actualParams != null) { params = new LinearLayout.LayoutParams(actionItem.getLayoutParams()); params.width = 0; } else { params = new LinearLayout.LayoutParams(0, mRowHeight); } if (actionItem instanceof MenuItemActionView) { params.weight = ((MenuItemActionView) actionItem).getChildCount(); } else { params.weight = 1.0f; } mWeightSum += params.weight; actionItem.setLayoutParams(params); addView(actionItem); setWeightSum(mWeightSum); return true; } @Override public void removeActionItem(View actionItem) { if (indexOfChild(actionItem) != -1) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) actionItem.getLayoutParams(); mWeightSum -= params.weight; removeView(actionItem); } } } // Adapter to bind menu items to the list. private class MenuItemsAdapter extends BaseAdapter { private static final int VIEW_TYPE_DEFAULT = 0; private static final int VIEW_TYPE_ACTION_MODE = 1; private List<GeckoMenuItem> mItems; public MenuItemsAdapter() { mItems = new ArrayList<GeckoMenuItem>(); } @Override public int getCount() { if (mItems == null) return 0; int visibleCount = 0; for (GeckoMenuItem item : mItems) { if (item.isVisible()) visibleCount++; } return visibleCount; } @Override public GeckoMenuItem getItem(int position) { for (GeckoMenuItem item : mItems) { if (item.isVisible()) { position--; if (position < 0) return item; } } return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { GeckoMenuItem item = getItem(position); GeckoMenuItem.Layout view = null; // Try to re-use the view. if (convertView == null && getItemViewType(position) == VIEW_TYPE_DEFAULT) { view = new MenuItemDefault(parent.getContext(), null); } else { view = (GeckoMenuItem.Layout) convertView; } if (view == null || view instanceof MenuItemActionView) { // Always get from the menu item. // This will ensure that the default activity is refreshed. view = (MenuItemActionView) item.getActionView(); // ListView will not perform an item click if the row has a focusable view in it. // Hence, forward the click event on the menu item in the action-view to the ListView. final View actionView = (View) view; final int pos = position; final long id = getItemId(position); ((MenuItemActionView) view).setMenuItemClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GeckoMenu listView = GeckoMenu.this; listView.performItemClick(actionView, pos + listView.getHeaderViewsCount(), id); } }); } // Initialize the view. view.setShowIcon(mShowIcons); view.initialize(item); return (View) view; } @Override public int getItemViewType(int position) { return getItem(position).getGeckoActionProvider() == null ? VIEW_TYPE_DEFAULT : VIEW_TYPE_ACTION_MODE; } @Override public int getViewTypeCount() { return 2; } @Override public boolean hasStableIds() { return false; } @Override public boolean areAllItemsEnabled() { // Setting this to true is a workaround to fix disappearing // dividers in the menu (bug 963249). return true; } @Override public boolean isEnabled(int position) { // Setting this to true is a workaround to fix disappearing // dividers in the menu in L (bug 1050780). return true; } public void addMenuItem(GeckoMenuItem menuItem) { if (mItems.contains(menuItem)) return; // Insert it<SUF> int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() > menuItem.getOrder()) { mItems.add(index, menuItem); notifyDataSetChanged(); return; } else { index++; } } // Add the menuItem at the end. mItems.add(menuItem); notifyDataSetChanged(); } public void removeMenuItem(GeckoMenuItem menuItem) { // Remove it from the list. mItems.remove(menuItem); notifyDataSetChanged(); } public void clear() { mItems.clear(); notifyDataSetChanged(); } public GeckoMenuItem getMenuItem(int id) { for (GeckoMenuItem item : mItems) { if (item.getItemId() == id) return item; } return null; } } }
24063_16
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.orc.stream; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import io.trino.orc.OrcCorruptionException; import io.trino.orc.checkpoint.DecimalStreamCheckpoint; import java.io.IOException; import static com.google.common.base.Verify.verify; import static io.trino.orc.checkpoint.InputStreamCheckpoint.decodeCompressedBlockOffset; import static io.trino.orc.checkpoint.InputStreamCheckpoint.decodeDecompressedOffset; public class DecimalInputStream implements ValueInputStream<DecimalStreamCheckpoint> { private static final long LONG_MASK = 0x80_80_80_80_80_80_80_80L; private static final int INT_MASK = 0x80_80_80_80; private final OrcChunkLoader chunkLoader; private Slice block = Slices.EMPTY_SLICE; // reference to current (decoded) data block. Can be either a reference to the buffer or to current chunk private int blockOffset; // position within current data block private long lastCheckpoint; public DecimalInputStream(OrcChunkLoader chunkLoader) { this.chunkLoader = chunkLoader; } @Override public void seekToCheckpoint(DecimalStreamCheckpoint checkpoint) throws IOException { long newCheckpoint = checkpoint.getInputStreamCheckpoint(); // if checkpoint starts at the same compressed position... // (we're checking for an empty block because empty blocks signify that we possibly read all the data in the existing // buffer, so last checkpoint is no longer valid) if (block.length() > 0 && decodeCompressedBlockOffset(newCheckpoint) == decodeCompressedBlockOffset(lastCheckpoint)) { // and decompressed position is within our block, reposition in the block directly int blockOffset = decodeDecompressedOffset(newCheckpoint) - decodeDecompressedOffset(lastCheckpoint); if (blockOffset >= 0 && blockOffset < block.length()) { this.blockOffset = blockOffset; // do not change last checkpoint because we have not moved positions return; } } chunkLoader.seekToCheckpoint(newCheckpoint); lastCheckpoint = newCheckpoint; block = Slices.EMPTY_SLICE; blockOffset = 0; } // result must have at least batchSize * 2 capacity @SuppressWarnings("PointlessBitwiseExpression") public void nextLongDecimal(long[] result, int batchSize) throws IOException { verify(result.length >= batchSize * 2); int count = 0; while (count < batchSize) { if (blockOffset == block.length()) { advance(); } while (blockOffset <= block.length() - 20) { // we'll read 2 longs + 1 int long low; long middle = 0; int high = 0; // low bits long current = block.getLong(blockOffset); int zeros = Long.numberOfTrailingZeros(~current & LONG_MASK); int end = (zeros + 1) / 8; blockOffset += end; boolean negative = (current & 1) == 1; low = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7; low |= (current & 0x7F_00_00_00_00_00_00L) >>> 6; low |= (current & 0x7F_00_00_00_00_00L) >>> 5; low |= (current & 0x7F_00_00_00_00L) >>> 4; low |= (current & 0x7F_00_00_00) >>> 3; low |= (current & 0x7F_00_00) >>> 2; low |= (current & 0x7F_00) >>> 1; low |= (current & 0x7F) >>> 0; low = low & ((1L << (end * 7)) - 1); // middle bits if (zeros == 64) { current = block.getLong(blockOffset); zeros = Long.numberOfTrailingZeros(~current & LONG_MASK); end = (zeros + 1) / 8; blockOffset += end; middle = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7; middle |= (current & 0x7F_00_00_00_00_00_00L) >>> 6; middle |= (current & 0x7F_00_00_00_00_00L) >>> 5; middle |= (current & 0x7F_00_00_00_00L) >>> 4; middle |= (current & 0x7F_00_00_00) >>> 3; middle |= (current & 0x7F_00_00) >>> 2; middle |= (current & 0x7F_00) >>> 1; middle |= (current & 0x7F) >>> 0; middle = middle & ((1L << (end * 7)) - 1); // high bits if (zeros == 64) { int last = block.getInt(blockOffset); zeros = Integer.numberOfTrailingZeros(~last & INT_MASK); end = (zeros + 1) / 8; blockOffset += end; high = (last & 0x7F_00_00) >>> 2; high |= (last & 0x7F_00) >>> 1; high |= (last & 0x7F) >>> 0; high = high & ((1 << (end * 7)) - 1); if (end == 4 || high > 0xFF_FF) { // only 127 - (55 + 56) = 16 bits allowed in high throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits"); } } } emitLongDecimal(result, count, low, middle, high, negative); count++; if (count == batchSize) { return; } } // handle the tail of the current block count = decodeLongDecimalTail(result, count, batchSize); } } private int decodeLongDecimalTail(long[] result, int count, int batchSize) throws IOException { boolean negative = false; long low = 0; long middle = 0; int high = 0; long value; boolean last = false; if (blockOffset == block.length()) { advance(); } int offset = 0; while (true) { value = block.getByte(blockOffset); blockOffset++; if (offset == 0) { negative = (value & 1) == 1; low |= (value & 0x7F); } else if (offset < 8) { low |= (value & 0x7F) << (offset * 7); } else if (offset < 16) { middle |= (value & 0x7F) << ((offset - 8) * 7); } else if (offset < 19) { high = (int) (high | (value & 0x7F) << ((offset - 16) * 7)); } else { throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits"); } offset++; if ((value & 0x80) == 0) { if (high > 0xFF_FF) { // only 127 - (55 + 56) = 16 bits allowed in high throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits"); } emitLongDecimal(result, count, low, middle, high, negative); count++; low = 0; middle = 0; high = 0; offset = 0; if (blockOffset == block.length()) { // the last value aligns with the end of the block, so just // reset the block and loop around to optimized decoding break; } if (last || count == batchSize) { break; } } else if (blockOffset == block.length()) { last = true; advance(); } } return count; } private static void emitLongDecimal(long[] result, int offset, long low, long middle, long high, boolean negative) { long lower = (low >>> 1) | (middle << 55); // drop the sign bit from low long upper = (middle >>> 9) | (high << 47); if (negative) { // ORC encodes decimals using a zig-zag vint strategy // For negative values, the encoded value is given by: // encoded = -value * 2 - 1 // // Therefore, // value = -(encoded + 1) / 2 // = -encoded / 2 - 1/2 // // Given the identity -v = ~v + 1 for negating a value using // two's complement representation, // // value = (~encoded + 1) / 2 - 1/2 // = ~encoded / 2 + 1/2 - 1/2 // = ~encoded / 2 // // The shift is performed above as the bits are assembled. The negation // is performed here. lower = ~lower; upper = ~upper; } result[2 * offset] = upper; result[2 * offset + 1] = lower; } @SuppressWarnings("PointlessBitwiseExpression") public void nextShortDecimal(long[] result, int batchSize) throws IOException { verify(result.length >= batchSize); int count = 0; while (count < batchSize) { if (blockOffset == block.length()) { advance(); } while (blockOffset <= block.length() - 12) { // we'll read 1 longs + 1 int long low; int high = 0; // low bits long current = block.getLong(blockOffset); int zeros = Long.numberOfTrailingZeros(~current & LONG_MASK); int end = (zeros + 1) / 8; blockOffset += end; low = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7; low |= (current & 0x7F_00_00_00_00_00_00L) >>> 6; low |= (current & 0x7F_00_00_00_00_00L) >>> 5; low |= (current & 0x7F_00_00_00_00L) >>> 4; low |= (current & 0x7F_00_00_00) >>> 3; low |= (current & 0x7F_00_00) >>> 2; low |= (current & 0x7F_00) >>> 1; low |= (current & 0x7F) >>> 0; low = low & ((1L << (end * 7)) - 1); // high bits if (zeros == 64) { int last = block.getInt(blockOffset); zeros = Integer.numberOfTrailingZeros(~last & INT_MASK); end = (zeros + 1) / 8; blockOffset += end; high = (last & 0x7F_00) >>> 1; high |= (last & 0x7F) >>> 0; high = high & ((1 << (end * 7)) - 1); if (end >= 3 || high > 0xFF) { // only 63 - (55) = 8 bits allowed in high throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)"); } } emitShortDecimal(result, count, low, high); count++; if (count == batchSize) { return; } } // handle the tail of the current block count = decodeShortDecimalTail(result, count, batchSize); } } private int decodeShortDecimalTail(long[] result, int count, int batchSize) throws IOException { long low = 0; long high = 0; long value; boolean last = false; int offset = 0; if (blockOffset == block.length()) { advance(); } while (true) { value = block.getByte(blockOffset); blockOffset++; if (offset == 0) { low |= (value & 0x7F); } else if (offset < 8) { low |= (value & 0x7F) << (offset * 7); } else if (offset < 11) { high |= (value & 0x7F) << ((offset - 8) * 7); } else { throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)"); } offset++; if ((value & 0x80) == 0) { if (high > 0xFF) { // only 63 - (55) = 8 bits allowed in high throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)"); } emitShortDecimal(result, count, low, high); count++; low = 0; high = 0; offset = 0; if (blockOffset == block.length()) { // the last value aligns with the end of the block, so just // reset the block and loop around to optimized decoding break; } if (last || count == batchSize) { break; } } else if (blockOffset == block.length()) { last = true; advance(); } } return count; } private static void emitShortDecimal(long[] result, int offset, long low, long high) { boolean negative = (low & 1) == 1; long value = (low >>> 1) | (high << 55); // drop the sign bit from low if (negative) { value = ~value; } result[offset] = value; } @Override public void skip(long items) throws IOException { if (items == 0) { return; } if (blockOffset == block.length()) { advance(); } int count = 0; while (true) { while (blockOffset <= block.length() - Long.BYTES) { // only safe if there's at least one long to read long current = block.getLong(blockOffset); int increment = Long.bitCount(~current & LONG_MASK); if (count + increment >= items) { // reached the tail, so bail out and process byte at a time break; } count += increment; blockOffset += Long.BYTES; } while (blockOffset < block.length()) { // tail -- byte at a time byte current = block.getByte(blockOffset); blockOffset++; if ((current & 0x80) == 0) { count++; if (count == items) { return; } } } advance(); } } private void advance() throws IOException { block = chunkLoader.nextChunk(); lastCheckpoint = chunkLoader.getLastCheckpoint(); blockOffset = 0; } }
trinodb/trino
lib/trino-orc/src/main/java/io/trino/orc/stream/DecimalInputStream.java
4,176
// ORC encodes decimals using a zig-zag vint strategy
line_comment
nl
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.orc.stream; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import io.trino.orc.OrcCorruptionException; import io.trino.orc.checkpoint.DecimalStreamCheckpoint; import java.io.IOException; import static com.google.common.base.Verify.verify; import static io.trino.orc.checkpoint.InputStreamCheckpoint.decodeCompressedBlockOffset; import static io.trino.orc.checkpoint.InputStreamCheckpoint.decodeDecompressedOffset; public class DecimalInputStream implements ValueInputStream<DecimalStreamCheckpoint> { private static final long LONG_MASK = 0x80_80_80_80_80_80_80_80L; private static final int INT_MASK = 0x80_80_80_80; private final OrcChunkLoader chunkLoader; private Slice block = Slices.EMPTY_SLICE; // reference to current (decoded) data block. Can be either a reference to the buffer or to current chunk private int blockOffset; // position within current data block private long lastCheckpoint; public DecimalInputStream(OrcChunkLoader chunkLoader) { this.chunkLoader = chunkLoader; } @Override public void seekToCheckpoint(DecimalStreamCheckpoint checkpoint) throws IOException { long newCheckpoint = checkpoint.getInputStreamCheckpoint(); // if checkpoint starts at the same compressed position... // (we're checking for an empty block because empty blocks signify that we possibly read all the data in the existing // buffer, so last checkpoint is no longer valid) if (block.length() > 0 && decodeCompressedBlockOffset(newCheckpoint) == decodeCompressedBlockOffset(lastCheckpoint)) { // and decompressed position is within our block, reposition in the block directly int blockOffset = decodeDecompressedOffset(newCheckpoint) - decodeDecompressedOffset(lastCheckpoint); if (blockOffset >= 0 && blockOffset < block.length()) { this.blockOffset = blockOffset; // do not change last checkpoint because we have not moved positions return; } } chunkLoader.seekToCheckpoint(newCheckpoint); lastCheckpoint = newCheckpoint; block = Slices.EMPTY_SLICE; blockOffset = 0; } // result must have at least batchSize * 2 capacity @SuppressWarnings("PointlessBitwiseExpression") public void nextLongDecimal(long[] result, int batchSize) throws IOException { verify(result.length >= batchSize * 2); int count = 0; while (count < batchSize) { if (blockOffset == block.length()) { advance(); } while (blockOffset <= block.length() - 20) { // we'll read 2 longs + 1 int long low; long middle = 0; int high = 0; // low bits long current = block.getLong(blockOffset); int zeros = Long.numberOfTrailingZeros(~current & LONG_MASK); int end = (zeros + 1) / 8; blockOffset += end; boolean negative = (current & 1) == 1; low = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7; low |= (current & 0x7F_00_00_00_00_00_00L) >>> 6; low |= (current & 0x7F_00_00_00_00_00L) >>> 5; low |= (current & 0x7F_00_00_00_00L) >>> 4; low |= (current & 0x7F_00_00_00) >>> 3; low |= (current & 0x7F_00_00) >>> 2; low |= (current & 0x7F_00) >>> 1; low |= (current & 0x7F) >>> 0; low = low & ((1L << (end * 7)) - 1); // middle bits if (zeros == 64) { current = block.getLong(blockOffset); zeros = Long.numberOfTrailingZeros(~current & LONG_MASK); end = (zeros + 1) / 8; blockOffset += end; middle = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7; middle |= (current & 0x7F_00_00_00_00_00_00L) >>> 6; middle |= (current & 0x7F_00_00_00_00_00L) >>> 5; middle |= (current & 0x7F_00_00_00_00L) >>> 4; middle |= (current & 0x7F_00_00_00) >>> 3; middle |= (current & 0x7F_00_00) >>> 2; middle |= (current & 0x7F_00) >>> 1; middle |= (current & 0x7F) >>> 0; middle = middle & ((1L << (end * 7)) - 1); // high bits if (zeros == 64) { int last = block.getInt(blockOffset); zeros = Integer.numberOfTrailingZeros(~last & INT_MASK); end = (zeros + 1) / 8; blockOffset += end; high = (last & 0x7F_00_00) >>> 2; high |= (last & 0x7F_00) >>> 1; high |= (last & 0x7F) >>> 0; high = high & ((1 << (end * 7)) - 1); if (end == 4 || high > 0xFF_FF) { // only 127 - (55 + 56) = 16 bits allowed in high throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits"); } } } emitLongDecimal(result, count, low, middle, high, negative); count++; if (count == batchSize) { return; } } // handle the tail of the current block count = decodeLongDecimalTail(result, count, batchSize); } } private int decodeLongDecimalTail(long[] result, int count, int batchSize) throws IOException { boolean negative = false; long low = 0; long middle = 0; int high = 0; long value; boolean last = false; if (blockOffset == block.length()) { advance(); } int offset = 0; while (true) { value = block.getByte(blockOffset); blockOffset++; if (offset == 0) { negative = (value & 1) == 1; low |= (value & 0x7F); } else if (offset < 8) { low |= (value & 0x7F) << (offset * 7); } else if (offset < 16) { middle |= (value & 0x7F) << ((offset - 8) * 7); } else if (offset < 19) { high = (int) (high | (value & 0x7F) << ((offset - 16) * 7)); } else { throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits"); } offset++; if ((value & 0x80) == 0) { if (high > 0xFF_FF) { // only 127 - (55 + 56) = 16 bits allowed in high throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits"); } emitLongDecimal(result, count, low, middle, high, negative); count++; low = 0; middle = 0; high = 0; offset = 0; if (blockOffset == block.length()) { // the last value aligns with the end of the block, so just // reset the block and loop around to optimized decoding break; } if (last || count == batchSize) { break; } } else if (blockOffset == block.length()) { last = true; advance(); } } return count; } private static void emitLongDecimal(long[] result, int offset, long low, long middle, long high, boolean negative) { long lower = (low >>> 1) | (middle << 55); // drop the sign bit from low long upper = (middle >>> 9) | (high << 47); if (negative) { // ORC encodes<SUF> // For negative values, the encoded value is given by: // encoded = -value * 2 - 1 // // Therefore, // value = -(encoded + 1) / 2 // = -encoded / 2 - 1/2 // // Given the identity -v = ~v + 1 for negating a value using // two's complement representation, // // value = (~encoded + 1) / 2 - 1/2 // = ~encoded / 2 + 1/2 - 1/2 // = ~encoded / 2 // // The shift is performed above as the bits are assembled. The negation // is performed here. lower = ~lower; upper = ~upper; } result[2 * offset] = upper; result[2 * offset + 1] = lower; } @SuppressWarnings("PointlessBitwiseExpression") public void nextShortDecimal(long[] result, int batchSize) throws IOException { verify(result.length >= batchSize); int count = 0; while (count < batchSize) { if (blockOffset == block.length()) { advance(); } while (blockOffset <= block.length() - 12) { // we'll read 1 longs + 1 int long low; int high = 0; // low bits long current = block.getLong(blockOffset); int zeros = Long.numberOfTrailingZeros(~current & LONG_MASK); int end = (zeros + 1) / 8; blockOffset += end; low = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7; low |= (current & 0x7F_00_00_00_00_00_00L) >>> 6; low |= (current & 0x7F_00_00_00_00_00L) >>> 5; low |= (current & 0x7F_00_00_00_00L) >>> 4; low |= (current & 0x7F_00_00_00) >>> 3; low |= (current & 0x7F_00_00) >>> 2; low |= (current & 0x7F_00) >>> 1; low |= (current & 0x7F) >>> 0; low = low & ((1L << (end * 7)) - 1); // high bits if (zeros == 64) { int last = block.getInt(blockOffset); zeros = Integer.numberOfTrailingZeros(~last & INT_MASK); end = (zeros + 1) / 8; blockOffset += end; high = (last & 0x7F_00) >>> 1; high |= (last & 0x7F) >>> 0; high = high & ((1 << (end * 7)) - 1); if (end >= 3 || high > 0xFF) { // only 63 - (55) = 8 bits allowed in high throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)"); } } emitShortDecimal(result, count, low, high); count++; if (count == batchSize) { return; } } // handle the tail of the current block count = decodeShortDecimalTail(result, count, batchSize); } } private int decodeShortDecimalTail(long[] result, int count, int batchSize) throws IOException { long low = 0; long high = 0; long value; boolean last = false; int offset = 0; if (blockOffset == block.length()) { advance(); } while (true) { value = block.getByte(blockOffset); blockOffset++; if (offset == 0) { low |= (value & 0x7F); } else if (offset < 8) { low |= (value & 0x7F) << (offset * 7); } else if (offset < 11) { high |= (value & 0x7F) << ((offset - 8) * 7); } else { throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)"); } offset++; if ((value & 0x80) == 0) { if (high > 0xFF) { // only 63 - (55) = 8 bits allowed in high throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)"); } emitShortDecimal(result, count, low, high); count++; low = 0; high = 0; offset = 0; if (blockOffset == block.length()) { // the last value aligns with the end of the block, so just // reset the block and loop around to optimized decoding break; } if (last || count == batchSize) { break; } } else if (blockOffset == block.length()) { last = true; advance(); } } return count; } private static void emitShortDecimal(long[] result, int offset, long low, long high) { boolean negative = (low & 1) == 1; long value = (low >>> 1) | (high << 55); // drop the sign bit from low if (negative) { value = ~value; } result[offset] = value; } @Override public void skip(long items) throws IOException { if (items == 0) { return; } if (blockOffset == block.length()) { advance(); } int count = 0; while (true) { while (blockOffset <= block.length() - Long.BYTES) { // only safe if there's at least one long to read long current = block.getLong(blockOffset); int increment = Long.bitCount(~current & LONG_MASK); if (count + increment >= items) { // reached the tail, so bail out and process byte at a time break; } count += increment; blockOffset += Long.BYTES; } while (blockOffset < block.length()) { // tail -- byte at a time byte current = block.getByte(blockOffset); blockOffset++; if ((current & 0x80) == 0) { count++; if (count == items) { return; } } } advance(); } } private void advance() throws IOException { block = chunkLoader.nextChunk(); lastCheckpoint = chunkLoader.getLastCheckpoint(); blockOffset = 0; } }
128157_1
package nl.pdok; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; /** * * @author Raymond Kroon <[email protected]> */ public class BoyerMoorePatternMatcher { public final static int NO_OF_CHARS = 256; public final static int MAX_BUFFER_SIZE = 1024; private InputStream src; private HashMap<String, PatternCache> cache = new HashMap<>(); private boolean isAtMatch = false; private int bufferSize = 0; private byte[] buffer = new byte[MAX_BUFFER_SIZE]; private int bufferPosition = 0; private String previousPatternId = null; private int suggestedBufferPosition = 0; public BoyerMoorePatternMatcher(InputStream src) { this.src = src; } public boolean currentPositionIsMatch() { return isAtMatch; } public byte[] flushToNextMatch(String patternId) throws IOException { // een stukje buffer lezen, en de buffer aanvullen mits nodig // fuck de copy pasta onzin.... if (previousPatternId != null && previousPatternId.equals(patternId)) { bufferPosition = suggestedBufferPosition; } previousPatternId = patternId; byte[] flushResult = new byte[0]; isAtMatch = false; PatternCache pc = cache.get(patternId); while (true) { SearchResult result = search(buffer, bufferSize, pc.pattern, pc.patternLength, pc.badchars, bufferPosition); bufferPosition = result.offset; suggestedBufferPosition = result.suggestedNewOffset; flushResult = concat(flushResult, flushBuffer()); if (result.matched) { isAtMatch = true; return flushResult; } else { if (!fillBuffer()) { isAtMatch = false; flushResult = concat(flushResult, flushBuffer()); return flushResult; } } } } private byte[] flushBuffer() { // System.out.println("buffer"); // System.out.println(new String(buffer)); // System.out.println("/buffer/" + bufferPosition); byte[] flushed = Arrays.copyOfRange(buffer, 0, bufferPosition); // move currentPosition to front; buffer = Arrays.copyOfRange(buffer, bufferPosition, MAX_BUFFER_SIZE + bufferPosition); bufferSize = bufferSize - bufferPosition; suggestedBufferPosition = suggestedBufferPosition - bufferPosition; bufferPosition = 0; return flushed; } private boolean fillBuffer() throws IOException { if (bufferSize < MAX_BUFFER_SIZE) { int read = src.read(buffer, bufferSize, MAX_BUFFER_SIZE - bufferSize); bufferSize += read; return read > 0; } return true; } public byte[] concat(byte[] a, byte[] b) { int aLen = a.length; int bLen = b.length; byte[] c = new byte[aLen + bLen]; System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } private class PatternCache { public final byte[] pattern; public final int patternLength; public final int[] badchars; public PatternCache(byte[] pattern) { this.pattern = pattern; this.patternLength = pattern.length; this.badchars = badCharHeuristic(pattern); } } public void setPattern(String id, byte[] pattern) { cache.put(id, new PatternCache(pattern)); } public static int[] badCharHeuristic(byte[] pattern) { int[] result = new int[NO_OF_CHARS]; int patternSize = pattern.length; // default = -1 Arrays.fill(result, -1); for (int i = 0; i < patternSize; ++i) { result[byteValue(pattern[i])] = i; } return result; } public static class SearchResult { public final boolean matched; public final int offset; public final int suggestedNewOffset; public SearchResult(boolean matched, int offset, int suggestedNewOffset) { this.matched = matched; this.offset = offset; this.suggestedNewOffset = suggestedNewOffset; } } public static SearchResult search(byte[] src, byte[] pattern, int offset) { /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ return search(src, src.length, pattern, pattern.length, badCharHeuristic(pattern), offset); } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ public static SearchResult search(byte[] src, int srcLength, byte[] pattern, int patternLength, int[] badchars, int offset) { int s = offset; // s is shift of the pattern with respect to text while (s <= (srcLength - patternLength)) { int j = patternLength - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while (j >= 0 && pattern[j] == src[s + j]) { j--; } /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { //System.out.println("pattern found at index = " + s); /* Shift the pattern so that the next character in src aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ //s += (s+patternLength < srcLength) ? patternLength - badchars[src[s+patternLength]] : 1; return new SearchResult(true, s, (s + patternLength < srcLength) ? s + patternLength - badchars[src[s + patternLength]] : s + 1); } else { /* Shift the pattern so that the bad character in src aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += Math.max(1, j - badchars[byteValue(src[s + j])]); } } return new SearchResult(false, srcLength, s); } private static int byteValue(byte b) { return (int) b & 0xFF; } }
PDOK/xml-splitter
src/java/nl/pdok/BoyerMoorePatternMatcher.java
1,667
// een stukje buffer lezen, en de buffer aanvullen mits nodig
line_comment
nl
package nl.pdok; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; /** * * @author Raymond Kroon <[email protected]> */ public class BoyerMoorePatternMatcher { public final static int NO_OF_CHARS = 256; public final static int MAX_BUFFER_SIZE = 1024; private InputStream src; private HashMap<String, PatternCache> cache = new HashMap<>(); private boolean isAtMatch = false; private int bufferSize = 0; private byte[] buffer = new byte[MAX_BUFFER_SIZE]; private int bufferPosition = 0; private String previousPatternId = null; private int suggestedBufferPosition = 0; public BoyerMoorePatternMatcher(InputStream src) { this.src = src; } public boolean currentPositionIsMatch() { return isAtMatch; } public byte[] flushToNextMatch(String patternId) throws IOException { // een stukje<SUF> // fuck de copy pasta onzin.... if (previousPatternId != null && previousPatternId.equals(patternId)) { bufferPosition = suggestedBufferPosition; } previousPatternId = patternId; byte[] flushResult = new byte[0]; isAtMatch = false; PatternCache pc = cache.get(patternId); while (true) { SearchResult result = search(buffer, bufferSize, pc.pattern, pc.patternLength, pc.badchars, bufferPosition); bufferPosition = result.offset; suggestedBufferPosition = result.suggestedNewOffset; flushResult = concat(flushResult, flushBuffer()); if (result.matched) { isAtMatch = true; return flushResult; } else { if (!fillBuffer()) { isAtMatch = false; flushResult = concat(flushResult, flushBuffer()); return flushResult; } } } } private byte[] flushBuffer() { // System.out.println("buffer"); // System.out.println(new String(buffer)); // System.out.println("/buffer/" + bufferPosition); byte[] flushed = Arrays.copyOfRange(buffer, 0, bufferPosition); // move currentPosition to front; buffer = Arrays.copyOfRange(buffer, bufferPosition, MAX_BUFFER_SIZE + bufferPosition); bufferSize = bufferSize - bufferPosition; suggestedBufferPosition = suggestedBufferPosition - bufferPosition; bufferPosition = 0; return flushed; } private boolean fillBuffer() throws IOException { if (bufferSize < MAX_BUFFER_SIZE) { int read = src.read(buffer, bufferSize, MAX_BUFFER_SIZE - bufferSize); bufferSize += read; return read > 0; } return true; } public byte[] concat(byte[] a, byte[] b) { int aLen = a.length; int bLen = b.length; byte[] c = new byte[aLen + bLen]; System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } private class PatternCache { public final byte[] pattern; public final int patternLength; public final int[] badchars; public PatternCache(byte[] pattern) { this.pattern = pattern; this.patternLength = pattern.length; this.badchars = badCharHeuristic(pattern); } } public void setPattern(String id, byte[] pattern) { cache.put(id, new PatternCache(pattern)); } public static int[] badCharHeuristic(byte[] pattern) { int[] result = new int[NO_OF_CHARS]; int patternSize = pattern.length; // default = -1 Arrays.fill(result, -1); for (int i = 0; i < patternSize; ++i) { result[byteValue(pattern[i])] = i; } return result; } public static class SearchResult { public final boolean matched; public final int offset; public final int suggestedNewOffset; public SearchResult(boolean matched, int offset, int suggestedNewOffset) { this.matched = matched; this.offset = offset; this.suggestedNewOffset = suggestedNewOffset; } } public static SearchResult search(byte[] src, byte[] pattern, int offset) { /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ return search(src, src.length, pattern, pattern.length, badCharHeuristic(pattern), offset); } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ public static SearchResult search(byte[] src, int srcLength, byte[] pattern, int patternLength, int[] badchars, int offset) { int s = offset; // s is shift of the pattern with respect to text while (s <= (srcLength - patternLength)) { int j = patternLength - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while (j >= 0 && pattern[j] == src[s + j]) { j--; } /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { //System.out.println("pattern found at index = " + s); /* Shift the pattern so that the next character in src aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ //s += (s+patternLength < srcLength) ? patternLength - badchars[src[s+patternLength]] : 1; return new SearchResult(true, s, (s + patternLength < srcLength) ? s + patternLength - badchars[src[s + patternLength]] : s + 1); } else { /* Shift the pattern so that the bad character in src aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += Math.max(1, j - badchars[byteValue(src[s + j])]); } } return new SearchResult(false, srcLength, s); } private static int byteValue(byte b) { return (int) b & 0xFF; } }
82968_4
/* * Renjin : JVM-based interpreter for the R language for the statistical analysis * Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, a copy is available at * https://www.gnu.org/licenses/gpl-2.0.txt */ package org.renjin.primitives.combine; import org.renjin.eval.Context; import org.renjin.sexp.AtomicVector; import org.renjin.sexp.Null; import org.renjin.sexp.SEXP; import org.renjin.sexp.Vector; import java.util.List; /** * Special function to do rbind and use objectnames as rownames */ public class RowBindFunction extends AbstractBindFunction { public RowBindFunction() { super("rbind", MatrixDim.ROW); } @Override protected SEXP apply(Context context, List<BindArgument> bindArguments) { // establish the number of columns // First check actual matrices int columns = computeColumnCount(context, bindArguments); // Zero-length vectors like integer(0) are ONLY included // if the output has zero columns. Otherwise they are discarded. if(columns > 0) { bindArguments = excludeZeroLengthVectors(bindArguments); } int rows = countRowOrCols(bindArguments, MatrixDim.ROW); // Construct the result Vector.Builder vectorBuilder = builderForCommonType(bindArguments); Matrix2dBuilder builder = new Matrix2dBuilder(vectorBuilder, rows, columns); for (int j = 0; j != columns; ++j) { for (BindArgument argument : bindArguments) { for (int i = 0; i != argument.getRows(); ++i) { builder.addFrom(argument, i, j); } } } AtomicVector rowNames = combineDimNames(bindArguments, MatrixDim.ROW); AtomicVector colNames = dimNamesFromLongest(bindArguments, MatrixDim.COL, columns); if(allZeroLengthVectors(bindArguments)) { // This doesn't seem like a great choice, but reproduce // behavior of GNU R builder.setDimNames(Null.INSTANCE, Null.INSTANCE); } else if(rowNames != Null.INSTANCE || colNames != Null.INSTANCE) { builder.setDimNames(rowNames, colNames); } return builder.build(); } private int computeColumnCount(Context context, List<BindArgument> bindArguments) { int columns = findCommonMatrixDimLength(bindArguments, MatrixDim.COL); // if there are no actual matrices, then use the longest // vector length as the number of columns if (columns == -1) { columns = findMaxLength(bindArguments); } // now check that all vectors lengths are multiples of the column length warnIfVectorLengthsAreNotMultiple(context, bindArguments, columns); return columns; } }
bedatadriven/renjin
core/src/main/java/org/renjin/primitives/combine/RowBindFunction.java
856
// Zero-length vectors like integer(0) are ONLY included
line_comment
nl
/* * Renjin : JVM-based interpreter for the R language for the statistical analysis * Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, a copy is available at * https://www.gnu.org/licenses/gpl-2.0.txt */ package org.renjin.primitives.combine; import org.renjin.eval.Context; import org.renjin.sexp.AtomicVector; import org.renjin.sexp.Null; import org.renjin.sexp.SEXP; import org.renjin.sexp.Vector; import java.util.List; /** * Special function to do rbind and use objectnames as rownames */ public class RowBindFunction extends AbstractBindFunction { public RowBindFunction() { super("rbind", MatrixDim.ROW); } @Override protected SEXP apply(Context context, List<BindArgument> bindArguments) { // establish the number of columns // First check actual matrices int columns = computeColumnCount(context, bindArguments); // Zero-length vectors<SUF> // if the output has zero columns. Otherwise they are discarded. if(columns > 0) { bindArguments = excludeZeroLengthVectors(bindArguments); } int rows = countRowOrCols(bindArguments, MatrixDim.ROW); // Construct the result Vector.Builder vectorBuilder = builderForCommonType(bindArguments); Matrix2dBuilder builder = new Matrix2dBuilder(vectorBuilder, rows, columns); for (int j = 0; j != columns; ++j) { for (BindArgument argument : bindArguments) { for (int i = 0; i != argument.getRows(); ++i) { builder.addFrom(argument, i, j); } } } AtomicVector rowNames = combineDimNames(bindArguments, MatrixDim.ROW); AtomicVector colNames = dimNamesFromLongest(bindArguments, MatrixDim.COL, columns); if(allZeroLengthVectors(bindArguments)) { // This doesn't seem like a great choice, but reproduce // behavior of GNU R builder.setDimNames(Null.INSTANCE, Null.INSTANCE); } else if(rowNames != Null.INSTANCE || colNames != Null.INSTANCE) { builder.setDimNames(rowNames, colNames); } return builder.build(); } private int computeColumnCount(Context context, List<BindArgument> bindArguments) { int columns = findCommonMatrixDimLength(bindArguments, MatrixDim.COL); // if there are no actual matrices, then use the longest // vector length as the number of columns if (columns == -1) { columns = findMaxLength(bindArguments); } // now check that all vectors lengths are multiples of the column length warnIfVectorLengthsAreNotMultiple(context, bindArguments, columns); return columns; } }
90913_11
/* * "ChemLab", Desktop helper application for chemists. * Copyright (C) 1996-1998, 2015 by Serg V. Zhdanovskih (aka Alchemist, aka Norseman). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package chemlab.core.chemical; import bslib.common.BaseObject; import bslib.common.RefObject; import bslib.math.ExtMath; /** * * @author Serg V. Zhdanovskih, Ruslan N. Garipov * @since 0.3.0 */ public final class BalanceSolver extends BaseObject { public static final int RES_OK = 0; public static final int RES_NoUniqueSolution = 1; public static final int RES_EquationCanNotBeBalanced = 2; private final int[][] fData = new int[9][10]; private int[] fFactors; private int fElementsCount; private int fReagentsCount; public final void setReagentsCount(int value) { this.fReagentsCount = value; } public final int addElement(int elementId) { for (int i = 0; i < this.fElementsCount; i++) { if (this.fData[i][0] == elementId) { return i; } } this.fData[this.fElementsCount][0] = elementId; return this.fElementsCount++; } public final int getFactor(int reagentIndex) { return this.fFactors[reagentIndex]; } public final void setData(int elemIndex, int reagentIndex, boolean isProduct, int value) { if (isProduct) { this.fData[elemIndex][reagentIndex] -= value; } else { this.fData[elemIndex][reagentIndex] += value; } } public final int balanceByLeastSquares() { int[][] A = new int[this.fReagentsCount - 1][this.fReagentsCount - 1]; int[] b = new int[A.length]; for (int i = 0; i < A.length; i++) { // 'Cos `A` is a square matrix I use `A.length` field for the both sizes. for (int j = 0; j < A.length; j++) { for (int k = 0; k < this.fElementsCount; ++k) { A[i][j] += this.fData[k][i + 1] * this.fData[k][j + 1]; if (0 == j) { b[i] -= this.fData[k][i + 1] * this.fData[k][this.fReagentsCount]; } } } } // You're gonna cancel out the matrix `A` and vector `b`, aren't you? int G = 0; for (int i = 0; i < A.length; i++) { int min = ExtMath.gcd(ExtMath.gcd(A[i], 0), b[i]); for (int j = 0; j < A.length; j++) { A[i][j] /= min; } b[i] /= min; } RefObject<Integer> refG = new RefObject<>(G); A = this.inversion(A, refG); G = refG.argValue; if (G == 0) { return BalanceSolver.RES_NoUniqueSolution; } b = this.multiply(A, b); // WOW! The following is array resizing in Java? int[] bTemp = new int[b.length + 1]; System.arraycopy(b, 0, bTemp, 0, b.length); b = bTemp; b[b.length - 1] = G; simplify(b); fFactors = b.clone(); int result = 0; for (int i = 0; i < this.fElementsCount; i++) { int r = 0; for (int j = 0; j < this.fReagentsCount; j++) { r += this.fData[i][j + 1] * this.fFactors[j]; } result += Math.abs(r); } if (0 != result) { java.util.Arrays.fill(fFactors, 1); return BalanceSolver.RES_EquationCanNotBeBalanced; } return result; } /** * `private static int swap(int[] permutation, int k, int m, int teken)` * 'teken' ain't used in the swap operation; I believe it must be removed from the argument list. I mean 'teken' is * independent of swap op itself, it is some kind of invariant from point of view of the "swap". */ private static void swap(int[] permutation, int k, int m) { int tmp = permutation[m]; permutation[m] = permutation[k]; permutation[k] = tmp; } /** * Finds a next possible permutations of the given sequence. * @param permutation * On input this is a previous permutation of the sequence. On return this is the next one. * On the first call to the method this array must be a sequence with ascending order. * On each consecutive call the method generates the next permutation in-place. * @param parity * parity of the transpositions of the previous permutation ("parity of the permutation"). * @return parity of the transpositions made during this permutation (-1 for odd and 1 for even). * * Remarks * The method implements generation in lexicographic order (https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order). * * The sign of a permutation σ is defined as +1 if σ is even and −1 if σ is odd. * * [Ruslan N. Garipov]: Why is the method called 'dijkstra'? Dijkstra's algorithm is an algorithm for finding * the shortest paths between nodes in a graph. Not for finding possible commutation of elements. Do I confuse * with that? */ private static int dijkstra(int[] permutation, int parity) { /* * Search inversions. * * Search for an ordered subrange, starting from the last element in the array. */ int i = permutation.length - 1; while (permutation[i - 1] >= permutation[i]) { --i; } /* * Find a replacement for the "bad" element -- one that breaks ascending order after the subrange [{i}; {last}). * Here {i} is an index of array element and "ascending order" is when you read the array from right to left. * * Since the caller of this method limits number of such calls to `permutation.length!` (length factorial) * neither `i` not `j` may be negative number after subtractions made by `--` op. */ int j = permutation.length - 1; while (permutation[i - 1] >= permutation[j]) { --j; } parity = -parity; // zsv: I like it better /* * Move a bigger element to the left. And because initially, at the first call to `dijkstra`, the `permutation` was * an ordered sequence, now, after the swap, subrange [{i}, {last}) has descending order, if you look on it from * left to right (it also was such before the swap, but now the difference between each pair of neighbouring * elements is always one). */ swap(permutation, i - 1, j); /* * Reverse elements order in the [{i}, {last}) range. */ j = permutation.length - 1; while (i < j) { parity = -parity; swap(permutation, i, j); ++i; --j; } return parity; } // The method returns the matrix of cofactors not the inverse of `mtx`! private int[][] inversion(int[][] mtx, RefObject<Integer> det) { if (mtx.length < 1) { throw new RuntimeException("Inversion: wrong input"); } int[][] invert = new int[mtx.length][mtx.length]; det.argValue = 0; for (int i = 0; i < invert.length; i++) { for (int j = 0; j < invert.length; j++) { invert[i][j] = getCofactor(j, i, mtx, mtx.length); } // Now, here, the first row in `invert` matrix is initialized (invert[0][{any}]). det.argValue += mtx[i][0] * invert[0][i]; } return invert; } private int[] multiply(int[][] een, int[] twee) { int[] uit = new int[een.length]; for (int i = 0; i < uit.length; i++) { for (int j = 0; j < uit.length; j++) { uit[i] += een[i][j] * twee[j]; } } return uit; } private void simplify(int[] b) { int from = 0; int gcd = ExtMath.gcd(b, from); for (int i = from; i < b.length; i++) { b[i] = Math.abs(b[i] / gcd); } } /** * Finds matrix cofactor of the specified entry. * @param row * Row index of entry for which the method calculates cofactor. * @param column * Column index of entry for which the method calculates cofactor. * @param mtx * Source matrix for which cofactors are calculated. It's a square matrix of size `size` x `size`. * @param size * Size of `mtx`. Can be removed from the code; it can use `mtx.length` property instead. * @return * Cofactor 'C' of the entry (`row`, `column`). */ private static int getCofactor(int row, int column, int[][] mtx, int size) { if ((size < 1) || (size > 8)) { // Why such limits? throw new RuntimeException("subdet: input invalid"); } // We're about to calculate determinant of the `mtx` _sub_matrix (a matrix without one row and column). int[] permutation = new int[size - 1]; /* * Number of all possible commutations of numbers in `permutation` is factorial of `permutation` length. */ int numberOfPermutations = 1; for (int k = 0; k < permutation.length; k++) { permutation[k] = k; numberOfPermutations *= k + 1; } int minor = 0; // The identity permutation is an even permutation (its signature is +1). int sgn = 1; for (int m = 0; m < numberOfPermutations; ++m) { if (0 < m) { // Find a permutation; for the first iteration use `permutation` as the first possible permutation. sgn = dijkstra(permutation, sgn); } int value = sgn; for (int k = 0; k < permutation.length; k++) { // "delete" the `row`-th row and `column`-th column. int i = (k >= row) ? k + 1 : k; int j = (permutation[k] >= column) ? permutation[k] + 1 : permutation[k]; value *= mtx[i][j]; } minor += value; } // Get cofactor of the entry in the `row`-th row and `column`-th column (it's the product of // (-1)^(`row` + `column`) and `minor`). return 0 != ((row + column) % 2) ? -minor : minor; } }
Serg-Norseman/ChemLab
src/chemlab/core/chemical/BalanceSolver.java
3,251
/* * Reverse elements order in the [{i}, {last}) range. */
block_comment
nl
/* * "ChemLab", Desktop helper application for chemists. * Copyright (C) 1996-1998, 2015 by Serg V. Zhdanovskih (aka Alchemist, aka Norseman). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package chemlab.core.chemical; import bslib.common.BaseObject; import bslib.common.RefObject; import bslib.math.ExtMath; /** * * @author Serg V. Zhdanovskih, Ruslan N. Garipov * @since 0.3.0 */ public final class BalanceSolver extends BaseObject { public static final int RES_OK = 0; public static final int RES_NoUniqueSolution = 1; public static final int RES_EquationCanNotBeBalanced = 2; private final int[][] fData = new int[9][10]; private int[] fFactors; private int fElementsCount; private int fReagentsCount; public final void setReagentsCount(int value) { this.fReagentsCount = value; } public final int addElement(int elementId) { for (int i = 0; i < this.fElementsCount; i++) { if (this.fData[i][0] == elementId) { return i; } } this.fData[this.fElementsCount][0] = elementId; return this.fElementsCount++; } public final int getFactor(int reagentIndex) { return this.fFactors[reagentIndex]; } public final void setData(int elemIndex, int reagentIndex, boolean isProduct, int value) { if (isProduct) { this.fData[elemIndex][reagentIndex] -= value; } else { this.fData[elemIndex][reagentIndex] += value; } } public final int balanceByLeastSquares() { int[][] A = new int[this.fReagentsCount - 1][this.fReagentsCount - 1]; int[] b = new int[A.length]; for (int i = 0; i < A.length; i++) { // 'Cos `A` is a square matrix I use `A.length` field for the both sizes. for (int j = 0; j < A.length; j++) { for (int k = 0; k < this.fElementsCount; ++k) { A[i][j] += this.fData[k][i + 1] * this.fData[k][j + 1]; if (0 == j) { b[i] -= this.fData[k][i + 1] * this.fData[k][this.fReagentsCount]; } } } } // You're gonna cancel out the matrix `A` and vector `b`, aren't you? int G = 0; for (int i = 0; i < A.length; i++) { int min = ExtMath.gcd(ExtMath.gcd(A[i], 0), b[i]); for (int j = 0; j < A.length; j++) { A[i][j] /= min; } b[i] /= min; } RefObject<Integer> refG = new RefObject<>(G); A = this.inversion(A, refG); G = refG.argValue; if (G == 0) { return BalanceSolver.RES_NoUniqueSolution; } b = this.multiply(A, b); // WOW! The following is array resizing in Java? int[] bTemp = new int[b.length + 1]; System.arraycopy(b, 0, bTemp, 0, b.length); b = bTemp; b[b.length - 1] = G; simplify(b); fFactors = b.clone(); int result = 0; for (int i = 0; i < this.fElementsCount; i++) { int r = 0; for (int j = 0; j < this.fReagentsCount; j++) { r += this.fData[i][j + 1] * this.fFactors[j]; } result += Math.abs(r); } if (0 != result) { java.util.Arrays.fill(fFactors, 1); return BalanceSolver.RES_EquationCanNotBeBalanced; } return result; } /** * `private static int swap(int[] permutation, int k, int m, int teken)` * 'teken' ain't used in the swap operation; I believe it must be removed from the argument list. I mean 'teken' is * independent of swap op itself, it is some kind of invariant from point of view of the "swap". */ private static void swap(int[] permutation, int k, int m) { int tmp = permutation[m]; permutation[m] = permutation[k]; permutation[k] = tmp; } /** * Finds a next possible permutations of the given sequence. * @param permutation * On input this is a previous permutation of the sequence. On return this is the next one. * On the first call to the method this array must be a sequence with ascending order. * On each consecutive call the method generates the next permutation in-place. * @param parity * parity of the transpositions of the previous permutation ("parity of the permutation"). * @return parity of the transpositions made during this permutation (-1 for odd and 1 for even). * * Remarks * The method implements generation in lexicographic order (https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order). * * The sign of a permutation σ is defined as +1 if σ is even and −1 if σ is odd. * * [Ruslan N. Garipov]: Why is the method called 'dijkstra'? Dijkstra's algorithm is an algorithm for finding * the shortest paths between nodes in a graph. Not for finding possible commutation of elements. Do I confuse * with that? */ private static int dijkstra(int[] permutation, int parity) { /* * Search inversions. * * Search for an ordered subrange, starting from the last element in the array. */ int i = permutation.length - 1; while (permutation[i - 1] >= permutation[i]) { --i; } /* * Find a replacement for the "bad" element -- one that breaks ascending order after the subrange [{i}; {last}). * Here {i} is an index of array element and "ascending order" is when you read the array from right to left. * * Since the caller of this method limits number of such calls to `permutation.length!` (length factorial) * neither `i` not `j` may be negative number after subtractions made by `--` op. */ int j = permutation.length - 1; while (permutation[i - 1] >= permutation[j]) { --j; } parity = -parity; // zsv: I like it better /* * Move a bigger element to the left. And because initially, at the first call to `dijkstra`, the `permutation` was * an ordered sequence, now, after the swap, subrange [{i}, {last}) has descending order, if you look on it from * left to right (it also was such before the swap, but now the difference between each pair of neighbouring * elements is always one). */ swap(permutation, i - 1, j); /* * Reverse elements order<SUF>*/ j = permutation.length - 1; while (i < j) { parity = -parity; swap(permutation, i, j); ++i; --j; } return parity; } // The method returns the matrix of cofactors not the inverse of `mtx`! private int[][] inversion(int[][] mtx, RefObject<Integer> det) { if (mtx.length < 1) { throw new RuntimeException("Inversion: wrong input"); } int[][] invert = new int[mtx.length][mtx.length]; det.argValue = 0; for (int i = 0; i < invert.length; i++) { for (int j = 0; j < invert.length; j++) { invert[i][j] = getCofactor(j, i, mtx, mtx.length); } // Now, here, the first row in `invert` matrix is initialized (invert[0][{any}]). det.argValue += mtx[i][0] * invert[0][i]; } return invert; } private int[] multiply(int[][] een, int[] twee) { int[] uit = new int[een.length]; for (int i = 0; i < uit.length; i++) { for (int j = 0; j < uit.length; j++) { uit[i] += een[i][j] * twee[j]; } } return uit; } private void simplify(int[] b) { int from = 0; int gcd = ExtMath.gcd(b, from); for (int i = from; i < b.length; i++) { b[i] = Math.abs(b[i] / gcd); } } /** * Finds matrix cofactor of the specified entry. * @param row * Row index of entry for which the method calculates cofactor. * @param column * Column index of entry for which the method calculates cofactor. * @param mtx * Source matrix for which cofactors are calculated. It's a square matrix of size `size` x `size`. * @param size * Size of `mtx`. Can be removed from the code; it can use `mtx.length` property instead. * @return * Cofactor 'C' of the entry (`row`, `column`). */ private static int getCofactor(int row, int column, int[][] mtx, int size) { if ((size < 1) || (size > 8)) { // Why such limits? throw new RuntimeException("subdet: input invalid"); } // We're about to calculate determinant of the `mtx` _sub_matrix (a matrix without one row and column). int[] permutation = new int[size - 1]; /* * Number of all possible commutations of numbers in `permutation` is factorial of `permutation` length. */ int numberOfPermutations = 1; for (int k = 0; k < permutation.length; k++) { permutation[k] = k; numberOfPermutations *= k + 1; } int minor = 0; // The identity permutation is an even permutation (its signature is +1). int sgn = 1; for (int m = 0; m < numberOfPermutations; ++m) { if (0 < m) { // Find a permutation; for the first iteration use `permutation` as the first possible permutation. sgn = dijkstra(permutation, sgn); } int value = sgn; for (int k = 0; k < permutation.length; k++) { // "delete" the `row`-th row and `column`-th column. int i = (k >= row) ? k + 1 : k; int j = (permutation[k] >= column) ? permutation[k] + 1 : permutation[k]; value *= mtx[i][j]; } minor += value; } // Get cofactor of the entry in the `row`-th row and `column`-th column (it's the product of // (-1)^(`row` + `column`) and `minor`). return 0 != ((row + column) % 2) ? -minor : minor; } }
201039_3
package com.francelabs.datafari.servlets.admin.cluster; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.francelabs.datafari.utils.AuthenticatedUserName; import com.francelabs.datafari.utils.ClusterActionsConfiguration; import com.francelabs.datafari.utils.Environment; import com.francelabs.datafari.audit.AuditLogUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * Servlet implementation class getAllUsersAndRoles */ @WebServlet("/admin/cluster/reinitializemcf") public class ClusterReinit extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = LogManager.getLogger(ClusterReinit.class); // Threshold to compare dates, if dates are closer than the threshold, they are // considered equal. This is in seconds. private static final long THRESHOLD = 10; private static final String DATAFARI_HOME = Environment.getEnvironmentVariable("DATAFARI_HOME") != null ? Environment.getEnvironmentVariable("DATAFARI_HOME") : "/opt/datafari"; private static final String SCRIPT_WORKING_DIR = DATAFARI_HOME + "/bin"; private static final String REPORT_BASE_DIR = DATAFARI_HOME + "/logs"; /** * @see HttpServlet#HttpServlet() */ public ClusterReinit() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String action = request.getParameter("action"); if (action != null && action.equals("getReport")) { ClusterActionsUtils.outputReport(request, response, ClusterAction.REINIT); } else { ClusterActionsUtils.outputStatus(request, response, ClusterAction.REINIT); } } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { ClusterActionsUtils.setUnmanagedDoPost(req, resp); } @Override protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { DateTimeFormatter dateFormatter = ClusterActionsConfiguration.dateFormatter; ClusterActionsConfiguration config = ClusterActionsConfiguration.getInstance(); final JSONObject jsonResponse = new JSONObject(); req.setCharacterEncoding("utf8"); resp.setContentType("application/json"); req.getParameter("annotatorActivation"); try { BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); final JSONParser parser = new JSONParser(); JSONObject requestBody = (JSONObject) parser.parse(br); String lastReinitString = config.getProperty(ClusterActionsConfiguration.LAST_REINIT_DATE); Instant putDate = Instant.parse((String) requestBody.get("date")); Instant now = Instant.now(); Instant lastReinit = Instant.MIN; if (lastReinitString != null && !lastReinitString.equals("")) { Instant.parse(lastReinitString); } long nowToPutDate = Math.abs(now.until(putDate, ChronoUnit.SECONDS)); long lastReinitToPutDate = Math.abs(lastReinit.until(putDate, ChronoUnit.SECONDS)); if (lastReinitToPutDate > THRESHOLD && nowToPutDate < THRESHOLD) { // If the put date is far enough from the last restart // and close enough to the current time => we can restart // But we need first to check that the install is standard (mandatory) // and that we are either in unmanaged mode, or no other action is in progress String unmanagedString = config.getProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE); boolean unmanagedMode = unmanagedString != null && unmanagedString.contentEquals("true"); boolean noActionInProgress = true; for (ClusterAction action : ClusterAction.values()) { try { noActionInProgress = noActionInProgress && !ClusterActionsUtils.isActionInProgress(action); } catch (FileNotFoundException e) { logger.info("Last report file for " + action + " not found, actions are not blocked."); } } if (ClusterActionsUtils.isStandardInstall() && (unmanagedMode || noActionInProgress)) { // retrieve AuthenticatedUserName if user authenticated (it should be as we are // in the admin...) String authenticatedUserName = AuthenticatedUserName.getName(req); // Log for audit purposes who did the request String unmanagedModeNotice = unmanagedMode ? " with UNMANAGED UI state" : ""; AuditLogUtil.log("Reinitialization", authenticatedUserName, req.getRemoteAddr(), "Datafari full reinitialization request received from user " + authenticatedUserName + " from ip " + req.getRemoteAddr() + unmanagedModeNotice + " through the admin UI, answering YES to both questions: Do you confirm " + "that you successfully backed up the connectors beforehand (it " + "is part of the backup process) ? and Do you confirm that " + "you have understood that you will need to reindex you data ?"); String reportName = "cluster-reinitialization-" + dateFormatter.format(putDate) + ".log"; // Set the property file containing the last reinitialization date config.setProperty(ClusterActionsConfiguration.LAST_REINIT_DATE, dateFormatter.format(putDate)); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_IP, req.getRemoteAddr()); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_USER, authenticatedUserName); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_REPORT, reportName); config.setProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE, "false"); config.saveProperties(); // Wire up the call to the bash script final String workingDirectory = SCRIPT_WORKING_DIR; final String filePath = REPORT_BASE_DIR + File.separator + reportName; final String[] command = { "/bin/bash", "./reinitUtils/global_reinit_restore_mcf.sh" }; final ProcessBuilder p = new ProcessBuilder(command); p.redirectErrorStream(true); p.redirectOutput(new File(filePath)); p.directory(new File(workingDirectory)); // Not storing the Process in any manner, tomcat will be restarted anyway so any // variable would be lost, this would be useless. Could store a process ID but // it is not necessary as the report file will provide us information about the // status. p.start(); jsonResponse.put("success", "true"); jsonResponse.put("message", "Datafari reinitializing"); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); for (ClusterAction action : ClusterAction.values()) { try { if (ClusterActionsUtils.isActionInProgress(action)) { // Only the last action in progress will be added to the result // object, but there should be only one active at a time anyway. jsonResponse.put("message", "A " + action + " is in progress."); }; } catch (FileNotFoundException e) { // Nothing to do here, but the file being missing is not a problem, so // catch it to ensure it does not escalate. } } if(jsonResponse.get("message") == null) { jsonResponse.put("message", "An unidentified error prevented the action completion."); } } } else { // Send an error message. if (nowToPutDate >= THRESHOLD) { logger.warn("Trying to perform a cluster reinitialization with a date that is not now. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); jsonResponse.put("message", "Can't reinitialize with a date different than now, now and provided date differ by " + lastReinitToPutDate + "seconds"); } else if (lastReinitToPutDate <= THRESHOLD) { logger.warn( "Trying to perform a cluster reinitialization with a date that is too close to the last reinitialization. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); jsonResponse.put("success", "false"); jsonResponse.put("message", "Server already reinitialized at this date"); } } } catch (Exception e) { logger.error("Couldn't perform the cluster reinitialization.", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); jsonResponse.clear(); jsonResponse.put("success", "false"); jsonResponse.put("message", "Unexpected server error while processing the reinitialization query"); } final PrintWriter out = resp.getWriter(); out.print(jsonResponse); } }
francelabs/datafari
datafari-webapp/src/main/java/com/francelabs/datafari/servlets/admin/cluster/ClusterReinit.java
2,389
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
package com.francelabs.datafari.servlets.admin.cluster; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.francelabs.datafari.utils.AuthenticatedUserName; import com.francelabs.datafari.utils.ClusterActionsConfiguration; import com.francelabs.datafari.utils.Environment; import com.francelabs.datafari.audit.AuditLogUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * Servlet implementation class getAllUsersAndRoles */ @WebServlet("/admin/cluster/reinitializemcf") public class ClusterReinit extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = LogManager.getLogger(ClusterReinit.class); // Threshold to compare dates, if dates are closer than the threshold, they are // considered equal. This is in seconds. private static final long THRESHOLD = 10; private static final String DATAFARI_HOME = Environment.getEnvironmentVariable("DATAFARI_HOME") != null ? Environment.getEnvironmentVariable("DATAFARI_HOME") : "/opt/datafari"; private static final String SCRIPT_WORKING_DIR = DATAFARI_HOME + "/bin"; private static final String REPORT_BASE_DIR = DATAFARI_HOME + "/logs"; /** * @see HttpServlet#HttpServlet() <SUF>*/ public ClusterReinit() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String action = request.getParameter("action"); if (action != null && action.equals("getReport")) { ClusterActionsUtils.outputReport(request, response, ClusterAction.REINIT); } else { ClusterActionsUtils.outputStatus(request, response, ClusterAction.REINIT); } } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { ClusterActionsUtils.setUnmanagedDoPost(req, resp); } @Override protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { DateTimeFormatter dateFormatter = ClusterActionsConfiguration.dateFormatter; ClusterActionsConfiguration config = ClusterActionsConfiguration.getInstance(); final JSONObject jsonResponse = new JSONObject(); req.setCharacterEncoding("utf8"); resp.setContentType("application/json"); req.getParameter("annotatorActivation"); try { BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); final JSONParser parser = new JSONParser(); JSONObject requestBody = (JSONObject) parser.parse(br); String lastReinitString = config.getProperty(ClusterActionsConfiguration.LAST_REINIT_DATE); Instant putDate = Instant.parse((String) requestBody.get("date")); Instant now = Instant.now(); Instant lastReinit = Instant.MIN; if (lastReinitString != null && !lastReinitString.equals("")) { Instant.parse(lastReinitString); } long nowToPutDate = Math.abs(now.until(putDate, ChronoUnit.SECONDS)); long lastReinitToPutDate = Math.abs(lastReinit.until(putDate, ChronoUnit.SECONDS)); if (lastReinitToPutDate > THRESHOLD && nowToPutDate < THRESHOLD) { // If the put date is far enough from the last restart // and close enough to the current time => we can restart // But we need first to check that the install is standard (mandatory) // and that we are either in unmanaged mode, or no other action is in progress String unmanagedString = config.getProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE); boolean unmanagedMode = unmanagedString != null && unmanagedString.contentEquals("true"); boolean noActionInProgress = true; for (ClusterAction action : ClusterAction.values()) { try { noActionInProgress = noActionInProgress && !ClusterActionsUtils.isActionInProgress(action); } catch (FileNotFoundException e) { logger.info("Last report file for " + action + " not found, actions are not blocked."); } } if (ClusterActionsUtils.isStandardInstall() && (unmanagedMode || noActionInProgress)) { // retrieve AuthenticatedUserName if user authenticated (it should be as we are // in the admin...) String authenticatedUserName = AuthenticatedUserName.getName(req); // Log for audit purposes who did the request String unmanagedModeNotice = unmanagedMode ? " with UNMANAGED UI state" : ""; AuditLogUtil.log("Reinitialization", authenticatedUserName, req.getRemoteAddr(), "Datafari full reinitialization request received from user " + authenticatedUserName + " from ip " + req.getRemoteAddr() + unmanagedModeNotice + " through the admin UI, answering YES to both questions: Do you confirm " + "that you successfully backed up the connectors beforehand (it " + "is part of the backup process) ? and Do you confirm that " + "you have understood that you will need to reindex you data ?"); String reportName = "cluster-reinitialization-" + dateFormatter.format(putDate) + ".log"; // Set the property file containing the last reinitialization date config.setProperty(ClusterActionsConfiguration.LAST_REINIT_DATE, dateFormatter.format(putDate)); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_IP, req.getRemoteAddr()); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_USER, authenticatedUserName); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_REPORT, reportName); config.setProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE, "false"); config.saveProperties(); // Wire up the call to the bash script final String workingDirectory = SCRIPT_WORKING_DIR; final String filePath = REPORT_BASE_DIR + File.separator + reportName; final String[] command = { "/bin/bash", "./reinitUtils/global_reinit_restore_mcf.sh" }; final ProcessBuilder p = new ProcessBuilder(command); p.redirectErrorStream(true); p.redirectOutput(new File(filePath)); p.directory(new File(workingDirectory)); // Not storing the Process in any manner, tomcat will be restarted anyway so any // variable would be lost, this would be useless. Could store a process ID but // it is not necessary as the report file will provide us information about the // status. p.start(); jsonResponse.put("success", "true"); jsonResponse.put("message", "Datafari reinitializing"); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); for (ClusterAction action : ClusterAction.values()) { try { if (ClusterActionsUtils.isActionInProgress(action)) { // Only the last action in progress will be added to the result // object, but there should be only one active at a time anyway. jsonResponse.put("message", "A " + action + " is in progress."); }; } catch (FileNotFoundException e) { // Nothing to do here, but the file being missing is not a problem, so // catch it to ensure it does not escalate. } } if(jsonResponse.get("message") == null) { jsonResponse.put("message", "An unidentified error prevented the action completion."); } } } else { // Send an error message. if (nowToPutDate >= THRESHOLD) { logger.warn("Trying to perform a cluster reinitialization with a date that is not now. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); jsonResponse.put("message", "Can't reinitialize with a date different than now, now and provided date differ by " + lastReinitToPutDate + "seconds"); } else if (lastReinitToPutDate <= THRESHOLD) { logger.warn( "Trying to perform a cluster reinitialization with a date that is too close to the last reinitialization. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); jsonResponse.put("success", "false"); jsonResponse.put("message", "Server already reinitialized at this date"); } } } catch (Exception e) { logger.error("Couldn't perform the cluster reinitialization.", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); jsonResponse.clear(); jsonResponse.put("success", "false"); jsonResponse.put("message", "Unexpected server error while processing the reinitialization query"); } final PrintWriter out = resp.getWriter(); out.print(jsonResponse); } }
102384_18
package rstar; /* Modified by Josephine Wong 23 Nov 1997 Improve User Interface of the program */ public class Constants { public static final boolean recordLeavesOnly = false; /* These values are now set by the users - see UserInterface module.*/ // for experimental rects public static final int MAXCOORD = 100; public static final int MAXWIDTH = 60; public static final int NUMRECTS = 200; public static final int DIMENSION = 2; public static final int BLOCKLENGTH = 1024; public static final int CACHESIZE = 128; // for queries static final int RANGEQUERY = 0; static final int POINTQUERY = 1; static final int CIRCLEQUERY = 2; static final int RINGQUERY = 3; static final int CONSTQUERY = 4; // for buffering static final int SIZEOF_BOOLEAN = 1; static final int SIZEOF_SHORT = 2; static final int SIZEOF_CHAR = 1; static final int SIZEOF_BYTE = 1; static final int SIZEOF_FLOAT = 4; static final int SIZEOF_INT = 4; public final static int RTDataNode__dimension = 2; public final static float MAXREAL = (float)9.99e20; public final static int MAX_DIMENSION = 256; // for comparisons public final static float min(float a, float b) {return (a < b)? a : b;} public final static int min(int a, int b) {return (a < b)? a : b;} public final static float max(float a, float b) {return (a > b)? a : b;} public final static int max(int a, int b) {return (a > b)? a : b;} // for comparing mbrs public final static int OVERLAP=0; public final static int INSIDE=1; public final static int S_NONE=2; // for the insert algorithm public final static int SPLIT=0; public final static int REINSERT=1; public final static int NONE=2; // for header blocks public final static int BFHEAD_LENGTH = SIZEOF_INT*2; // sorting criteria public final static int SORT_LOWER_MBR = 0; //for mbrs public final static int SORT_UPPER_MBR = 1; //for mbrs public final static int SORT_CENTER_MBR = 2; //for mbrs public final static int SORT_MINDIST = 3; //for branchlists public final static int BLK_SIZE=4096; public final static int MAXLONGINT=32768; public final static int NUM_TRIES=10; // for errors public static void error (String msg, boolean fatal) { System.out.println(msg); if (fatal) System.exit(1); } // returns the d-dimension area of the mbr public static float area(int dimension, float mbr[]) { int i; float sum; sum = (float)1.0; for (i = 0; i < dimension; i++) sum *= mbr[2*i+1] - mbr[2*i]; return sum; } // returns the margin of the mbr. That is the sum of all projections // to the axes public static float margin(int dimension, float mbr[]) { int i; int ml, mu, m_last; float sum; sum = (float)0.0; m_last = 2*dimension; ml = 0; mu = ml + 1; while (mu < m_last) { sum += mbr[mu] - mbr[ml]; ml += 2; mu += 2; } return sum; } // ist ein Skalar in einem Intervall ? public static boolean inside(float p, float lb, float ub) { return (p >= lb && p <= ub); } // ist ein Vektor in einer Box ? public static boolean inside(float v[], float mbr[], int dimension) { int i; for (i = 0; i < dimension; i++) if (!inside(v[i], mbr[2*i], mbr[2*i+1])) return false; return true; } // calcutales the overlapping area of r1 and r2 // calculate overlap in every dimension and multiplicate the values public static float overlap(int dimension, float r1[], float r2[]) { float sum; int r1pos, r2pos, r1last; float r1_lb, r1_ub, r2_lb, r2_ub; sum = (float)1.0; r1pos = 0; r2pos = 0; r1last = 2 * dimension; while (r1pos < r1last) { r1_lb = r1[r1pos++]; r1_ub = r1[r1pos++]; r2_lb = r2[r2pos++]; r2_ub = r2[r2pos++]; // calculate overlap in this dimension if (inside(r1_ub, r2_lb, r2_ub)) // upper bound of r1 is inside r2 { if (inside(r1_lb, r2_lb, r2_ub)) // and lower bound of r1 is inside sum *= (r1_ub - r1_lb); else sum *= (r1_ub - r2_lb); } else { if (inside(r1_lb, r2_lb, r2_ub)) // and lower bound of r1 is inside sum *= (r2_ub - r1_lb); else { if (inside(r2_lb, r1_lb, r1_ub) && inside(r2_ub, r1_lb, r1_ub)) // r1 contains r2 sum *= (r2_ub - r2_lb); else // r1 and r2 do not overlap sum = (float)0.0; } } } return sum; } // enlarge r in a way that it contains s public static void enlarge(int dimension, float mbr[], float r1[], float r2[]) { int i; //mbr = new float[2*dimension]; for (i = 0; i < 2*dimension; i += 2) { mbr[i] = min(r1[i], r2[i]); mbr[i+1] = max(r1[i+1], r2[i+1]); } /*System.out.println("Enlarge was called with parameters:"); System.out.println("r1 = " + r1[0] + " " + r1[1] + " " + r1[2] + " " + r1[3]); System.out.println("r2 = " + r2[0] + " " + r2[1] + " " + r2[2] + " " + r2[3]); System.out.println("r1 = " + mbr[0] + " " + mbr[1] + " " + mbr[2] + " " + mbr[3]); */ //#ifdef CHECK_MBR // check_mbr(dimension,*mbr); //#endif } /** * returns true if the two mbrs intersect */ public static boolean section(int dimension, float mbr1[], float mbr2[]) { int i; for (i = 0; i < dimension; i++) { if (mbr1[2*i] > mbr2[2*i + 1] || mbr1[2*i + 1] < mbr2[2*i]) return false; } return true; } /** * returns true if the specified mbr intersects the specified circle */ public static boolean section_c(int dimension, float mbr1[], Object center, float radius) { float r2; r2 = radius * radius; // if MBR contains circle center (MINDIST) return true // if r2>MINDIST return true //if ((MINDIST(center,mbr1) != 0) || // (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8))) if ((r2 - MINDIST(center,mbr1)) < (float)1.0e-8) return false; else return true; } //new function public static boolean section_c_2(int dimension, float mbr1[], Object center, float radius) { if (radius < MINDIST(center,mbr1)) return false; else return true; } /** * returns true if the specified mbr intersects the specified circle */ public static boolean section_ring(int dimension, float mbr1[], Object center, float radius1, float radius2) { float r_c1; //inner circle radius float r_c2; //outer circle radius if (radius1 < radius2) { r_c1 = radius1 * radius1; r_c2 = radius2 * radius2; } else { r_c1 = radius2 * radius2; r_c2 = radius1 * radius1; } // if MBR contains circle center (MINDIST) return true // if r2>MINDIST return true //if ((MINDIST(center,mbr1) != 0) || // (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8))) if (((r_c1 - MAXDIST(center,mbr1)) < (float)1.0e-8) && ((MINDIST(center,mbr1) - r_c2) < (float)1.0e-8)) return true; else return false; } /** This is a generic version of C.A.R Hoare's Quick Sort * algorithm. This will handle arrays that are already * sorted, and arrays with duplicate keys. * * If you think of a one dimensional array as going from * the lowest index on the left to the highest index on the right * then the parameters to this function are lowest index or * left and highest index or right. The first time you call * this function it will be with the parameters 0, a.length - 1. * * @param a a Sortable array * @param lo0 left boundary of array partition * @param hi0 right boundary of array partition */ public static void quickSort(Sortable a[], int lo0, int hi0, int sortCriterion) { int lo = lo0; int hi = hi0; Sortable mid; if (hi0 > lo0) { /* Arbitrarily establishing partition element as the midpoint of * the array. */ mid = a[ ( lo0 + hi0 ) / 2 ]; // loop through the array until indices cross while( lo <= hi ) { /* find the first element that is greater than or equal to * the partition element starting from the left Index. */ while( ( lo < hi0 ) && ( a[lo].lessThan(mid, sortCriterion) )) ++lo; /* find an element that is smaller than or equal to * the partition element starting from the right Index. */ while( ( hi > lo0 ) && ( a[hi].greaterThan(mid, sortCriterion))) --hi; // if the indexes have not crossed, swap if( lo <= hi ) { swap(a, lo, hi); ++lo; --hi; } } /* If the right index has not reached the left side of array * must now sort the left partition. */ if( lo0 < hi ) quickSort( a, lo0, hi, sortCriterion ); /* If the left index has not reached the right side of array * must now sort the right partition. */ if( lo < hi0 ) quickSort( a, lo, hi0, sortCriterion ); } } //Swaps two entries in an array of objects to be sorted. //See Constants.quickSort() public static void swap(Sortable a[], int i, int j) { Sortable T; T = a[i]; a[i] = a[j]; a[j] = T; } /** * computes the square of the Euclidean distance between 2 points */ public static float objectDIST(PPoint point1, PPoint point2) { // // Berechnet das Quadrat der euklid'schen Metrik. // (Der tatsaechliche Abstand ist uninteressant, weil // die anderen Metriken (MINDIST und MINMAXDIST fuer // die NearestNarborQuery nur relativ nie absolut // gebraucht werden; nur Aussagen "<" oder ">" sind // relevant. // float sum = (float)0; int i; for( i = 0; i < point1.dimension; i++) sum += java.lang.Math.pow(point1.data[i] - point2.data[i], 2); //return( sqrt(sum) ); //return(sum); return ((float)java.lang.Math.sqrt(sum)); } /** * computes the MINDIST between 1 pt and 1 MBR (see [Rous95]) * the MINDIST ensures that the nearest neighbor from this pt to a * rect in this MBR is at at least this distance */ public static float MINDIST(Object pt, float bounces[]) { // // Berechne die kuerzeste Entfernung zwischen einem Punkt Point // und einem MBR bounces (Lotrecht!) // PPoint point = (PPoint)pt; float sum = (float)0.0; float r; int i; for(i = 0; i < point.dimension; i++) { if (point.data[i] < bounces[2*i]) r = bounces[2*i]; else { if (point.data[i] > bounces[2*i+1]) r = bounces[2*i+1]; else r = point.data[i]; } sum += java.lang.Math.pow(point.data[i] - r , 2); } //return(sum); return((float)java.lang.Math.sqrt(sum)); } /** * computes the MAXDIST between 1 pt and 1 MBR. It is defined as the * maximum distance of a MBR vertex against the specified point * Used as an upper bound of the furthest rectangle inside an MBR from a specific * point */ public static float MAXDIST(Object pt, float bounces[]) { PPoint point = (PPoint)pt; float sum = (float)0.0; float maxdiff; int i; for(i = 0; i < point.dimension; i++) { maxdiff = max(java.lang.Math.abs(point.data[i] - bounces[2*i]), java.lang.Math.abs(point.data[i] - bounces[2*i+1])); sum += java.lang.Math.pow(maxdiff, 2); } //return(sum); return ((float)java.lang.Math.sqrt(sum)); } /** * computes the MINMAXDIST between 1 pt and 1 MBR (see [Rous95]) * the MINMAXDIST ensures that there is at least 1 object in the MBR * that is at most MINMAXDIST far away of the point */ public static float MINMAXDIST(PPoint point, float bounces[]) { // Berechne den kleinsten maximalen Abstand von einem Punkt Point // zu einem MBR bounces. // Wird benutzt zur Abschaetzung von Abstaenden bei NearestNarborQuery. // Kann als Supremum fuer die aktuell kuerzeste Distanz: // Alle Punkte mit einem Abstand > MINMAXDIST sind keine Kandidaten mehr // fuer den NearestNarbor // vgl. Literatur: // Nearest Narbor Query v. Roussopoulos, Kelley und Vincent, // University of Maryland float sum = 0; float minimum = (float)1.0e20; float S = 0; float rmk, rMi; int k,i,j; for( i = 0; i < point.dimension; i++) { rMi = (point.data[i] >= (bounces[2*i]+bounces[2*i+1])/2) ? bounces[2*i] : bounces[2*i+1]; S += java.lang.Math.pow( point.data[i] - rMi , 2 ); } for( k = 0; k < point.dimension; k++) { rmk = ( point.data[k] <= (bounces[2*k]+bounces[2*k+1]) / 2 ) ? bounces[2*k] : bounces[2*k+1]; sum = (float)java.lang.Math.pow(point.data[k] - rmk , 2 ); rMi = (point.data[k] >= (bounces[2*k]+bounces[2*k+1]) / 2 ) ? bounces[2*k] : bounces[2*k+1]; sum += S - java.lang.Math.pow(point.data[k] - rMi , 2); minimum = min(minimum,sum); } return(minimum); //return ((float)java.lang.Math.sqrt(minimum)); } /* public static int sortmindist(Object element1, Object element2) { // // Vergleichsfunktion fuer die Sortierung der BranchList bei der // NearestNarborQuery (Sort, Branch and Prune) // BranchList e1,e2; e1 = (BranchList ) element1; e2 = (BranchList ) element2; if (e1.mindist < e2.mindist) return(-1); else if (e1.mindist > e2.mindist) return(1); else return(0); }*/ public static int pruneBranchList(float nearest_distanz/*[]*/, Object activebranchList[], int n) { // Schneidet im Array BranchList alle Eintraege ab, deren Distanz groesser // ist als die aktuell naeheste Distanz // BranchList bl[]; int i,j,k, aktlast; bl = (BranchList[]) activebranchList; // 1. Strategie: // // Ist MINDIST(P,M1) > MINMAXDIST(P,M2), so kann der // NearestNeighbor auf keinen Fall mehr in M1 liegen! // aktlast = n; for( i = 0; i < aktlast ; i++ ) { if (bl[i].minmaxdist < bl[aktlast-1].mindist) for(j = 0; (j < aktlast) ; j++ ) if ((i!=j) && (bl[j].mindist>bl[i].minmaxdist)) { aktlast = j; break; } } // 2. Strategie: // // nearest_distanz > MINMAXDIST(P,M) // -> nearest_distanz = MIMMAXDIST(P,M) // for( i = 0; i < aktlast; i++) if (nearest_distanz/*[0]*/ > bl[i].minmaxdist) nearest_distanz/*[0]*/ = bl[i].minmaxdist; // 3. Strategie: // // nearest_distanz < MINDIST(P,M) // // in M kann der Nearest-Narbor sicher nicht mehr liegen. // for( i = 0; (i < aktlast) && (nearest_distanz/*[0]*/ >= bl[i].mindist) ; i++); aktlast = i; // printf("n: %d aktlast: %d \n",n,aktlast); return (aktlast); } public static int testBranchList(Object abL[], Object sL[], int n, int last) { // Schneidet im Array BranchList alle Eintr"age ab, deren Distanz gr"o"ser // ist als die aktuell naeheste Distanz // BranchList activebranchList[], sectionList[]; int i,number, aktlast; activebranchList = (BranchList[]) abL; sectionList = (BranchList[]) sL; aktlast = last; for(i = last; i < n ; i++) { number = activebranchList[i].entry_number; if (sectionList[number].section) { // obwohl vom Abstand her dieser Eintrag gecanceld werden // m"usste, wird hier der Eintrag in die ABL wieder // aufgenommen, da evtl. ein Treffer der range-Query zu erwarten ist! // // An der letzten Stelle der Liste kommt der aktuelle Eintrag! aktlast++; activebranchList[aktlast].entry_number = activebranchList[i].entry_number; activebranchList[aktlast].mindist = activebranchList[i].mindist; activebranchList[aktlast].minmaxdist = activebranchList[i].minmaxdist; } } return (aktlast); } public static void check_mbr(int dimension, float mbr[]) { } public static rectangle toRectangle (float rect[]) { rectangle r = new rectangle(0); r.LX = (int) rect[0]; r.UX = (int) rect[1]; r.LY = (int) rect[2]; r.UY = (int) rect[3]; return r; } }
Haibo-Wang-ORG/Most-Popular-Route
src/rstar/Constants.java
5,932
// r1 and r2 do not overlap
line_comment
nl
package rstar; /* Modified by Josephine Wong 23 Nov 1997 Improve User Interface of the program */ public class Constants { public static final boolean recordLeavesOnly = false; /* These values are now set by the users - see UserInterface module.*/ // for experimental rects public static final int MAXCOORD = 100; public static final int MAXWIDTH = 60; public static final int NUMRECTS = 200; public static final int DIMENSION = 2; public static final int BLOCKLENGTH = 1024; public static final int CACHESIZE = 128; // for queries static final int RANGEQUERY = 0; static final int POINTQUERY = 1; static final int CIRCLEQUERY = 2; static final int RINGQUERY = 3; static final int CONSTQUERY = 4; // for buffering static final int SIZEOF_BOOLEAN = 1; static final int SIZEOF_SHORT = 2; static final int SIZEOF_CHAR = 1; static final int SIZEOF_BYTE = 1; static final int SIZEOF_FLOAT = 4; static final int SIZEOF_INT = 4; public final static int RTDataNode__dimension = 2; public final static float MAXREAL = (float)9.99e20; public final static int MAX_DIMENSION = 256; // for comparisons public final static float min(float a, float b) {return (a < b)? a : b;} public final static int min(int a, int b) {return (a < b)? a : b;} public final static float max(float a, float b) {return (a > b)? a : b;} public final static int max(int a, int b) {return (a > b)? a : b;} // for comparing mbrs public final static int OVERLAP=0; public final static int INSIDE=1; public final static int S_NONE=2; // for the insert algorithm public final static int SPLIT=0; public final static int REINSERT=1; public final static int NONE=2; // for header blocks public final static int BFHEAD_LENGTH = SIZEOF_INT*2; // sorting criteria public final static int SORT_LOWER_MBR = 0; //for mbrs public final static int SORT_UPPER_MBR = 1; //for mbrs public final static int SORT_CENTER_MBR = 2; //for mbrs public final static int SORT_MINDIST = 3; //for branchlists public final static int BLK_SIZE=4096; public final static int MAXLONGINT=32768; public final static int NUM_TRIES=10; // for errors public static void error (String msg, boolean fatal) { System.out.println(msg); if (fatal) System.exit(1); } // returns the d-dimension area of the mbr public static float area(int dimension, float mbr[]) { int i; float sum; sum = (float)1.0; for (i = 0; i < dimension; i++) sum *= mbr[2*i+1] - mbr[2*i]; return sum; } // returns the margin of the mbr. That is the sum of all projections // to the axes public static float margin(int dimension, float mbr[]) { int i; int ml, mu, m_last; float sum; sum = (float)0.0; m_last = 2*dimension; ml = 0; mu = ml + 1; while (mu < m_last) { sum += mbr[mu] - mbr[ml]; ml += 2; mu += 2; } return sum; } // ist ein Skalar in einem Intervall ? public static boolean inside(float p, float lb, float ub) { return (p >= lb && p <= ub); } // ist ein Vektor in einer Box ? public static boolean inside(float v[], float mbr[], int dimension) { int i; for (i = 0; i < dimension; i++) if (!inside(v[i], mbr[2*i], mbr[2*i+1])) return false; return true; } // calcutales the overlapping area of r1 and r2 // calculate overlap in every dimension and multiplicate the values public static float overlap(int dimension, float r1[], float r2[]) { float sum; int r1pos, r2pos, r1last; float r1_lb, r1_ub, r2_lb, r2_ub; sum = (float)1.0; r1pos = 0; r2pos = 0; r1last = 2 * dimension; while (r1pos < r1last) { r1_lb = r1[r1pos++]; r1_ub = r1[r1pos++]; r2_lb = r2[r2pos++]; r2_ub = r2[r2pos++]; // calculate overlap in this dimension if (inside(r1_ub, r2_lb, r2_ub)) // upper bound of r1 is inside r2 { if (inside(r1_lb, r2_lb, r2_ub)) // and lower bound of r1 is inside sum *= (r1_ub - r1_lb); else sum *= (r1_ub - r2_lb); } else { if (inside(r1_lb, r2_lb, r2_ub)) // and lower bound of r1 is inside sum *= (r2_ub - r1_lb); else { if (inside(r2_lb, r1_lb, r1_ub) && inside(r2_ub, r1_lb, r1_ub)) // r1 contains r2 sum *= (r2_ub - r2_lb); else // r1 and<SUF> sum = (float)0.0; } } } return sum; } // enlarge r in a way that it contains s public static void enlarge(int dimension, float mbr[], float r1[], float r2[]) { int i; //mbr = new float[2*dimension]; for (i = 0; i < 2*dimension; i += 2) { mbr[i] = min(r1[i], r2[i]); mbr[i+1] = max(r1[i+1], r2[i+1]); } /*System.out.println("Enlarge was called with parameters:"); System.out.println("r1 = " + r1[0] + " " + r1[1] + " " + r1[2] + " " + r1[3]); System.out.println("r2 = " + r2[0] + " " + r2[1] + " " + r2[2] + " " + r2[3]); System.out.println("r1 = " + mbr[0] + " " + mbr[1] + " " + mbr[2] + " " + mbr[3]); */ //#ifdef CHECK_MBR // check_mbr(dimension,*mbr); //#endif } /** * returns true if the two mbrs intersect */ public static boolean section(int dimension, float mbr1[], float mbr2[]) { int i; for (i = 0; i < dimension; i++) { if (mbr1[2*i] > mbr2[2*i + 1] || mbr1[2*i + 1] < mbr2[2*i]) return false; } return true; } /** * returns true if the specified mbr intersects the specified circle */ public static boolean section_c(int dimension, float mbr1[], Object center, float radius) { float r2; r2 = radius * radius; // if MBR contains circle center (MINDIST) return true // if r2>MINDIST return true //if ((MINDIST(center,mbr1) != 0) || // (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8))) if ((r2 - MINDIST(center,mbr1)) < (float)1.0e-8) return false; else return true; } //new function public static boolean section_c_2(int dimension, float mbr1[], Object center, float radius) { if (radius < MINDIST(center,mbr1)) return false; else return true; } /** * returns true if the specified mbr intersects the specified circle */ public static boolean section_ring(int dimension, float mbr1[], Object center, float radius1, float radius2) { float r_c1; //inner circle radius float r_c2; //outer circle radius if (radius1 < radius2) { r_c1 = radius1 * radius1; r_c2 = radius2 * radius2; } else { r_c1 = radius2 * radius2; r_c2 = radius1 * radius1; } // if MBR contains circle center (MINDIST) return true // if r2>MINDIST return true //if ((MINDIST(center,mbr1) != 0) || // (((r2 - MINDIST(center,mbr1)) < (float)1.0e-8))) if (((r_c1 - MAXDIST(center,mbr1)) < (float)1.0e-8) && ((MINDIST(center,mbr1) - r_c2) < (float)1.0e-8)) return true; else return false; } /** This is a generic version of C.A.R Hoare's Quick Sort * algorithm. This will handle arrays that are already * sorted, and arrays with duplicate keys. * * If you think of a one dimensional array as going from * the lowest index on the left to the highest index on the right * then the parameters to this function are lowest index or * left and highest index or right. The first time you call * this function it will be with the parameters 0, a.length - 1. * * @param a a Sortable array * @param lo0 left boundary of array partition * @param hi0 right boundary of array partition */ public static void quickSort(Sortable a[], int lo0, int hi0, int sortCriterion) { int lo = lo0; int hi = hi0; Sortable mid; if (hi0 > lo0) { /* Arbitrarily establishing partition element as the midpoint of * the array. */ mid = a[ ( lo0 + hi0 ) / 2 ]; // loop through the array until indices cross while( lo <= hi ) { /* find the first element that is greater than or equal to * the partition element starting from the left Index. */ while( ( lo < hi0 ) && ( a[lo].lessThan(mid, sortCriterion) )) ++lo; /* find an element that is smaller than or equal to * the partition element starting from the right Index. */ while( ( hi > lo0 ) && ( a[hi].greaterThan(mid, sortCriterion))) --hi; // if the indexes have not crossed, swap if( lo <= hi ) { swap(a, lo, hi); ++lo; --hi; } } /* If the right index has not reached the left side of array * must now sort the left partition. */ if( lo0 < hi ) quickSort( a, lo0, hi, sortCriterion ); /* If the left index has not reached the right side of array * must now sort the right partition. */ if( lo < hi0 ) quickSort( a, lo, hi0, sortCriterion ); } } //Swaps two entries in an array of objects to be sorted. //See Constants.quickSort() public static void swap(Sortable a[], int i, int j) { Sortable T; T = a[i]; a[i] = a[j]; a[j] = T; } /** * computes the square of the Euclidean distance between 2 points */ public static float objectDIST(PPoint point1, PPoint point2) { // // Berechnet das Quadrat der euklid'schen Metrik. // (Der tatsaechliche Abstand ist uninteressant, weil // die anderen Metriken (MINDIST und MINMAXDIST fuer // die NearestNarborQuery nur relativ nie absolut // gebraucht werden; nur Aussagen "<" oder ">" sind // relevant. // float sum = (float)0; int i; for( i = 0; i < point1.dimension; i++) sum += java.lang.Math.pow(point1.data[i] - point2.data[i], 2); //return( sqrt(sum) ); //return(sum); return ((float)java.lang.Math.sqrt(sum)); } /** * computes the MINDIST between 1 pt and 1 MBR (see [Rous95]) * the MINDIST ensures that the nearest neighbor from this pt to a * rect in this MBR is at at least this distance */ public static float MINDIST(Object pt, float bounces[]) { // // Berechne die kuerzeste Entfernung zwischen einem Punkt Point // und einem MBR bounces (Lotrecht!) // PPoint point = (PPoint)pt; float sum = (float)0.0; float r; int i; for(i = 0; i < point.dimension; i++) { if (point.data[i] < bounces[2*i]) r = bounces[2*i]; else { if (point.data[i] > bounces[2*i+1]) r = bounces[2*i+1]; else r = point.data[i]; } sum += java.lang.Math.pow(point.data[i] - r , 2); } //return(sum); return((float)java.lang.Math.sqrt(sum)); } /** * computes the MAXDIST between 1 pt and 1 MBR. It is defined as the * maximum distance of a MBR vertex against the specified point * Used as an upper bound of the furthest rectangle inside an MBR from a specific * point */ public static float MAXDIST(Object pt, float bounces[]) { PPoint point = (PPoint)pt; float sum = (float)0.0; float maxdiff; int i; for(i = 0; i < point.dimension; i++) { maxdiff = max(java.lang.Math.abs(point.data[i] - bounces[2*i]), java.lang.Math.abs(point.data[i] - bounces[2*i+1])); sum += java.lang.Math.pow(maxdiff, 2); } //return(sum); return ((float)java.lang.Math.sqrt(sum)); } /** * computes the MINMAXDIST between 1 pt and 1 MBR (see [Rous95]) * the MINMAXDIST ensures that there is at least 1 object in the MBR * that is at most MINMAXDIST far away of the point */ public static float MINMAXDIST(PPoint point, float bounces[]) { // Berechne den kleinsten maximalen Abstand von einem Punkt Point // zu einem MBR bounces. // Wird benutzt zur Abschaetzung von Abstaenden bei NearestNarborQuery. // Kann als Supremum fuer die aktuell kuerzeste Distanz: // Alle Punkte mit einem Abstand > MINMAXDIST sind keine Kandidaten mehr // fuer den NearestNarbor // vgl. Literatur: // Nearest Narbor Query v. Roussopoulos, Kelley und Vincent, // University of Maryland float sum = 0; float minimum = (float)1.0e20; float S = 0; float rmk, rMi; int k,i,j; for( i = 0; i < point.dimension; i++) { rMi = (point.data[i] >= (bounces[2*i]+bounces[2*i+1])/2) ? bounces[2*i] : bounces[2*i+1]; S += java.lang.Math.pow( point.data[i] - rMi , 2 ); } for( k = 0; k < point.dimension; k++) { rmk = ( point.data[k] <= (bounces[2*k]+bounces[2*k+1]) / 2 ) ? bounces[2*k] : bounces[2*k+1]; sum = (float)java.lang.Math.pow(point.data[k] - rmk , 2 ); rMi = (point.data[k] >= (bounces[2*k]+bounces[2*k+1]) / 2 ) ? bounces[2*k] : bounces[2*k+1]; sum += S - java.lang.Math.pow(point.data[k] - rMi , 2); minimum = min(minimum,sum); } return(minimum); //return ((float)java.lang.Math.sqrt(minimum)); } /* public static int sortmindist(Object element1, Object element2) { // // Vergleichsfunktion fuer die Sortierung der BranchList bei der // NearestNarborQuery (Sort, Branch and Prune) // BranchList e1,e2; e1 = (BranchList ) element1; e2 = (BranchList ) element2; if (e1.mindist < e2.mindist) return(-1); else if (e1.mindist > e2.mindist) return(1); else return(0); }*/ public static int pruneBranchList(float nearest_distanz/*[]*/, Object activebranchList[], int n) { // Schneidet im Array BranchList alle Eintraege ab, deren Distanz groesser // ist als die aktuell naeheste Distanz // BranchList bl[]; int i,j,k, aktlast; bl = (BranchList[]) activebranchList; // 1. Strategie: // // Ist MINDIST(P,M1) > MINMAXDIST(P,M2), so kann der // NearestNeighbor auf keinen Fall mehr in M1 liegen! // aktlast = n; for( i = 0; i < aktlast ; i++ ) { if (bl[i].minmaxdist < bl[aktlast-1].mindist) for(j = 0; (j < aktlast) ; j++ ) if ((i!=j) && (bl[j].mindist>bl[i].minmaxdist)) { aktlast = j; break; } } // 2. Strategie: // // nearest_distanz > MINMAXDIST(P,M) // -> nearest_distanz = MIMMAXDIST(P,M) // for( i = 0; i < aktlast; i++) if (nearest_distanz/*[0]*/ > bl[i].minmaxdist) nearest_distanz/*[0]*/ = bl[i].minmaxdist; // 3. Strategie: // // nearest_distanz < MINDIST(P,M) // // in M kann der Nearest-Narbor sicher nicht mehr liegen. // for( i = 0; (i < aktlast) && (nearest_distanz/*[0]*/ >= bl[i].mindist) ; i++); aktlast = i; // printf("n: %d aktlast: %d \n",n,aktlast); return (aktlast); } public static int testBranchList(Object abL[], Object sL[], int n, int last) { // Schneidet im Array BranchList alle Eintr"age ab, deren Distanz gr"o"ser // ist als die aktuell naeheste Distanz // BranchList activebranchList[], sectionList[]; int i,number, aktlast; activebranchList = (BranchList[]) abL; sectionList = (BranchList[]) sL; aktlast = last; for(i = last; i < n ; i++) { number = activebranchList[i].entry_number; if (sectionList[number].section) { // obwohl vom Abstand her dieser Eintrag gecanceld werden // m"usste, wird hier der Eintrag in die ABL wieder // aufgenommen, da evtl. ein Treffer der range-Query zu erwarten ist! // // An der letzten Stelle der Liste kommt der aktuelle Eintrag! aktlast++; activebranchList[aktlast].entry_number = activebranchList[i].entry_number; activebranchList[aktlast].mindist = activebranchList[i].mindist; activebranchList[aktlast].minmaxdist = activebranchList[i].minmaxdist; } } return (aktlast); } public static void check_mbr(int dimension, float mbr[]) { } public static rectangle toRectangle (float rect[]) { rectangle r = new rectangle(0); r.LX = (int) rect[0]; r.UX = (int) rect[1]; r.LY = (int) rect[2]; r.UY = (int) rect[3]; return r; } }
209134_1
package com.example.opt3_tristan; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import java.util.function.Supplier; public class HoofdmenuController extends SwitchableScene implements Initializable { @FXML private Label ingelogdeMederwerkerLabel; @FXML private ListView<Medewerker> ingelogdeGebruikersListView; @FXML private TabPane mainPane; public ObservableList<HuurItem> huurItems = FXCollections.observableArrayList(); @Override public void initialize(URL url, ResourceBundle resourceBundle) { ingelogdeMederwerkerLabel.setText(Medewerker.huidigeMedewerker.getUsername()); for (Medewerker medewerker : Medewerker.IngelogdeMedewerkers) { ingelogdeGebruikersListView.getItems().add(medewerker); } //3 hardcoded personenauto's HuurItem auto1 = new Personenauto("Toyota", 1200, "Een comfortabele personenauto"); huurItems.add(auto1); HuurItem auto2 = new Personenauto("Volvo", 2500, "Een veilige personenauto"); huurItems.add(auto2); HuurItem auto3 = new Personenauto("Porsche", 1500, "Een vrij snelle personenauto"); huurItems.add(auto3); //3 hardcoded vrachtwagens HuurItem vrachtwagen1 = new Vrachtwagen(20000, 18000,"Een wat kleinere vrachtwagen met 2 assen"); huurItems.add(vrachtwagen1); HuurItem vrachtwagen2 = new Vrachtwagen(30000, 25000,"Een middelgrote vrachtwagen met 3 assen"); huurItems.add(vrachtwagen2); HuurItem vrachtwagen3 = new Vrachtwagen(32000, 30000,"Een grote vrachtwagen met 4 assen"); huurItems.add(vrachtwagen3); //3 hardcoded Boormachines HuurItem boormachine1 = new Boormachine("Makita","HP457DWE accu schroef en klopboormachine","een veelzijdige schroefboormachine die ook als klopboor kan functioneren"); huurItems.add(boormachine1); HuurItem boormachine2 = new Boormachine("Bosch","EasyDrill","Een comfortabele en veelzijdige boormachine"); huurItems.add(boormachine2); HuurItem boormachine3 = new Boormachine("Einhell","TE-CD","een krachtige alleskunner"); huurItems.add(boormachine3); } public void wisselVanGebruiker(){ Medewerker selectedItem = ingelogdeGebruikersListView.getSelectionModel().getSelectedItem(); if (selectedItem != null) { System.out.println("Gewisseld naar: "+selectedItem); Medewerker.huidigeMedewerker = ingelogdeGebruikersListView.getSelectionModel().getSelectedItem(); ingelogdeMederwerkerLabel.setText(Medewerker.huidigeMedewerker.getUsername()); } } public void openOverzicht() { Tab overzichtTab = new Tab(); overzichtTab.setText("Overzicht"); overzichtTab.setClosable(true); ListView<HuurItem> producten = new ListView<>(); producten.setItems(huurItems); TextArea textArea = new TextArea(); textArea.setVisible(false); producten.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (newValue != null) { textArea.setText(newValue.getInformatie()); textArea.setVisible(true); } }); BorderPane borderPane = new BorderPane(); borderPane.setLeft(producten); borderPane.setRight(textArea); Label bottomLabel = new Label("Ingelogde medewerker: " + Medewerker.huidigeMedewerker.getUsername()); borderPane.setBottom(bottomLabel); BorderPane.setAlignment(bottomLabel, javafx.geometry.Pos.BOTTOM_LEFT); overzichtTab.setContent(borderPane); mainPane.getTabs().add(overzichtTab); } public void openBeheer() { Tab beheerTab = createBeheerTab("Beheer", huurItems); ComboBox<String> itemTypeComboBox = (ComboBox<String>) beheerTab.getContent().lookup(".combo-box"); ListView<HuurItem> producten = (ListView<HuurItem>) beheerTab.getContent().lookup(".list-view"); Label messageLabel = new Label(); VBox creationBox = new VBox(); setupItemTypeComboBoxAction(itemTypeComboBox, creationBox, messageLabel, producten); TextArea textArea = createTextArea(producten); BorderPane borderPane = createMainBorderPane(itemTypeComboBox, creationBox, messageLabel, producten, textArea); beheerTab.setContent(borderPane); mainPane.getTabs().add(beheerTab); } private Tab createBeheerTab(String tabText, ObservableList<HuurItem> items) { Tab tab = new Tab(); tab.setText(tabText); tab.setClosable(true); ComboBox<String> comboBox = new ComboBox<>(); comboBox.getItems().addAll("Personenauto", "Vrachtwagen", "Boormachine"); ListView<HuurItem> listView = new ListView<>(); listView.setItems(items); VBox vbox = new VBox(comboBox, listView); BorderPane borderPane = new BorderPane(); borderPane.setCenter(vbox); tab.setContent(borderPane); return tab; } private void setupItemTypeComboBoxAction(ComboBox<String> itemTypeComboBox, VBox creationBox, Label messageLabel, ListView<HuurItem> producten) { itemTypeComboBox.setPromptText("Toevoegen"); Map<String, Supplier<ItemCreationTemplate>> creationSuppliers = new HashMap<>(); creationSuppliers.put("Personenauto", () -> new PersonenautoCreation(creationBox, messageLabel, producten, huurItems)); creationSuppliers.put("Vrachtwagen", () -> new VrachtwagenCreation(creationBox, messageLabel, producten, huurItems)); creationSuppliers.put("Boormachine", () -> new BoormachineCreation(creationBox, messageLabel, producten, huurItems)); itemTypeComboBox.setOnAction(e -> { creationBox.getChildren().clear(); messageLabel.setText(""); Supplier<ItemCreationTemplate> supplier = creationSuppliers.get(itemTypeComboBox.getValue()); if (supplier != null) { ItemCreationTemplate creationTemplate = supplier.get(); creationTemplate.setupItemCreation(); } }); } private TextArea createTextArea(ListView<HuurItem> producten) { TextArea textArea = new TextArea(); textArea.setVisible(false); producten.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (newValue != null) { textArea.setText(newValue.getInformatie()); textArea.setVisible(true); } }); return textArea; } private BorderPane createMainBorderPane(ComboBox<String> itemTypeComboBox, VBox creationBox, Label messageLabel, ListView<HuurItem> producten, TextArea textArea) { BorderPane borderPane = new BorderPane(); borderPane.setLeft(producten); borderPane.setRight(textArea); borderPane.setTop(new VBox(itemTypeComboBox, creationBox, messageLabel)); Label bottomLabel = new Label("Ingelogde medewerker: " + Medewerker.huidigeMedewerker.getUsername()); borderPane.setBottom(bottomLabel); BorderPane.setAlignment(bottomLabel, javafx.geometry.Pos.BOTTOM_LEFT); return borderPane; } public void loguit(ActionEvent event){ Medewerker.IngelogdeMedewerkers.remove(Medewerker.huidigeMedewerker); System.out.println(Medewerker.huidigeMedewerker.getUsername() + " has been logged out."); Medewerker.huidigeMedewerker = null; super.switchScene(event,"login.fxml"); } public void login(ActionEvent event){ super.switchScene(event,"login.fxml"); } }
Triistan/Opt3
Opt3_Tristan/src/main/java/com/example/opt3_tristan/HoofdmenuController.java
2,074
//3 hardcoded vrachtwagens
line_comment
nl
package com.example.opt3_tristan; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import java.util.function.Supplier; public class HoofdmenuController extends SwitchableScene implements Initializable { @FXML private Label ingelogdeMederwerkerLabel; @FXML private ListView<Medewerker> ingelogdeGebruikersListView; @FXML private TabPane mainPane; public ObservableList<HuurItem> huurItems = FXCollections.observableArrayList(); @Override public void initialize(URL url, ResourceBundle resourceBundle) { ingelogdeMederwerkerLabel.setText(Medewerker.huidigeMedewerker.getUsername()); for (Medewerker medewerker : Medewerker.IngelogdeMedewerkers) { ingelogdeGebruikersListView.getItems().add(medewerker); } //3 hardcoded personenauto's HuurItem auto1 = new Personenauto("Toyota", 1200, "Een comfortabele personenauto"); huurItems.add(auto1); HuurItem auto2 = new Personenauto("Volvo", 2500, "Een veilige personenauto"); huurItems.add(auto2); HuurItem auto3 = new Personenauto("Porsche", 1500, "Een vrij snelle personenauto"); huurItems.add(auto3); //3 hardcoded<SUF> HuurItem vrachtwagen1 = new Vrachtwagen(20000, 18000,"Een wat kleinere vrachtwagen met 2 assen"); huurItems.add(vrachtwagen1); HuurItem vrachtwagen2 = new Vrachtwagen(30000, 25000,"Een middelgrote vrachtwagen met 3 assen"); huurItems.add(vrachtwagen2); HuurItem vrachtwagen3 = new Vrachtwagen(32000, 30000,"Een grote vrachtwagen met 4 assen"); huurItems.add(vrachtwagen3); //3 hardcoded Boormachines HuurItem boormachine1 = new Boormachine("Makita","HP457DWE accu schroef en klopboormachine","een veelzijdige schroefboormachine die ook als klopboor kan functioneren"); huurItems.add(boormachine1); HuurItem boormachine2 = new Boormachine("Bosch","EasyDrill","Een comfortabele en veelzijdige boormachine"); huurItems.add(boormachine2); HuurItem boormachine3 = new Boormachine("Einhell","TE-CD","een krachtige alleskunner"); huurItems.add(boormachine3); } public void wisselVanGebruiker(){ Medewerker selectedItem = ingelogdeGebruikersListView.getSelectionModel().getSelectedItem(); if (selectedItem != null) { System.out.println("Gewisseld naar: "+selectedItem); Medewerker.huidigeMedewerker = ingelogdeGebruikersListView.getSelectionModel().getSelectedItem(); ingelogdeMederwerkerLabel.setText(Medewerker.huidigeMedewerker.getUsername()); } } public void openOverzicht() { Tab overzichtTab = new Tab(); overzichtTab.setText("Overzicht"); overzichtTab.setClosable(true); ListView<HuurItem> producten = new ListView<>(); producten.setItems(huurItems); TextArea textArea = new TextArea(); textArea.setVisible(false); producten.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (newValue != null) { textArea.setText(newValue.getInformatie()); textArea.setVisible(true); } }); BorderPane borderPane = new BorderPane(); borderPane.setLeft(producten); borderPane.setRight(textArea); Label bottomLabel = new Label("Ingelogde medewerker: " + Medewerker.huidigeMedewerker.getUsername()); borderPane.setBottom(bottomLabel); BorderPane.setAlignment(bottomLabel, javafx.geometry.Pos.BOTTOM_LEFT); overzichtTab.setContent(borderPane); mainPane.getTabs().add(overzichtTab); } public void openBeheer() { Tab beheerTab = createBeheerTab("Beheer", huurItems); ComboBox<String> itemTypeComboBox = (ComboBox<String>) beheerTab.getContent().lookup(".combo-box"); ListView<HuurItem> producten = (ListView<HuurItem>) beheerTab.getContent().lookup(".list-view"); Label messageLabel = new Label(); VBox creationBox = new VBox(); setupItemTypeComboBoxAction(itemTypeComboBox, creationBox, messageLabel, producten); TextArea textArea = createTextArea(producten); BorderPane borderPane = createMainBorderPane(itemTypeComboBox, creationBox, messageLabel, producten, textArea); beheerTab.setContent(borderPane); mainPane.getTabs().add(beheerTab); } private Tab createBeheerTab(String tabText, ObservableList<HuurItem> items) { Tab tab = new Tab(); tab.setText(tabText); tab.setClosable(true); ComboBox<String> comboBox = new ComboBox<>(); comboBox.getItems().addAll("Personenauto", "Vrachtwagen", "Boormachine"); ListView<HuurItem> listView = new ListView<>(); listView.setItems(items); VBox vbox = new VBox(comboBox, listView); BorderPane borderPane = new BorderPane(); borderPane.setCenter(vbox); tab.setContent(borderPane); return tab; } private void setupItemTypeComboBoxAction(ComboBox<String> itemTypeComboBox, VBox creationBox, Label messageLabel, ListView<HuurItem> producten) { itemTypeComboBox.setPromptText("Toevoegen"); Map<String, Supplier<ItemCreationTemplate>> creationSuppliers = new HashMap<>(); creationSuppliers.put("Personenauto", () -> new PersonenautoCreation(creationBox, messageLabel, producten, huurItems)); creationSuppliers.put("Vrachtwagen", () -> new VrachtwagenCreation(creationBox, messageLabel, producten, huurItems)); creationSuppliers.put("Boormachine", () -> new BoormachineCreation(creationBox, messageLabel, producten, huurItems)); itemTypeComboBox.setOnAction(e -> { creationBox.getChildren().clear(); messageLabel.setText(""); Supplier<ItemCreationTemplate> supplier = creationSuppliers.get(itemTypeComboBox.getValue()); if (supplier != null) { ItemCreationTemplate creationTemplate = supplier.get(); creationTemplate.setupItemCreation(); } }); } private TextArea createTextArea(ListView<HuurItem> producten) { TextArea textArea = new TextArea(); textArea.setVisible(false); producten.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (newValue != null) { textArea.setText(newValue.getInformatie()); textArea.setVisible(true); } }); return textArea; } private BorderPane createMainBorderPane(ComboBox<String> itemTypeComboBox, VBox creationBox, Label messageLabel, ListView<HuurItem> producten, TextArea textArea) { BorderPane borderPane = new BorderPane(); borderPane.setLeft(producten); borderPane.setRight(textArea); borderPane.setTop(new VBox(itemTypeComboBox, creationBox, messageLabel)); Label bottomLabel = new Label("Ingelogde medewerker: " + Medewerker.huidigeMedewerker.getUsername()); borderPane.setBottom(bottomLabel); BorderPane.setAlignment(bottomLabel, javafx.geometry.Pos.BOTTOM_LEFT); return borderPane; } public void loguit(ActionEvent event){ Medewerker.IngelogdeMedewerkers.remove(Medewerker.huidigeMedewerker); System.out.println(Medewerker.huidigeMedewerker.getUsername() + " has been logged out."); Medewerker.huidigeMedewerker = null; super.switchScene(event,"login.fxml"); } public void login(ActionEvent event){ super.switchScene(event,"login.fxml"); } }
158367_2
package de.gwdg.europeanaqa.spark.graph; import com.jayway.jsonpath.InvalidJsonException; import de.gwdg.europeanaqa.api.abbreviation.EdmDataProviderManager; import de.gwdg.europeanaqa.api.calculator.MultiFieldExtractor; import de.gwdg.europeanaqa.api.model.Format; import de.gwdg.europeanaqa.spark.bean.Graph4PLD; import de.gwdg.europeanaqa.spark.cli.Parameters; import de.gwdg.metadataqa.api.model.pathcache.JsonPathCache; import de.gwdg.metadataqa.api.model.XmlFieldInstance; import de.gwdg.metadataqa.api.schema.EdmFullBeanSchema; import de.gwdg.metadataqa.api.schema.EdmOaiPmhXmlSchema; import de.gwdg.metadataqa.api.schema.Schema; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.SparkSession; import java.io.FileNotFoundException; import java.util.*; import java.util.logging.Logger; import static org.apache.spark.sql.functions.col; /** * * @author Péter Király <peter.kiraly at gwdg.de> */ public class GraphByPLDExtractor { private static final Logger logger = Logger.getLogger(GraphByPLDExtractor.class.getCanonicalName()); private static Options options = new Options(); private static final EdmDataProviderManager dataProviderManager = new EdmDataProviderManager(); public static void main(String[] args) throws FileNotFoundException, ParseException { if (args.length < 1) { System.err.println("Please provide a full path to the input files"); System.exit(0); } if (args.length < 2) { System.err.println("Please provide a full path to the output file"); System.exit(0); } Parameters parameters = new Parameters(args); final String inputFileName = parameters.getInputFileName(); final String outputDirName = parameters.getOutputFileName(); final boolean checkSkippableCollections = parameters.getSkipEnrichments(); // (args.length >= 5 && args[4].equals("checkSkippableCollections")); logger.info("arg length: " + args.length); logger.info("Input file is " + inputFileName); logger.info("Output file is " + outputDirName); logger.info("checkSkippableCollections: " + checkSkippableCollections); System.err.println("Input file is " + inputFileName); SparkConf conf = new SparkConf().setAppName("GraphExtractor"); JavaSparkContext context = new JavaSparkContext(conf); SparkSession spark = SparkSession.builder().getOrCreate(); Map<String, String> extractableFields = new LinkedHashMap<>(); Schema qaSchema = null; if (parameters.getFormat() == null || parameters.getFormat().equals(Format.OAI_PMH_XML)) { qaSchema = new EdmOaiPmhXmlSchema(); // extractableFields.put("recordId", "$.identifier"); extractableFields.put("dataProvider", "$.['ore:Aggregation'][0]['edm:dataProvider'][0]"); extractableFields.put("provider", "$.['ore:Aggregation'][0]['edm:provider'][0]"); extractableFields.put("agent", "$.['edm:Agent'][*]['@about']"); extractableFields.put("concept", "$.['skos:Concept'][*]['@about']"); extractableFields.put("place", "$.['edm:Place'][*]['@about']"); extractableFields.put("timespan", "$.['edm:TimeSpan'][*]['@about']"); } else { qaSchema = new EdmFullBeanSchema(); // extractableFields.put("recordId", "$.identifier"); extractableFields.put("dataProvider", "$.['aggregations'][0]['edmDataProvider'][0]"); extractableFields.put("provider", "$.['aggregations'][0]['edmProvider'][0]"); extractableFields.put("agent", "$.['agents'][*]['about']"); extractableFields.put("concept", "$.['concepts'][*]['about']"); extractableFields.put("place", "$.['places'][*]['about']"); extractableFields.put("timespan", "$.['timespans'][*]['about']"); } qaSchema.setExtractableFields(extractableFields); final MultiFieldExtractor fieldExtractor = new MultiFieldExtractor(qaSchema); List<String> entities = Arrays.asList("agent", "concept", "place", "timespan"); List<List<String>> statistics = new ArrayList<>(); JavaRDD<String> inputFile = context.textFile(inputFileName); // statistics.add(Arrays.asList("proxy-nodes", String.valueOf(inputFile.count()))); JavaRDD<Graph4PLD> idsRDD = inputFile .flatMap(jsonString -> { List<Graph4PLD> values = new ArrayList<>(); try { JsonPathCache<? extends XmlFieldInstance> cache = new JsonPathCache<>(jsonString); fieldExtractor.measure(cache); Map<String, ? extends Object> map = fieldExtractor.getResultMap(); // String recordId = ((List<String>) map.get("recordId")).get(0); String dataProvider = extractValue(map, "dataProvider"); String provider = extractValue(map, "provider"); String providerId = (dataProvider != null) ? getDataProviderCode(dataProvider) : (provider != null ? getDataProviderCode(provider) : "0"); for (String entity : entities) { for (String item : (List<String>) map.get(entity)) { values.add(new Graph4PLD(providerId, entity, extractPLD(item))); } } } catch (InvalidJsonException e) { logger.severe(String.format("Invalid JSON in %s: %s. Error message: %s.", inputFileName, jsonString, e.getLocalizedMessage())); } return values.iterator(); } ); Dataset<Row> df = spark.createDataFrame(idsRDD, Graph4PLD.class).distinct(); df.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld-raw"); Dataset<Row> counted = df .groupBy("type", "vocabulary") .count(); counted.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld-counted"); Dataset<Row> ordered = counted .orderBy(col("type"), col("count").desc()); // output every individual entity IDs with count ordered.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld"); } public static String getDataProviderCode(String dataProvider) { String dataProviderCode; if (dataProvider == null) { dataProviderCode = "0"; } else if (dataProviderManager != null) { dataProviderCode = String.valueOf(dataProviderManager.lookup(dataProvider)); } else { dataProviderCode = dataProvider; } return dataProviderCode; } public static String extractPLD(String identifier) { String pld = identifier .replaceAll("https?://", "[pld]") .replaceAll("data.europeana.eu/agent/.*", "data.europeana.eu/agent/") .replaceAll("data.europeana.eu/place/.*", "data.europeana.eu/place/") .replaceAll("data.europeana.eu/concept/.*", "data.europeana.eu/concept/") .replaceAll("rdf.kulturarvvasternorrland.se/.*", "rdf.kulturarvvasternorrland.se") .replaceAll("d-nb.info/gnd/.*", "d-nb.info/gnd/") .replaceAll("^#person-.*", "#person") .replaceAll("^#agent_.*", "#agent") .replaceAll("^RM0001.PEOPLE.*", "RM0001.PEOPLE") .replaceAll("^RM0001.THESAU.*", "RM0001.THESAU") .replaceAll("^person_uuid.*", "person_uuid") .replaceAll("^MTB-PE-.*", "MTB-PE") .replaceAll("^#[0-9a-f]{8}-[0-9a-f]{4}-.*", "#uuid") .replaceAll("^[0-9a-f]{8}-[0-9a-f]{4}-.*", "uuid") .replaceAll("^#ort-dargestellt-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-dargestellt") .replaceAll("^#ort-herstellung-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-herstellung") .replaceAll("^#ort-fund-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-fund") .replaceAll("^HA\\d+/SP", "HA___/SP") .replaceAll("^iid:\\d{7}", "iid") .replaceAll("^iid:\\d{4}", "iid") .replaceAll("^iid:\\d{3}", "iid") .replaceAll("^#5[5-9]\\..*", "#5x.coord") .replaceAll("^#6[0-5]\\..*", "#6x.coord") .replaceAll("^#locationOf:nn.*", "#locationOf:nn") .replaceAll("^#placeOf:.*", "#placeOf") .replaceAll("^Rijksmonumentnummer.*", "Rijksmonumentnummer") .replaceAll("^urn:nbn:nl:ui:13-.*", "urn:nbn:nl:ui:13") .replaceAll("^KIVOTOS_CETI_.*", "KIVOTOS_CETI") .replaceAll("^DMS01-.*", "DMS01") .replaceAll("^DMS02-.*", "DMS02") .replaceAll("^UJAEN_HASSET_.*", "UJAEN_HASSET") .replaceAll("^5500\\d{5}/", "5500") // concept .replaceAll("^urn:Mood:.*", "urn:Mood") .replaceAll("^urn:Instrument:.*", "urn:Instrument") .replaceAll("^DASI:supL.*", "DASI:supL") .replaceAll("^context_\\d{4}.*", "context_yyyy") .replaceAll("^context_AUR_\\d{4}.*", "context_AUR_yyyy") .replaceAll("^context_SLA_OU_\\d{4}.*", "context_SLA_OU_yyyy") .replaceAll("^context_AT-KLA_.*", "context_AT-KLA") .replaceAll("^context_WienStClaraOSCI_.*", "context_WienStClaraOSCI") .replaceAll("^context_A_.*", "context_A") .replaceAll("^context_B_.*", "context_B") .replaceAll("^context_C_.*", "context_C") .replaceAll("^context_D_.*", "context_D") .replaceAll("^context_E_.*", "context_E") .replaceAll("^context_F_.*", "context_F") .replaceAll("^context_G_.*", "context_G") .replaceAll("^context_H_.*", "context_H") .replaceAll("^context_I_.*", "context_I") .replaceAll("^context_K_.*", "context_K") .replaceAll("^context_L_.*", "context_L") .replaceAll("^context_M_.*", "context_M") .replaceAll("^context_O_.*", "context_O") .replaceAll("^context_P_.*", "context_P") .replaceAll("^context_.*", "context") .replaceAll("^#concept-.*", "#concept") // timespan .replaceAll("^#Timesspan_OpenUp!.*", "#Timesspan_OpenUp!") .replaceAll("^#57620.*", "#57620") .replaceAll("^#datierung-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#datierung") .replaceAll("^datierung_uuid=[0-9a-f]{8}-[0-9a-f]{4}-.*", "datierung_uuid") ; if (!pld.contains("data.europeana.eu/agent/") && !pld.contains("data.europeana.eu/place/") && !pld.contains("data.europeana.eu/concept/") && !pld.contains("d-nb.info/gnd/")) { pld = pld.replaceAll("/.+", "/"); } if (pld == null) pld = ""; return pld; } private static String extractValue(Map map, String key) { String value = null; if (map.get(key) != null && !((List<String>) map.get(key)).isEmpty()) value = ((List<String>) map.get(key)).get(0); return value; } private static void help() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -cp [jar] de.gwdg.europeanaqa.spark.CompletenessCount [options]", options); } }
pkiraly/europeana-qa-spark
src/main/java/de/gwdg/europeanaqa/spark/graph/GraphByPLDExtractor.java
3,368
// String recordId = ((List<String>) map.get("recordId")).get(0);
line_comment
nl
package de.gwdg.europeanaqa.spark.graph; import com.jayway.jsonpath.InvalidJsonException; import de.gwdg.europeanaqa.api.abbreviation.EdmDataProviderManager; import de.gwdg.europeanaqa.api.calculator.MultiFieldExtractor; import de.gwdg.europeanaqa.api.model.Format; import de.gwdg.europeanaqa.spark.bean.Graph4PLD; import de.gwdg.europeanaqa.spark.cli.Parameters; import de.gwdg.metadataqa.api.model.pathcache.JsonPathCache; import de.gwdg.metadataqa.api.model.XmlFieldInstance; import de.gwdg.metadataqa.api.schema.EdmFullBeanSchema; import de.gwdg.metadataqa.api.schema.EdmOaiPmhXmlSchema; import de.gwdg.metadataqa.api.schema.Schema; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.SparkSession; import java.io.FileNotFoundException; import java.util.*; import java.util.logging.Logger; import static org.apache.spark.sql.functions.col; /** * * @author Péter Király <peter.kiraly at gwdg.de> */ public class GraphByPLDExtractor { private static final Logger logger = Logger.getLogger(GraphByPLDExtractor.class.getCanonicalName()); private static Options options = new Options(); private static final EdmDataProviderManager dataProviderManager = new EdmDataProviderManager(); public static void main(String[] args) throws FileNotFoundException, ParseException { if (args.length < 1) { System.err.println("Please provide a full path to the input files"); System.exit(0); } if (args.length < 2) { System.err.println("Please provide a full path to the output file"); System.exit(0); } Parameters parameters = new Parameters(args); final String inputFileName = parameters.getInputFileName(); final String outputDirName = parameters.getOutputFileName(); final boolean checkSkippableCollections = parameters.getSkipEnrichments(); // (args.length >= 5 && args[4].equals("checkSkippableCollections")); logger.info("arg length: " + args.length); logger.info("Input file is " + inputFileName); logger.info("Output file is " + outputDirName); logger.info("checkSkippableCollections: " + checkSkippableCollections); System.err.println("Input file is " + inputFileName); SparkConf conf = new SparkConf().setAppName("GraphExtractor"); JavaSparkContext context = new JavaSparkContext(conf); SparkSession spark = SparkSession.builder().getOrCreate(); Map<String, String> extractableFields = new LinkedHashMap<>(); Schema qaSchema = null; if (parameters.getFormat() == null || parameters.getFormat().equals(Format.OAI_PMH_XML)) { qaSchema = new EdmOaiPmhXmlSchema(); // extractableFields.put("recordId", "$.identifier"); extractableFields.put("dataProvider", "$.['ore:Aggregation'][0]['edm:dataProvider'][0]"); extractableFields.put("provider", "$.['ore:Aggregation'][0]['edm:provider'][0]"); extractableFields.put("agent", "$.['edm:Agent'][*]['@about']"); extractableFields.put("concept", "$.['skos:Concept'][*]['@about']"); extractableFields.put("place", "$.['edm:Place'][*]['@about']"); extractableFields.put("timespan", "$.['edm:TimeSpan'][*]['@about']"); } else { qaSchema = new EdmFullBeanSchema(); // extractableFields.put("recordId", "$.identifier"); extractableFields.put("dataProvider", "$.['aggregations'][0]['edmDataProvider'][0]"); extractableFields.put("provider", "$.['aggregations'][0]['edmProvider'][0]"); extractableFields.put("agent", "$.['agents'][*]['about']"); extractableFields.put("concept", "$.['concepts'][*]['about']"); extractableFields.put("place", "$.['places'][*]['about']"); extractableFields.put("timespan", "$.['timespans'][*]['about']"); } qaSchema.setExtractableFields(extractableFields); final MultiFieldExtractor fieldExtractor = new MultiFieldExtractor(qaSchema); List<String> entities = Arrays.asList("agent", "concept", "place", "timespan"); List<List<String>> statistics = new ArrayList<>(); JavaRDD<String> inputFile = context.textFile(inputFileName); // statistics.add(Arrays.asList("proxy-nodes", String.valueOf(inputFile.count()))); JavaRDD<Graph4PLD> idsRDD = inputFile .flatMap(jsonString -> { List<Graph4PLD> values = new ArrayList<>(); try { JsonPathCache<? extends XmlFieldInstance> cache = new JsonPathCache<>(jsonString); fieldExtractor.measure(cache); Map<String, ? extends Object> map = fieldExtractor.getResultMap(); // String recordId<SUF> String dataProvider = extractValue(map, "dataProvider"); String provider = extractValue(map, "provider"); String providerId = (dataProvider != null) ? getDataProviderCode(dataProvider) : (provider != null ? getDataProviderCode(provider) : "0"); for (String entity : entities) { for (String item : (List<String>) map.get(entity)) { values.add(new Graph4PLD(providerId, entity, extractPLD(item))); } } } catch (InvalidJsonException e) { logger.severe(String.format("Invalid JSON in %s: %s. Error message: %s.", inputFileName, jsonString, e.getLocalizedMessage())); } return values.iterator(); } ); Dataset<Row> df = spark.createDataFrame(idsRDD, Graph4PLD.class).distinct(); df.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld-raw"); Dataset<Row> counted = df .groupBy("type", "vocabulary") .count(); counted.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld-counted"); Dataset<Row> ordered = counted .orderBy(col("type"), col("count").desc()); // output every individual entity IDs with count ordered.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld"); } public static String getDataProviderCode(String dataProvider) { String dataProviderCode; if (dataProvider == null) { dataProviderCode = "0"; } else if (dataProviderManager != null) { dataProviderCode = String.valueOf(dataProviderManager.lookup(dataProvider)); } else { dataProviderCode = dataProvider; } return dataProviderCode; } public static String extractPLD(String identifier) { String pld = identifier .replaceAll("https?://", "[pld]") .replaceAll("data.europeana.eu/agent/.*", "data.europeana.eu/agent/") .replaceAll("data.europeana.eu/place/.*", "data.europeana.eu/place/") .replaceAll("data.europeana.eu/concept/.*", "data.europeana.eu/concept/") .replaceAll("rdf.kulturarvvasternorrland.se/.*", "rdf.kulturarvvasternorrland.se") .replaceAll("d-nb.info/gnd/.*", "d-nb.info/gnd/") .replaceAll("^#person-.*", "#person") .replaceAll("^#agent_.*", "#agent") .replaceAll("^RM0001.PEOPLE.*", "RM0001.PEOPLE") .replaceAll("^RM0001.THESAU.*", "RM0001.THESAU") .replaceAll("^person_uuid.*", "person_uuid") .replaceAll("^MTB-PE-.*", "MTB-PE") .replaceAll("^#[0-9a-f]{8}-[0-9a-f]{4}-.*", "#uuid") .replaceAll("^[0-9a-f]{8}-[0-9a-f]{4}-.*", "uuid") .replaceAll("^#ort-dargestellt-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-dargestellt") .replaceAll("^#ort-herstellung-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-herstellung") .replaceAll("^#ort-fund-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-fund") .replaceAll("^HA\\d+/SP", "HA___/SP") .replaceAll("^iid:\\d{7}", "iid") .replaceAll("^iid:\\d{4}", "iid") .replaceAll("^iid:\\d{3}", "iid") .replaceAll("^#5[5-9]\\..*", "#5x.coord") .replaceAll("^#6[0-5]\\..*", "#6x.coord") .replaceAll("^#locationOf:nn.*", "#locationOf:nn") .replaceAll("^#placeOf:.*", "#placeOf") .replaceAll("^Rijksmonumentnummer.*", "Rijksmonumentnummer") .replaceAll("^urn:nbn:nl:ui:13-.*", "urn:nbn:nl:ui:13") .replaceAll("^KIVOTOS_CETI_.*", "KIVOTOS_CETI") .replaceAll("^DMS01-.*", "DMS01") .replaceAll("^DMS02-.*", "DMS02") .replaceAll("^UJAEN_HASSET_.*", "UJAEN_HASSET") .replaceAll("^5500\\d{5}/", "5500") // concept .replaceAll("^urn:Mood:.*", "urn:Mood") .replaceAll("^urn:Instrument:.*", "urn:Instrument") .replaceAll("^DASI:supL.*", "DASI:supL") .replaceAll("^context_\\d{4}.*", "context_yyyy") .replaceAll("^context_AUR_\\d{4}.*", "context_AUR_yyyy") .replaceAll("^context_SLA_OU_\\d{4}.*", "context_SLA_OU_yyyy") .replaceAll("^context_AT-KLA_.*", "context_AT-KLA") .replaceAll("^context_WienStClaraOSCI_.*", "context_WienStClaraOSCI") .replaceAll("^context_A_.*", "context_A") .replaceAll("^context_B_.*", "context_B") .replaceAll("^context_C_.*", "context_C") .replaceAll("^context_D_.*", "context_D") .replaceAll("^context_E_.*", "context_E") .replaceAll("^context_F_.*", "context_F") .replaceAll("^context_G_.*", "context_G") .replaceAll("^context_H_.*", "context_H") .replaceAll("^context_I_.*", "context_I") .replaceAll("^context_K_.*", "context_K") .replaceAll("^context_L_.*", "context_L") .replaceAll("^context_M_.*", "context_M") .replaceAll("^context_O_.*", "context_O") .replaceAll("^context_P_.*", "context_P") .replaceAll("^context_.*", "context") .replaceAll("^#concept-.*", "#concept") // timespan .replaceAll("^#Timesspan_OpenUp!.*", "#Timesspan_OpenUp!") .replaceAll("^#57620.*", "#57620") .replaceAll("^#datierung-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#datierung") .replaceAll("^datierung_uuid=[0-9a-f]{8}-[0-9a-f]{4}-.*", "datierung_uuid") ; if (!pld.contains("data.europeana.eu/agent/") && !pld.contains("data.europeana.eu/place/") && !pld.contains("data.europeana.eu/concept/") && !pld.contains("d-nb.info/gnd/")) { pld = pld.replaceAll("/.+", "/"); } if (pld == null) pld = ""; return pld; } private static String extractValue(Map map, String key) { String value = null; if (map.get(key) != null && !((List<String>) map.get(key)).isEmpty()) value = ((List<String>) map.get(key)).get(0); return value; } private static void help() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -cp [jar] de.gwdg.europeanaqa.spark.CompletenessCount [options]", options); } }
90982_49
/* LanguageTool, a natural language style checker * Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.chunking.Chunker; import org.languagetool.chunking.GermanChunker; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.*; import org.languagetool.rules.de.LongSentenceRule; import org.languagetool.rules.de.SentenceWhitespaceRule; import org.languagetool.rules.de.*; import org.languagetool.rules.spelling.SpellingCheckRule; import org.languagetool.synthesis.GermanSynthesizer; import org.languagetool.synthesis.Synthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.de.GermanTagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.rules.de.GermanRuleDisambiguator; import org.languagetool.tokenizers.*; import org.languagetool.tokenizers.de.GermanCompoundTokenizer; import org.languagetool.tokenizers.de.GermanWordTokenizer; import org.languagetool.tools.Tools; import java.io.File; import java.io.IOException; import java.util.*; /** * Support for German - use the sub classes {@link GermanyGerman}, {@link SwissGerman}, or {@link AustrianGerman} * if you need spell checking. */ public class German extends Language implements AutoCloseable { private LanguageModel languageModel; /** * @deprecated use {@link GermanyGerman}, {@link AustrianGerman}, or {@link SwissGerman} instead - * they have rules for spell checking, this class doesn't (deprecated since 3.2) */ @Deprecated public German() { } @Override public Language getDefaultLanguageVariant() { return GermanyGerman.INSTANCE; } @Override public SpellingCheckRule createDefaultSpellingRule(ResourceBundle messages) throws IOException { return new GermanSpellerRule(messages, this); } @NotNull @Override public GermanSpellerRule getDefaultSpellingRule() { return (GermanSpellerRule) Objects.requireNonNull(super.getDefaultSpellingRule()); } @Override public Disambiguator createDefaultDisambiguator() { return new GermanRuleDisambiguator(); } @Nullable @Override public Chunker createDefaultPostDisambiguationChunker() { return new GermanChunker(); } @Override public String getName() { return "German"; } @Override public String getShortCode() { return "de"; } @Override public String[] getCountries() { return new String[]{"LU", "LI", "BE"}; } @NotNull @Override public Tagger createDefaultTagger() { return GermanTagger.INSTANCE; } @Nullable @Override public Synthesizer createDefaultSynthesizer() { return GermanSynthesizer.INSTANCE; } @Override public SentenceTokenizer createDefaultSentenceTokenizer() { return new SRXSentenceTokenizer(this); } @Override public Contributor[] getMaintainers() { return new Contributor[] { new Contributor("Jan Schreiber"), Contributors.DANIEL_NABER, }; } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException { return Arrays.asList( new CommaWhitespaceRule(messages, Example.wrong("Die Partei<marker> ,</marker> die die letzte Wahl gewann."), Example.fixed("Die Partei<marker>,</marker> die die letzte Wahl gewann."), Tools.getUrl("https://languagetool.org/insights/de/beitrag/grammatik-leerzeichen/#fehler-1-leerzeichen-vor-und-nach-satzzeichen")), new GermanUnpairedBracketsRule(messages, this), new UppercaseSentenceStartRule(messages, this, Example.wrong("Das Haus ist alt. <marker>es</marker> wurde 1950 gebaut."), Example.fixed("Das Haus ist alt. <marker>Es</marker> wurde 1950 gebaut."), Tools.getUrl("https://languagetool.org/insights/de/beitrag/gross-klein-schreibung-rechtschreibung/#1-satzanf%C3%A4nge-schreiben-wir-gro%C3%9F")), new MultipleWhitespaceRule(messages, this), new WhiteSpaceBeforeParagraphEnd(messages, this), new WhiteSpaceAtBeginOfParagraph(messages), new EmptyLineRule(messages, this), new LongParagraphRule(messages, this, userConfig), new PunctuationMarkAtParagraphEnd(messages, this), // specific to German: new SimpleReplaceRule(messages, this), new OldSpellingRule(messages), new SentenceWhitespaceRule(messages), new GermanDoublePunctuationRule(messages), new MissingVerbRule(messages, this), new GermanWordRepeatRule(messages, this), new GermanWordRepeatBeginningRule(messages, this), new GermanWrongWordInContextRule(messages), new AgreementRule(messages, this), new AgreementRule2(messages, this), new CaseRule(messages, this), new DashRule(messages), new VerbAgreementRule(messages, this), new SubjectVerbAgreementRule(messages, this), new WordCoherencyRule(messages), new SimilarNameRule(messages), new WiederVsWiderRule(messages), new GermanStyleRepeatedWordRule(messages, this, userConfig), new CompoundCoherencyRule(messages), new LongSentenceRule(messages, userConfig, 40), new GermanFillerWordsRule(messages, this, userConfig), new PassiveSentenceRule(messages, this, userConfig), new SentenceWithModalVerbRule(messages, this, userConfig), new SentenceWithManRule(messages, this, userConfig), new ConjunctionAtBeginOfSentenceRule(messages, this, userConfig), new NonSignificantVerbsRule(messages, this, userConfig), new UnnecessaryPhraseRule(messages, this, userConfig), new GermanParagraphRepeatBeginningRule(messages, this), new DuUpperLowerCaseRule(messages), new UnitConversionRule(messages), new MissingCommaRelativeClauseRule(messages), new MissingCommaRelativeClauseRule(messages, true), new RedundantModalOrAuxiliaryVerb(messages), new GermanReadabilityRule(messages, this, userConfig, true), new GermanReadabilityRule(messages, this, userConfig, false), new CompoundInfinitivRule(messages, this, userConfig), new StyleRepeatedVeryShortSentences(messages, this), new StyleRepeatedSentenceBeginning(messages), new GermanRepeatedWordsRule(messages) ); } /** * @since 2.7 */ public CompoundWordTokenizer getNonStrictCompoundSplitter() { GermanCompoundTokenizer tokenizer = GermanCompoundTokenizer.getNonStrictInstance(); // there's a spelling mistake in (at least) one part, so strict mode wouldn't split the word return word -> new ArrayList<>(tokenizer.tokenize(word)); } /** * @since 2.7 */ public GermanCompoundTokenizer getStrictCompoundTokenizer() { return GermanCompoundTokenizer.getStrictInstance(); } @Override public synchronized LanguageModel getLanguageModel(File indexDir) throws IOException { languageModel = initLanguageModel(indexDir, languageModel); return languageModel; } /** @since 3.1 */ @Override public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel, UserConfig userConfig) throws IOException { return Arrays.asList( new UpperCaseNgramRule(messages, languageModel, this), new GermanConfusionProbabilityRule(messages, languageModel, this), new ProhibitedCompoundRule(messages, languageModel, userConfig) ); } @Override public Tokenizer createDefaultWordTokenizer() { return new GermanWordTokenizer(); } /** * Closes the language model, if any. * @since 3.1 */ @Override public void close() throws Exception { if (languageModel != null) { languageModel.close(); } } /** @since 5.1 */ @Override public String getOpeningDoubleQuote() { return "„"; } /** @since 5.1 */ @Override public String getClosingDoubleQuote() { return "“"; } /** @since 5.1 */ @Override public String getOpeningSingleQuote() { return "‚"; } /** @since 5.1 */ @Override public String getClosingSingleQuote() { return "‘"; } /** @since 5.1 */ @Override public boolean isAdvancedTypographyEnabled() { return true; } @Override public String toAdvancedTypography(String input) { String output = super.toAdvancedTypography(input); //non-breaking space output = output.replaceAll("\\b([a-zA-Z]\\.)([a-zA-Z]\\.)", "$1\u00a0$2"); output = output.replaceAll("\\b([a-zA-Z]\\.)([a-zA-Z]\\.)", "$1\u00a0$2"); return output; } @Override public LanguageMaintainedState getMaintainedState() { return LanguageMaintainedState.ActivelyMaintained; } @Override protected int getPriorityForId(String id) { switch (id) { // Rule ids: case "DE_PROHIBITED_PHRASE": return 11; case "WRONG_SPELLING_PREMIUM_INTERNAL": return 10; case "OLD_SPELLING_INTERNAL": return 10; case "DE_COMPOUNDS": return 10; case "TELEFON_NR": return 10; case "IRGEND_COMPOUND": return 10; case "DA_DURCH": return 2; // prefer over SUBSTANTIVIERUNG_NACH_DURCH and DURCH_SCHAUEN and DURCH_WACHSEN case "BEI_GOOGLE" : return 2; // prefer over agreement rules and VOR_BEI case "EINE_ORIGINAL_RECHNUNG_TEST" : return 2; // prefer over agreement rules case "VONSTATTEN_GEHEN" : return 2; // prefer over EINE_ORIGINAL_RECHNUNG case "VERWECHSLUNG_MIR_DIR_MIR_DIE": return 1; // prefer over MIR_DIR case "ERNEUERBARE_ENERGIEN": return 1; // prefer over VEREINBAREN case "DRIVE_IN": return 1; // prefer over agreement rules case "AN_STATT": return 1; // prefer over agreement rules case "VOR_BEI": return 1; // prefer over BEI_BEHALTEN case "ALLES_GUTE": return 1; // prefer over premium rules case "NEUN_NEUEN": return 1; // prefer over VIELZAHL_PLUS_SINGULAR case "VERWANDET_VERWANDTE": return 1; // prefer over DE_CASE case "IN_DEUTSCHE_SPRACHE": return 1; // prefer over most other rules case "SEIT_LAENGEREN": return 1; // prefer over DE_CASE case "SEIT_KLEIN_AUF": return 1; // prefer over agreement rules case "SEIT_GEBURT_AN": return 1; // prefer over agreement rules case "WO_VON": return 1; // prefer over most agreement rules case "ICH_BIN_STAND_JETZT_KOMMA": return 1; // prefer over most agreement rules case "EIN_LOGGEN": return 1; // prefer over most agreement rules case "ZU_GENÜGE" : return 1; // prefer over ZU_KOENNE case "IMPFLICHT" : return 1; // prefer over agreement rules DE_AGREEMENT case "NULL_KOMMA_NICHTS" : return 1; // prefer over agreement rules case "ZWEI_AN_HALB" : return 1; // prefer over agreement rules case "BLUETOOTH_LAUTSPRECHER" : return 1; // prefer over agreement rules case "KOENNT_ICH" : return 1; // prefer over DE_VERBAGREEMENT case "WIR_HABE" : return 1; // prefer over DE_VERBAGREEMENT case "ICH_KOENNT" : return 1; // prefer over DE_VERBAGREEMENT case "HAT_DU" : return 1; // prefer over agreement rules case "HAST_DICH" : return 1; // prefer over agreement rules case "GRUNDE" : return 1; // prefer over agreement rules case "EIN_FACH" : return 1; // prefer over agreement rules case "WOGEN_SUBST" : return 1; // prefer over agreement rules case "SO_WIES_IST" : return 1; // prefer over agreement rules case "SICH_SICHT" : return 1; // prefer over agreement rules case "MIT_VERANTWORTLICH" : return 1; // prefer over agreement rules case "VOR_LACHEN" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "TOUREN_SUBST" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "AUF_DRÄNGEN" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "AUF_ZACK" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "UNTER_DRUCK" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "ZUCCHINIS" : return 1; // overwrite spell checker case "PASSWORTE" : return 1; // overwrite agreement rules case "ANGL_PA_ED_UNANGEMESSEN" : return 1; // overwrite spell checker case "ANFUEHRUNGSZEICHEN_DE_AT": return 1; // higher prio than UNPAIRED_BRACKETS case "ANFUEHRUNGSZEICHEN_CH_FR": return 1; // higher prio than UNPAIRED_BRACKETS case "EMAIL": return 1; // better suggestion than SIMPLE_AGREEMENT_* case "IM_STICH_LASSEN": return 1; // higher prio than agreement rules case "ZULANGE": return 1; // better suggestion than SAGT_RUFT case "ROCK_N_ROLL": return 1; // better error than DE_CASE case "JOE_BIDEN": return 1; // better error than DE_CASE case "RESOURCE_RESSOURCE": return 1; // better error than DE_CASE case "DE_PROHIBITED_COMPOUNDS": return 1; // a more detailed error message than from spell checker case "ANS_OHNE_APOSTROPH": return 1; case "DIESEN_JAHRES": return 1; case "TAG_EIN_TAG_AUS": return 1; // prefer over agreement rules case "WERT_SEIN": return 1; // prefer over DE_AGREEMENT case "EBEN_FALLS": return 1; case "IN_UND_AUSWENDIG": return 1; // prefer over DE_CASE case "HIER_MIT": return 1; // prefer over agreement rules case "HIER_FUER": return 1; // prefer over agreement rules case "MIT_REISSEN": return 1; // prefer over agreement rules case "JEDEN_FALLS": return 1; case "MOEGLICHER_WEISE_ETC": return 1; // prefer over agreement rules case "UST_ID": return 1; case "INS_FITNESS": return 1; // prefer over DE_AGREEMENT case "MIT_UNTER": return 1; // prefer over agreement rules case "SEIT_VS_SEID": return 1; // prefer over some agreement rules (HABE_BIN from premium) case "ZU_KOMMEN_LASSEN": return 1; // prefer over INFINITIVGRP_VERMOD_PKT case "ZU_SCHICKEN_LASSEN": return 1; // prefer over INFINITIVGRP_VERMOD_PKT case "IM_UM": return 1; // prefer over MIT_MIR and IM_ERSCHEINUNG (premium) case "EINEN_VERSUCH_WERT": return 1; // prefer over DE_AGREEMENT case "DASS_DAS_PA2_DAS_PROIND": return 1; // prefer over HILFSVERB_HABEN_SEIN, DE_AGREEMENT case "AUF_BITTEN": return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "MEINET_WEGEN": return 1; // prefer over AUF_DEM_WEG case "FUER_INBESONDERE": return 1; // prefer over KOMMA_VOR_ERLAEUTERUNG case "COVID_19": return 1; // prefer over PRAEP_GEN and DE_AGREEMENT case "DA_VOR": return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "KLEINSCHREIBUNG_MAL": return 1; // prefer over DE_AGREEMENT case "VERINF_DAS_DASS_SUB": return 1; // prefer over DE_AGREEMENT case "IM_ALTER": return 1; // prefer over ART_ADJ_SOL case "DAS_ALTER": return 1; // prefer over ART_ADJ_SOL case "VER_INF_PKT_VER_INF": return 1; // prefer over DE_CASE case "DASS_MIT_VERB": return 1; // prefer over SUBJUNKTION_KOMMA ("Dass wird Konsequenzen haben.") case "AB_TEST": return 1; // prefer over spell checker and agreement case "BZGL_ABK": return 1; // prefer over spell checker case "DURCH_WACHSEN": return 1; // prefer over SUBSTANTIVIERUNG_NACH_DURCH case "ICH_WARTE": return 1; // prefer over verb agreement rules (e.g. SUBJECT_VERB_AGREEMENT) case "RUNDUM_SORGLOS_PAKET": return 1; // higher prio than DE_CASE case "MIT_FREUNDLICHEN_GRUESSE": return 1; // higher prio than MEIN_KLEIN_HAUS case "OK": return 1; // higher prio than KOMMA_NACH_PARTIKEL_SENT_START[3] case "EINE_ORIGINAL_RECHNUNG": return 1; // higher prio than DE_CASE, DE_AGREEMENT and MEIN_KLEIN_HAUS case "VALENZ_TEST": return 1; // see if this generates more corpus matches case "WAEHRUNGSANGABEN_CHF": return 1; // higher prio than WAEHRUNGSANGABEN_KOMMA // default is 0 case "FALSCHES_ANFUEHRUNGSZEICHEN": return -1; // less prio than most grammar rules but higher prio than UNPAIRED_BRACKETS case "VER_KOMMA_PRO_RIN": return -1; // prefer WENN_WEN case "DE_PROHIBITED_COMPOUNDS_PREMIUM": return -1; // prefer other rules (e.g. AUS_MITTEL) case "VER_INF_VER_INF": return -1; // prefer case rules case "DE_COMPOUND_COHERENCY": return -1; // prefer EMAIL case "GEFEATURED": return -1; // prefer over spell checker case "NUMBER_SUB": return -1; // prefer over spell checker case "VER123_VERAUXMOD": return -1; // prefer casing rules case "DE_AGREEMENT": return -1; // prefer RECHT_MACHEN, MONTAGS, KONJUNKTION_DASS_DAS, DESWEITEREN, DIES_BEZUEGLICH and other case "DE_AGREEMENT2": return -1; // prefer WILLKOMMEN_GROSS and other rules that offer suggestions case "CONFUSION_RULE": return -1; // probably less specific than the rules from grammar.xml case "KOMMA_NEBEN_UND_HAUPTSATZ": return -1; // prefer SAGT_RUFT case "FALSCHES_RELATIVPRONOMEN": return -1; // prefer dass/das rules case "AKZENT_STATT_APOSTROPH": return -1; // lower prio than PLURAL_APOSTROPH case "BEENDE_IST_SENTEND": return -1; // prefer more specific rules case "VER_ADJ_ZU_SCHLAFEN": return -1; // prefer ETWAS_GUTES case "MIO_PUNKT": return -1; // higher prio than spell checker case "AUSLASSUNGSPUNKTE_LEERZEICHEN": return -1; // higher prio than spell checker case "IM_ERSCHEINUNG": return -1; // prefer ZUM_FEM_NOMEN case "SPACE_BEFORE_OG": return -1; // higher prio than spell checker case "VERSEHENTLICHERWEISE": return -1; // higher prio than spell checker case "VERMOD_SKIP_VER_PKT": return -1; // less prio than casing rules case "EINZELBUCHSTABE_PREMIUM": return -1; // lower prio than "A_LA_CARTE" case "KATARI": return -2; // higher prio than spell checker case "SCHOENE_WETTER": return -2; // prefer more specific rules that offer a suggestion (e.g. DE_AGREEMENT) case "MEIN_KLEIN_HAUS": return -2; // prefer more specific rules that offer a suggestion (e.g. DIES_BEZÜGLICH) case "UNPAIRED_BRACKETS": return -2; case "ICH_GLAUBE_FUER_EUCH": return -2; // prefer agreement rules case "OBJECT_AGREEMENT": return -2; // less prio than DE_AGREEMENT case "ICH_INF_PREMIUM": return -2; // prefer more specific rules that offer a suggestion (e.g. SUBJECT_VERB_AGREEMENT) case "MEHRERE_WOCHE_PREMIUM": return -2; // less prio than DE_AGREEMENT case "DOPPELTER_NOMINATIV": return -2; // give precedence to wie-wir-wird confusion rules case "ALTERNATIVEN_FUER_ANGLIZISMEN" : return -2; // overwrite spell checker case "ANGLIZISMUS_INTERNAL" : return -2; // overwrite spell checker case "DOPPELUNG_VER_MOD_AUX": return -2; case "AERZTEN_INNEN": return -2; // overwrite speller ("Ärzte/-innen") case "ANGLIZISMEN" : return -2; // overwrite spell checker case "ANGLIZISMUS_PA_MIT_ED" : return -2; // overwrite spell checker case "ZAHL_IM_WORT": return -2; //should not override rules like H2O case "ICH_LIEBS": return -2; // higher prio than spell checker case "ICH_GEHE_DU_BLEIBST": return -3; // prefer ICH_GLAUBE_FUER_EUCH case "GERMAN_SPELLER_RULE": return -3; // assume most other rules are more specific and helpful than the spelling rule case "AUSTRIAN_GERMAN_SPELLER_RULE": return -3; // assume most other rules are more specific and helpful than the spelling rule case "SWISS_GERMAN_SPELLER_RULE": return -3; // assume most other rules are more specific and helpful than the spelling rule case "DE_VERBAGREEMENT": return -4; // prefer more specific rules (e.g DU_WUENSCHT) and speller case "PUNKT_ENDE_DIREKTE_REDE": return -4; // prefer speller case "LEERZEICHEN_NACH_VOR_ANFUEHRUNGSZEICHEN": return -4; // prefer speller case "ZEICHENSETZUNG_DIREKTE_REDE": return -4; // prefer speller case "GROSSSCHREIBUNG_WOERTLICHER_REDE": return -4; // prefer speller case "IM_IHM": return -4; // lower prio than spell checker case "IN_UNKNOWNKLEIN_VER": return -4; // lower prio than spell checker case "SEHR_GEEHRTER_NAME": return -4; // lower prio than spell checker case "DE_PHRASE_REPETITION": return -4; // lower prio than spell checker case "FRAGEZEICHEN_NACH_DIREKTER_REDE": return -4; // lower prio than spell checker case "PUNCTUATION_PARAGRAPH_END": return -4; // don't hide spelling mistakes case "TEST_F_ANSTATT_PH": return -4; // don't hide spelling mistakes case "DAS_WETTER_IST": return -5; // lower prio than spell checker case "WER_STARK_SCHWITZ": return -5; // lower prio than spell checker case "VERBEN_PRAEFIX_AUS": return -5; // lower prio than spell checker case "ANFUEHRUNG_VERSCHACHTELT": return -5; // lower prio than speller and FALSCHES_ANFUEHRUNGSZEICHEN case "SATZBAU_AN_DEN_KOMMT": return -5; // lower prio than rules that give a suggestion case "SUBJECT_VERB_AGREEMENT": return -5; // prefer more specific rules that offer a suggestion (e.g. DE_VERBAGREEMENT) case "SAGT_SAGT": return -9; // higher pro than KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ_2 and GERMAN_WORD_REPEAT_RULE case "PUNKT_ENDE_ABSATZ": return -10; // should never hide other errors, as chance for a false alarm is quite high case "KOMMA_VOR_RELATIVSATZ": return -10; case "KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ_2": return -12; case "VON_LEBENSLAEUFE": return -12; // less prio than AI case "ZUSAMMENGESETZTE_VERBEN": return -12; // less prio than most more specific rules and AI case "PRP_VER_PRGK": return -13; // lower prio than ZUSAMMENGESETZTE_VERBEN case "COMMA_IN_FRONT_RELATIVE_CLAUSE": return -13; // prefer other rules (KONJUNKTION_DASS_DAS, ALL_DAS_WAS_KOMMA, AI) but higher prio than style case "SAGT_RUFT": return -13; // prefer case rules, DE_VERBAGREEMENT, AI and speller case "GERMAN_WORD_REPEAT_RULE": return -14; // prefer SAGT_RUFT case "BEI_VERB": return -14; // prefer case, spelling and AI rules case "MODALVERB_FLEKT_VERB": return -14; // prefer case, spelling and AI rules case "DATIV_NACH_PRP": return -14; // spelling and AI rules case "SENT_START_SIN_PLU": return -14; // prefer more specific rules that offer a suggestion (A.I., spelling) case "SENT_START_PLU_SIN": return -14; // prefer more specific rules that offer a suggestion (A.I., spelling) case "VER_INFNOMEN": return -14; // prefer spelling and AI rules case "TOO_LONG_PARAGRAPH": return -15; case "ALL_UPPERCASE": return -15; case "COMMA_BEHIND_RELATIVE_CLAUSE": return -52; // less prio than AI_DE_HYDRA_LEO case "DOPPELUNG_MODALVERB": return -52; // prefer comma rules (DOPPELUNG_MODALVERB, AI) case "VER_DOPPELUNG": return -52; // prefer comma rules (including AI) case "DEF_ARTIKEL_INDEF_ADJ": return -52; // less prio than DE_AGREMEENT and less prio than most comma rules case "PRP_ADJ_AGREEMENT": return -52; // less prio than DE_AGREMEENT and less prio than most comma rules case "SIE_WOLLTEN_SIND": return -52; case "ART_ADJ_SOL": return -52; // prefer comma rules case "WURDEN_WORDEN_1": return -52; // prefer comma rules case "KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ": return -53; case "VERB_IST": return -53; // less prio than comma rules and spell checker case "WAR_WERDEN": return -53; // less prio than comma rules case "INF_VER_MOD": return -53; // prefer case, spelling and AI rules case "VERB_FEM_SUBST": return -54; // prefer comma rules (including AI) case "SUBJUNKTION_KOMMA_2": return -54; // lower prio than KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ and KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ_2 case "DOPPELUNG_GLEICHES_VERB": return -55; // prefer comma rules case "FEHLENDES_NOMEN": return -60; // lower prio than most rules case "REPETITIONS_STYLE": return -60; case "MAN_SIEHT_SEHR_SCHOEN": return -14; // prefer over SEHR_SCHOEN // Category ids - make sure style issues don't hide overlapping "real" errors: case "COLLOQUIALISMS": return -15; case "STYLE": return -15; case "REDUNDANCY": return -15; case "GENDER_NEUTRALITY": return -15; case "TYPOGRAPHY": return -15; } if (id.startsWith("CONFUSION_RULE_")) { return -1; } if (id.startsWith("AI_DE_HYDRA_LEO")) { // prefer more specific rules (also speller) if (id.startsWith("AI_DE_HYDRA_LEO_MISSING_COMMA")) { return -51; // prefer comma style rules. } if (id.startsWith("AI_DE_HYDRA_LEO_CP")) { return 2; } if (id.startsWith("AI_DE_HYDRA_LEO_DATAKK")) { return 1; } return -11; } if (id.startsWith("AI_DE_KOMMA")) { return -52; // prefer comma style rules and AI_DE_HYDRA_LEO_MISSING_COMMA } return super.getPriorityForId(id); } public boolean hasMinMatchesRules() { return true; } }
sohaibafifi/languagetool
languagetool-language-modules/de/src/main/java/org/languagetool/language/German.java
7,936
// overwrite agreement rules
line_comment
nl
/* LanguageTool, a natural language style checker * Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.chunking.Chunker; import org.languagetool.chunking.GermanChunker; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.*; import org.languagetool.rules.de.LongSentenceRule; import org.languagetool.rules.de.SentenceWhitespaceRule; import org.languagetool.rules.de.*; import org.languagetool.rules.spelling.SpellingCheckRule; import org.languagetool.synthesis.GermanSynthesizer; import org.languagetool.synthesis.Synthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.de.GermanTagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.rules.de.GermanRuleDisambiguator; import org.languagetool.tokenizers.*; import org.languagetool.tokenizers.de.GermanCompoundTokenizer; import org.languagetool.tokenizers.de.GermanWordTokenizer; import org.languagetool.tools.Tools; import java.io.File; import java.io.IOException; import java.util.*; /** * Support for German - use the sub classes {@link GermanyGerman}, {@link SwissGerman}, or {@link AustrianGerman} * if you need spell checking. */ public class German extends Language implements AutoCloseable { private LanguageModel languageModel; /** * @deprecated use {@link GermanyGerman}, {@link AustrianGerman}, or {@link SwissGerman} instead - * they have rules for spell checking, this class doesn't (deprecated since 3.2) */ @Deprecated public German() { } @Override public Language getDefaultLanguageVariant() { return GermanyGerman.INSTANCE; } @Override public SpellingCheckRule createDefaultSpellingRule(ResourceBundle messages) throws IOException { return new GermanSpellerRule(messages, this); } @NotNull @Override public GermanSpellerRule getDefaultSpellingRule() { return (GermanSpellerRule) Objects.requireNonNull(super.getDefaultSpellingRule()); } @Override public Disambiguator createDefaultDisambiguator() { return new GermanRuleDisambiguator(); } @Nullable @Override public Chunker createDefaultPostDisambiguationChunker() { return new GermanChunker(); } @Override public String getName() { return "German"; } @Override public String getShortCode() { return "de"; } @Override public String[] getCountries() { return new String[]{"LU", "LI", "BE"}; } @NotNull @Override public Tagger createDefaultTagger() { return GermanTagger.INSTANCE; } @Nullable @Override public Synthesizer createDefaultSynthesizer() { return GermanSynthesizer.INSTANCE; } @Override public SentenceTokenizer createDefaultSentenceTokenizer() { return new SRXSentenceTokenizer(this); } @Override public Contributor[] getMaintainers() { return new Contributor[] { new Contributor("Jan Schreiber"), Contributors.DANIEL_NABER, }; } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException { return Arrays.asList( new CommaWhitespaceRule(messages, Example.wrong("Die Partei<marker> ,</marker> die die letzte Wahl gewann."), Example.fixed("Die Partei<marker>,</marker> die die letzte Wahl gewann."), Tools.getUrl("https://languagetool.org/insights/de/beitrag/grammatik-leerzeichen/#fehler-1-leerzeichen-vor-und-nach-satzzeichen")), new GermanUnpairedBracketsRule(messages, this), new UppercaseSentenceStartRule(messages, this, Example.wrong("Das Haus ist alt. <marker>es</marker> wurde 1950 gebaut."), Example.fixed("Das Haus ist alt. <marker>Es</marker> wurde 1950 gebaut."), Tools.getUrl("https://languagetool.org/insights/de/beitrag/gross-klein-schreibung-rechtschreibung/#1-satzanf%C3%A4nge-schreiben-wir-gro%C3%9F")), new MultipleWhitespaceRule(messages, this), new WhiteSpaceBeforeParagraphEnd(messages, this), new WhiteSpaceAtBeginOfParagraph(messages), new EmptyLineRule(messages, this), new LongParagraphRule(messages, this, userConfig), new PunctuationMarkAtParagraphEnd(messages, this), // specific to German: new SimpleReplaceRule(messages, this), new OldSpellingRule(messages), new SentenceWhitespaceRule(messages), new GermanDoublePunctuationRule(messages), new MissingVerbRule(messages, this), new GermanWordRepeatRule(messages, this), new GermanWordRepeatBeginningRule(messages, this), new GermanWrongWordInContextRule(messages), new AgreementRule(messages, this), new AgreementRule2(messages, this), new CaseRule(messages, this), new DashRule(messages), new VerbAgreementRule(messages, this), new SubjectVerbAgreementRule(messages, this), new WordCoherencyRule(messages), new SimilarNameRule(messages), new WiederVsWiderRule(messages), new GermanStyleRepeatedWordRule(messages, this, userConfig), new CompoundCoherencyRule(messages), new LongSentenceRule(messages, userConfig, 40), new GermanFillerWordsRule(messages, this, userConfig), new PassiveSentenceRule(messages, this, userConfig), new SentenceWithModalVerbRule(messages, this, userConfig), new SentenceWithManRule(messages, this, userConfig), new ConjunctionAtBeginOfSentenceRule(messages, this, userConfig), new NonSignificantVerbsRule(messages, this, userConfig), new UnnecessaryPhraseRule(messages, this, userConfig), new GermanParagraphRepeatBeginningRule(messages, this), new DuUpperLowerCaseRule(messages), new UnitConversionRule(messages), new MissingCommaRelativeClauseRule(messages), new MissingCommaRelativeClauseRule(messages, true), new RedundantModalOrAuxiliaryVerb(messages), new GermanReadabilityRule(messages, this, userConfig, true), new GermanReadabilityRule(messages, this, userConfig, false), new CompoundInfinitivRule(messages, this, userConfig), new StyleRepeatedVeryShortSentences(messages, this), new StyleRepeatedSentenceBeginning(messages), new GermanRepeatedWordsRule(messages) ); } /** * @since 2.7 */ public CompoundWordTokenizer getNonStrictCompoundSplitter() { GermanCompoundTokenizer tokenizer = GermanCompoundTokenizer.getNonStrictInstance(); // there's a spelling mistake in (at least) one part, so strict mode wouldn't split the word return word -> new ArrayList<>(tokenizer.tokenize(word)); } /** * @since 2.7 */ public GermanCompoundTokenizer getStrictCompoundTokenizer() { return GermanCompoundTokenizer.getStrictInstance(); } @Override public synchronized LanguageModel getLanguageModel(File indexDir) throws IOException { languageModel = initLanguageModel(indexDir, languageModel); return languageModel; } /** @since 3.1 */ @Override public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel, UserConfig userConfig) throws IOException { return Arrays.asList( new UpperCaseNgramRule(messages, languageModel, this), new GermanConfusionProbabilityRule(messages, languageModel, this), new ProhibitedCompoundRule(messages, languageModel, userConfig) ); } @Override public Tokenizer createDefaultWordTokenizer() { return new GermanWordTokenizer(); } /** * Closes the language model, if any. * @since 3.1 */ @Override public void close() throws Exception { if (languageModel != null) { languageModel.close(); } } /** @since 5.1 */ @Override public String getOpeningDoubleQuote() { return "„"; } /** @since 5.1 */ @Override public String getClosingDoubleQuote() { return "“"; } /** @since 5.1 */ @Override public String getOpeningSingleQuote() { return "‚"; } /** @since 5.1 */ @Override public String getClosingSingleQuote() { return "‘"; } /** @since 5.1 */ @Override public boolean isAdvancedTypographyEnabled() { return true; } @Override public String toAdvancedTypography(String input) { String output = super.toAdvancedTypography(input); //non-breaking space output = output.replaceAll("\\b([a-zA-Z]\\.)([a-zA-Z]\\.)", "$1\u00a0$2"); output = output.replaceAll("\\b([a-zA-Z]\\.)([a-zA-Z]\\.)", "$1\u00a0$2"); return output; } @Override public LanguageMaintainedState getMaintainedState() { return LanguageMaintainedState.ActivelyMaintained; } @Override protected int getPriorityForId(String id) { switch (id) { // Rule ids: case "DE_PROHIBITED_PHRASE": return 11; case "WRONG_SPELLING_PREMIUM_INTERNAL": return 10; case "OLD_SPELLING_INTERNAL": return 10; case "DE_COMPOUNDS": return 10; case "TELEFON_NR": return 10; case "IRGEND_COMPOUND": return 10; case "DA_DURCH": return 2; // prefer over SUBSTANTIVIERUNG_NACH_DURCH and DURCH_SCHAUEN and DURCH_WACHSEN case "BEI_GOOGLE" : return 2; // prefer over agreement rules and VOR_BEI case "EINE_ORIGINAL_RECHNUNG_TEST" : return 2; // prefer over agreement rules case "VONSTATTEN_GEHEN" : return 2; // prefer over EINE_ORIGINAL_RECHNUNG case "VERWECHSLUNG_MIR_DIR_MIR_DIE": return 1; // prefer over MIR_DIR case "ERNEUERBARE_ENERGIEN": return 1; // prefer over VEREINBAREN case "DRIVE_IN": return 1; // prefer over agreement rules case "AN_STATT": return 1; // prefer over agreement rules case "VOR_BEI": return 1; // prefer over BEI_BEHALTEN case "ALLES_GUTE": return 1; // prefer over premium rules case "NEUN_NEUEN": return 1; // prefer over VIELZAHL_PLUS_SINGULAR case "VERWANDET_VERWANDTE": return 1; // prefer over DE_CASE case "IN_DEUTSCHE_SPRACHE": return 1; // prefer over most other rules case "SEIT_LAENGEREN": return 1; // prefer over DE_CASE case "SEIT_KLEIN_AUF": return 1; // prefer over agreement rules case "SEIT_GEBURT_AN": return 1; // prefer over agreement rules case "WO_VON": return 1; // prefer over most agreement rules case "ICH_BIN_STAND_JETZT_KOMMA": return 1; // prefer over most agreement rules case "EIN_LOGGEN": return 1; // prefer over most agreement rules case "ZU_GENÜGE" : return 1; // prefer over ZU_KOENNE case "IMPFLICHT" : return 1; // prefer over agreement rules DE_AGREEMENT case "NULL_KOMMA_NICHTS" : return 1; // prefer over agreement rules case "ZWEI_AN_HALB" : return 1; // prefer over agreement rules case "BLUETOOTH_LAUTSPRECHER" : return 1; // prefer over agreement rules case "KOENNT_ICH" : return 1; // prefer over DE_VERBAGREEMENT case "WIR_HABE" : return 1; // prefer over DE_VERBAGREEMENT case "ICH_KOENNT" : return 1; // prefer over DE_VERBAGREEMENT case "HAT_DU" : return 1; // prefer over agreement rules case "HAST_DICH" : return 1; // prefer over agreement rules case "GRUNDE" : return 1; // prefer over agreement rules case "EIN_FACH" : return 1; // prefer over agreement rules case "WOGEN_SUBST" : return 1; // prefer over agreement rules case "SO_WIES_IST" : return 1; // prefer over agreement rules case "SICH_SICHT" : return 1; // prefer over agreement rules case "MIT_VERANTWORTLICH" : return 1; // prefer over agreement rules case "VOR_LACHEN" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "TOUREN_SUBST" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "AUF_DRÄNGEN" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "AUF_ZACK" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "UNTER_DRUCK" : return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "ZUCCHINIS" : return 1; // overwrite spell checker case "PASSWORTE" : return 1; // overwrite agreement<SUF> case "ANGL_PA_ED_UNANGEMESSEN" : return 1; // overwrite spell checker case "ANFUEHRUNGSZEICHEN_DE_AT": return 1; // higher prio than UNPAIRED_BRACKETS case "ANFUEHRUNGSZEICHEN_CH_FR": return 1; // higher prio than UNPAIRED_BRACKETS case "EMAIL": return 1; // better suggestion than SIMPLE_AGREEMENT_* case "IM_STICH_LASSEN": return 1; // higher prio than agreement rules case "ZULANGE": return 1; // better suggestion than SAGT_RUFT case "ROCK_N_ROLL": return 1; // better error than DE_CASE case "JOE_BIDEN": return 1; // better error than DE_CASE case "RESOURCE_RESSOURCE": return 1; // better error than DE_CASE case "DE_PROHIBITED_COMPOUNDS": return 1; // a more detailed error message than from spell checker case "ANS_OHNE_APOSTROPH": return 1; case "DIESEN_JAHRES": return 1; case "TAG_EIN_TAG_AUS": return 1; // prefer over agreement rules case "WERT_SEIN": return 1; // prefer over DE_AGREEMENT case "EBEN_FALLS": return 1; case "IN_UND_AUSWENDIG": return 1; // prefer over DE_CASE case "HIER_MIT": return 1; // prefer over agreement rules case "HIER_FUER": return 1; // prefer over agreement rules case "MIT_REISSEN": return 1; // prefer over agreement rules case "JEDEN_FALLS": return 1; case "MOEGLICHER_WEISE_ETC": return 1; // prefer over agreement rules case "UST_ID": return 1; case "INS_FITNESS": return 1; // prefer over DE_AGREEMENT case "MIT_UNTER": return 1; // prefer over agreement rules case "SEIT_VS_SEID": return 1; // prefer over some agreement rules (HABE_BIN from premium) case "ZU_KOMMEN_LASSEN": return 1; // prefer over INFINITIVGRP_VERMOD_PKT case "ZU_SCHICKEN_LASSEN": return 1; // prefer over INFINITIVGRP_VERMOD_PKT case "IM_UM": return 1; // prefer over MIT_MIR and IM_ERSCHEINUNG (premium) case "EINEN_VERSUCH_WERT": return 1; // prefer over DE_AGREEMENT case "DASS_DAS_PA2_DAS_PROIND": return 1; // prefer over HILFSVERB_HABEN_SEIN, DE_AGREEMENT case "AUF_BITTEN": return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "MEINET_WEGEN": return 1; // prefer over AUF_DEM_WEG case "FUER_INBESONDERE": return 1; // prefer over KOMMA_VOR_ERLAEUTERUNG case "COVID_19": return 1; // prefer over PRAEP_GEN and DE_AGREEMENT case "DA_VOR": return 1; // prefer over ZUSAMMENGESETZTE_VERBEN case "KLEINSCHREIBUNG_MAL": return 1; // prefer over DE_AGREEMENT case "VERINF_DAS_DASS_SUB": return 1; // prefer over DE_AGREEMENT case "IM_ALTER": return 1; // prefer over ART_ADJ_SOL case "DAS_ALTER": return 1; // prefer over ART_ADJ_SOL case "VER_INF_PKT_VER_INF": return 1; // prefer over DE_CASE case "DASS_MIT_VERB": return 1; // prefer over SUBJUNKTION_KOMMA ("Dass wird Konsequenzen haben.") case "AB_TEST": return 1; // prefer over spell checker and agreement case "BZGL_ABK": return 1; // prefer over spell checker case "DURCH_WACHSEN": return 1; // prefer over SUBSTANTIVIERUNG_NACH_DURCH case "ICH_WARTE": return 1; // prefer over verb agreement rules (e.g. SUBJECT_VERB_AGREEMENT) case "RUNDUM_SORGLOS_PAKET": return 1; // higher prio than DE_CASE case "MIT_FREUNDLICHEN_GRUESSE": return 1; // higher prio than MEIN_KLEIN_HAUS case "OK": return 1; // higher prio than KOMMA_NACH_PARTIKEL_SENT_START[3] case "EINE_ORIGINAL_RECHNUNG": return 1; // higher prio than DE_CASE, DE_AGREEMENT and MEIN_KLEIN_HAUS case "VALENZ_TEST": return 1; // see if this generates more corpus matches case "WAEHRUNGSANGABEN_CHF": return 1; // higher prio than WAEHRUNGSANGABEN_KOMMA // default is 0 case "FALSCHES_ANFUEHRUNGSZEICHEN": return -1; // less prio than most grammar rules but higher prio than UNPAIRED_BRACKETS case "VER_KOMMA_PRO_RIN": return -1; // prefer WENN_WEN case "DE_PROHIBITED_COMPOUNDS_PREMIUM": return -1; // prefer other rules (e.g. AUS_MITTEL) case "VER_INF_VER_INF": return -1; // prefer case rules case "DE_COMPOUND_COHERENCY": return -1; // prefer EMAIL case "GEFEATURED": return -1; // prefer over spell checker case "NUMBER_SUB": return -1; // prefer over spell checker case "VER123_VERAUXMOD": return -1; // prefer casing rules case "DE_AGREEMENT": return -1; // prefer RECHT_MACHEN, MONTAGS, KONJUNKTION_DASS_DAS, DESWEITEREN, DIES_BEZUEGLICH and other case "DE_AGREEMENT2": return -1; // prefer WILLKOMMEN_GROSS and other rules that offer suggestions case "CONFUSION_RULE": return -1; // probably less specific than the rules from grammar.xml case "KOMMA_NEBEN_UND_HAUPTSATZ": return -1; // prefer SAGT_RUFT case "FALSCHES_RELATIVPRONOMEN": return -1; // prefer dass/das rules case "AKZENT_STATT_APOSTROPH": return -1; // lower prio than PLURAL_APOSTROPH case "BEENDE_IST_SENTEND": return -1; // prefer more specific rules case "VER_ADJ_ZU_SCHLAFEN": return -1; // prefer ETWAS_GUTES case "MIO_PUNKT": return -1; // higher prio than spell checker case "AUSLASSUNGSPUNKTE_LEERZEICHEN": return -1; // higher prio than spell checker case "IM_ERSCHEINUNG": return -1; // prefer ZUM_FEM_NOMEN case "SPACE_BEFORE_OG": return -1; // higher prio than spell checker case "VERSEHENTLICHERWEISE": return -1; // higher prio than spell checker case "VERMOD_SKIP_VER_PKT": return -1; // less prio than casing rules case "EINZELBUCHSTABE_PREMIUM": return -1; // lower prio than "A_LA_CARTE" case "KATARI": return -2; // higher prio than spell checker case "SCHOENE_WETTER": return -2; // prefer more specific rules that offer a suggestion (e.g. DE_AGREEMENT) case "MEIN_KLEIN_HAUS": return -2; // prefer more specific rules that offer a suggestion (e.g. DIES_BEZÜGLICH) case "UNPAIRED_BRACKETS": return -2; case "ICH_GLAUBE_FUER_EUCH": return -2; // prefer agreement rules case "OBJECT_AGREEMENT": return -2; // less prio than DE_AGREEMENT case "ICH_INF_PREMIUM": return -2; // prefer more specific rules that offer a suggestion (e.g. SUBJECT_VERB_AGREEMENT) case "MEHRERE_WOCHE_PREMIUM": return -2; // less prio than DE_AGREEMENT case "DOPPELTER_NOMINATIV": return -2; // give precedence to wie-wir-wird confusion rules case "ALTERNATIVEN_FUER_ANGLIZISMEN" : return -2; // overwrite spell checker case "ANGLIZISMUS_INTERNAL" : return -2; // overwrite spell checker case "DOPPELUNG_VER_MOD_AUX": return -2; case "AERZTEN_INNEN": return -2; // overwrite speller ("Ärzte/-innen") case "ANGLIZISMEN" : return -2; // overwrite spell checker case "ANGLIZISMUS_PA_MIT_ED" : return -2; // overwrite spell checker case "ZAHL_IM_WORT": return -2; //should not override rules like H2O case "ICH_LIEBS": return -2; // higher prio than spell checker case "ICH_GEHE_DU_BLEIBST": return -3; // prefer ICH_GLAUBE_FUER_EUCH case "GERMAN_SPELLER_RULE": return -3; // assume most other rules are more specific and helpful than the spelling rule case "AUSTRIAN_GERMAN_SPELLER_RULE": return -3; // assume most other rules are more specific and helpful than the spelling rule case "SWISS_GERMAN_SPELLER_RULE": return -3; // assume most other rules are more specific and helpful than the spelling rule case "DE_VERBAGREEMENT": return -4; // prefer more specific rules (e.g DU_WUENSCHT) and speller case "PUNKT_ENDE_DIREKTE_REDE": return -4; // prefer speller case "LEERZEICHEN_NACH_VOR_ANFUEHRUNGSZEICHEN": return -4; // prefer speller case "ZEICHENSETZUNG_DIREKTE_REDE": return -4; // prefer speller case "GROSSSCHREIBUNG_WOERTLICHER_REDE": return -4; // prefer speller case "IM_IHM": return -4; // lower prio than spell checker case "IN_UNKNOWNKLEIN_VER": return -4; // lower prio than spell checker case "SEHR_GEEHRTER_NAME": return -4; // lower prio than spell checker case "DE_PHRASE_REPETITION": return -4; // lower prio than spell checker case "FRAGEZEICHEN_NACH_DIREKTER_REDE": return -4; // lower prio than spell checker case "PUNCTUATION_PARAGRAPH_END": return -4; // don't hide spelling mistakes case "TEST_F_ANSTATT_PH": return -4; // don't hide spelling mistakes case "DAS_WETTER_IST": return -5; // lower prio than spell checker case "WER_STARK_SCHWITZ": return -5; // lower prio than spell checker case "VERBEN_PRAEFIX_AUS": return -5; // lower prio than spell checker case "ANFUEHRUNG_VERSCHACHTELT": return -5; // lower prio than speller and FALSCHES_ANFUEHRUNGSZEICHEN case "SATZBAU_AN_DEN_KOMMT": return -5; // lower prio than rules that give a suggestion case "SUBJECT_VERB_AGREEMENT": return -5; // prefer more specific rules that offer a suggestion (e.g. DE_VERBAGREEMENT) case "SAGT_SAGT": return -9; // higher pro than KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ_2 and GERMAN_WORD_REPEAT_RULE case "PUNKT_ENDE_ABSATZ": return -10; // should never hide other errors, as chance for a false alarm is quite high case "KOMMA_VOR_RELATIVSATZ": return -10; case "KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ_2": return -12; case "VON_LEBENSLAEUFE": return -12; // less prio than AI case "ZUSAMMENGESETZTE_VERBEN": return -12; // less prio than most more specific rules and AI case "PRP_VER_PRGK": return -13; // lower prio than ZUSAMMENGESETZTE_VERBEN case "COMMA_IN_FRONT_RELATIVE_CLAUSE": return -13; // prefer other rules (KONJUNKTION_DASS_DAS, ALL_DAS_WAS_KOMMA, AI) but higher prio than style case "SAGT_RUFT": return -13; // prefer case rules, DE_VERBAGREEMENT, AI and speller case "GERMAN_WORD_REPEAT_RULE": return -14; // prefer SAGT_RUFT case "BEI_VERB": return -14; // prefer case, spelling and AI rules case "MODALVERB_FLEKT_VERB": return -14; // prefer case, spelling and AI rules case "DATIV_NACH_PRP": return -14; // spelling and AI rules case "SENT_START_SIN_PLU": return -14; // prefer more specific rules that offer a suggestion (A.I., spelling) case "SENT_START_PLU_SIN": return -14; // prefer more specific rules that offer a suggestion (A.I., spelling) case "VER_INFNOMEN": return -14; // prefer spelling and AI rules case "TOO_LONG_PARAGRAPH": return -15; case "ALL_UPPERCASE": return -15; case "COMMA_BEHIND_RELATIVE_CLAUSE": return -52; // less prio than AI_DE_HYDRA_LEO case "DOPPELUNG_MODALVERB": return -52; // prefer comma rules (DOPPELUNG_MODALVERB, AI) case "VER_DOPPELUNG": return -52; // prefer comma rules (including AI) case "DEF_ARTIKEL_INDEF_ADJ": return -52; // less prio than DE_AGREMEENT and less prio than most comma rules case "PRP_ADJ_AGREEMENT": return -52; // less prio than DE_AGREMEENT and less prio than most comma rules case "SIE_WOLLTEN_SIND": return -52; case "ART_ADJ_SOL": return -52; // prefer comma rules case "WURDEN_WORDEN_1": return -52; // prefer comma rules case "KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ": return -53; case "VERB_IST": return -53; // less prio than comma rules and spell checker case "WAR_WERDEN": return -53; // less prio than comma rules case "INF_VER_MOD": return -53; // prefer case, spelling and AI rules case "VERB_FEM_SUBST": return -54; // prefer comma rules (including AI) case "SUBJUNKTION_KOMMA_2": return -54; // lower prio than KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ and KOMMA_ZWISCHEN_HAUPT_UND_NEBENSATZ_2 case "DOPPELUNG_GLEICHES_VERB": return -55; // prefer comma rules case "FEHLENDES_NOMEN": return -60; // lower prio than most rules case "REPETITIONS_STYLE": return -60; case "MAN_SIEHT_SEHR_SCHOEN": return -14; // prefer over SEHR_SCHOEN // Category ids - make sure style issues don't hide overlapping "real" errors: case "COLLOQUIALISMS": return -15; case "STYLE": return -15; case "REDUNDANCY": return -15; case "GENDER_NEUTRALITY": return -15; case "TYPOGRAPHY": return -15; } if (id.startsWith("CONFUSION_RULE_")) { return -1; } if (id.startsWith("AI_DE_HYDRA_LEO")) { // prefer more specific rules (also speller) if (id.startsWith("AI_DE_HYDRA_LEO_MISSING_COMMA")) { return -51; // prefer comma style rules. } if (id.startsWith("AI_DE_HYDRA_LEO_CP")) { return 2; } if (id.startsWith("AI_DE_HYDRA_LEO_DATAKK")) { return 1; } return -11; } if (id.startsWith("AI_DE_KOMMA")) { return -52; // prefer comma style rules and AI_DE_HYDRA_LEO_MISSING_COMMA } return super.getPriorityForId(id); } public boolean hasMinMatchesRules() { return true; } }
76776_3
package org.color; import org.liberty.android.fantastischmemo.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.Resources; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.BlurMaskFilter.Blur; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.LayerDrawable; import android.os.SystemClock; import android.util.Log; import android.util.StateSet; import android.view.LayoutInflater; import android.view.View; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; public class ColorDialog extends AlertDialog implements OnSeekBarChangeListener, OnClickListener { public interface OnClickListener { public void onClick(View view, int color); } private SeekBar mHue; private SeekBar mSaturation; private SeekBar mValue; private ColorDialog.OnClickListener mListener; private int mColor; private View mView; private GradientDrawable mPreviewDrawable; public ColorDialog(Context context, View view, int color, OnClickListener listener) { super(context); mView = view; mListener = listener; Resources res = context.getResources(); setTitle(res.getText(R.string.color_dialog_title)); setButton(BUTTON_POSITIVE, res.getText(android.R.string.yes), this); setButton(BUTTON_NEGATIVE, res.getText(android.R.string.cancel), this); View root = LayoutInflater.from(context).inflate(R.layout.color_picker, null); setView(root); View preview = root.findViewById(R.id.preview); mPreviewDrawable = new GradientDrawable(); // 2 pix more than color_picker_frame's radius mPreviewDrawable.setCornerRadius(7); Drawable[] layers = { mPreviewDrawable, res.getDrawable(R.drawable.color_picker_frame), }; preview.setBackgroundDrawable(new LayerDrawable(layers)); mHue = (SeekBar) root.findViewById(R.id.hue); mSaturation = (SeekBar) root.findViewById(R.id.saturation); mValue = (SeekBar) root.findViewById(R.id.value); mColor = color; float[] hsv = new float[3]; Color.colorToHSV(color, hsv); int h = (int) (hsv[0] * mHue.getMax() / 360); int s = (int) (hsv[1] * mSaturation.getMax()); int v = (int) (hsv[2] * mValue.getMax()); setupSeekBar(mHue, R.string.color_h, h, res); setupSeekBar(mSaturation, R.string.color_s, s, res); setupSeekBar(mValue, R.string.color_v, v, res); updatePreview(color); } private void setupSeekBar(SeekBar seekBar, int id, int value, Resources res) { seekBar.setProgressDrawable(new TextSeekBarDrawable(res, id, value < seekBar.getMax() / 2)); seekBar.setProgress(value); seekBar.setOnSeekBarChangeListener(this); } private void update() { float[] hsv = { 360 * mHue.getProgress() / (float) mHue.getMax(), mSaturation.getProgress() / (float) mSaturation.getMax(), mValue.getProgress() / (float) mValue.getMax(), }; mColor = Color.HSVToColor(hsv); updatePreview(mColor); } private void updatePreview(int color) { mPreviewDrawable.setColor(color); mPreviewDrawable.invalidateSelf(); } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { update(); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { } public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { mListener.onClick(mView, mColor); } dismiss(); } static final int[] STATE_FOCUSED = {android.R.attr.state_focused}; static final int[] STATE_PRESSED = {android.R.attr.state_pressed}; class TextSeekBarDrawable extends Drawable implements Runnable { private static final String TAG = "TextSeekBarDrawable"; private static final long DELAY = 25; private String mText; private Drawable mProgress; private Paint mPaint; private Paint mOutlinePaint; private float mTextWidth; private boolean mActive; private float mTextX; private float mDelta; public TextSeekBarDrawable(Resources res, int id, boolean labelOnRight) { mText = res.getString(id); mProgress = res.getDrawable(android.R.drawable.progress_horizontal); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setTypeface(Typeface.DEFAULT_BOLD); mPaint.setTextSize(16); mPaint.setColor(0xff000000); mOutlinePaint = new Paint(mPaint); mOutlinePaint.setStyle(Style.STROKE); mOutlinePaint.setStrokeWidth(3); mOutlinePaint.setColor(0xbbffc300); mOutlinePaint.setMaskFilter(new BlurMaskFilter(1, Blur.NORMAL)); mTextWidth = mOutlinePaint.measureText(mText); mTextX = labelOnRight? 1 : 0; } @Override protected void onBoundsChange(Rect bounds) { mProgress.setBounds(bounds); } @Override protected boolean onStateChange(int[] state) { mActive = StateSet.stateSetMatches(STATE_FOCUSED, state) | StateSet.stateSetMatches(STATE_PRESSED, state); invalidateSelf(); return false; } @Override public boolean isStateful() { return true; } @Override protected boolean onLevelChange(int level) { // Log.d(TAG, "onLevelChange " + level); if (level < 4000 && mDelta <= 0) { mDelta = 0.05f; // Log.d(TAG, "onLevelChange scheduleSelf ++"); scheduleSelf(this, SystemClock.uptimeMillis() + DELAY); } else if (level > 6000 && mDelta >= 0) { // Log.d(TAG, "onLevelChange scheduleSelf --"); mDelta = -0.05f; scheduleSelf(this, SystemClock.uptimeMillis() + DELAY); } return mProgress.setLevel(level); } @Override public void draw(Canvas canvas) { mProgress.draw(canvas); Rect bounds = getBounds(); float x = 6 + mTextX * (bounds.width() - mTextWidth - 6 - 6); float y = (bounds.height() + mPaint.getTextSize()) / 2; mOutlinePaint.setAlpha(mActive? 255 : 255 / 2); mPaint.setAlpha(mActive? 255 : 255 / 2); canvas.drawText(mText, x, y, mOutlinePaint); canvas.drawText(mText, x, y, mPaint); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(ColorFilter cf) { } public void run() { mTextX += mDelta; if (mTextX >= 1) { mTextX = 1; mDelta = 0; } else if (mTextX <= 0) { mTextX = 0; mDelta = 0; } else { scheduleSelf(this, SystemClock.uptimeMillis() + DELAY); } invalidateSelf(); // Log.d(TAG, "run " + mTextX + " " + SystemClock.uptimeMillis()); } } }
nicolas-raoul/AnyMemo
src/org/color/ColorDialog.java
2,119
// Log.d(TAG, "onLevelChange scheduleSelf --");
line_comment
nl
package org.color; import org.liberty.android.fantastischmemo.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.Resources; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.BlurMaskFilter.Blur; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.LayerDrawable; import android.os.SystemClock; import android.util.Log; import android.util.StateSet; import android.view.LayoutInflater; import android.view.View; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; public class ColorDialog extends AlertDialog implements OnSeekBarChangeListener, OnClickListener { public interface OnClickListener { public void onClick(View view, int color); } private SeekBar mHue; private SeekBar mSaturation; private SeekBar mValue; private ColorDialog.OnClickListener mListener; private int mColor; private View mView; private GradientDrawable mPreviewDrawable; public ColorDialog(Context context, View view, int color, OnClickListener listener) { super(context); mView = view; mListener = listener; Resources res = context.getResources(); setTitle(res.getText(R.string.color_dialog_title)); setButton(BUTTON_POSITIVE, res.getText(android.R.string.yes), this); setButton(BUTTON_NEGATIVE, res.getText(android.R.string.cancel), this); View root = LayoutInflater.from(context).inflate(R.layout.color_picker, null); setView(root); View preview = root.findViewById(R.id.preview); mPreviewDrawable = new GradientDrawable(); // 2 pix more than color_picker_frame's radius mPreviewDrawable.setCornerRadius(7); Drawable[] layers = { mPreviewDrawable, res.getDrawable(R.drawable.color_picker_frame), }; preview.setBackgroundDrawable(new LayerDrawable(layers)); mHue = (SeekBar) root.findViewById(R.id.hue); mSaturation = (SeekBar) root.findViewById(R.id.saturation); mValue = (SeekBar) root.findViewById(R.id.value); mColor = color; float[] hsv = new float[3]; Color.colorToHSV(color, hsv); int h = (int) (hsv[0] * mHue.getMax() / 360); int s = (int) (hsv[1] * mSaturation.getMax()); int v = (int) (hsv[2] * mValue.getMax()); setupSeekBar(mHue, R.string.color_h, h, res); setupSeekBar(mSaturation, R.string.color_s, s, res); setupSeekBar(mValue, R.string.color_v, v, res); updatePreview(color); } private void setupSeekBar(SeekBar seekBar, int id, int value, Resources res) { seekBar.setProgressDrawable(new TextSeekBarDrawable(res, id, value < seekBar.getMax() / 2)); seekBar.setProgress(value); seekBar.setOnSeekBarChangeListener(this); } private void update() { float[] hsv = { 360 * mHue.getProgress() / (float) mHue.getMax(), mSaturation.getProgress() / (float) mSaturation.getMax(), mValue.getProgress() / (float) mValue.getMax(), }; mColor = Color.HSVToColor(hsv); updatePreview(mColor); } private void updatePreview(int color) { mPreviewDrawable.setColor(color); mPreviewDrawable.invalidateSelf(); } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { update(); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { } public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { mListener.onClick(mView, mColor); } dismiss(); } static final int[] STATE_FOCUSED = {android.R.attr.state_focused}; static final int[] STATE_PRESSED = {android.R.attr.state_pressed}; class TextSeekBarDrawable extends Drawable implements Runnable { private static final String TAG = "TextSeekBarDrawable"; private static final long DELAY = 25; private String mText; private Drawable mProgress; private Paint mPaint; private Paint mOutlinePaint; private float mTextWidth; private boolean mActive; private float mTextX; private float mDelta; public TextSeekBarDrawable(Resources res, int id, boolean labelOnRight) { mText = res.getString(id); mProgress = res.getDrawable(android.R.drawable.progress_horizontal); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setTypeface(Typeface.DEFAULT_BOLD); mPaint.setTextSize(16); mPaint.setColor(0xff000000); mOutlinePaint = new Paint(mPaint); mOutlinePaint.setStyle(Style.STROKE); mOutlinePaint.setStrokeWidth(3); mOutlinePaint.setColor(0xbbffc300); mOutlinePaint.setMaskFilter(new BlurMaskFilter(1, Blur.NORMAL)); mTextWidth = mOutlinePaint.measureText(mText); mTextX = labelOnRight? 1 : 0; } @Override protected void onBoundsChange(Rect bounds) { mProgress.setBounds(bounds); } @Override protected boolean onStateChange(int[] state) { mActive = StateSet.stateSetMatches(STATE_FOCUSED, state) | StateSet.stateSetMatches(STATE_PRESSED, state); invalidateSelf(); return false; } @Override public boolean isStateful() { return true; } @Override protected boolean onLevelChange(int level) { // Log.d(TAG, "onLevelChange " + level); if (level < 4000 && mDelta <= 0) { mDelta = 0.05f; // Log.d(TAG, "onLevelChange scheduleSelf ++"); scheduleSelf(this, SystemClock.uptimeMillis() + DELAY); } else if (level > 6000 && mDelta >= 0) { // Log.d(TAG, "onLevelChange<SUF> mDelta = -0.05f; scheduleSelf(this, SystemClock.uptimeMillis() + DELAY); } return mProgress.setLevel(level); } @Override public void draw(Canvas canvas) { mProgress.draw(canvas); Rect bounds = getBounds(); float x = 6 + mTextX * (bounds.width() - mTextWidth - 6 - 6); float y = (bounds.height() + mPaint.getTextSize()) / 2; mOutlinePaint.setAlpha(mActive? 255 : 255 / 2); mPaint.setAlpha(mActive? 255 : 255 / 2); canvas.drawText(mText, x, y, mOutlinePaint); canvas.drawText(mText, x, y, mPaint); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(ColorFilter cf) { } public void run() { mTextX += mDelta; if (mTextX >= 1) { mTextX = 1; mDelta = 0; } else if (mTextX <= 0) { mTextX = 0; mDelta = 0; } else { scheduleSelf(this, SystemClock.uptimeMillis() + DELAY); } invalidateSelf(); // Log.d(TAG, "run " + mTextX + " " + SystemClock.uptimeMillis()); } } }
105237_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.worldpainter.layers.exporters; import com.google.common.collect.ImmutableMap; import org.pepsoft.minecraft.Chunk; import org.pepsoft.minecraft.Material; import org.pepsoft.util.PerlinNoise; import org.pepsoft.worldpainter.Dimension; import org.pepsoft.worldpainter.Platform; import org.pepsoft.worldpainter.Tile; import org.pepsoft.worldpainter.exporting.AbstractLayerExporter; import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter; import org.pepsoft.worldpainter.layers.Resources; import org.pepsoft.worldpainter.layers.Void; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.*; import static org.pepsoft.minecraft.Constants.*; import static org.pepsoft.minecraft.Material.*; import static org.pepsoft.worldpainter.Constants.*; import static org.pepsoft.worldpainter.DefaultPlugin.*; import static org.pepsoft.worldpainter.layers.exporters.ResourcesExporter.ResourcesExporterSettings.defaultSettings; /** * * @author pepijn */ public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter { public ResourcesExporter() { super(Resources.INSTANCE); } @Override public void setSettings(ExporterSettings settings) { super.setSettings(settings); ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings(); if (resourcesSettings != null) { Set<Material> allMaterials = resourcesSettings.getMaterials(); List<Material> activeMaterials = new ArrayList<>(allMaterials.size()); for (Material material: allMaterials) { if (resourcesSettings.getChance(material) > 0) { activeMaterials.add(material); } } this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]); noiseGenerators = new PerlinNoise[this.activeMaterials.length]; seedOffsets = new long[this.activeMaterials.length]; minLevels = new int[this.activeMaterials.length]; maxLevels = new int[this.activeMaterials.length]; chances = new float[this.activeMaterials.length][16]; for (int i = 0; i < this.activeMaterials.length; i++) { noiseGenerators[i] = new PerlinNoise(0); seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]); minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]); maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]); chances[i] = new float[16]; for (int j = 0; j < 16; j++) { chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f)); } } } } @Override public void render(Dimension dimension, Tile tile, Chunk chunk, Platform platform) { ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings(); if (settings == null) { settings = defaultSettings(platform, dimension.getDim(), dimension.getMaxHeight()); setSettings(settings); } final int minimumLevel = settings.getMinimumLevel(); final int xOffset = (chunk.getxPos() & 7) << 4; final int zOffset = (chunk.getzPos() & 7) << 4; final long seed = dimension.getSeed(); final int minY = dimension.getMinHeight(), maxY = dimension.getMaxHeight() - 1; final boolean coverSteepTerrain = dimension.isCoverSteepTerrain(), nether = (dimension.getDim() == DIM_NETHER); if ((currentSeed == 0) || (currentSeed != seed)) { for (int i = 0; i < activeMaterials.length; i++) { if (noiseGenerators[i].getSeed() != (seed + seedOffsets[i])) { noiseGenerators[i].setSeed(seed + seedOffsets[i]); } } currentSeed = seed; } // int[] counts = new int[256]; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { final int localX = xOffset + x, localY = zOffset + z; final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY; if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) { continue; } final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY)); if (resourcesValue > 0) { final int terrainheight = tile.getIntHeight(localX, localY); final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight); int subsurfaceMaxHeight = terrainheight - topLayerDepth; if (coverSteepTerrain) { subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight, Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE), dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)), Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE), dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE)))); } final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS; final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS; // Capping to maxY really shouldn't be necessary, but we've // had several reports from the wild of this going higher // than maxHeight, so there must be some obscure way in // which the terrainHeight can be raised too high for (int y = Math.min(subsurfaceMaxHeight, maxY); y > minY; y--) { final double dz = y / TINY_BLOBS; final double dirtZ = y / SMALL_BLOBS; for (int i = 0; i < activeMaterials.length; i++) { final float chance = chances[i][resourcesValue]; if ((chance <= 0.5f) && (y >= minLevels[i]) && (y <= maxLevels[i]) && (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL) ? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance) : (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) { // counts[oreType]++; final Material existingMaterial = chunk.getMaterial(x, y, z); if (existingMaterial.isNamed(MC_DEEPSLATE) && ORE_TO_DEEPSLATE_VARIANT.containsKey(activeMaterials[i].name)) { chunk.setMaterial(x, y, z, ORE_TO_DEEPSLATE_VARIANT.get(activeMaterials[i].name)); } else if (nether && (activeMaterials[i].isNamed(MC_GOLD_ORE))) { chunk.setMaterial(x, y, z, NETHER_GOLD_ORE); } else { chunk.setMaterial(x, y, z, activeMaterials[i]); } break; } } } } } } // System.out.println("Tile " + tile.getX() + "," + tile.getY()); // for (i = 0; i < 256; i++) { // if (counts[i] > 0) { // System.out.printf("Exported %6d of ore type %3d%n", counts[i], i); // } // } // System.out.println(); } // TODO: resource frequenties onderzoeken met Statistics tool! private Material[] activeMaterials; private PerlinNoise[] noiseGenerators; private long[] seedOffsets; private int[] minLevels, maxLevels; private float[][] chances; private long currentSeed; private static final Map<String, Material> ORE_TO_DEEPSLATE_VARIANT = ImmutableMap.of( MC_COAL_ORE, DEEPSLATE_COAL_ORE, MC_COPPER_ORE, DEEPSLATE_COPPER_ORE, MC_LAPIS_ORE, DEEPSLATE_LAPIS_ORE, MC_IRON_ORE, DEEPSLATE_IRON_ORE, MC_GOLD_ORE, DEEPSLATE_GOLD_ORE, MC_REDSTONE_ORE, DEEPSLATE_REDSTONE_ORE, MC_DIAMOND_ORE, DEEPSLATE_DIAMOND_ORE, MC_EMERALD_ORE, DEEPSLATE_EMERALD_ORE ); public static class ResourcesExporterSettings implements ExporterSettings { private ResourcesExporterSettings(Map<Material, ResourceSettings> settings) { this.settings = settings; } @Override public boolean isApplyEverywhere() { return minimumLevel > 0; } public int getMinimumLevel() { return minimumLevel; } public void setMinimumLevel(int minimumLevel) { this.minimumLevel = minimumLevel; } public Set<Material> getMaterials() { return settings.keySet(); } public int getMinLevel(Material material) { return settings.get(material).minLevel; } public void setMinLevel(Material material, int minLevel) { settings.get(material).minLevel = minLevel; } public int getMaxLevel(Material material) { return settings.get(material).maxLevel; } public void setMaxLevel(Material material, int maxLevel) { settings.get(material).maxLevel = maxLevel; } public int getChance(Material material) { return settings.get(material).chance; } public void setChance(Material material, int chance) { settings.get(material).chance = chance; } public long getSeedOffset(Material material) { return settings.get(material).seedOffset; } @Override public Resources getLayer() { return Resources.INSTANCE; } @Override public ResourcesExporterSettings clone() { try { ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone(); clone.settings = new LinkedHashMap<>(); settings.forEach((material, settings) -> clone.settings.put(material, settings.clone())); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static ResourcesExporterSettings defaultSettings(Platform platform, int dim, int maxHeight) { final Random random = new Random(); final Map<Material, ResourceSettings> settings = new HashMap<>(); switch (dim) { case DIM_NORMAL: // TODO make these normal distributions or something else more similar to Minecraft settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 57, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 28, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, 31, 1, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 6, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 10, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 1, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 1, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 8, random.nextLong())); settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 1, random.nextLong())); settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 2, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, (platform != JAVA_MCREGION) ? 1 : 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, ((platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ? 6 : 0, random.nextLong())); settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, 0, random.nextLong())); break; case DIM_NETHER: settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, (platform != JAVA_MCREGION) ? 7 : 0, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, maxHeight - 1, ((platform == JAVA_ANVIL_1_15) || (platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ? 3 : 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, ((platform == JAVA_ANVIL_1_15) || (platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ? 1 : 0, random.nextLong())); settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 0, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 0, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 0, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 0, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 0, random.nextLong())); settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 0, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); break; case DIM_END: settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 0, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, 31, 0, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 0, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 0, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 0, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 0, random.nextLong())); settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 0, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, 0, random.nextLong())); break; default: throw new IllegalArgumentException("Dimension " + dim + " not supported"); } return new ResourcesExporterSettings(settings); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (version < 1) { // Legacy conversions // Fix static water and lava if (! maxLevels.containsKey(BLK_WATER)) { logger.warn("Fixing water and lava settings"); maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER)); chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER)); seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER)); maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA)); chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA)); seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA)); maxLevels.remove(BLK_STATIONARY_WATER); chances.remove(BLK_STATIONARY_WATER); seedOffsets.remove(BLK_STATIONARY_WATER); maxLevels.remove(BLK_STATIONARY_LAVA); chances.remove(BLK_STATIONARY_LAVA); seedOffsets.remove(BLK_STATIONARY_LAVA); } if (! maxLevels.containsKey(BLK_EMERALD_ORE)) { maxLevels.put(BLK_EMERALD_ORE, 31); chances.put(BLK_EMERALD_ORE, 0); } Random random = new Random(); if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) { seedOffsets.put(BLK_EMERALD_ORE, random.nextLong()); } if (minLevels == null) { minLevels = new HashMap<>(); for (int blockType: maxLevels.keySet()) { minLevels.put(blockType, 0); } } if (! minLevels.containsKey(BLK_QUARTZ_ORE)) { minLevels.put(BLK_QUARTZ_ORE, 0); maxLevels.put(BLK_QUARTZ_ORE, 255); chances.put(BLK_QUARTZ_ORE, 0); seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong()); } // Convert integer-based settings to material-based settings settings = new LinkedHashMap<>(); for (int blockType: maxLevels.keySet()) { Material material = get(blockType); settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType), chances.get(blockType), seedOffsets.get(blockType))); } minLevels = null; maxLevels = null; chances = null; seedOffsets = null; } if (version < 2) { // Add new resources final Random random = new Random(); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, -64, 319, 0, random.nextLong())); } version = 2; // Not sure how, but the liquids are reverting to the stationary // variants (something to do with the Minecraft 1.14 migration?). // Just keep changing them back if (settings.containsKey(STATIONARY_WATER)) { settings.put(WATER, settings.get(STATIONARY_WATER)); settings.remove(STATIONARY_WATER); } if (settings.containsKey(STATIONARY_LAVA)) { settings.put(LAVA, settings.get(STATIONARY_LAVA)); settings.remove(STATIONARY_LAVA); } } private int minimumLevel = 8; private Map<Material, ResourceSettings> settings = new LinkedHashMap<>(); /** @deprecated */ private Map<Integer, Integer> maxLevels = null; /** @deprecated */ private Map<Integer, Integer> chances = null; /** @deprecated */ private Map<Integer, Long> seedOffsets = null; /** @deprecated */ private Map<Integer, Integer> minLevels = null; private int version = 1; private static final long serialVersionUID = 1L; private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class); } static class ResourceSettings implements Serializable, Cloneable { ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) { this.material = material; this.minLevel = minLevel; this.maxLevel = maxLevel; this.chance = chance; this.seedOffset = seedOffset; } @Override public ResourceSettings clone() { try { return (ResourceSettings) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e); } } Material material; int minLevel, maxLevel, chance; long seedOffset; private static final long serialVersionUID = 1L; } }
Malfrador/WorldPainter
WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/exporters/ResourcesExporter.java
5,934
/** * * @author pepijn */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.worldpainter.layers.exporters; import com.google.common.collect.ImmutableMap; import org.pepsoft.minecraft.Chunk; import org.pepsoft.minecraft.Material; import org.pepsoft.util.PerlinNoise; import org.pepsoft.worldpainter.Dimension; import org.pepsoft.worldpainter.Platform; import org.pepsoft.worldpainter.Tile; import org.pepsoft.worldpainter.exporting.AbstractLayerExporter; import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter; import org.pepsoft.worldpainter.layers.Resources; import org.pepsoft.worldpainter.layers.Void; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.*; import static org.pepsoft.minecraft.Constants.*; import static org.pepsoft.minecraft.Material.*; import static org.pepsoft.worldpainter.Constants.*; import static org.pepsoft.worldpainter.DefaultPlugin.*; import static org.pepsoft.worldpainter.layers.exporters.ResourcesExporter.ResourcesExporterSettings.defaultSettings; /** * * @author pepijn <SUF>*/ public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter { public ResourcesExporter() { super(Resources.INSTANCE); } @Override public void setSettings(ExporterSettings settings) { super.setSettings(settings); ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings(); if (resourcesSettings != null) { Set<Material> allMaterials = resourcesSettings.getMaterials(); List<Material> activeMaterials = new ArrayList<>(allMaterials.size()); for (Material material: allMaterials) { if (resourcesSettings.getChance(material) > 0) { activeMaterials.add(material); } } this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]); noiseGenerators = new PerlinNoise[this.activeMaterials.length]; seedOffsets = new long[this.activeMaterials.length]; minLevels = new int[this.activeMaterials.length]; maxLevels = new int[this.activeMaterials.length]; chances = new float[this.activeMaterials.length][16]; for (int i = 0; i < this.activeMaterials.length; i++) { noiseGenerators[i] = new PerlinNoise(0); seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]); minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]); maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]); chances[i] = new float[16]; for (int j = 0; j < 16; j++) { chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f)); } } } } @Override public void render(Dimension dimension, Tile tile, Chunk chunk, Platform platform) { ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings(); if (settings == null) { settings = defaultSettings(platform, dimension.getDim(), dimension.getMaxHeight()); setSettings(settings); } final int minimumLevel = settings.getMinimumLevel(); final int xOffset = (chunk.getxPos() & 7) << 4; final int zOffset = (chunk.getzPos() & 7) << 4; final long seed = dimension.getSeed(); final int minY = dimension.getMinHeight(), maxY = dimension.getMaxHeight() - 1; final boolean coverSteepTerrain = dimension.isCoverSteepTerrain(), nether = (dimension.getDim() == DIM_NETHER); if ((currentSeed == 0) || (currentSeed != seed)) { for (int i = 0; i < activeMaterials.length; i++) { if (noiseGenerators[i].getSeed() != (seed + seedOffsets[i])) { noiseGenerators[i].setSeed(seed + seedOffsets[i]); } } currentSeed = seed; } // int[] counts = new int[256]; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { final int localX = xOffset + x, localY = zOffset + z; final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY; if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) { continue; } final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY)); if (resourcesValue > 0) { final int terrainheight = tile.getIntHeight(localX, localY); final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight); int subsurfaceMaxHeight = terrainheight - topLayerDepth; if (coverSteepTerrain) { subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight, Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE), dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)), Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE), dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE)))); } final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS; final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS; // Capping to maxY really shouldn't be necessary, but we've // had several reports from the wild of this going higher // than maxHeight, so there must be some obscure way in // which the terrainHeight can be raised too high for (int y = Math.min(subsurfaceMaxHeight, maxY); y > minY; y--) { final double dz = y / TINY_BLOBS; final double dirtZ = y / SMALL_BLOBS; for (int i = 0; i < activeMaterials.length; i++) { final float chance = chances[i][resourcesValue]; if ((chance <= 0.5f) && (y >= minLevels[i]) && (y <= maxLevels[i]) && (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL) ? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance) : (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) { // counts[oreType]++; final Material existingMaterial = chunk.getMaterial(x, y, z); if (existingMaterial.isNamed(MC_DEEPSLATE) && ORE_TO_DEEPSLATE_VARIANT.containsKey(activeMaterials[i].name)) { chunk.setMaterial(x, y, z, ORE_TO_DEEPSLATE_VARIANT.get(activeMaterials[i].name)); } else if (nether && (activeMaterials[i].isNamed(MC_GOLD_ORE))) { chunk.setMaterial(x, y, z, NETHER_GOLD_ORE); } else { chunk.setMaterial(x, y, z, activeMaterials[i]); } break; } } } } } } // System.out.println("Tile " + tile.getX() + "," + tile.getY()); // for (i = 0; i < 256; i++) { // if (counts[i] > 0) { // System.out.printf("Exported %6d of ore type %3d%n", counts[i], i); // } // } // System.out.println(); } // TODO: resource frequenties onderzoeken met Statistics tool! private Material[] activeMaterials; private PerlinNoise[] noiseGenerators; private long[] seedOffsets; private int[] minLevels, maxLevels; private float[][] chances; private long currentSeed; private static final Map<String, Material> ORE_TO_DEEPSLATE_VARIANT = ImmutableMap.of( MC_COAL_ORE, DEEPSLATE_COAL_ORE, MC_COPPER_ORE, DEEPSLATE_COPPER_ORE, MC_LAPIS_ORE, DEEPSLATE_LAPIS_ORE, MC_IRON_ORE, DEEPSLATE_IRON_ORE, MC_GOLD_ORE, DEEPSLATE_GOLD_ORE, MC_REDSTONE_ORE, DEEPSLATE_REDSTONE_ORE, MC_DIAMOND_ORE, DEEPSLATE_DIAMOND_ORE, MC_EMERALD_ORE, DEEPSLATE_EMERALD_ORE ); public static class ResourcesExporterSettings implements ExporterSettings { private ResourcesExporterSettings(Map<Material, ResourceSettings> settings) { this.settings = settings; } @Override public boolean isApplyEverywhere() { return minimumLevel > 0; } public int getMinimumLevel() { return minimumLevel; } public void setMinimumLevel(int minimumLevel) { this.minimumLevel = minimumLevel; } public Set<Material> getMaterials() { return settings.keySet(); } public int getMinLevel(Material material) { return settings.get(material).minLevel; } public void setMinLevel(Material material, int minLevel) { settings.get(material).minLevel = minLevel; } public int getMaxLevel(Material material) { return settings.get(material).maxLevel; } public void setMaxLevel(Material material, int maxLevel) { settings.get(material).maxLevel = maxLevel; } public int getChance(Material material) { return settings.get(material).chance; } public void setChance(Material material, int chance) { settings.get(material).chance = chance; } public long getSeedOffset(Material material) { return settings.get(material).seedOffset; } @Override public Resources getLayer() { return Resources.INSTANCE; } @Override public ResourcesExporterSettings clone() { try { ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone(); clone.settings = new LinkedHashMap<>(); settings.forEach((material, settings) -> clone.settings.put(material, settings.clone())); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static ResourcesExporterSettings defaultSettings(Platform platform, int dim, int maxHeight) { final Random random = new Random(); final Map<Material, ResourceSettings> settings = new HashMap<>(); switch (dim) { case DIM_NORMAL: // TODO make these normal distributions or something else more similar to Minecraft settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 57, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 28, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, 31, 1, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 6, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 10, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 1, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 1, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 8, random.nextLong())); settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 1, random.nextLong())); settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 2, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, (platform != JAVA_MCREGION) ? 1 : 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, ((platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ? 6 : 0, random.nextLong())); settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, 0, random.nextLong())); break; case DIM_NETHER: settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, (platform != JAVA_MCREGION) ? 7 : 0, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, maxHeight - 1, ((platform == JAVA_ANVIL_1_15) || (platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ? 3 : 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, ((platform == JAVA_ANVIL_1_15) || (platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ? 1 : 0, random.nextLong())); settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 0, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 0, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 0, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 0, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 0, random.nextLong())); settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 0, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); break; case DIM_END: settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 0, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, 31, 0, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 0, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 0, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 0, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 0, random.nextLong())); settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 0, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, 0, random.nextLong())); break; default: throw new IllegalArgumentException("Dimension " + dim + " not supported"); } return new ResourcesExporterSettings(settings); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (version < 1) { // Legacy conversions // Fix static water and lava if (! maxLevels.containsKey(BLK_WATER)) { logger.warn("Fixing water and lava settings"); maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER)); chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER)); seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER)); maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA)); chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA)); seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA)); maxLevels.remove(BLK_STATIONARY_WATER); chances.remove(BLK_STATIONARY_WATER); seedOffsets.remove(BLK_STATIONARY_WATER); maxLevels.remove(BLK_STATIONARY_LAVA); chances.remove(BLK_STATIONARY_LAVA); seedOffsets.remove(BLK_STATIONARY_LAVA); } if (! maxLevels.containsKey(BLK_EMERALD_ORE)) { maxLevels.put(BLK_EMERALD_ORE, 31); chances.put(BLK_EMERALD_ORE, 0); } Random random = new Random(); if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) { seedOffsets.put(BLK_EMERALD_ORE, random.nextLong()); } if (minLevels == null) { minLevels = new HashMap<>(); for (int blockType: maxLevels.keySet()) { minLevels.put(blockType, 0); } } if (! minLevels.containsKey(BLK_QUARTZ_ORE)) { minLevels.put(BLK_QUARTZ_ORE, 0); maxLevels.put(BLK_QUARTZ_ORE, 255); chances.put(BLK_QUARTZ_ORE, 0); seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong()); } // Convert integer-based settings to material-based settings settings = new LinkedHashMap<>(); for (int blockType: maxLevels.keySet()) { Material material = get(blockType); settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType), chances.get(blockType), seedOffsets.get(blockType))); } minLevels = null; maxLevels = null; chances = null; seedOffsets = null; } if (version < 2) { // Add new resources final Random random = new Random(); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, -64, 319, 0, random.nextLong())); } version = 2; // Not sure how, but the liquids are reverting to the stationary // variants (something to do with the Minecraft 1.14 migration?). // Just keep changing them back if (settings.containsKey(STATIONARY_WATER)) { settings.put(WATER, settings.get(STATIONARY_WATER)); settings.remove(STATIONARY_WATER); } if (settings.containsKey(STATIONARY_LAVA)) { settings.put(LAVA, settings.get(STATIONARY_LAVA)); settings.remove(STATIONARY_LAVA); } } private int minimumLevel = 8; private Map<Material, ResourceSettings> settings = new LinkedHashMap<>(); /** @deprecated */ private Map<Integer, Integer> maxLevels = null; /** @deprecated */ private Map<Integer, Integer> chances = null; /** @deprecated */ private Map<Integer, Long> seedOffsets = null; /** @deprecated */ private Map<Integer, Integer> minLevels = null; private int version = 1; private static final long serialVersionUID = 1L; private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class); } static class ResourceSettings implements Serializable, Cloneable { ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) { this.material = material; this.minLevel = minLevel; this.maxLevel = maxLevel; this.chance = chance; this.seedOffset = seedOffset; } @Override public ResourceSettings clone() { try { return (ResourceSettings) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e); } } Material material; int minLevel, maxLevel, chance; long seedOffset; private static final long serialVersionUID = 1L; } }
75974_3
package byps.http; import java.util.concurrent.atomic.AtomicLong; /* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import byps.BAsyncResult; import byps.BException; import byps.BExceptionC; import byps.BMessage; import byps.BMessageHeader; import byps.BOutput; import byps.BServer; import byps.BServerR; import byps.BTransport; /** * LongPoll-Nachricht: * */ public class HServerR extends BServerR { protected static final AtomicLong requstCounter = new AtomicLong(); public HServerR(BTransport transport, BServer server, int nbOfConns) { super(transport, server); this.nbOfConns = nbOfConns; this.sleepMillisBeforeRetry = 30 * 1000; } @Override public void start() throws BException { if (log.isDebugEnabled()) log.debug("start("); synchronized (refDone) { refDone[0] = false; } for (int i = 0; i < nbOfConns; i++) { sendLongPoll(null); } if (log.isDebugEnabled()) log.debug(")start"); } @Override public void done() { if (log.isDebugEnabled()) log.debug("done("); synchronized (refDone) { refDone[0] = true; refDone.notifyAll(); } // Wird von HWireClient.done() aufgerufen. // Dort werden die Long-Polls vom Server beendet. // workerThread.interrupt(); // // try { // workerThread.join(1000); // } // catch (InterruptedException ignored) {} if (log.isDebugEnabled()) log.debug(")done"); } protected class LongPoll implements Runnable { protected BMessage methodResult; protected LongPoll(BMessage methodResult) throws BException { if (log.isDebugEnabled()) log.debug("LongPoll(" + methodResult); final long requestId = HServerR.requstCounter.incrementAndGet(); if (methodResult != null) { this.methodResult = methodResult; } else { BOutput outp = transport.getOutput(); outp.header.flags |= BMessageHeader.FLAG_RESPONSE; outp.store(null); // irgendwas, damit auch der Header in den ByteBuffer // geschrieben wird. this.methodResult = outp.toMessage(requestId); } if (log.isDebugEnabled()) log.debug(")LongPoll"); } public void run() { if (log.isDebugEnabled()) log.debug("run("); final long startTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId()); final BAsyncResult<BMessage> asyncResult = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("setAsyncResult(" + msg); final long requestId = HServerR.requstCounter.incrementAndGet(); try { if (e != null) { BOutput out = transport.getOutput(); out.header.flags = BMessageHeader.FLAG_RESPONSE; out.setException(e); msg = out.toMessage(requestId); } sendLongPoll(msg); } catch (BException e1) { if (log.isErrorEnabled()) log.error("Failed to send longpoll for obj=" + msg, e1); } if (log.isDebugEnabled()) log.debug(")setAsyncResult"); } }; BAsyncResult<BMessage> nextAsyncMethod = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("asyncMethod.setAsyncResult(" + msg + ", e=" + e); try { long endTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId() + "[" + (endTime-startTime) + "]"); if (e == null) { // Execute the method received from server. transport.recv(server, msg, asyncResult); } else { BException ex = (BException) e; switch (ex.code) { case BExceptionC.SESSION_CLOSED: // Session was invalidated. log.info("Reverse request stops due to closed session."); break; case BExceptionC.UNAUTHORIZED: // Re-login required log.info("Reverse request was unauthorized."); break; case BExceptionC.CANCELLED: log.info("Reverse request was cancelled."); // no retry break; case BExceptionC.RESEND_LONG_POLL: log.info("Reverse request refreshs long-poll."); // HWireClientR has released the expried long-poll. // Ignore the error and send a new long-poll. asyncResult.setAsyncResult(null, null); break; default: onLostConnection(ex); break; } } } catch (Throwable ex) { // transport.recv failed if (log.isDebugEnabled()) log.debug("recv failed.", e); asyncResult.setAsyncResult(null, ex); } if (log.isDebugEnabled()) log.debug(")asyncMethod.setAsyncResult"); } private void onLostConnection(BException ex) { boolean callLostConnectionHandler = false; synchronized (refDone) { // Server still running? if (!refDone[0]) { try { if (lostConnectionHandler != null) { callLostConnectionHandler = true; } else { // Wait some seconds before next retry refDone.wait(sleepMillisBeforeRetry); } } catch (InterruptedException e1) { } } } if (callLostConnectionHandler) { log.info("Reverse request lost connection due to " + ex + ", call handler for lost connection."); lostConnectionHandler.onLostConnection(ex); } else { log.info("Reverse request refreshs long-poll after due to " + ex); asyncResult.setAsyncResult(null, null); } } }; // Sende den longPoll-Request // Im Body befindet sich die Antwort auf die vorige vom Server gestellte // Anfrage. // Als Ergebnis des longPoll kommt eine neue Serveranfrage (Methode). transport.getWire().sendR(methodResult, nextAsyncMethod); if (log.isDebugEnabled()) log.debug(")run"); } } protected void sendLongPoll(BMessage obj) throws BException { if (log.isDebugEnabled()) log.debug("sendLongPollInWorkerThread(" + obj); synchronized (refDone) { if (!refDone[0]) { LongPoll lp = new LongPoll(obj); lp.run(); } } // synchronized(this) { // if (log.isDebugEnabled()) log.debug("execute in worker thread"); // currentLongPoll_access_sync = lp; // this.notifyAll(); // } if (log.isDebugEnabled()) log.debug(")sendLongPollInWorkerThread"); } // protected class WorkerThread extends Thread { // WorkerThread() { // setName("longpoll-" + c_longPollCounter.incrementAndGet()); // } // // public void run() { // if (log.isDebugEnabled()) log.debug("LongPoll.run("); // try { // while (!isInterrupted()) { // LongPoll lp = null; // synchronized(HServerR.this) { // while (currentLongPoll_access_sync == null) { // if (log.isDebugEnabled()) log.debug("wait for LongPoll"); // HServerR.this.wait(); // } // lp = currentLongPoll_access_sync; // currentLongPoll_access_sync = null; // } // // try { // if (log.isDebugEnabled()) log.debug("execute LongPoll"); // lp.run(); // } // catch (Throwable e) { // log.error("LongPoll worker thread received uncaught exception.", e); // } // } // if (log.isDebugEnabled()) log.debug("Worker interrupted"); // } // catch (InterruptedException e) { // if (log.isDebugEnabled()) log.debug("Recevied "+ e); // } // if (log.isDebugEnabled()) log.debug(")LongPoll.run"); // } // } protected int nbOfConns; protected boolean[] refDone = new boolean[1]; protected final long sleepMillisBeforeRetry; // protected final Thread workerThread = new WorkerThread(); // protected LongPoll currentLongPoll_access_sync; private final static Logger log = LoggerFactory.getLogger(HServerR.class); }
wolfgangimig/byps
java/bypshttp/src/byps/http/HServerR.java
2,265
// Dort werden die Long-Polls vom Server beendet.
line_comment
nl
package byps.http; import java.util.concurrent.atomic.AtomicLong; /* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import byps.BAsyncResult; import byps.BException; import byps.BExceptionC; import byps.BMessage; import byps.BMessageHeader; import byps.BOutput; import byps.BServer; import byps.BServerR; import byps.BTransport; /** * LongPoll-Nachricht: * */ public class HServerR extends BServerR { protected static final AtomicLong requstCounter = new AtomicLong(); public HServerR(BTransport transport, BServer server, int nbOfConns) { super(transport, server); this.nbOfConns = nbOfConns; this.sleepMillisBeforeRetry = 30 * 1000; } @Override public void start() throws BException { if (log.isDebugEnabled()) log.debug("start("); synchronized (refDone) { refDone[0] = false; } for (int i = 0; i < nbOfConns; i++) { sendLongPoll(null); } if (log.isDebugEnabled()) log.debug(")start"); } @Override public void done() { if (log.isDebugEnabled()) log.debug("done("); synchronized (refDone) { refDone[0] = true; refDone.notifyAll(); } // Wird von HWireClient.done() aufgerufen. // Dort werden<SUF> // workerThread.interrupt(); // // try { // workerThread.join(1000); // } // catch (InterruptedException ignored) {} if (log.isDebugEnabled()) log.debug(")done"); } protected class LongPoll implements Runnable { protected BMessage methodResult; protected LongPoll(BMessage methodResult) throws BException { if (log.isDebugEnabled()) log.debug("LongPoll(" + methodResult); final long requestId = HServerR.requstCounter.incrementAndGet(); if (methodResult != null) { this.methodResult = methodResult; } else { BOutput outp = transport.getOutput(); outp.header.flags |= BMessageHeader.FLAG_RESPONSE; outp.store(null); // irgendwas, damit auch der Header in den ByteBuffer // geschrieben wird. this.methodResult = outp.toMessage(requestId); } if (log.isDebugEnabled()) log.debug(")LongPoll"); } public void run() { if (log.isDebugEnabled()) log.debug("run("); final long startTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId()); final BAsyncResult<BMessage> asyncResult = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("setAsyncResult(" + msg); final long requestId = HServerR.requstCounter.incrementAndGet(); try { if (e != null) { BOutput out = transport.getOutput(); out.header.flags = BMessageHeader.FLAG_RESPONSE; out.setException(e); msg = out.toMessage(requestId); } sendLongPoll(msg); } catch (BException e1) { if (log.isErrorEnabled()) log.error("Failed to send longpoll for obj=" + msg, e1); } if (log.isDebugEnabled()) log.debug(")setAsyncResult"); } }; BAsyncResult<BMessage> nextAsyncMethod = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("asyncMethod.setAsyncResult(" + msg + ", e=" + e); try { long endTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId() + "[" + (endTime-startTime) + "]"); if (e == null) { // Execute the method received from server. transport.recv(server, msg, asyncResult); } else { BException ex = (BException) e; switch (ex.code) { case BExceptionC.SESSION_CLOSED: // Session was invalidated. log.info("Reverse request stops due to closed session."); break; case BExceptionC.UNAUTHORIZED: // Re-login required log.info("Reverse request was unauthorized."); break; case BExceptionC.CANCELLED: log.info("Reverse request was cancelled."); // no retry break; case BExceptionC.RESEND_LONG_POLL: log.info("Reverse request refreshs long-poll."); // HWireClientR has released the expried long-poll. // Ignore the error and send a new long-poll. asyncResult.setAsyncResult(null, null); break; default: onLostConnection(ex); break; } } } catch (Throwable ex) { // transport.recv failed if (log.isDebugEnabled()) log.debug("recv failed.", e); asyncResult.setAsyncResult(null, ex); } if (log.isDebugEnabled()) log.debug(")asyncMethod.setAsyncResult"); } private void onLostConnection(BException ex) { boolean callLostConnectionHandler = false; synchronized (refDone) { // Server still running? if (!refDone[0]) { try { if (lostConnectionHandler != null) { callLostConnectionHandler = true; } else { // Wait some seconds before next retry refDone.wait(sleepMillisBeforeRetry); } } catch (InterruptedException e1) { } } } if (callLostConnectionHandler) { log.info("Reverse request lost connection due to " + ex + ", call handler for lost connection."); lostConnectionHandler.onLostConnection(ex); } else { log.info("Reverse request refreshs long-poll after due to " + ex); asyncResult.setAsyncResult(null, null); } } }; // Sende den longPoll-Request // Im Body befindet sich die Antwort auf die vorige vom Server gestellte // Anfrage. // Als Ergebnis des longPoll kommt eine neue Serveranfrage (Methode). transport.getWire().sendR(methodResult, nextAsyncMethod); if (log.isDebugEnabled()) log.debug(")run"); } } protected void sendLongPoll(BMessage obj) throws BException { if (log.isDebugEnabled()) log.debug("sendLongPollInWorkerThread(" + obj); synchronized (refDone) { if (!refDone[0]) { LongPoll lp = new LongPoll(obj); lp.run(); } } // synchronized(this) { // if (log.isDebugEnabled()) log.debug("execute in worker thread"); // currentLongPoll_access_sync = lp; // this.notifyAll(); // } if (log.isDebugEnabled()) log.debug(")sendLongPollInWorkerThread"); } // protected class WorkerThread extends Thread { // WorkerThread() { // setName("longpoll-" + c_longPollCounter.incrementAndGet()); // } // // public void run() { // if (log.isDebugEnabled()) log.debug("LongPoll.run("); // try { // while (!isInterrupted()) { // LongPoll lp = null; // synchronized(HServerR.this) { // while (currentLongPoll_access_sync == null) { // if (log.isDebugEnabled()) log.debug("wait for LongPoll"); // HServerR.this.wait(); // } // lp = currentLongPoll_access_sync; // currentLongPoll_access_sync = null; // } // // try { // if (log.isDebugEnabled()) log.debug("execute LongPoll"); // lp.run(); // } // catch (Throwable e) { // log.error("LongPoll worker thread received uncaught exception.", e); // } // } // if (log.isDebugEnabled()) log.debug("Worker interrupted"); // } // catch (InterruptedException e) { // if (log.isDebugEnabled()) log.debug("Recevied "+ e); // } // if (log.isDebugEnabled()) log.debug(")LongPoll.run"); // } // } protected int nbOfConns; protected boolean[] refDone = new boolean[1]; protected final long sleepMillisBeforeRetry; // protected final Thread workerThread = new WorkerThread(); // protected LongPoll currentLongPoll_access_sync; private final static Logger log = LoggerFactory.getLogger(HServerR.class); }
80499_2
/* * P2Tools Copyright (C) 2023 W. Xaver W.Xaver[at]googlemail.com * https://www.p2tools.de/ * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the * License, or any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If * not, see <http://www.gnu.org/licenses/>. */ package de.p2tools.p2lib.tools.log; import de.p2tools.p2lib.P2LibConst; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.ArrayList; /** * diese Meldungen können in einem Tab "Meldungen" angesehen werden * und sind für die User gedacht (werden aber auch im PLog eingetragen) */ public class P2UserMessage { public static ObservableList<String> msgList = FXCollections.observableArrayList(); private static final int MAX_SIZE_1 = 50000; private static final int MAX_SIZE_2 = 30000; private static int lineNo = 0; static synchronized void userMsg(ArrayList<String> text) { message(text.toArray(new String[]{})); } static synchronized void userMsg(String[] text) { message(text); } static synchronized void userMsg(String text) { message(new String[]{text}); } private static void message(String[] text) { if (text.length <= 1) { notify(text[0]); } else { String line = "---------------------------------------- "; notify(line); for (int i = 0; i < text.length; ++i) { if (i == 0) { notify(text[i]); } else { notify(" " + text[i]); } } notify(" "); } } public static void clearText() { lineNo = 0; msgList.clear(); } private static void notify(String line) { addText(msgList, "[" + getNr(lineNo++) + "] " + line); } private static String getNr(int no) { final int MAX_STELLEN = 5; final String FUELL_ZEICHEN = "0"; String str = String.valueOf(no); while (str.length() < MAX_STELLEN) { str = FUELL_ZEICHEN + str; } return str; } private synchronized static void addText(ObservableList<String> text, String texte) { if (text.size() > MAX_SIZE_1) { text.remove(0, MAX_SIZE_2); } text.add(texte + P2LibConst.LINE_SEPARATOR); } public synchronized static String getText() { // wegen synchronized hier return String.join("", msgList); } }
xaverW/P2Lib
src/main/java/de/p2tools/p2lib/tools/log/P2UserMessage.java
815
// wegen synchronized hier
line_comment
nl
/* * P2Tools Copyright (C) 2023 W. Xaver W.Xaver[at]googlemail.com * https://www.p2tools.de/ * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the * License, or any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If * not, see <http://www.gnu.org/licenses/>. */ package de.p2tools.p2lib.tools.log; import de.p2tools.p2lib.P2LibConst; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.ArrayList; /** * diese Meldungen können in einem Tab "Meldungen" angesehen werden * und sind für die User gedacht (werden aber auch im PLog eingetragen) */ public class P2UserMessage { public static ObservableList<String> msgList = FXCollections.observableArrayList(); private static final int MAX_SIZE_1 = 50000; private static final int MAX_SIZE_2 = 30000; private static int lineNo = 0; static synchronized void userMsg(ArrayList<String> text) { message(text.toArray(new String[]{})); } static synchronized void userMsg(String[] text) { message(text); } static synchronized void userMsg(String text) { message(new String[]{text}); } private static void message(String[] text) { if (text.length <= 1) { notify(text[0]); } else { String line = "---------------------------------------- "; notify(line); for (int i = 0; i < text.length; ++i) { if (i == 0) { notify(text[i]); } else { notify(" " + text[i]); } } notify(" "); } } public static void clearText() { lineNo = 0; msgList.clear(); } private static void notify(String line) { addText(msgList, "[" + getNr(lineNo++) + "] " + line); } private static String getNr(int no) { final int MAX_STELLEN = 5; final String FUELL_ZEICHEN = "0"; String str = String.valueOf(no); while (str.length() < MAX_STELLEN) { str = FUELL_ZEICHEN + str; } return str; } private synchronized static void addText(ObservableList<String> text, String texte) { if (text.size() > MAX_SIZE_1) { text.remove(0, MAX_SIZE_2); } text.add(texte + P2LibConst.LINE_SEPARATOR); } public synchronized static String getText() { // wegen synchronized<SUF> return String.join("", msgList); } }
15237_19
package org.ofbiz.widget.model; import java.io.Serializable; 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.Set; import java.util.regex.Pattern; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.cache.UtilCache; import org.ofbiz.base.util.string.FlexibleStringExpander; import org.ofbiz.widget.renderer.WidgetRenderTargetExpr; import org.ofbiz.widget.renderer.WidgetRenderTargetExpr.Token; import org.w3c.dom.Element; /** * SCIPIO: Widget screen section contains-expression - special expression that instructs renderer which sections * contain or don't contain which other sections and elements. * <p> * See widget-screen.xsd "attlist.generic-screen-widget-elem" "contains" attribute for details. * <p> * In targeted rendering, this is used by widget renderer to determine which sections can be skipped entirely (their * full execution including actions, not just output). * <p> * Usually functions in blacklist fashion ("!"), so that by default all sections are said to possibly contain * all others. * <p> * TODO: currently this is unable to consolidate the ^ and % operators, or any other operators * for that matter. attributes and wildcards won't work as expected. * STILL NEED TO IMPLEMENT WidgetRenderTargetExpr NORMALIZATION AND HANDLING * FROM ContainsExpr SO THAT EXCLUDE OPTIMIZATIONS ARE FULLY HONORED. * Currently, only some simple exclusions based on $ and # operators work at all. * <p> * ex: * <pre>{@code * "$MySection1, !$MySection2, !$MySections-*, #MyContainerId, !#myContainerId2, *" * }</pre> */ @SuppressWarnings("serial") public class ContainsExpr implements Serializable { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); private static final UtilCache<String, ContainsExpr> cache = UtilCache.createUtilCache("widget.screen.containsexpr"); // entries are comma-separated private static final Pattern containsExprTokenSplitPat = Pattern.compile("\\s*,\\s*"); // general language public static final char EXCLUDE = '!'; // pre-build expressions public static final ContainsExpr MATCH_ALL = new MatchAllContainsExpr(); public static final ContainsExpr MATCH_NONE = new MatchNoneContainsExpr(); public static final ContainsExpr DEFAULT = MATCH_ALL; static { // SPECIAL: pre-cache the default instances so they'll always be the ones looked up cache.put(MATCH_ALL.getStrExpr(), MATCH_ALL); cache.put(MATCH_NONE.getStrExpr(), MATCH_NONE); //cache.put(DEFAULT.getStrExpr(), DEFAULT); } /* * FIXME: * this whole class needs to be updated to support the Token expressions. * currently the "%" type and bracket attributes won't work properly. * I have not figured out the way to implement the comparison logic. * the current comparison logic is "dumb". */ // NOTE: these follow natural specificity private final String strExpr; private final Set<String> exactIncludes; private final Set<String> exactExcludes; private final List<String> wildIncludes; // TODO: find way to optimize private final List<String> wildExcludes; // TODO: find way to optimize private final Map<Character, Boolean> matchAllTypes; private final boolean matchAll; public ContainsExpr(String strExpr) throws IllegalArgumentException { this(strExpr, null); } public ContainsExpr(String strExpr, Element widgetElement) throws IllegalArgumentException { this.strExpr = strExpr; String[] tokenArr = containsExprTokenSplitPat.split(strExpr.trim()); if (tokenArr.length <= 0) throw new IllegalArgumentException(makeErrorMsg("no names in expression", null, strExpr, widgetElement)); // NOTE: these are layered by specificity from most exact to most generic Set<String> exactIncludes = new HashSet<>(); Set<String> exactExcludes = new HashSet<>(); ArrayList<String> wildIncludes = new ArrayList<>(); ArrayList<String> wildExcludes = new ArrayList<>(); Map<Character, Boolean> matchAllTypes = new HashMap<>(); Boolean matchAll = null; for(String fullToken : tokenArr) { String tokenStr = fullToken; boolean exclude = (tokenStr.charAt(0) == EXCLUDE); if (exclude) tokenStr = tokenStr.substring(1); if (WidgetRenderTargetExpr.WILDCARD_STRING.equals(tokenStr)) { // special case matchAll = !exclude; continue; } else if (tokenStr.isEmpty()) { throw new IllegalArgumentException(makeErrorMsg("invalid or empty name", fullToken, strExpr, widgetElement)); } // OLD - this did not extract the attributes // char type = tokenStr.charAt(0); // if (!WidgetRenderTargetExpr.MET_ALL.contains(type)) // throw new IllegalArgumentException(makeErrorMsg("name has missing" // + " or invalid type specifier (should start with one of: " + WidgetRenderTargetExpr.MET_ALL_STR + ")", fullToken, strExpr, widgetElement)); // String name = tokenStr.substring(1); Token token; try { token = Token.interpret(tokenStr); } catch(Exception e) { throw new IllegalArgumentException(makeErrorMsg(e.getMessage(), fullToken, strExpr, widgetElement)); } String name = token.getName().toString(); char type = token.getType(); String normTokenStr = token.getCmpNormStringExpr(); // FIXME: this does not properly compare supported Tokens // nor does it recognized the bracketed attributes // because we are ditching the Token instances if (name.equals(WidgetRenderTargetExpr.WILDCARD_STRING)) { // FIXME: missing attribute support - we are ditching attributes! if (token.hasAttr()) { Debug.logWarning(makeErrorMsg("token wildcard expression has attributes; attributes not yet supported here; attributes ignored!", fullToken, strExpr, widgetElement), module); } matchAllTypes.put(type, !exclude); } else if (name.contains(WidgetRenderTargetExpr.WILDCARD_STRING)) { if (name.indexOf(WidgetRenderTargetExpr.WILDCARD) != name.lastIndexOf(WidgetRenderTargetExpr.WILDCARD)) { // TODO?: support multiple wildcard throw new UnsupportedOperationException(makeErrorMsg("name has" + " with multiple wildcards, which is not supported", fullToken, strExpr, widgetElement)); } // FIXME: missing attribute support - we are ditching attributes! if (token.hasAttr()) { Debug.logWarning(makeErrorMsg("token wildcard expression has attributes; attributes not yet supported here; attributes ignored!", fullToken, strExpr, widgetElement), module); } if (exclude) { wildExcludes.add(type + name); } else { wildIncludes.add(type + name); } } else { if (token.hasAttr()) { Debug.logWarning(makeErrorMsg("token expression has attributes; not fully supported here; may not work as expected", fullToken, strExpr, widgetElement), module); } // FIXME: we lose Token instance here if (exclude) { exactExcludes.add(normTokenStr); } else { exactIncludes.add(normTokenStr); } } } this.exactIncludes = exactIncludes.isEmpty() ? Collections.<String> emptySet() : exactIncludes; this.exactExcludes = exactExcludes.isEmpty() ? Collections.<String> emptySet() : exactExcludes; wildIncludes.trimToSize(); this.wildIncludes = wildIncludes.isEmpty() ? null : wildIncludes; wildExcludes.trimToSize(); this.wildExcludes = wildExcludes.isEmpty() ? null : wildExcludes; this.matchAllTypes = matchAllTypes.isEmpty() ? null : matchAllTypes; if (matchAll == null) { Debug.logWarning(makeErrorMsg("missing match-all (\"*\") or match-none (\"!*\") wildcard entry;" + " cannot tell if blacklist or whitelist intended", null, strExpr, widgetElement), module); matchAll = ContainsExpr.DEFAULT.matches("dummy"); // stay consistent with the default } this.matchAll = matchAll; } private static String makeErrorMsg(String msg, String token, String strExpr, Element widgetElement) { String str = "Widget element contains=\"...\" expression error: " + msg + ":"; if (token != null) { str += " [name: \"" + token + "\"]"; } if (strExpr != null) { str += " [expression: \"" + strExpr + "\"]"; } if (widgetElement != null) { str += " [" + WidgetDocumentInfo.getElementDescriptor(widgetElement) + "]"; } return str; } /** * Gets instance from CACHE. */ public static ContainsExpr getInstance(String strExpr, Element widgetElement) { if (strExpr == null) return null; if (!strExpr.isEmpty()) { ContainsExpr expr = cache.get(strExpr); if (expr == null) { // no sync needed expr = new ContainsExpr(strExpr, widgetElement); cache.put(strExpr, expr); } return expr; } else return null; } public static ContainsExpr getInstanceOrDefault(String strExpr, Element widgetElement, ContainsExpr defaultValue) { ContainsExpr expr = getInstance(strExpr, widgetElement); return expr != null ? expr : defaultValue; } public static ContainsExpr getInstanceOrDefault(String strExpr, Element widgetElement) { return getInstanceOrDefault(strExpr, widgetElement, DEFAULT); } public static ContainsExpr getInstanceOrDefault(String strExpr) { return getInstanceOrDefault(strExpr, null, DEFAULT); } /** * Always creates new instance. */ public static ContainsExpr makeInstance(String strExpr, Element widgetElement) { if (strExpr == null) return null; if (!strExpr.isEmpty()) return new ContainsExpr(strExpr, widgetElement); else return null; } public static ContainsExpr makeInstanceOrDefault(String strExpr, Element widgetElement, ContainsExpr defaultValue) { ContainsExpr expr = makeInstance(strExpr, widgetElement); return expr != null ? expr : defaultValue; } public static ContainsExpr makeInstanceOrDefault(String strExpr, Element widgetElement) { return makeInstanceOrDefault(strExpr, widgetElement, DEFAULT); } /** * Checks if name expression matches this contains expression. * Name MUST be prefixed by one of the characters defined in * {@link WidgetRenderTargetExpr#MET_ALL}. * NOTE: this specific method ONLY supports an exact name (no wildcards) * and no bracketed attributes and will never support more. */ public boolean matches(String nameExpr) { if (exactIncludes.contains(nameExpr)) return true; else if (exactExcludes.contains(nameExpr)) return false; else return matchesWild(nameExpr); } /** * Returns true if and only if ALL of the names match. * So one false prevents match. * If no names, also returns true. * NOTE: this specific method ONLY supports an exact name (no wildcards) * and no bracketed attributes and will never support more. */ public boolean matchesAllNames(List<String> nameExprList) { for(String nameExpr : nameExprList) { if (!matches(nameExpr)) return false; } return true; } /** * Returns true if and only if ALL of the tokens match. * So one false prevents match. * If no names, also returns true. * <p> * FIXME: currently this is not able to handle wildcard tokens or bracketed attributes. * It will only recognize exact names and may ignore entries altogether (treated as matched). * The comparison logic needed to resolve this is extremely complex. * <p> * TODO: currently this is unable to consolidate the ^ and % operators, or any other operators * for that matter. STILL NEED TO IMPLEMENT WidgetRenderTargetExpr NORMALIZATION AND HANDLING * FROM ContainsExpr SO THAT EXCLUDE OPTIMIZATIONS ARE FULLY HONORED. * Currently, only some simple exclusions based on $ and # operators work at all. */ public boolean matchesAllNameTokens(List<Token> nameTokenList) { // FIXME: this does not properly compare supported Tokens // for now we'll just get the original expression as a string and compare that directly, // BUT we cannot do this for the bracketed attributes for(Token nameExpr : nameTokenList) { if (nameExpr.hasAttr()) { // FIXME: no wildcards for bracketed attributes because current code will mess it up if (!matchesExact(nameExpr.getCmpNormStringExpr())) return false; } else { if (!matches(nameExpr.getCmpNormStringExpr())) return false; } } return true; } private boolean matchesExact(String nameExpr) { if (exactIncludes.contains(nameExpr)) return true; else if (exactExcludes.contains(nameExpr)) return false; else return matchAll; } private boolean matchesWild(String nameExpr) { if (wildIncludes != null) { for(String match : wildIncludes) { if (checkWildNameMatch(match, nameExpr)) { return true; } } } if (wildExcludes != null) { for(String match : wildExcludes) { if (checkWildNameMatch(match, nameExpr)) { return false; } } } if (matchAllTypes != null) { char nameType = nameExpr.charAt(0); Boolean matchExpl = matchAllTypes.get(nameType); if (matchExpl != null) return matchExpl; } return matchAll; } private boolean checkWildNameMatch(String match, String name) { if (match.charAt(0) == name.charAt(0)) { // same type String pureName = name.substring(1); if (match.charAt(match.length() - 1) == WidgetRenderTargetExpr.WILDCARD) { String part = match.substring(1, match.length() - 1); return pureName.startsWith(part); } else if (match.charAt(1) == WidgetRenderTargetExpr.WILDCARD) { String part = match.substring(2); return pureName.endsWith(part); } else { int wildIndex = match.lastIndexOf(WidgetRenderTargetExpr.WILDCARD); if (wildIndex < 1) { throw new IllegalStateException("Section contains-expression name has missing or unexpected wildcard: " + match); } String firstPart = match.substring(2, wildIndex); String lastPart = match.substring(wildIndex + 1, match.length()); return pureName.startsWith(firstPart) && pureName.endsWith(lastPart); } } return false; } public String getStrExpr() { return strExpr; } @Override public String toString() { return strExpr; } @Override public boolean equals(Object other) { return (other instanceof ContainsExpr) && this.strExpr.equals(((ContainsExpr) other).strExpr); } public static final class MatchAllContainsExpr extends ContainsExpr { private MatchAllContainsExpr() throws IllegalArgumentException { super("*"); } @Override public boolean matches(String nameExpr) { return true; } @Override public boolean matchesAllNames(List<String> nameExprList) { return true; } @Override public boolean matchesAllNameTokens(List<Token> nameTokenList) { return true; } } public static final class MatchNoneContainsExpr extends ContainsExpr { private MatchNoneContainsExpr() throws IllegalArgumentException { super("!*"); } @Override public boolean matches(String nameExpr) { return false; } @Override public boolean matchesAllNames(List<String> nameExprList) { return false; } @Override public boolean matchesAllNameTokens(List<Token> nameTokenList) { return false; } } /** * SCIPIO: For any ModelWidget that supports a contains-expression. */ public interface FlexibleContainsExprAttrWidget { ContainsExpr getContainsExpr(Map<String, Object> context); } /** * SCIPIO: Special holder that allows to manage Flexible expressions automatically * and prevent creating unnecessary ones. */ public static abstract class ContainsExprHolder implements FlexibleContainsExprAttrWidget, Serializable { public static ContainsExprHolder getInstanceOrDefault(String strExpr, Element widgetElement) { FlexibleStringExpander exdr = FlexibleStringExpander.getInstance(strExpr); if (FlexibleStringExpander.containsExpression(exdr)) { return new FlexibleContainsExprHolder(exdr); } else { ContainsExpr expr = ContainsExpr.getInstanceOrDefault(strExpr, widgetElement); if (ContainsExpr.DEFAULT.equals(expr)) { return getDefaultInstance(); } else { return new SimpleContainsExprHolder(expr); } } } public static DefaultContainsExprHolder getDefaultInstance() { return DefaultContainsExprHolder.INSTANCE; } public static class DefaultContainsExprHolder extends ContainsExprHolder { private static final DefaultContainsExprHolder INSTANCE = new DefaultContainsExprHolder(); private DefaultContainsExprHolder() {} @Override public ContainsExpr getContainsExpr(Map<String, Object> context) { return ContainsExpr.DEFAULT; } } public static class SimpleContainsExprHolder extends ContainsExprHolder { private final ContainsExpr containsExpr; public SimpleContainsExprHolder(ContainsExpr containsExpr) { super(); this.containsExpr = containsExpr; } @Override public ContainsExpr getContainsExpr(Map<String, Object> context) { return containsExpr; } } public static class FlexibleContainsExprHolder extends ContainsExprHolder { private final FlexibleStringExpander containsExprExdr; public FlexibleContainsExprHolder(FlexibleStringExpander containsExprExdr) { super(); this.containsExprExdr = containsExprExdr; } @Override public ContainsExpr getContainsExpr(Map<String, Object> context) { return ContainsExpr.getInstanceOrDefault(containsExprExdr.expandString(context)); } } } }
avontd2868/scipio-erp
framework/widget/src/org/ofbiz/widget/model/ContainsExpr.java
4,545
// FIXME: we lose Token instance here
line_comment
nl
package org.ofbiz.widget.model; import java.io.Serializable; 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.Set; import java.util.regex.Pattern; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.cache.UtilCache; import org.ofbiz.base.util.string.FlexibleStringExpander; import org.ofbiz.widget.renderer.WidgetRenderTargetExpr; import org.ofbiz.widget.renderer.WidgetRenderTargetExpr.Token; import org.w3c.dom.Element; /** * SCIPIO: Widget screen section contains-expression - special expression that instructs renderer which sections * contain or don't contain which other sections and elements. * <p> * See widget-screen.xsd "attlist.generic-screen-widget-elem" "contains" attribute for details. * <p> * In targeted rendering, this is used by widget renderer to determine which sections can be skipped entirely (their * full execution including actions, not just output). * <p> * Usually functions in blacklist fashion ("!"), so that by default all sections are said to possibly contain * all others. * <p> * TODO: currently this is unable to consolidate the ^ and % operators, or any other operators * for that matter. attributes and wildcards won't work as expected. * STILL NEED TO IMPLEMENT WidgetRenderTargetExpr NORMALIZATION AND HANDLING * FROM ContainsExpr SO THAT EXCLUDE OPTIMIZATIONS ARE FULLY HONORED. * Currently, only some simple exclusions based on $ and # operators work at all. * <p> * ex: * <pre>{@code * "$MySection1, !$MySection2, !$MySections-*, #MyContainerId, !#myContainerId2, *" * }</pre> */ @SuppressWarnings("serial") public class ContainsExpr implements Serializable { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); private static final UtilCache<String, ContainsExpr> cache = UtilCache.createUtilCache("widget.screen.containsexpr"); // entries are comma-separated private static final Pattern containsExprTokenSplitPat = Pattern.compile("\\s*,\\s*"); // general language public static final char EXCLUDE = '!'; // pre-build expressions public static final ContainsExpr MATCH_ALL = new MatchAllContainsExpr(); public static final ContainsExpr MATCH_NONE = new MatchNoneContainsExpr(); public static final ContainsExpr DEFAULT = MATCH_ALL; static { // SPECIAL: pre-cache the default instances so they'll always be the ones looked up cache.put(MATCH_ALL.getStrExpr(), MATCH_ALL); cache.put(MATCH_NONE.getStrExpr(), MATCH_NONE); //cache.put(DEFAULT.getStrExpr(), DEFAULT); } /* * FIXME: * this whole class needs to be updated to support the Token expressions. * currently the "%" type and bracket attributes won't work properly. * I have not figured out the way to implement the comparison logic. * the current comparison logic is "dumb". */ // NOTE: these follow natural specificity private final String strExpr; private final Set<String> exactIncludes; private final Set<String> exactExcludes; private final List<String> wildIncludes; // TODO: find way to optimize private final List<String> wildExcludes; // TODO: find way to optimize private final Map<Character, Boolean> matchAllTypes; private final boolean matchAll; public ContainsExpr(String strExpr) throws IllegalArgumentException { this(strExpr, null); } public ContainsExpr(String strExpr, Element widgetElement) throws IllegalArgumentException { this.strExpr = strExpr; String[] tokenArr = containsExprTokenSplitPat.split(strExpr.trim()); if (tokenArr.length <= 0) throw new IllegalArgumentException(makeErrorMsg("no names in expression", null, strExpr, widgetElement)); // NOTE: these are layered by specificity from most exact to most generic Set<String> exactIncludes = new HashSet<>(); Set<String> exactExcludes = new HashSet<>(); ArrayList<String> wildIncludes = new ArrayList<>(); ArrayList<String> wildExcludes = new ArrayList<>(); Map<Character, Boolean> matchAllTypes = new HashMap<>(); Boolean matchAll = null; for(String fullToken : tokenArr) { String tokenStr = fullToken; boolean exclude = (tokenStr.charAt(0) == EXCLUDE); if (exclude) tokenStr = tokenStr.substring(1); if (WidgetRenderTargetExpr.WILDCARD_STRING.equals(tokenStr)) { // special case matchAll = !exclude; continue; } else if (tokenStr.isEmpty()) { throw new IllegalArgumentException(makeErrorMsg("invalid or empty name", fullToken, strExpr, widgetElement)); } // OLD - this did not extract the attributes // char type = tokenStr.charAt(0); // if (!WidgetRenderTargetExpr.MET_ALL.contains(type)) // throw new IllegalArgumentException(makeErrorMsg("name has missing" // + " or invalid type specifier (should start with one of: " + WidgetRenderTargetExpr.MET_ALL_STR + ")", fullToken, strExpr, widgetElement)); // String name = tokenStr.substring(1); Token token; try { token = Token.interpret(tokenStr); } catch(Exception e) { throw new IllegalArgumentException(makeErrorMsg(e.getMessage(), fullToken, strExpr, widgetElement)); } String name = token.getName().toString(); char type = token.getType(); String normTokenStr = token.getCmpNormStringExpr(); // FIXME: this does not properly compare supported Tokens // nor does it recognized the bracketed attributes // because we are ditching the Token instances if (name.equals(WidgetRenderTargetExpr.WILDCARD_STRING)) { // FIXME: missing attribute support - we are ditching attributes! if (token.hasAttr()) { Debug.logWarning(makeErrorMsg("token wildcard expression has attributes; attributes not yet supported here; attributes ignored!", fullToken, strExpr, widgetElement), module); } matchAllTypes.put(type, !exclude); } else if (name.contains(WidgetRenderTargetExpr.WILDCARD_STRING)) { if (name.indexOf(WidgetRenderTargetExpr.WILDCARD) != name.lastIndexOf(WidgetRenderTargetExpr.WILDCARD)) { // TODO?: support multiple wildcard throw new UnsupportedOperationException(makeErrorMsg("name has" + " with multiple wildcards, which is not supported", fullToken, strExpr, widgetElement)); } // FIXME: missing attribute support - we are ditching attributes! if (token.hasAttr()) { Debug.logWarning(makeErrorMsg("token wildcard expression has attributes; attributes not yet supported here; attributes ignored!", fullToken, strExpr, widgetElement), module); } if (exclude) { wildExcludes.add(type + name); } else { wildIncludes.add(type + name); } } else { if (token.hasAttr()) { Debug.logWarning(makeErrorMsg("token expression has attributes; not fully supported here; may not work as expected", fullToken, strExpr, widgetElement), module); } // FIXME: we<SUF> if (exclude) { exactExcludes.add(normTokenStr); } else { exactIncludes.add(normTokenStr); } } } this.exactIncludes = exactIncludes.isEmpty() ? Collections.<String> emptySet() : exactIncludes; this.exactExcludes = exactExcludes.isEmpty() ? Collections.<String> emptySet() : exactExcludes; wildIncludes.trimToSize(); this.wildIncludes = wildIncludes.isEmpty() ? null : wildIncludes; wildExcludes.trimToSize(); this.wildExcludes = wildExcludes.isEmpty() ? null : wildExcludes; this.matchAllTypes = matchAllTypes.isEmpty() ? null : matchAllTypes; if (matchAll == null) { Debug.logWarning(makeErrorMsg("missing match-all (\"*\") or match-none (\"!*\") wildcard entry;" + " cannot tell if blacklist or whitelist intended", null, strExpr, widgetElement), module); matchAll = ContainsExpr.DEFAULT.matches("dummy"); // stay consistent with the default } this.matchAll = matchAll; } private static String makeErrorMsg(String msg, String token, String strExpr, Element widgetElement) { String str = "Widget element contains=\"...\" expression error: " + msg + ":"; if (token != null) { str += " [name: \"" + token + "\"]"; } if (strExpr != null) { str += " [expression: \"" + strExpr + "\"]"; } if (widgetElement != null) { str += " [" + WidgetDocumentInfo.getElementDescriptor(widgetElement) + "]"; } return str; } /** * Gets instance from CACHE. */ public static ContainsExpr getInstance(String strExpr, Element widgetElement) { if (strExpr == null) return null; if (!strExpr.isEmpty()) { ContainsExpr expr = cache.get(strExpr); if (expr == null) { // no sync needed expr = new ContainsExpr(strExpr, widgetElement); cache.put(strExpr, expr); } return expr; } else return null; } public static ContainsExpr getInstanceOrDefault(String strExpr, Element widgetElement, ContainsExpr defaultValue) { ContainsExpr expr = getInstance(strExpr, widgetElement); return expr != null ? expr : defaultValue; } public static ContainsExpr getInstanceOrDefault(String strExpr, Element widgetElement) { return getInstanceOrDefault(strExpr, widgetElement, DEFAULT); } public static ContainsExpr getInstanceOrDefault(String strExpr) { return getInstanceOrDefault(strExpr, null, DEFAULT); } /** * Always creates new instance. */ public static ContainsExpr makeInstance(String strExpr, Element widgetElement) { if (strExpr == null) return null; if (!strExpr.isEmpty()) return new ContainsExpr(strExpr, widgetElement); else return null; } public static ContainsExpr makeInstanceOrDefault(String strExpr, Element widgetElement, ContainsExpr defaultValue) { ContainsExpr expr = makeInstance(strExpr, widgetElement); return expr != null ? expr : defaultValue; } public static ContainsExpr makeInstanceOrDefault(String strExpr, Element widgetElement) { return makeInstanceOrDefault(strExpr, widgetElement, DEFAULT); } /** * Checks if name expression matches this contains expression. * Name MUST be prefixed by one of the characters defined in * {@link WidgetRenderTargetExpr#MET_ALL}. * NOTE: this specific method ONLY supports an exact name (no wildcards) * and no bracketed attributes and will never support more. */ public boolean matches(String nameExpr) { if (exactIncludes.contains(nameExpr)) return true; else if (exactExcludes.contains(nameExpr)) return false; else return matchesWild(nameExpr); } /** * Returns true if and only if ALL of the names match. * So one false prevents match. * If no names, also returns true. * NOTE: this specific method ONLY supports an exact name (no wildcards) * and no bracketed attributes and will never support more. */ public boolean matchesAllNames(List<String> nameExprList) { for(String nameExpr : nameExprList) { if (!matches(nameExpr)) return false; } return true; } /** * Returns true if and only if ALL of the tokens match. * So one false prevents match. * If no names, also returns true. * <p> * FIXME: currently this is not able to handle wildcard tokens or bracketed attributes. * It will only recognize exact names and may ignore entries altogether (treated as matched). * The comparison logic needed to resolve this is extremely complex. * <p> * TODO: currently this is unable to consolidate the ^ and % operators, or any other operators * for that matter. STILL NEED TO IMPLEMENT WidgetRenderTargetExpr NORMALIZATION AND HANDLING * FROM ContainsExpr SO THAT EXCLUDE OPTIMIZATIONS ARE FULLY HONORED. * Currently, only some simple exclusions based on $ and # operators work at all. */ public boolean matchesAllNameTokens(List<Token> nameTokenList) { // FIXME: this does not properly compare supported Tokens // for now we'll just get the original expression as a string and compare that directly, // BUT we cannot do this for the bracketed attributes for(Token nameExpr : nameTokenList) { if (nameExpr.hasAttr()) { // FIXME: no wildcards for bracketed attributes because current code will mess it up if (!matchesExact(nameExpr.getCmpNormStringExpr())) return false; } else { if (!matches(nameExpr.getCmpNormStringExpr())) return false; } } return true; } private boolean matchesExact(String nameExpr) { if (exactIncludes.contains(nameExpr)) return true; else if (exactExcludes.contains(nameExpr)) return false; else return matchAll; } private boolean matchesWild(String nameExpr) { if (wildIncludes != null) { for(String match : wildIncludes) { if (checkWildNameMatch(match, nameExpr)) { return true; } } } if (wildExcludes != null) { for(String match : wildExcludes) { if (checkWildNameMatch(match, nameExpr)) { return false; } } } if (matchAllTypes != null) { char nameType = nameExpr.charAt(0); Boolean matchExpl = matchAllTypes.get(nameType); if (matchExpl != null) return matchExpl; } return matchAll; } private boolean checkWildNameMatch(String match, String name) { if (match.charAt(0) == name.charAt(0)) { // same type String pureName = name.substring(1); if (match.charAt(match.length() - 1) == WidgetRenderTargetExpr.WILDCARD) { String part = match.substring(1, match.length() - 1); return pureName.startsWith(part); } else if (match.charAt(1) == WidgetRenderTargetExpr.WILDCARD) { String part = match.substring(2); return pureName.endsWith(part); } else { int wildIndex = match.lastIndexOf(WidgetRenderTargetExpr.WILDCARD); if (wildIndex < 1) { throw new IllegalStateException("Section contains-expression name has missing or unexpected wildcard: " + match); } String firstPart = match.substring(2, wildIndex); String lastPart = match.substring(wildIndex + 1, match.length()); return pureName.startsWith(firstPart) && pureName.endsWith(lastPart); } } return false; } public String getStrExpr() { return strExpr; } @Override public String toString() { return strExpr; } @Override public boolean equals(Object other) { return (other instanceof ContainsExpr) && this.strExpr.equals(((ContainsExpr) other).strExpr); } public static final class MatchAllContainsExpr extends ContainsExpr { private MatchAllContainsExpr() throws IllegalArgumentException { super("*"); } @Override public boolean matches(String nameExpr) { return true; } @Override public boolean matchesAllNames(List<String> nameExprList) { return true; } @Override public boolean matchesAllNameTokens(List<Token> nameTokenList) { return true; } } public static final class MatchNoneContainsExpr extends ContainsExpr { private MatchNoneContainsExpr() throws IllegalArgumentException { super("!*"); } @Override public boolean matches(String nameExpr) { return false; } @Override public boolean matchesAllNames(List<String> nameExprList) { return false; } @Override public boolean matchesAllNameTokens(List<Token> nameTokenList) { return false; } } /** * SCIPIO: For any ModelWidget that supports a contains-expression. */ public interface FlexibleContainsExprAttrWidget { ContainsExpr getContainsExpr(Map<String, Object> context); } /** * SCIPIO: Special holder that allows to manage Flexible expressions automatically * and prevent creating unnecessary ones. */ public static abstract class ContainsExprHolder implements FlexibleContainsExprAttrWidget, Serializable { public static ContainsExprHolder getInstanceOrDefault(String strExpr, Element widgetElement) { FlexibleStringExpander exdr = FlexibleStringExpander.getInstance(strExpr); if (FlexibleStringExpander.containsExpression(exdr)) { return new FlexibleContainsExprHolder(exdr); } else { ContainsExpr expr = ContainsExpr.getInstanceOrDefault(strExpr, widgetElement); if (ContainsExpr.DEFAULT.equals(expr)) { return getDefaultInstance(); } else { return new SimpleContainsExprHolder(expr); } } } public static DefaultContainsExprHolder getDefaultInstance() { return DefaultContainsExprHolder.INSTANCE; } public static class DefaultContainsExprHolder extends ContainsExprHolder { private static final DefaultContainsExprHolder INSTANCE = new DefaultContainsExprHolder(); private DefaultContainsExprHolder() {} @Override public ContainsExpr getContainsExpr(Map<String, Object> context) { return ContainsExpr.DEFAULT; } } public static class SimpleContainsExprHolder extends ContainsExprHolder { private final ContainsExpr containsExpr; public SimpleContainsExprHolder(ContainsExpr containsExpr) { super(); this.containsExpr = containsExpr; } @Override public ContainsExpr getContainsExpr(Map<String, Object> context) { return containsExpr; } } public static class FlexibleContainsExprHolder extends ContainsExprHolder { private final FlexibleStringExpander containsExprExdr; public FlexibleContainsExprHolder(FlexibleStringExpander containsExprExdr) { super(); this.containsExprExdr = containsExprExdr; } @Override public ContainsExpr getContainsExpr(Map<String, Object> context) { return ContainsExpr.getInstanceOrDefault(containsExprExdr.expandString(context)); } } } }
188122_28
/** * Created Aug 23, 2007 * * @by Sebastian Lenz ([email protected]) * * Copyright 2007 Sebastian Lenz * * This file is part of parsemis. * * Licence: * LGPL: http://www.gnu.org/licenses/lgpl.html * EPL: http://www.eclipse.org/org/documents/epl-v10.php * See the LICENSE file in the project's top-level directory for details. */ package de.parsemis.visualisation; import java.awt.geom.Point2D; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; import prefuse.action.layout.graph.TreeLayout; import prefuse.data.Graph; import prefuse.util.collections.IntIterator; import prefuse.visual.NodeItem; /** * * @author Sebastian Lenz ([email protected]) */ public class SugiyamaLayout extends TreeLayout { // public static String sync = "sync"; public static class Co { private double x; private final int y; final private int id; public Co(final double x, final int y, final int id) { this.x = x; this.y = y; this.id = id; } public void changeX(final double i) { this.x = i; } public int getId() { return this.id; } public double getX() { return this.x; } public int getY() { return this.y; } } private double m_bspace = 30; // the spacing between sibling nodes private double m_tspace = 25; // the spacing between subtrees private double m_dspace = 50; // the spacing between depth levels private double m_offset = 50; // pixel offset for root node position private final double[] m_depths = new double[10]; private double m_ax, m_ay; // for holding anchor co-ordinates private int[] degree; private final Map<Integer, Collection<Double>> calc; private Co[] coord; private int maxLen; // ------------------------------------------------------------------------ boolean ready = false; /** * * @param group * the data group to layout. Must resolve to a Graph instance. */ public SugiyamaLayout(final String group) { super(group); calc = new HashMap<Integer, Collection<Double>>(); } private void computeX(final Graph g) { Arrays.sort(coord, new Comparator<Co>() { public int compare(final Co co1, final Co co2) { final Double x1 = co1.getX(); final Integer y1 = co1.getY(); final Integer id1 = co1.getId(); final Double x2 = co2.getX(); final Integer y2 = co2.getY(); final Integer id2 = co2.getId(); if (!(y1.equals(y2))) { return y1.compareTo(y2); } else if (!(x1.equals(x2))) { return x1.compareTo(x2); } else { return id1.compareTo(id2); } } }); double fix = 0; int i = 0; int layer = 0; int state = 0; int arraypos = 0; int layerstart = 0; double istSum = 0; double sollSum = 0; while (i < coord.length) { switch (state) { case 0: // layer = 0, x wird gesetzt coord[arraypos].changeX(fix); fix++; arraypos++; if (arraypos == coord.length) { // keine knoten mehr uebrig, // abbruchbedingung i = arraypos; break; } if (coord[arraypos].getY() != layer) { // ende aktueller layer state = 2; } break; case 1: // layer != 0, x muss berechnet werden double erg = 0; if (calc.containsKey(coord[arraypos].getId())) { final Collection<Double> test = calc.get(coord[arraypos] .getId()); final Iterator<Double> values = test.iterator(); while (values.hasNext()) { erg = erg + values.next(); } erg = erg / test.size(); } else { assert (false); } coord[arraypos].changeX(erg); arraypos++; if (arraypos == coord.length) {// keine knoten mehr uebrig state = 3;// kein abbruch, da noch ueberpruefung auf // ueberschneidung noetig break; } if (coord[arraypos].getY() != layer) {// ende aktueller layer state = 3; break; } break; case 2: // vorberechnung der nachfolger if (arraypos == coord.length) {// keine knoten mehr uebrig, // abbruchbedingung i = arraypos; break; } for (int j = layerstart; j < arraypos; j++) { double f = 0; final IntIterator it = g.outEdgeRows(coord[j].getId()); final double n = g.getOutDegree(coord[j].getId()); while (it.hasNext()) { final int e = it.nextInt(); final int t = g.getTargetNode(e); Collection<Double> temp = calc.get(t); if (temp == null) { temp = new Vector<Double>(); } temp.add(-((n - 1) / 2) + f + coord[j].getX()); calc.put(t, temp); f = f + 1.0; } } state = 1; layer++; layerstart = arraypos; i = arraypos; break; case 3: // test auf eventuelle ueberschneidungen sollSum = 0; istSum = 0; Arrays.sort(coord, layerstart, arraypos, new Comparator<Co>() {// aktueller // layer // nach // x // sortieren public int compare(final Co co1, final Co co2) { // um // feste // reihefolge // fuer // schleife // zu haben final Double x1 = co1.getX(); final Integer id1 = co1.getId(); final Double x2 = co2.getX(); final Integer id2 = co2.getId(); if (!(x1.equals(x2))) { return x1.compareTo(x2); } else { return id1.compareTo(id2); } } }); for (int j = layerstart; j < arraypos - 1; j++) { final double diff = Math.abs(coord[j].getX() - coord[j + 1].getX()); if (diff < 1) { sollSum++; } else { sollSum = sollSum + diff; } istSum = istSum + diff; } if (Math.abs(istSum - sollSum) < .0000001) { // keine ueberschneidung // state = 2; //weiter mit vorberechnung state = 5; // weiter mit Kantenkreuzungen bereinigen } else {// ueberschneidung, korrigieren ... state = 4; } break; case 4: // korrigieren der ueberschneidungen double oldPosX = coord[layerstart].getX(); coord[layerstart].changeX(oldPosX - (sollSum - istSum) / 2); for (int j = layerstart; j < arraypos - 2; j++) { final double diff = Math.abs(oldPosX - coord[j + 1].getX()); oldPosX = coord[j + 1].getX(); if (diff < 1) { coord[j + 1].changeX(coord[j].getX() + 1); } else { coord[j + 1].changeX(coord[j].getX() + diff); } } coord[arraypos - 1].changeX(coord[arraypos - 1].getX() + (sollSum - istSum) / 2); // state = 2; //weiter mit vorberechnung state = 5; // weiter mit Kantenkreuzungen bereinigen break; case 5: // entfernen der kantenkreuzungen for (int j = layerstart; j < arraypos - 1; j++) { final IntIterator it = g.inEdgeRows(coord[j].getId());// vorgaenger // knoten 1 // finden Co[] test1 = null; int y = 0; while (it.hasNext()) { final int e = it.nextInt(); final int t = g.getSourceNode(e); if (test1 == null) { test1 = new Co[g.getInDegree(coord[j].getId())]; } int z = 0; while (coord[z].getId() != t) { z++; } test1[y] = coord[z]; y++; } final IntIterator et = g.inEdgeRows(coord[j + 1].getId());// vorgaenger // knoten // 2 // finden Co[] test2 = null; y = 0; while (et.hasNext()) { final int e = et.nextInt(); final int t = g.getSourceNode(e); if (test2 == null) { test2 = new Co[g.getInDegree(coord[j + 1].getId())]; } int z = 0; while (coord[z].getId() != t) { z++; } test2[y] = coord[z]; y++; } if (test1 == null | test2 == null) { break; } // vorgaenger nach x sortieren if (test1.length > 1) { Arrays.sort(test1, new Comparator<Co>() { public int compare(final Co co1, final Co co2) { final Double x1 = co1.getX(); final Double x2 = co2.getX(); return x1.compareTo(x2); } }); } if (test2.length > 1) { Arrays.sort(test2, new Comparator<Co>() { public int compare(final Co co1, final Co co2) { final Double x1 = co1.getX(); final Double x2 = co2.getX(); return x1.compareTo(x2); } }); } // wenn der linkeste vorgaenger des rechten knoten < der // rechteste vorgaenger des linken knotens if (test2[0].getX() < test1[test1.length - 1].getX()) { final double sw = coord[j].getX(); coord[j].changeX(coord[j + 1].getX()); coord[j + 1].changeX(sw); } } state = 2; break; default: break; }// end-switch }// end-while } private void computeY(final Graph g) { int r = 0; int c = 0; final int cnt = g.getNodeCount(); degree = new int[cnt]; final IntIterator it = g.nodeRows(); while (it.hasNext()) { final int i = it.nextInt(); degree[i] = g.getInDegree(i); } while (c != cnt) { c = rank(r, c, g); r++; } } /** * Get the spacing between neighbor nodes. * * @return the breadth spacing */ public double getBreadthSpacing() { return m_bspace; } /** * Get the spacing between depth levels. * * @return the depth spacing */ public double getDepthSpacing() { return m_dspace; } /** * Get the offset value for placing the root node of the tree. * * @return the value by which the root node of the tree is offset */ public double getRootNodeOffset() { return m_offset; } /** * Get the spacing between neighboring subtrees. * * @return the subtree spacing */ public double getSubtreeSpacing() { return m_tspace; } // ----------------------------------------------------------------------- private int rank(final int r, int c, final Graph g) { final int cnt = g.getNodeCount(); for (int j = 0; j < cnt; j++) { if (degree[j] == 0) { coord[j] = new Co(0.0, r, j); maxLen = Math.max(maxLen, g.getNode(j).getString("name") .length()); degree[j] = -1; } } for (int j = 0; j < cnt; j++) { if (degree[j] == -1) { final IntIterator ed = g.outEdgeRows(j); while (ed.hasNext()) { final int e = ed.nextInt(); degree[g.getTargetNode(e)]--; } degree[j] = -2; c++; } } return c; } public synchronized boolean ready() { return ready; } /** * @see prefuse.action.Action#run(double) */ @Override public synchronized void run(final double frac) { maxLen = 0; final Graph g = (Graph) m_vis.getGroup(m_group); Arrays.fill(m_depths, 0); final Point2D a = getLayoutAnchor(); m_ax = a.getX(); m_ay = a.getY(); // ----- coord = new Co[g.getNodeCount()]; computeY(g); computeX(g); for (int i = 0; i < g.getNodeCount(); i++) { final NodeItem n = (NodeItem) g.getNode(coord[i].getId()); double hoch = coord[i].getY(); double breit = coord[i].getX(); breit = breit * m_bspace * Math.sqrt(maxLen); hoch = hoch * m_dspace; setBreadth(n, null, breit); setDepth(n, null, hoch); } ready = true; } private void setBreadth(final NodeItem n, final NodeItem p, final double b) { setX(n, p, m_ax + b); } /** * Set the spacing between neighbor nodes. * * @param b * the breadth spacing to use */ public void setBreadthSpacing(final double b) { m_bspace = b; } private void setDepth(final NodeItem n, final NodeItem p, final double d) { setY(n, p, m_ay + d); } /** * Set the spacing between depth levels. * * @param d * the depth spacing to use */ public void setDepthSpacing(final double d) { m_dspace = d; } /** * Set the offset value for placing the root node of the tree. The dimension * in which this offset is applied is dependent upon the orientation of the * tree. For example, in a left-to-right orientation, the offset will a * horizontal offset from the left edge of the layout bounds. * * @param o * the value by which to offset the root node of the tree */ public void setRootNodeOffset(final double o) { m_offset = o; } /** * Set the spacing between neighboring subtrees. * * @param s * the subtree spacing to use */ public void setSubtreeSpacing(final double s) { m_tspace = s; } }
timtadh/parsemis
src/de/parsemis/visualisation/SugiyamaLayout.java
4,189
// rechteste vorgaenger des linken knotens
line_comment
nl
/** * Created Aug 23, 2007 * * @by Sebastian Lenz ([email protected]) * * Copyright 2007 Sebastian Lenz * * This file is part of parsemis. * * Licence: * LGPL: http://www.gnu.org/licenses/lgpl.html * EPL: http://www.eclipse.org/org/documents/epl-v10.php * See the LICENSE file in the project's top-level directory for details. */ package de.parsemis.visualisation; import java.awt.geom.Point2D; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; import prefuse.action.layout.graph.TreeLayout; import prefuse.data.Graph; import prefuse.util.collections.IntIterator; import prefuse.visual.NodeItem; /** * * @author Sebastian Lenz ([email protected]) */ public class SugiyamaLayout extends TreeLayout { // public static String sync = "sync"; public static class Co { private double x; private final int y; final private int id; public Co(final double x, final int y, final int id) { this.x = x; this.y = y; this.id = id; } public void changeX(final double i) { this.x = i; } public int getId() { return this.id; } public double getX() { return this.x; } public int getY() { return this.y; } } private double m_bspace = 30; // the spacing between sibling nodes private double m_tspace = 25; // the spacing between subtrees private double m_dspace = 50; // the spacing between depth levels private double m_offset = 50; // pixel offset for root node position private final double[] m_depths = new double[10]; private double m_ax, m_ay; // for holding anchor co-ordinates private int[] degree; private final Map<Integer, Collection<Double>> calc; private Co[] coord; private int maxLen; // ------------------------------------------------------------------------ boolean ready = false; /** * * @param group * the data group to layout. Must resolve to a Graph instance. */ public SugiyamaLayout(final String group) { super(group); calc = new HashMap<Integer, Collection<Double>>(); } private void computeX(final Graph g) { Arrays.sort(coord, new Comparator<Co>() { public int compare(final Co co1, final Co co2) { final Double x1 = co1.getX(); final Integer y1 = co1.getY(); final Integer id1 = co1.getId(); final Double x2 = co2.getX(); final Integer y2 = co2.getY(); final Integer id2 = co2.getId(); if (!(y1.equals(y2))) { return y1.compareTo(y2); } else if (!(x1.equals(x2))) { return x1.compareTo(x2); } else { return id1.compareTo(id2); } } }); double fix = 0; int i = 0; int layer = 0; int state = 0; int arraypos = 0; int layerstart = 0; double istSum = 0; double sollSum = 0; while (i < coord.length) { switch (state) { case 0: // layer = 0, x wird gesetzt coord[arraypos].changeX(fix); fix++; arraypos++; if (arraypos == coord.length) { // keine knoten mehr uebrig, // abbruchbedingung i = arraypos; break; } if (coord[arraypos].getY() != layer) { // ende aktueller layer state = 2; } break; case 1: // layer != 0, x muss berechnet werden double erg = 0; if (calc.containsKey(coord[arraypos].getId())) { final Collection<Double> test = calc.get(coord[arraypos] .getId()); final Iterator<Double> values = test.iterator(); while (values.hasNext()) { erg = erg + values.next(); } erg = erg / test.size(); } else { assert (false); } coord[arraypos].changeX(erg); arraypos++; if (arraypos == coord.length) {// keine knoten mehr uebrig state = 3;// kein abbruch, da noch ueberpruefung auf // ueberschneidung noetig break; } if (coord[arraypos].getY() != layer) {// ende aktueller layer state = 3; break; } break; case 2: // vorberechnung der nachfolger if (arraypos == coord.length) {// keine knoten mehr uebrig, // abbruchbedingung i = arraypos; break; } for (int j = layerstart; j < arraypos; j++) { double f = 0; final IntIterator it = g.outEdgeRows(coord[j].getId()); final double n = g.getOutDegree(coord[j].getId()); while (it.hasNext()) { final int e = it.nextInt(); final int t = g.getTargetNode(e); Collection<Double> temp = calc.get(t); if (temp == null) { temp = new Vector<Double>(); } temp.add(-((n - 1) / 2) + f + coord[j].getX()); calc.put(t, temp); f = f + 1.0; } } state = 1; layer++; layerstart = arraypos; i = arraypos; break; case 3: // test auf eventuelle ueberschneidungen sollSum = 0; istSum = 0; Arrays.sort(coord, layerstart, arraypos, new Comparator<Co>() {// aktueller // layer // nach // x // sortieren public int compare(final Co co1, final Co co2) { // um // feste // reihefolge // fuer // schleife // zu haben final Double x1 = co1.getX(); final Integer id1 = co1.getId(); final Double x2 = co2.getX(); final Integer id2 = co2.getId(); if (!(x1.equals(x2))) { return x1.compareTo(x2); } else { return id1.compareTo(id2); } } }); for (int j = layerstart; j < arraypos - 1; j++) { final double diff = Math.abs(coord[j].getX() - coord[j + 1].getX()); if (diff < 1) { sollSum++; } else { sollSum = sollSum + diff; } istSum = istSum + diff; } if (Math.abs(istSum - sollSum) < .0000001) { // keine ueberschneidung // state = 2; //weiter mit vorberechnung state = 5; // weiter mit Kantenkreuzungen bereinigen } else {// ueberschneidung, korrigieren ... state = 4; } break; case 4: // korrigieren der ueberschneidungen double oldPosX = coord[layerstart].getX(); coord[layerstart].changeX(oldPosX - (sollSum - istSum) / 2); for (int j = layerstart; j < arraypos - 2; j++) { final double diff = Math.abs(oldPosX - coord[j + 1].getX()); oldPosX = coord[j + 1].getX(); if (diff < 1) { coord[j + 1].changeX(coord[j].getX() + 1); } else { coord[j + 1].changeX(coord[j].getX() + diff); } } coord[arraypos - 1].changeX(coord[arraypos - 1].getX() + (sollSum - istSum) / 2); // state = 2; //weiter mit vorberechnung state = 5; // weiter mit Kantenkreuzungen bereinigen break; case 5: // entfernen der kantenkreuzungen for (int j = layerstart; j < arraypos - 1; j++) { final IntIterator it = g.inEdgeRows(coord[j].getId());// vorgaenger // knoten 1 // finden Co[] test1 = null; int y = 0; while (it.hasNext()) { final int e = it.nextInt(); final int t = g.getSourceNode(e); if (test1 == null) { test1 = new Co[g.getInDegree(coord[j].getId())]; } int z = 0; while (coord[z].getId() != t) { z++; } test1[y] = coord[z]; y++; } final IntIterator et = g.inEdgeRows(coord[j + 1].getId());// vorgaenger // knoten // 2 // finden Co[] test2 = null; y = 0; while (et.hasNext()) { final int e = et.nextInt(); final int t = g.getSourceNode(e); if (test2 == null) { test2 = new Co[g.getInDegree(coord[j + 1].getId())]; } int z = 0; while (coord[z].getId() != t) { z++; } test2[y] = coord[z]; y++; } if (test1 == null | test2 == null) { break; } // vorgaenger nach x sortieren if (test1.length > 1) { Arrays.sort(test1, new Comparator<Co>() { public int compare(final Co co1, final Co co2) { final Double x1 = co1.getX(); final Double x2 = co2.getX(); return x1.compareTo(x2); } }); } if (test2.length > 1) { Arrays.sort(test2, new Comparator<Co>() { public int compare(final Co co1, final Co co2) { final Double x1 = co1.getX(); final Double x2 = co2.getX(); return x1.compareTo(x2); } }); } // wenn der linkeste vorgaenger des rechten knoten < der // rechteste vorgaenger<SUF> if (test2[0].getX() < test1[test1.length - 1].getX()) { final double sw = coord[j].getX(); coord[j].changeX(coord[j + 1].getX()); coord[j + 1].changeX(sw); } } state = 2; break; default: break; }// end-switch }// end-while } private void computeY(final Graph g) { int r = 0; int c = 0; final int cnt = g.getNodeCount(); degree = new int[cnt]; final IntIterator it = g.nodeRows(); while (it.hasNext()) { final int i = it.nextInt(); degree[i] = g.getInDegree(i); } while (c != cnt) { c = rank(r, c, g); r++; } } /** * Get the spacing between neighbor nodes. * * @return the breadth spacing */ public double getBreadthSpacing() { return m_bspace; } /** * Get the spacing between depth levels. * * @return the depth spacing */ public double getDepthSpacing() { return m_dspace; } /** * Get the offset value for placing the root node of the tree. * * @return the value by which the root node of the tree is offset */ public double getRootNodeOffset() { return m_offset; } /** * Get the spacing between neighboring subtrees. * * @return the subtree spacing */ public double getSubtreeSpacing() { return m_tspace; } // ----------------------------------------------------------------------- private int rank(final int r, int c, final Graph g) { final int cnt = g.getNodeCount(); for (int j = 0; j < cnt; j++) { if (degree[j] == 0) { coord[j] = new Co(0.0, r, j); maxLen = Math.max(maxLen, g.getNode(j).getString("name") .length()); degree[j] = -1; } } for (int j = 0; j < cnt; j++) { if (degree[j] == -1) { final IntIterator ed = g.outEdgeRows(j); while (ed.hasNext()) { final int e = ed.nextInt(); degree[g.getTargetNode(e)]--; } degree[j] = -2; c++; } } return c; } public synchronized boolean ready() { return ready; } /** * @see prefuse.action.Action#run(double) */ @Override public synchronized void run(final double frac) { maxLen = 0; final Graph g = (Graph) m_vis.getGroup(m_group); Arrays.fill(m_depths, 0); final Point2D a = getLayoutAnchor(); m_ax = a.getX(); m_ay = a.getY(); // ----- coord = new Co[g.getNodeCount()]; computeY(g); computeX(g); for (int i = 0; i < g.getNodeCount(); i++) { final NodeItem n = (NodeItem) g.getNode(coord[i].getId()); double hoch = coord[i].getY(); double breit = coord[i].getX(); breit = breit * m_bspace * Math.sqrt(maxLen); hoch = hoch * m_dspace; setBreadth(n, null, breit); setDepth(n, null, hoch); } ready = true; } private void setBreadth(final NodeItem n, final NodeItem p, final double b) { setX(n, p, m_ax + b); } /** * Set the spacing between neighbor nodes. * * @param b * the breadth spacing to use */ public void setBreadthSpacing(final double b) { m_bspace = b; } private void setDepth(final NodeItem n, final NodeItem p, final double d) { setY(n, p, m_ay + d); } /** * Set the spacing between depth levels. * * @param d * the depth spacing to use */ public void setDepthSpacing(final double d) { m_dspace = d; } /** * Set the offset value for placing the root node of the tree. The dimension * in which this offset is applied is dependent upon the orientation of the * tree. For example, in a left-to-right orientation, the offset will a * horizontal offset from the left edge of the layout bounds. * * @param o * the value by which to offset the root node of the tree */ public void setRootNodeOffset(final double o) { m_offset = o; } /** * Set the spacing between neighboring subtrees. * * @param s * the subtree spacing to use */ public void setSubtreeSpacing(final double s) { m_tspace = s; } }
85318_58
package edu.ucsf.mousedatabase; import java.sql.*; import java.util.Collection; import java.util.HashMap; import java.util.Properties; import java.lang.Thread; import edu.ucsf.mousedatabase.beans.MouseSubmission; import edu.ucsf.mousedatabase.dataimport.ImportStatusTracker; import edu.ucsf.mousedatabase.dataimport.ImportStatusTracker.ImportStatus; import edu.ucsf.mousedatabase.objects.MGIResult; public class MGIConnect { //todo get these from the mgi database, they shouldn't be static public static int MGI_MARKER = 2; public static int MGI_ALLELE = 11; public static int MGI_REFERENCE = 1; public static int MGI_MARKER_OTHER_GENOME_FEATURE = 9; public static final String pmDBurl = "http://www.ncbi.nlm.nih.gov/pubmed/"; public static final String pmDBurlTail = "?dopt=Abstract"; public static final String mgiDBurl = "http://www.informatics.jax.org/accession/MGI:"; private static String databaseConnectionString; private static String databaseDriverName; private static boolean initialized = false; public static boolean verbose = false; public static boolean Initialize(String databaseDriverName, String databaseConnectionString) { if (initialized) { return false; } MGIConnect.databaseDriverName = databaseDriverName; MGIConnect.databaseConnectionString = databaseConnectionString; initialized = true; return true; } // TODO make this method public and make callers figure out typeIDs public static MGIResult doMGIQuery(String accessionID, int expectedTypeID, String wrongTypeString) { return doMGIQuery(accessionID, expectedTypeID, wrongTypeString, true); } public static MGIResult doMGIQuery(String accessionID, int expectedTypeID, String wrongTypeString, boolean offlineOK) { MGIResult result = new MGIResult(); result.setAccessionID(accessionID); result.setType(expectedTypeID); String query = ""; Connection connection = null; String accID = accessionID; if (expectedTypeID != MGI_REFERENCE) { accID = "MGI:" + accessionID; } try { connection = connect(); query = "select _Accession_key, ACC_Accession._MGIType_key, primaryKeyName, _Object_key, tableName " + "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " + "where accID='" + accID + "' " + "and ACC_Accession._MGIType_key in(" + MGI_MARKER + "," + MGI_ALLELE + "," + MGI_REFERENCE + ")"; // the last line above is kind of a hack because sometimes you get multiple // results for accession ids, such as evidence types java.sql.Statement stmt = connection.createStatement(); if (verbose) System.out.println(query); ResultSet rs = stmt.executeQuery(query); if (rs.next()) { // int accessionKey = rs.getInt("_Accession_key"); int mgiTypeKey = rs.getInt("_MGIType_key"); String primaryKeyName = rs.getString("primaryKeyName"); int objectKey = rs.getInt("_Object_key"); String tableName = rs.getString("tableName"); if (mgiTypeKey != expectedTypeID) // TODO lookup type id, don't hard code it { if (verbose) System.out.println("type key mismatch! " + mgiTypeKey + " != " + expectedTypeID); // see if this is a possible other genome feature issue if (mgiTypeKey == MGI_MARKER && expectedTypeID == MGI_ALLELE) { query = "select * from " + tableName + " where " + primaryKeyName + "=" + objectKey; if (verbose) System.out.println(query); stmt = connection.createStatement(); rs = stmt.executeQuery(query); if (rs.next() && rs.getInt("_Marker_Type_key") == MGI_MARKER_OTHER_GENOME_FEATURE) { query = getAlleleQueryFromOGFID(accessionID); stmt = connection.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { String allelePageID = rs.getString("accID"); return doMGIQuery(allelePageID, expectedTypeID, wrongTypeString); } } } result.setValid(false); result.setErrorString(wrongTypeString); } else { query = "select * from " + tableName + " where " + primaryKeyName + "=" + objectKey; if (verbose) System.out.println(query); stmt = connection.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { if (mgiTypeKey == MGI_ALLELE) { result.setSymbol(rs.getString("symbol")); result.setName(trimOfficialName(rs.getString("name"))); result.setValid(true); query = "select term from ALL_Allele aa inner join voc_term voc on aa._Allele_Type_key=voc._Term_key where _Allele_key=" + objectKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { String alleleType = rs.getString("term"); if (verbose) System.out.println("allele type: " + alleleType); if (alleleType.equalsIgnoreCase("QTL")) { result.setValid(false); result.setErrorString( "This ID corresponds to a QTL variant. Please go back to step 2 and do a submission for the relevant inbred strain"); } } } else if (mgiTypeKey == MGI_MARKER) { result.setSymbol(rs.getString("symbol")); result.setName(rs.getString("name")); result.setValid(true); } else if (mgiTypeKey == MGI_REFERENCE) { result.setAuthors(rs.getString("authors")); result.setTitle(rs.getString("title")); result.setValid(true); } } } } else { if (expectedTypeID == MGI_REFERENCE) { result.setErrorString("Not found. Please confirm that you have the correct Pubmed ID."); result.setValid(false); } else { result.setErrorString("Not found in MGI database. Confirm that you have the correct Accession ID"); result.setValid(false); } } } catch (NullPointerException e) { result.setValid(offlineOK); result.setErrorString("Connection to MGI timed out."); result.setTitle(result.getErrorString()); result.setAuthors(""); result.setName(result.getErrorString()); result.setSymbol(""); result.setMgiConnectionTimedout(true); e.printStackTrace(System.err); } catch (Exception e) { result.setValid(offlineOK); result.setErrorString( "MGI database connection unavailable. This is to be expected late at night on weekdays. Please manually verify that this is the correct ID"); result.setTitle(result.getErrorString()); result.setAuthors(""); result.setName(result.getErrorString()); result.setSymbol(""); result.setMgiOffline(true); // System.err.println(query); e.printStackTrace(System.err); } finally { if (connection != null) { try { connection.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } // Close the connection to MGI. return result; } public static HashMap<Integer, MouseSubmission> SubmissionFromMGI(Collection<Integer> accessionIDs, int importTaskId) { HashMap<Integer, MouseSubmission> newSubmissions = new HashMap<Integer, MouseSubmission>(); // TODO validate accession IDs first? so that we don't have to duplicate logic // like // checking that it isn't a QTL or other genome feature HashMap<Integer, Properties> results = getPropertiesFromAlleleMgiID(accessionIDs, importTaskId); for (int key : results.keySet()) { Properties props = results.get(key); if (props != null && !props.isEmpty()) { MouseSubmission sub = new MouseSubmission(); sub.setMouseMGIID(Integer.toString(key)); sub.setIsPublished("No"); sub.setHolderFacility("unassigned"); sub.setHolderName("unassigned"); sub.setMouseType("unknown"); if (verbose) System.out.println("*****************************"); if (verbose) System.out.println("Allele MGI ID: " + key); String geneId = null; StringBuilder propertyList = new StringBuilder(); for (String prop : props.stringPropertyNames()) { String value = props.getProperty(prop); if (verbose) System.out.println(prop + ": " + value); if (prop.equals("mouseName")) { sub.setOfficialMouseName(trimOfficialName(value)); } else if (prop.equals("mouseType")) { propertyList.append("*" + prop + ":* " + value + "\r\n"); //targeted captures knockout or knockin mice, can be transchromosomal if(value.startsWith("Targeted")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); if(value.contains("knock-out")) { } else if (value.contains("knock-in")) { } } //Added Radiation induced muations -EW else if (value.startsWith("Radiation")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else if (value.startsWith("Spontaneous")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else if (value.startsWith("Transgenic")) { sub.setMouseType("Transgene"); sub.setTransgenicType("undetermined"); sub.setTGExpressedSequence("undetermined"); //extract from 'Transgenic (Reporter)' //or 'Transgenic (random, expressed)' //or 'Transgenic (Cre/Flp)' } else if (value.startsWith("Gene trapped")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else if (value.startsWith("Not Applicable")) { sub.setMouseType("Inbred Strain"); //TODO ???? // Allele MGI ID: 3579311 // mouseType : Not Applicable // pubMedTitle : THE AKR THYMIC ANTIGEN AND ITS DISTRIBUTION IN LEUKEMIAS AND NERVOUS TISSUES. // gene name : thymus cell antigen 1, theta // gene symbol : Thy1 // mouseName : a variant // pubMedID : 14207060 // pubMedAuthor : REIF AE // officialSymbol : Thy1<a> // gene mgi ID : 98747 } else if (value.startsWith("QTL")) { sub.setMouseType("Inbred Strain"); } //Enodnuclease-mediated mice will switch to this type -EW else if (value.startsWith("Endonuclease-mediated")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } //Transposon induced added to Mutant Allele category -EW else if (value.startsWith("Transposon induced")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else if (value.startsWith("Chemically")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else { sub.setMouseType("undetermined"); } } else if (prop.equals("mutationType")) { propertyList.append("*" + prop + ":* " + value + "\r\n"); //????? if(value.equals("Insertion")) { //sub.setTransgenicType("random insertion"); } else if (value.equals("Single point mutation")) { } else if (value.equals("Other")) { } else if (value.equals("Intragenic deletion")) { } } else if(prop.equals("pubMedID")) { sub.setIsPublished("Yes"); sub.setPMID(value); } else if(prop.equals("geneMgiID")) { geneId = value; } else if (prop.equals("officialSymbol")) { sub.setOfficialSymbol(value); } else if (prop.equals("description")) { sub.setComment(value); } } if (sub.getMouseType() != null && sub.getMouseType().equals("Mutant Allele")) { sub.setMAMgiGeneID(geneId); } sub.setComment(sub.getComment() + "\r\n\r\nRaw properties returned from MGI:\r\n" + propertyList.toString()); newSubmissions.put(key, sub); } else { newSubmissions.put(key,null); } } return newSubmissions; } private static String trimOfficialName(String rawName) { return rawName; // if (rawName == null || rawName.isEmpty()) // { // return rawName; // } // // if (rawName.toLowerCase().indexOf("targeted mutation ") < 0 && rawName.toLowerCase().indexOf("transgene insertion ") < 0) // { // return rawName; // } // // int index = rawName.indexOf(',') + 1; // if (index >= rawName.length() - 1) // { // return rawName; // } // return rawName.substring(index).trim(); } public static HashMap<Integer,Properties> getPropertiesFromAlleleMgiID(Collection<Integer> accessionIDs, int importTaskId) { HashMap<Integer,Properties> results = new HashMap<Integer,Properties>(); Connection connection = null; Statement stmt = null; ResultSet rs = null; ImportStatusTracker.UpdateHeader(importTaskId, "Downloading Allele data from MGI (Task 2 of 3)"); ImportStatusTracker.SetProgress(importTaskId, 0); double mgiIdNumber = 1; double mgiCount = accessionIDs.size(); try { connection = connect(); stmt = connection.createStatement(); for(int accessionID : accessionIDs) { ImportStatusTracker.SetProgress(importTaskId, mgiIdNumber / mgiCount); mgiIdNumber++; if (accessionID < 0) { Log.Info("Ignored invalid accession ID: " + accessionID); continue; } if (verbose) System.out.println("Fetching details for MGI:" + accessionID); Properties props = new Properties(); results.put(accessionID, props); //TODO get the comment?? String query = "select _Object_key " + "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " + "where accid='MGI:" + accessionID + "' " + "and ACC_Accession._MGIType_key=11"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if(!rs.next()) { //accession ID not found, return early Log.Info("No matching alleles found for accession ID: " + accessionID); continue; } int alleleKey = rs.getInt("_Object_key"); query = "select _Marker_key,name,symbol from ALL_Allele where _Allele_key=" + alleleKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if(!rs.next()) { //no data in allele table, very strange if (verbose) System.out.println("No data found for allele key: " + alleleKey); continue; } props.setProperty("mouseName",rs.getString("name")); props.setProperty("officialSymbol",rs.getString("symbol")); ImportStatusTracker.AppendMessage(importTaskId, "MGI:" + accessionID + " -> " + HTMLUtilities.getCommentForDisplay(props.getProperty("officialSymbol"))); int markerKey = rs.getInt("_Marker_key"); query = "select term from ALL_Allele_Mutation mut inner join voc_term voc on mut._mutation_key=voc._term_key where _Allele_key=" + alleleKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { String mutation = rs.getString("term"); //convert MGI terminology to ours props.setProperty("mutationType",mutation); } query = "select term from ALL_Allele aa inner join voc_term voc on aa._Allele_Type_key=voc._Term_key where _Allele_key=" + alleleKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { String alleleType = rs.getString("term"); //convert MGI terminology to ours props.setProperty("mouseType",alleleType); } if (markerKey > 0) { query = "select symbol,name from MRK_Marker where _Marker_key=" + markerKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { //todo set gene properties String symbol = rs.getString("symbol"); String name = rs.getString("name"); props.setProperty("geneSymbol",symbol); props.setProperty("geneName",name); query = "select numericPart from ACC_Accession WHERE _MGIType_key=2 " + "and _Object_key=" + markerKey + " and prefixPart='MGI:' and preferred=1"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { int geneMgiId = rs.getInt("numericPart"); props.setProperty("geneMgiID",Integer.toString(geneMgiId)); //todo set gene MGI accession ID } } } else { Log.Info("No markers for allele MGI: " + accessionID); } query = "select _Refs_key from mgi_reference_assoc ref inner join mgi_refassoctype ty using(_refassoctype_key) where _Object_key=" + alleleKey + " and assoctype='Original'"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { int refKey = rs.getInt("_Refs_key"); query = "select _primary,title from BIB_refs where _Refs_key=" + refKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { props.setProperty("pubMedAuthor", rs.getString("_primary")); props.setProperty("pubMedTitle", rs.getString("title")); } query = "select accID from ACC_Accession where _MGIType_key=1 and _Object_key=" + refKey + " and prefixPart is NULL"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { props.setProperty("pubMedID", rs.getString("accID")); } else { query = "select accID from ACC_Accession where _MGIType_key=1 and _Object_key=" + refKey + "and prefixPart='MGI:'"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { props.setProperty("referenceMgiAccessionId", rs.getString("accID")); } } } StringBuilder sb = new StringBuilder(); //Fixed import comment from MGI_notechunk table does not exist query = "select note " + "from MGI_Note n, MGI_NoteType t "+ "where n._NoteType_key = t._NoteType_key " + "and n._MGIType_key = 11 " + "and _object_key="+ alleleKey + " " + "and noteType='Molecular'"; if (verbose) System.out.println(query); rs= stmt.executeQuery(query); while (rs.next()) { sb.append(rs.getString("note")); } if (sb.length() > 0) { props.setProperty("description", sb.toString()); } else { Log.Error("No description found for allele w/ accID: " + accessionID + ". Ran this query:\n" + query); } } } catch (Exception e) { Log.Error("Error fetching Allele details from MGI",e); ImportStatusTracker.UpdateStatus(importTaskId, ImportStatus.ERROR); ImportStatusTracker.AppendMessage(importTaskId,"Error fetching allele details: " + e.getMessage()); } finally { if(connection != null) { try { connection.close(); } catch(SQLException ex) { ex.printStackTrace(); } } ImportStatusTracker.SetProgress(importTaskId, 1); } if(verbose){ for(int mgiId : results.keySet()){ Properties props = results.get(mgiId); System.out.println("Properties for MGI:" + mgiId); for (String prop : props.stringPropertyNames()) { String value = props.getProperty(prop); System.out.println(prop + ": " + value); } } } return results; } // private static void getOfficialMouseNames(String[] accessionIds) // { // Connection connection = null; // Statement stmt = null; // ResultSet rs = null; // // try // { // connection = connect(); // stmt = connection.createStatement(); // for(String accessionID : accessionIds) // { // if (verbose) System.out.println("Fetching details for MGI:" + accessionID); // //Properties props = new Properties(); // //TODO get the comment?? // String query = "select ACC_Accession.numericPart, symbol,ALL_ALLELE.name " + // "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " + // "left join ALL_ALLELE on ACC_Accession._Object_key = ALL_Allele._Allele_key " + // "where accID='" + accessionID + "' " + // "and ACC_Accession._MGIType_key = 11 "; // if (verbose) System.out.println(query); // rs = stmt.executeQuery(query); // if(!rs.next()) // { // //accession ID not found, return early // Log.Info("No matching alleles found for accession ID: " + accessionID); // continue; // } // // int id = rs.getInt(1); // //String symbol = rs.getString(2); // String name = rs.getString(3); // // if (verbose) System.out.println(name + "\t" + id); // // } // // } // catch (Exception e) // { // e.printStackTrace(); // } // finally // { // if(connection != null) // { // try // { // connection.close(); // } // catch(SQLException ex) // { // ex.printStackTrace(); // } // } // } // // } private static String getAlleleQueryFromOGFID(String OGFID) { return "select a2.accId from acc_accession a1, all_allele e, acc_accession a2 where a1.accid='" + OGFID + "' and a1._mgitype_key=2 and a2._mgitype_key=11 and a2._object_key=e._allele_key and e._marker_key=a1._object_key"; } public static MGIResult DoReferenceQuery(String refAccessionID) { return doMGIQuery(refAccessionID, MGI_REFERENCE, "Pubmed ID not found. Please confirm that you entered it correctly."); } public static MGIResult DoMGIModifiedGeneQuery(String geneAccessionID) { return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene that is modified in the mouse being submitted and re-enter the ID."); } public static MGIResult DoMGIInsertGeneQuery(String geneAccessionID) { return doMGIQuery(geneAccessionID, MGI_MARKER, "Valid Accession ID, but not a gene detail page."); } public static MGIResult DoMGIExpressedGeneQuery(String geneAccessionID) { return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene that is expressed and re-enter the ID."); } public static MGIResult DoMGIKnockedinGeneQuery(String geneAccessionID) { return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene into which the expressed sequence was inserted and re-enter the ID."); } public static MGIResult DoMGIAlleleQuery(String alleleAccessionID) { return doMGIQuery(alleleAccessionID, MGI_ALLELE, "This is a valid Accession ID, but it does not correspond to an allele detail page. Click on the link to see what it does correspond to. Find the allele detail page for the mouse being submitted and re-enter the ID."); } public static MGIResult DoMGITransgeneQuery(String transgeneAccessionID) { return doMGIQuery(transgeneAccessionID, MGI_ALLELE, "This is a valid Accession ID, but it does not correspond to a transgene detail page. Click on the link to see what it does correspond to. Find the transgene detail page for the mouse being submitted and re-enter the ID. "); } private static Connection connect() throws Exception { if (!initialized) { throw new Exception("Tried to connect to MGI before initializing connection parameters!"); } ConnectionThread t = new ConnectionThread(); t.start(); long timeoutMillis = 10000; t.join(timeoutMillis); if (t.isAlive()) { //timeout reached, kill thread and throw timeout exception t.interrupt(); Log.Info("Timeout reached, interrupting mgi connection thread"); } return t.getConnection(); } private static class ConnectionThread extends Thread { private Connection connection = null; public ConnectionThread() { super(); } @Override public void run() { try { // Load the JDBC driver: MySQL MM JDBC driver Class.forName(databaseDriverName); // Create a new connection to MGI setConnection(DriverManager.getConnection(databaseConnectionString)); if (verbose) System.out.println("Successfully connected to MGI, returning connection"); } catch (ClassNotFoundException e) { Log.Error("Failed to connect to MGI:", e); } catch (SQLException e) { Log.Error("Failed to connect to MGI:", e); } } void setConnection(Connection connection) { this.connection = connection; } Connection getConnection() { return connection; } } }
musIndex/mouseinventory
src/main/java/edu/ucsf/mousedatabase/MGIConnect.java
7,204
// int id = rs.getInt(1);
line_comment
nl
package edu.ucsf.mousedatabase; import java.sql.*; import java.util.Collection; import java.util.HashMap; import java.util.Properties; import java.lang.Thread; import edu.ucsf.mousedatabase.beans.MouseSubmission; import edu.ucsf.mousedatabase.dataimport.ImportStatusTracker; import edu.ucsf.mousedatabase.dataimport.ImportStatusTracker.ImportStatus; import edu.ucsf.mousedatabase.objects.MGIResult; public class MGIConnect { //todo get these from the mgi database, they shouldn't be static public static int MGI_MARKER = 2; public static int MGI_ALLELE = 11; public static int MGI_REFERENCE = 1; public static int MGI_MARKER_OTHER_GENOME_FEATURE = 9; public static final String pmDBurl = "http://www.ncbi.nlm.nih.gov/pubmed/"; public static final String pmDBurlTail = "?dopt=Abstract"; public static final String mgiDBurl = "http://www.informatics.jax.org/accession/MGI:"; private static String databaseConnectionString; private static String databaseDriverName; private static boolean initialized = false; public static boolean verbose = false; public static boolean Initialize(String databaseDriverName, String databaseConnectionString) { if (initialized) { return false; } MGIConnect.databaseDriverName = databaseDriverName; MGIConnect.databaseConnectionString = databaseConnectionString; initialized = true; return true; } // TODO make this method public and make callers figure out typeIDs public static MGIResult doMGIQuery(String accessionID, int expectedTypeID, String wrongTypeString) { return doMGIQuery(accessionID, expectedTypeID, wrongTypeString, true); } public static MGIResult doMGIQuery(String accessionID, int expectedTypeID, String wrongTypeString, boolean offlineOK) { MGIResult result = new MGIResult(); result.setAccessionID(accessionID); result.setType(expectedTypeID); String query = ""; Connection connection = null; String accID = accessionID; if (expectedTypeID != MGI_REFERENCE) { accID = "MGI:" + accessionID; } try { connection = connect(); query = "select _Accession_key, ACC_Accession._MGIType_key, primaryKeyName, _Object_key, tableName " + "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " + "where accID='" + accID + "' " + "and ACC_Accession._MGIType_key in(" + MGI_MARKER + "," + MGI_ALLELE + "," + MGI_REFERENCE + ")"; // the last line above is kind of a hack because sometimes you get multiple // results for accession ids, such as evidence types java.sql.Statement stmt = connection.createStatement(); if (verbose) System.out.println(query); ResultSet rs = stmt.executeQuery(query); if (rs.next()) { // int accessionKey = rs.getInt("_Accession_key"); int mgiTypeKey = rs.getInt("_MGIType_key"); String primaryKeyName = rs.getString("primaryKeyName"); int objectKey = rs.getInt("_Object_key"); String tableName = rs.getString("tableName"); if (mgiTypeKey != expectedTypeID) // TODO lookup type id, don't hard code it { if (verbose) System.out.println("type key mismatch! " + mgiTypeKey + " != " + expectedTypeID); // see if this is a possible other genome feature issue if (mgiTypeKey == MGI_MARKER && expectedTypeID == MGI_ALLELE) { query = "select * from " + tableName + " where " + primaryKeyName + "=" + objectKey; if (verbose) System.out.println(query); stmt = connection.createStatement(); rs = stmt.executeQuery(query); if (rs.next() && rs.getInt("_Marker_Type_key") == MGI_MARKER_OTHER_GENOME_FEATURE) { query = getAlleleQueryFromOGFID(accessionID); stmt = connection.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { String allelePageID = rs.getString("accID"); return doMGIQuery(allelePageID, expectedTypeID, wrongTypeString); } } } result.setValid(false); result.setErrorString(wrongTypeString); } else { query = "select * from " + tableName + " where " + primaryKeyName + "=" + objectKey; if (verbose) System.out.println(query); stmt = connection.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { if (mgiTypeKey == MGI_ALLELE) { result.setSymbol(rs.getString("symbol")); result.setName(trimOfficialName(rs.getString("name"))); result.setValid(true); query = "select term from ALL_Allele aa inner join voc_term voc on aa._Allele_Type_key=voc._Term_key where _Allele_key=" + objectKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { String alleleType = rs.getString("term"); if (verbose) System.out.println("allele type: " + alleleType); if (alleleType.equalsIgnoreCase("QTL")) { result.setValid(false); result.setErrorString( "This ID corresponds to a QTL variant. Please go back to step 2 and do a submission for the relevant inbred strain"); } } } else if (mgiTypeKey == MGI_MARKER) { result.setSymbol(rs.getString("symbol")); result.setName(rs.getString("name")); result.setValid(true); } else if (mgiTypeKey == MGI_REFERENCE) { result.setAuthors(rs.getString("authors")); result.setTitle(rs.getString("title")); result.setValid(true); } } } } else { if (expectedTypeID == MGI_REFERENCE) { result.setErrorString("Not found. Please confirm that you have the correct Pubmed ID."); result.setValid(false); } else { result.setErrorString("Not found in MGI database. Confirm that you have the correct Accession ID"); result.setValid(false); } } } catch (NullPointerException e) { result.setValid(offlineOK); result.setErrorString("Connection to MGI timed out."); result.setTitle(result.getErrorString()); result.setAuthors(""); result.setName(result.getErrorString()); result.setSymbol(""); result.setMgiConnectionTimedout(true); e.printStackTrace(System.err); } catch (Exception e) { result.setValid(offlineOK); result.setErrorString( "MGI database connection unavailable. This is to be expected late at night on weekdays. Please manually verify that this is the correct ID"); result.setTitle(result.getErrorString()); result.setAuthors(""); result.setName(result.getErrorString()); result.setSymbol(""); result.setMgiOffline(true); // System.err.println(query); e.printStackTrace(System.err); } finally { if (connection != null) { try { connection.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } // Close the connection to MGI. return result; } public static HashMap<Integer, MouseSubmission> SubmissionFromMGI(Collection<Integer> accessionIDs, int importTaskId) { HashMap<Integer, MouseSubmission> newSubmissions = new HashMap<Integer, MouseSubmission>(); // TODO validate accession IDs first? so that we don't have to duplicate logic // like // checking that it isn't a QTL or other genome feature HashMap<Integer, Properties> results = getPropertiesFromAlleleMgiID(accessionIDs, importTaskId); for (int key : results.keySet()) { Properties props = results.get(key); if (props != null && !props.isEmpty()) { MouseSubmission sub = new MouseSubmission(); sub.setMouseMGIID(Integer.toString(key)); sub.setIsPublished("No"); sub.setHolderFacility("unassigned"); sub.setHolderName("unassigned"); sub.setMouseType("unknown"); if (verbose) System.out.println("*****************************"); if (verbose) System.out.println("Allele MGI ID: " + key); String geneId = null; StringBuilder propertyList = new StringBuilder(); for (String prop : props.stringPropertyNames()) { String value = props.getProperty(prop); if (verbose) System.out.println(prop + ": " + value); if (prop.equals("mouseName")) { sub.setOfficialMouseName(trimOfficialName(value)); } else if (prop.equals("mouseType")) { propertyList.append("*" + prop + ":* " + value + "\r\n"); //targeted captures knockout or knockin mice, can be transchromosomal if(value.startsWith("Targeted")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); if(value.contains("knock-out")) { } else if (value.contains("knock-in")) { } } //Added Radiation induced muations -EW else if (value.startsWith("Radiation")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else if (value.startsWith("Spontaneous")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else if (value.startsWith("Transgenic")) { sub.setMouseType("Transgene"); sub.setTransgenicType("undetermined"); sub.setTGExpressedSequence("undetermined"); //extract from 'Transgenic (Reporter)' //or 'Transgenic (random, expressed)' //or 'Transgenic (Cre/Flp)' } else if (value.startsWith("Gene trapped")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else if (value.startsWith("Not Applicable")) { sub.setMouseType("Inbred Strain"); //TODO ???? // Allele MGI ID: 3579311 // mouseType : Not Applicable // pubMedTitle : THE AKR THYMIC ANTIGEN AND ITS DISTRIBUTION IN LEUKEMIAS AND NERVOUS TISSUES. // gene name : thymus cell antigen 1, theta // gene symbol : Thy1 // mouseName : a variant // pubMedID : 14207060 // pubMedAuthor : REIF AE // officialSymbol : Thy1<a> // gene mgi ID : 98747 } else if (value.startsWith("QTL")) { sub.setMouseType("Inbred Strain"); } //Enodnuclease-mediated mice will switch to this type -EW else if (value.startsWith("Endonuclease-mediated")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } //Transposon induced added to Mutant Allele category -EW else if (value.startsWith("Transposon induced")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else if (value.startsWith("Chemically")) { sub.setMouseType("Mutant Allele"); sub.setMAModificationType("undetermined"); } else { sub.setMouseType("undetermined"); } } else if (prop.equals("mutationType")) { propertyList.append("*" + prop + ":* " + value + "\r\n"); //????? if(value.equals("Insertion")) { //sub.setTransgenicType("random insertion"); } else if (value.equals("Single point mutation")) { } else if (value.equals("Other")) { } else if (value.equals("Intragenic deletion")) { } } else if(prop.equals("pubMedID")) { sub.setIsPublished("Yes"); sub.setPMID(value); } else if(prop.equals("geneMgiID")) { geneId = value; } else if (prop.equals("officialSymbol")) { sub.setOfficialSymbol(value); } else if (prop.equals("description")) { sub.setComment(value); } } if (sub.getMouseType() != null && sub.getMouseType().equals("Mutant Allele")) { sub.setMAMgiGeneID(geneId); } sub.setComment(sub.getComment() + "\r\n\r\nRaw properties returned from MGI:\r\n" + propertyList.toString()); newSubmissions.put(key, sub); } else { newSubmissions.put(key,null); } } return newSubmissions; } private static String trimOfficialName(String rawName) { return rawName; // if (rawName == null || rawName.isEmpty()) // { // return rawName; // } // // if (rawName.toLowerCase().indexOf("targeted mutation ") < 0 && rawName.toLowerCase().indexOf("transgene insertion ") < 0) // { // return rawName; // } // // int index = rawName.indexOf(',') + 1; // if (index >= rawName.length() - 1) // { // return rawName; // } // return rawName.substring(index).trim(); } public static HashMap<Integer,Properties> getPropertiesFromAlleleMgiID(Collection<Integer> accessionIDs, int importTaskId) { HashMap<Integer,Properties> results = new HashMap<Integer,Properties>(); Connection connection = null; Statement stmt = null; ResultSet rs = null; ImportStatusTracker.UpdateHeader(importTaskId, "Downloading Allele data from MGI (Task 2 of 3)"); ImportStatusTracker.SetProgress(importTaskId, 0); double mgiIdNumber = 1; double mgiCount = accessionIDs.size(); try { connection = connect(); stmt = connection.createStatement(); for(int accessionID : accessionIDs) { ImportStatusTracker.SetProgress(importTaskId, mgiIdNumber / mgiCount); mgiIdNumber++; if (accessionID < 0) { Log.Info("Ignored invalid accession ID: " + accessionID); continue; } if (verbose) System.out.println("Fetching details for MGI:" + accessionID); Properties props = new Properties(); results.put(accessionID, props); //TODO get the comment?? String query = "select _Object_key " + "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " + "where accid='MGI:" + accessionID + "' " + "and ACC_Accession._MGIType_key=11"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if(!rs.next()) { //accession ID not found, return early Log.Info("No matching alleles found for accession ID: " + accessionID); continue; } int alleleKey = rs.getInt("_Object_key"); query = "select _Marker_key,name,symbol from ALL_Allele where _Allele_key=" + alleleKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if(!rs.next()) { //no data in allele table, very strange if (verbose) System.out.println("No data found for allele key: " + alleleKey); continue; } props.setProperty("mouseName",rs.getString("name")); props.setProperty("officialSymbol",rs.getString("symbol")); ImportStatusTracker.AppendMessage(importTaskId, "MGI:" + accessionID + " -> " + HTMLUtilities.getCommentForDisplay(props.getProperty("officialSymbol"))); int markerKey = rs.getInt("_Marker_key"); query = "select term from ALL_Allele_Mutation mut inner join voc_term voc on mut._mutation_key=voc._term_key where _Allele_key=" + alleleKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { String mutation = rs.getString("term"); //convert MGI terminology to ours props.setProperty("mutationType",mutation); } query = "select term from ALL_Allele aa inner join voc_term voc on aa._Allele_Type_key=voc._Term_key where _Allele_key=" + alleleKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { String alleleType = rs.getString("term"); //convert MGI terminology to ours props.setProperty("mouseType",alleleType); } if (markerKey > 0) { query = "select symbol,name from MRK_Marker where _Marker_key=" + markerKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { //todo set gene properties String symbol = rs.getString("symbol"); String name = rs.getString("name"); props.setProperty("geneSymbol",symbol); props.setProperty("geneName",name); query = "select numericPart from ACC_Accession WHERE _MGIType_key=2 " + "and _Object_key=" + markerKey + " and prefixPart='MGI:' and preferred=1"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { int geneMgiId = rs.getInt("numericPart"); props.setProperty("geneMgiID",Integer.toString(geneMgiId)); //todo set gene MGI accession ID } } } else { Log.Info("No markers for allele MGI: " + accessionID); } query = "select _Refs_key from mgi_reference_assoc ref inner join mgi_refassoctype ty using(_refassoctype_key) where _Object_key=" + alleleKey + " and assoctype='Original'"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { int refKey = rs.getInt("_Refs_key"); query = "select _primary,title from BIB_refs where _Refs_key=" + refKey; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { props.setProperty("pubMedAuthor", rs.getString("_primary")); props.setProperty("pubMedTitle", rs.getString("title")); } query = "select accID from ACC_Accession where _MGIType_key=1 and _Object_key=" + refKey + " and prefixPart is NULL"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { props.setProperty("pubMedID", rs.getString("accID")); } else { query = "select accID from ACC_Accession where _MGIType_key=1 and _Object_key=" + refKey + "and prefixPart='MGI:'"; if (verbose) System.out.println(query); rs = stmt.executeQuery(query); if (rs.next()) { props.setProperty("referenceMgiAccessionId", rs.getString("accID")); } } } StringBuilder sb = new StringBuilder(); //Fixed import comment from MGI_notechunk table does not exist query = "select note " + "from MGI_Note n, MGI_NoteType t "+ "where n._NoteType_key = t._NoteType_key " + "and n._MGIType_key = 11 " + "and _object_key="+ alleleKey + " " + "and noteType='Molecular'"; if (verbose) System.out.println(query); rs= stmt.executeQuery(query); while (rs.next()) { sb.append(rs.getString("note")); } if (sb.length() > 0) { props.setProperty("description", sb.toString()); } else { Log.Error("No description found for allele w/ accID: " + accessionID + ". Ran this query:\n" + query); } } } catch (Exception e) { Log.Error("Error fetching Allele details from MGI",e); ImportStatusTracker.UpdateStatus(importTaskId, ImportStatus.ERROR); ImportStatusTracker.AppendMessage(importTaskId,"Error fetching allele details: " + e.getMessage()); } finally { if(connection != null) { try { connection.close(); } catch(SQLException ex) { ex.printStackTrace(); } } ImportStatusTracker.SetProgress(importTaskId, 1); } if(verbose){ for(int mgiId : results.keySet()){ Properties props = results.get(mgiId); System.out.println("Properties for MGI:" + mgiId); for (String prop : props.stringPropertyNames()) { String value = props.getProperty(prop); System.out.println(prop + ": " + value); } } } return results; } // private static void getOfficialMouseNames(String[] accessionIds) // { // Connection connection = null; // Statement stmt = null; // ResultSet rs = null; // // try // { // connection = connect(); // stmt = connection.createStatement(); // for(String accessionID : accessionIds) // { // if (verbose) System.out.println("Fetching details for MGI:" + accessionID); // //Properties props = new Properties(); // //TODO get the comment?? // String query = "select ACC_Accession.numericPart, symbol,ALL_ALLELE.name " + // "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " + // "left join ALL_ALLELE on ACC_Accession._Object_key = ALL_Allele._Allele_key " + // "where accID='" + accessionID + "' " + // "and ACC_Accession._MGIType_key = 11 "; // if (verbose) System.out.println(query); // rs = stmt.executeQuery(query); // if(!rs.next()) // { // //accession ID not found, return early // Log.Info("No matching alleles found for accession ID: " + accessionID); // continue; // } // // int id<SUF> // //String symbol = rs.getString(2); // String name = rs.getString(3); // // if (verbose) System.out.println(name + "\t" + id); // // } // // } // catch (Exception e) // { // e.printStackTrace(); // } // finally // { // if(connection != null) // { // try // { // connection.close(); // } // catch(SQLException ex) // { // ex.printStackTrace(); // } // } // } // // } private static String getAlleleQueryFromOGFID(String OGFID) { return "select a2.accId from acc_accession a1, all_allele e, acc_accession a2 where a1.accid='" + OGFID + "' and a1._mgitype_key=2 and a2._mgitype_key=11 and a2._object_key=e._allele_key and e._marker_key=a1._object_key"; } public static MGIResult DoReferenceQuery(String refAccessionID) { return doMGIQuery(refAccessionID, MGI_REFERENCE, "Pubmed ID not found. Please confirm that you entered it correctly."); } public static MGIResult DoMGIModifiedGeneQuery(String geneAccessionID) { return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene that is modified in the mouse being submitted and re-enter the ID."); } public static MGIResult DoMGIInsertGeneQuery(String geneAccessionID) { return doMGIQuery(geneAccessionID, MGI_MARKER, "Valid Accession ID, but not a gene detail page."); } public static MGIResult DoMGIExpressedGeneQuery(String geneAccessionID) { return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene that is expressed and re-enter the ID."); } public static MGIResult DoMGIKnockedinGeneQuery(String geneAccessionID) { return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene into which the expressed sequence was inserted and re-enter the ID."); } public static MGIResult DoMGIAlleleQuery(String alleleAccessionID) { return doMGIQuery(alleleAccessionID, MGI_ALLELE, "This is a valid Accession ID, but it does not correspond to an allele detail page. Click on the link to see what it does correspond to. Find the allele detail page for the mouse being submitted and re-enter the ID."); } public static MGIResult DoMGITransgeneQuery(String transgeneAccessionID) { return doMGIQuery(transgeneAccessionID, MGI_ALLELE, "This is a valid Accession ID, but it does not correspond to a transgene detail page. Click on the link to see what it does correspond to. Find the transgene detail page for the mouse being submitted and re-enter the ID. "); } private static Connection connect() throws Exception { if (!initialized) { throw new Exception("Tried to connect to MGI before initializing connection parameters!"); } ConnectionThread t = new ConnectionThread(); t.start(); long timeoutMillis = 10000; t.join(timeoutMillis); if (t.isAlive()) { //timeout reached, kill thread and throw timeout exception t.interrupt(); Log.Info("Timeout reached, interrupting mgi connection thread"); } return t.getConnection(); } private static class ConnectionThread extends Thread { private Connection connection = null; public ConnectionThread() { super(); } @Override public void run() { try { // Load the JDBC driver: MySQL MM JDBC driver Class.forName(databaseDriverName); // Create a new connection to MGI setConnection(DriverManager.getConnection(databaseConnectionString)); if (verbose) System.out.println("Successfully connected to MGI, returning connection"); } catch (ClassNotFoundException e) { Log.Error("Failed to connect to MGI:", e); } catch (SQLException e) { Log.Error("Failed to connect to MGI:", e); } } void setConnection(Connection connection) { this.connection = connection; } Connection getConnection() { return connection; } } }
169859_1
/** * * Copyright 2012-2017 TNO Geologische Dienst Nederland * * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * https://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * * This work was sponsored by the Dutch Rijksoverheid, Basisregistratie * Ondergrond (BRO) Programme (https://bro.pleio.nl/) */ package nl.bro.cpt.gef.main; import static org.fest.assertions.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import java.util.logging.LogRecord; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import nl.bro.cpt.gef.main.util.TestHandler; public class ConverGefTest { @Before public void init() { TestHandler.LOG_RECORDS.clear(); } @After public void cleanup() { TestHandler.LOG_RECORDS.clear(); } private List<String> getMessages() { List<String> messages = new ArrayList<>(); for ( LogRecord record : TestHandler.LOG_RECORDS ) { messages.add( record.getMessage() ); } return messages; } @Test public void testNoArguments() { // -- action ConvertGef.main( new String[0] ); // -- verify List<String> messages = getMessages(); assertThat( messages ).contains( "Missing t option", "Missing r option", "Missing q option" ); } @Test public void testNonExistingFile() { ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "TEST.GEF" } ); List<String> messages = getMessages(); assertThat( messages.toString() ).contains( "kan niet gevonden worden" ); } /** * Ignore tot dat filenaam probleem is opgelost */ @Test @Ignore public void testNormal() { ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "-d", "target", "src/test/resources/CPT-F3b-i3-23913-completion-CPT.GEF", "src/test/resources/CPT-F3b-i3-23913-completion-DISS.GEF" } ); } }
tvcstseng/CPT_GEF_CONVERTER
gef_standalone/src/test/java/nl/bro/cpt/gef/main/ConverGefTest.java
735
/** * Ignore tot dat filenaam probleem is opgelost */
block_comment
nl
/** * * Copyright 2012-2017 TNO Geologische Dienst Nederland * * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * https://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * * This work was sponsored by the Dutch Rijksoverheid, Basisregistratie * Ondergrond (BRO) Programme (https://bro.pleio.nl/) */ package nl.bro.cpt.gef.main; import static org.fest.assertions.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import java.util.logging.LogRecord; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import nl.bro.cpt.gef.main.util.TestHandler; public class ConverGefTest { @Before public void init() { TestHandler.LOG_RECORDS.clear(); } @After public void cleanup() { TestHandler.LOG_RECORDS.clear(); } private List<String> getMessages() { List<String> messages = new ArrayList<>(); for ( LogRecord record : TestHandler.LOG_RECORDS ) { messages.add( record.getMessage() ); } return messages; } @Test public void testNoArguments() { // -- action ConvertGef.main( new String[0] ); // -- verify List<String> messages = getMessages(); assertThat( messages ).contains( "Missing t option", "Missing r option", "Missing q option" ); } @Test public void testNonExistingFile() { ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "TEST.GEF" } ); List<String> messages = getMessages(); assertThat( messages.toString() ).contains( "kan niet gevonden worden" ); } /** * Ignore tot dat<SUF>*/ @Test @Ignore public void testNormal() { ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "-d", "target", "src/test/resources/CPT-F3b-i3-23913-completion-CPT.GEF", "src/test/resources/CPT-F3b-i3-23913-completion-DISS.GEF" } ); } }
83530_4
package com.in28minutes.rest.webservices.restfulwebservices.helloWorld; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.*; import java.util.Locale; // Controller @RestController public class HelloWorldController { @Autowired private MessageSource messageSource; // GET // URI - /hello-world // method - "Hello World" @GetMapping(path = "/hello-world") public String helloWorld() { return "Hello World"; } @GetMapping(path = "/hello-world-bean") public HelloWorldBean helloWorldBean() { return new HelloWorldBean("Hello World"); } // /hello-world-bean/path-variable/in28minutes @GetMapping(path = "/hello-world-bean/path-variable/{name}") public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { return new HelloWorldBean(String.format("Hello World, %s", name)); } @GetMapping(path = "/hello-world-internationalized") public String helloWorldInternationalized( // @RequestHeader(name = "Accept-Language", required = false) Locale locale ) { return messageSource .getMessage("good.morning.message", null, "Default message" //, locale); , LocaleContextHolder.getLocale()); // return "Hello World"; // en = Hello World // nl = Goedemorgen // fr = Bonjour } }
surdav/restful-web-services
src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloWorld/HelloWorldController.java
390
// en = Hello World
line_comment
nl
package com.in28minutes.rest.webservices.restfulwebservices.helloWorld; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.*; import java.util.Locale; // Controller @RestController public class HelloWorldController { @Autowired private MessageSource messageSource; // GET // URI - /hello-world // method - "Hello World" @GetMapping(path = "/hello-world") public String helloWorld() { return "Hello World"; } @GetMapping(path = "/hello-world-bean") public HelloWorldBean helloWorldBean() { return new HelloWorldBean("Hello World"); } // /hello-world-bean/path-variable/in28minutes @GetMapping(path = "/hello-world-bean/path-variable/{name}") public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { return new HelloWorldBean(String.format("Hello World, %s", name)); } @GetMapping(path = "/hello-world-internationalized") public String helloWorldInternationalized( // @RequestHeader(name = "Accept-Language", required = false) Locale locale ) { return messageSource .getMessage("good.morning.message", null, "Default message" //, locale); , LocaleContextHolder.getLocale()); // return "Hello World"; // en =<SUF> // nl = Goedemorgen // fr = Bonjour } }
88318_3
/* * This file is part of the GeoLatte project. * * GeoLatte is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GeoLatte is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GeoLatte. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2010 - 2011 and Ownership of code is shared by: * Qmino bvba - Romeinsestraat 18 - 3001 Heverlee (http://www.qmino.com) * Geovise bvba - Generaal Eisenhowerlei 9 - 2140 Antwerpen (http://www.geovise.com) */ package org.geolatte.geom.codec; import org.geolatte.geom.Geometry; import org.geolatte.geom.GeometryType; import org.geolatte.geom.crs.CoordinateReferenceSystem; import java.util.*; import static org.geolatte.geom.crs.CoordinateReferenceSystems.hasMeasureAxis; import static org.geolatte.geom.crs.CoordinateReferenceSystems.hasVerticalAxis; /** * Punctuation and keywords for Postgis EWKT/WKT representations. * * @author Karel Maesen, Geovise BVBA, 2011 */ class PostgisWktVariant extends WktVariant { protected static final WktEmptyGeometryToken EMPTY = new WktEmptyGeometryToken(); private final static List<WktGeometryToken> GEOMETRIES = new ArrayList<WktGeometryToken>(); private final static Set<WktKeywordToken> KEYWORDS; protected PostgisWktVariant() { super('(', ')', ','); } static { //TODO -- this doesn't work well with LinearRings (geometry type doesn't match 1-1 to WKT types) //register the geometry tokens add(GeometryType.POINT, false, "POINT"); add(GeometryType.POINT, true, "POINTM"); add(GeometryType.LINESTRING, true, "LINESTRINGM"); add(GeometryType.LINESTRING, false, "LINESTRING"); add(GeometryType.POLYGON, false, "POLYGON"); add(GeometryType.POLYGON, true, "POLYGONM"); add(GeometryType.MULTIPOINT, true, "MULTIPOINTM"); add(GeometryType.MULTIPOINT, false, "MULTIPOINT"); add(GeometryType.MULTILINESTRING, false, "MULTILINESTRING"); add(GeometryType.MULTILINESTRING, true, "MULTILINESTRINGM"); add(GeometryType.MULTIPOLYGON, false, "MULTIPOLYGON"); add(GeometryType.MULTIPOLYGON, true, "MULTIPOLYGONM"); add(GeometryType.GEOMETRYCOLLECTION, false, "GEOMETRYCOLLECTION"); add(GeometryType.GEOMETRYCOLLECTION, true, "GEOMETRYCOLLECTIONM"); //create an unmodifiable set of all pattern tokens Set<WktKeywordToken> allTokens = new HashSet<WktKeywordToken>(); allTokens.addAll(GEOMETRIES); allTokens.add(EMPTY); KEYWORDS = Collections.unmodifiableSet(allTokens); } private static void add(GeometryType type, boolean isMeasured, String word) { GEOMETRIES.add(new WktGeometryToken(word, type, isMeasured)); } public String wordFor(Geometry geometry, boolean ignoreMeasureMarker) { for (WktGeometryToken candidate : GEOMETRIES) { if (sameGeometryType(candidate, geometry) && hasSameMeasuredSuffixInWkt(candidate, geometry, ignoreMeasureMarker)) { return candidate.getPattern().toString(); } } throw new IllegalStateException( String.format( "Geometry type %s not recognized.", geometry.getClass().getName() ) ); } @Override protected Set<WktKeywordToken> getWktKeywords() { return KEYWORDS; } public WktKeywordToken getEmpty() { return EMPTY; } protected boolean sameGeometryType(WktGeometryToken token, Geometry geometry) { //TODO Need better handling for difference WKT/Geometry types. See comment above . return token.getType() == geometry.getGeometryType() || (token.getType().equals(GeometryType.LINESTRING) && geometry.getGeometryType().equals(GeometryType.LINEARRING)); } /** * Determines whether the candidate has the same measured 'M' suffix as the geometry in WKT. * The suffix is only added when the geometry is measured and not 3D. * * POINT(x y): 2D point, * POINT(x y z): 3D point, * POINTM(x y m): 2D measured point (with 'M' suffix), * POINT(x y z m): 3D measured point (without 'M' suffix) * * * @param candidate The candidate wkt geometry token * @param geometry The geometry to check the candidate wkt geometry token for * @param ignoreMeasureMarker when set to true, this method returns true iff the candidate token is not measured * @return The candidate is measured if and only if the geometry is measured and not 3D */ private boolean hasSameMeasuredSuffixInWkt(WktGeometryToken candidate, Geometry geometry, boolean ignoreMeasureMarker) { if (ignoreMeasureMarker) { return !candidate.isMeasured(); } CoordinateReferenceSystem<?> crs = geometry.getCoordinateReferenceSystem(); if (hasMeasureAxis(crs) && ! hasVerticalAxis(crs)) { return candidate.isMeasured(); } else { return !candidate.isMeasured(); } } }
breglerj/geolatte-geom
geom/src/main/java/org/geolatte/geom/codec/PostgisWktVariant.java
1,485
//register the geometry tokens
line_comment
nl
/* * This file is part of the GeoLatte project. * * GeoLatte is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GeoLatte is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GeoLatte. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2010 - 2011 and Ownership of code is shared by: * Qmino bvba - Romeinsestraat 18 - 3001 Heverlee (http://www.qmino.com) * Geovise bvba - Generaal Eisenhowerlei 9 - 2140 Antwerpen (http://www.geovise.com) */ package org.geolatte.geom.codec; import org.geolatte.geom.Geometry; import org.geolatte.geom.GeometryType; import org.geolatte.geom.crs.CoordinateReferenceSystem; import java.util.*; import static org.geolatte.geom.crs.CoordinateReferenceSystems.hasMeasureAxis; import static org.geolatte.geom.crs.CoordinateReferenceSystems.hasVerticalAxis; /** * Punctuation and keywords for Postgis EWKT/WKT representations. * * @author Karel Maesen, Geovise BVBA, 2011 */ class PostgisWktVariant extends WktVariant { protected static final WktEmptyGeometryToken EMPTY = new WktEmptyGeometryToken(); private final static List<WktGeometryToken> GEOMETRIES = new ArrayList<WktGeometryToken>(); private final static Set<WktKeywordToken> KEYWORDS; protected PostgisWktVariant() { super('(', ')', ','); } static { //TODO -- this doesn't work well with LinearRings (geometry type doesn't match 1-1 to WKT types) //register the<SUF> add(GeometryType.POINT, false, "POINT"); add(GeometryType.POINT, true, "POINTM"); add(GeometryType.LINESTRING, true, "LINESTRINGM"); add(GeometryType.LINESTRING, false, "LINESTRING"); add(GeometryType.POLYGON, false, "POLYGON"); add(GeometryType.POLYGON, true, "POLYGONM"); add(GeometryType.MULTIPOINT, true, "MULTIPOINTM"); add(GeometryType.MULTIPOINT, false, "MULTIPOINT"); add(GeometryType.MULTILINESTRING, false, "MULTILINESTRING"); add(GeometryType.MULTILINESTRING, true, "MULTILINESTRINGM"); add(GeometryType.MULTIPOLYGON, false, "MULTIPOLYGON"); add(GeometryType.MULTIPOLYGON, true, "MULTIPOLYGONM"); add(GeometryType.GEOMETRYCOLLECTION, false, "GEOMETRYCOLLECTION"); add(GeometryType.GEOMETRYCOLLECTION, true, "GEOMETRYCOLLECTIONM"); //create an unmodifiable set of all pattern tokens Set<WktKeywordToken> allTokens = new HashSet<WktKeywordToken>(); allTokens.addAll(GEOMETRIES); allTokens.add(EMPTY); KEYWORDS = Collections.unmodifiableSet(allTokens); } private static void add(GeometryType type, boolean isMeasured, String word) { GEOMETRIES.add(new WktGeometryToken(word, type, isMeasured)); } public String wordFor(Geometry geometry, boolean ignoreMeasureMarker) { for (WktGeometryToken candidate : GEOMETRIES) { if (sameGeometryType(candidate, geometry) && hasSameMeasuredSuffixInWkt(candidate, geometry, ignoreMeasureMarker)) { return candidate.getPattern().toString(); } } throw new IllegalStateException( String.format( "Geometry type %s not recognized.", geometry.getClass().getName() ) ); } @Override protected Set<WktKeywordToken> getWktKeywords() { return KEYWORDS; } public WktKeywordToken getEmpty() { return EMPTY; } protected boolean sameGeometryType(WktGeometryToken token, Geometry geometry) { //TODO Need better handling for difference WKT/Geometry types. See comment above . return token.getType() == geometry.getGeometryType() || (token.getType().equals(GeometryType.LINESTRING) && geometry.getGeometryType().equals(GeometryType.LINEARRING)); } /** * Determines whether the candidate has the same measured 'M' suffix as the geometry in WKT. * The suffix is only added when the geometry is measured and not 3D. * * POINT(x y): 2D point, * POINT(x y z): 3D point, * POINTM(x y m): 2D measured point (with 'M' suffix), * POINT(x y z m): 3D measured point (without 'M' suffix) * * * @param candidate The candidate wkt geometry token * @param geometry The geometry to check the candidate wkt geometry token for * @param ignoreMeasureMarker when set to true, this method returns true iff the candidate token is not measured * @return The candidate is measured if and only if the geometry is measured and not 3D */ private boolean hasSameMeasuredSuffixInWkt(WktGeometryToken candidate, Geometry geometry, boolean ignoreMeasureMarker) { if (ignoreMeasureMarker) { return !candidate.isMeasured(); } CoordinateReferenceSystem<?> crs = geometry.getCoordinateReferenceSystem(); if (hasMeasureAxis(crs) && ! hasVerticalAxis(crs)) { return candidate.isMeasured(); } else { return !candidate.isMeasured(); } } }
94462_0
package nl.inholland.mijneersteapi.service; import nl.inholland.mijneersteapi.model.User; import nl.inholland.mijneersteapi.repository.UserRepository; import nl.inholland.mijneersteapi.security.JwtTokenProvider; import org.apache.tomcat.util.net.openssl.ciphers.Authentication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; @Service public class UserService { @Autowired UserRepository userRepository; @Autowired PasswordEncoder passwordEncoder; @Autowired AuthenticationManager authenticationManager; @Autowired JwtTokenProvider jwtTokenProvider; public String login(String username, String password) { try { //login authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); User user = userRepository.findByUsername(username); return jwtTokenProvider.createToken(username, user.getRoles()); } catch (AuthenticationException ex) { throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Login failed."); } } public User add(User user) { //Check of het al bestaat if (userRepository.findByUsername(user.getUsername()) == null) { user.setPassword(passwordEncoder.encode((user.getPassword()))); return userRepository.save(user); } else { throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Username already being used."); } } }
SanderBrijer/java-api
src/main/java/nl/inholland/mijneersteapi/service/UserService.java
434
//Check of het al bestaat
line_comment
nl
package nl.inholland.mijneersteapi.service; import nl.inholland.mijneersteapi.model.User; import nl.inholland.mijneersteapi.repository.UserRepository; import nl.inholland.mijneersteapi.security.JwtTokenProvider; import org.apache.tomcat.util.net.openssl.ciphers.Authentication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; @Service public class UserService { @Autowired UserRepository userRepository; @Autowired PasswordEncoder passwordEncoder; @Autowired AuthenticationManager authenticationManager; @Autowired JwtTokenProvider jwtTokenProvider; public String login(String username, String password) { try { //login authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); User user = userRepository.findByUsername(username); return jwtTokenProvider.createToken(username, user.getRoles()); } catch (AuthenticationException ex) { throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Login failed."); } } public User add(User user) { //Check of<SUF> if (userRepository.findByUsername(user.getUsername()) == null) { user.setPassword(passwordEncoder.encode((user.getPassword()))); return userRepository.save(user); } else { throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Username already being used."); } } }
135928_1
package controllers; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import models.Projet; import java.io.IOException; import java.util.ArrayList; import dataLayer.DataProjetManager; /** * Servlet implementation class DirecteurServlet */ public class DirecteurServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DirecteurServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String choixDirecteur = request.getParameter("choix"); if(choixDirecteur.equals("nouveau")) { request.getRequestDispatcher("nouveauProjet.jsp").forward(request, response); } if(choixDirecteur.equals("consulter")) { ArrayList<String> Noms = DataProjetManager.getListeNoms(); request.setAttribute("projetNoms", Noms); request.getRequestDispatcher("consulterProjet.jsp").forward(request, response); } } }
heniEl10/ProjetJEE
src/main/java/controllers/DirecteurServlet.java
407
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
package controllers; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import models.Projet; import java.io.IOException; import java.util.ArrayList; import dataLayer.DataProjetManager; /** * Servlet implementation class DirecteurServlet */ public class DirecteurServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() <SUF>*/ public DirecteurServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String choixDirecteur = request.getParameter("choix"); if(choixDirecteur.equals("nouveau")) { request.getRequestDispatcher("nouveauProjet.jsp").forward(request, response); } if(choixDirecteur.equals("consulter")) { ArrayList<String> Noms = DataProjetManager.getListeNoms(); request.setAttribute("projetNoms", Noms); request.getRequestDispatcher("consulterProjet.jsp").forward(request, response); } } }
125609_0
/* * @(#)Agent.java 2015-7-24 上午09:49:34 * javaagent * Copyright 2015 wenshuo, Inc. All rights reserved. * wenshuo PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.wenshuo.agent; import java.lang.instrument.Instrumentation; import com.wenshuo.agent.applog.AppLogFactory; import com.wenshuo.agent.applog.IAppLog; import com.wenshuo.agent.log.ExecuteLogUtils; import com.wenshuo.agent.transformer.AgentLogClassFileTransformer; /** * Agent * * @author dingjsh */ public class Agent { private static IAppLog log = AppLogFactory.getAppLog(Agent.class); public static void premain(String agentArs, Instrumentation inst) { // 初始化配置 ConfigUtils.initProperties(agentArs); log.info("javaagent启动成功,将自动记录方法的执行次数和时间,日志文件路径:" + ConfigUtils.getLogFileName()); ExecuteLogUtils.init(); inst.addTransformer(new AgentLogClassFileTransformer()); } }
dingjs/javaagent
src/main/java/com/wenshuo/agent/Agent.java
282
/* * @(#)Agent.java 2015-7-24 上午09:49:34 * javaagent * Copyright 2015 wenshuo, Inc. All rights reserved. * wenshuo PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */
block_comment
nl
/* * @(#)Agent.java 2015-7-24 上午09:49:34<SUF>*/ package com.wenshuo.agent; import java.lang.instrument.Instrumentation; import com.wenshuo.agent.applog.AppLogFactory; import com.wenshuo.agent.applog.IAppLog; import com.wenshuo.agent.log.ExecuteLogUtils; import com.wenshuo.agent.transformer.AgentLogClassFileTransformer; /** * Agent * * @author dingjsh */ public class Agent { private static IAppLog log = AppLogFactory.getAppLog(Agent.class); public static void premain(String agentArs, Instrumentation inst) { // 初始化配置 ConfigUtils.initProperties(agentArs); log.info("javaagent启动成功,将自动记录方法的执行次数和时间,日志文件路径:" + ConfigUtils.getLogFileName()); ExecuteLogUtils.init(); inst.addTransformer(new AgentLogClassFileTransformer()); } }
200227_3
/* * Drifting Souls 2 * Copyright (c) 2006 Christopher Jung * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package net.driftingsouls.ds2.server.entities; import net.driftingsouls.ds2.server.Locatable; import net.driftingsouls.ds2.server.Location; import net.driftingsouls.ds2.server.MutableLocation; import net.driftingsouls.ds2.server.WellKnownConfigValue; import net.driftingsouls.ds2.server.framework.ConfigService; import net.driftingsouls.ds2.server.framework.Context; import net.driftingsouls.ds2.server.framework.ContextMap; import net.driftingsouls.ds2.server.repositories.NebulaRepository; import net.driftingsouls.ds2.server.ships.Ship; import net.driftingsouls.ds2.server.ships.ShipTypeData; import net.driftingsouls.ds2.server.ships.Ships; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.Index; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.Table; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.IntConsumer; import java.util.stream.Collectors; /** * Ein Nebel. * @author Christopher Jung * */ @Entity @Table(name="nebel") @Immutable @BatchSize(size=50) public class Nebel implements Locatable { /** * Gibt den Nebeltyp an der angegebenen Position zurueck. Sollte sich an der Position kein * Nebel befinden, wird <code>null</code> zurueckgegeben. * @param loc Die Position * @return Der Nebeltyp oder <code>null</code> */ @SuppressWarnings("unchecked") public static synchronized Typ getNebula(Location loc) { return NebulaRepository.getInstance().getNebula(loc); } /** * Nebeltyp. */ public enum Typ { /** * Normaler Deutnebel. */ MEDIUM_DEUT(0, 7, false, 0, 0,"normaler Deuteriumnebel"), /** * Schwacher Deutnebel. */ LOW_DEUT(1, 5, false, -1, 0,"schwacher Deuteriumnebel"), /** * Dichter Deutnebel. */ STRONG_DEUT(2, 11, false, 1, 0,"starker Deuteriumnebel"), /** * Schwacher EMP-Nebel. */ LOW_EMP(3, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"schwacher EMP-Nebel"), /** * Normaler EMP-Nebel. */ MEDIUM_EMP(4, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"normaler EMP-Nebel"), /** * Dichter EMP-Nebel. */ STRONG_EMP(5, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"dichter EMP-Nebel" ), /** * Schadensnebel. */ DAMAGE(6, 7, false, Integer.MIN_VALUE, 0, "Schadensnebel"); private final int code; private final int minScansize; private final boolean emp; private final int deutfaktor; private final String beschreibung; Typ(int code, int minScansize, boolean emp, int deutfaktor, int minScanbareSchiffsgroesse, String beschreibung) { this.code = code; this.minScansize = minScansize; this.emp = emp; this.deutfaktor = deutfaktor; this.beschreibung = beschreibung; } /** * Erzeugt aus Typenids (Datenbank) enums. * * @param type Typenid. * @return Passendes enum. */ public static Typ getType(int type) { switch(type) { case 0: return MEDIUM_DEUT; case 1: return LOW_DEUT; case 2: return STRONG_DEUT; case 3: return LOW_EMP; case 4: return MEDIUM_EMP; case 5: return STRONG_EMP; case 6: return DAMAGE; default: throw new IllegalArgumentException("There's no nebula with type:" + type); } } /** * @return Die Beschreibung des Nebels. */ public String getDescription() { return this.beschreibung; } /** * @return Der Typcode des Nebels. */ public int getCode() { return this.code; } /** * @return Die Groesse ab der ein Schiff sichtbar ist in dem Nebel. */ public int getMinScansize() { return this.minScansize; } /** * Gibt zurueck, ob es sich um einen EMP-Nebel handelt. * @return <code>true</code> falls dem so ist */ public boolean isEmp() { return emp; } public boolean isDamage() { return getCode() == 6; } /** * Gibt zurueck, ob ein Nebel diesen Typs das Sammeln * von Deuterium ermoeglicht. * @return <code>true</code> falls dem so ist */ public boolean isDeuteriumNebel() { return this.deutfaktor > Integer.MIN_VALUE; } /** * Gibt den durch die Eigenschaften des Nebels modifizierten * Deuterium-Faktor beim Sammeln von Deuterium * in einem Nebel diesem Typs zurueck. Falls der modifizierte * Faktor <code>0</code> betraegt ist kein Sammeln moeglich. * Falls es sich nicht um einen Nebel handelt, * der das Sammeln von Deuterium erlaubt, wird * der Faktor immer auf <code>0</code> reduziert. * @param faktor Der zu modifizierende Faktor * @return Der modifizierte Deuteriumfaktor */ public long modifiziereDeutFaktor(long faktor) { if( faktor <= 0 ) { return 0; } long modfaktor = faktor + this.deutfaktor; if( modfaktor < 0 ) { return 0; } return modfaktor; } /** * Gibt alle Nebeltypen zurueck, die die Eigenschaft * EMP haben. * @return Die Liste * @see #isEmp() */ public static Set<Typ> getEmpNebula() { return Arrays.stream(values()) .filter(Typ::isEmp) .collect(Collectors.toCollection(HashSet::new)); } public static Set<Typ> getDamageNebula() { Set<Typ> nebula = new HashSet<>(); nebula.add(DAMAGE); return nebula; } /** * Gibt an, ob Schiffe in diesem Feld scannen duerfen. * * @return <code>true</code>, wenn sie scannen duerfen, sonst <code>false</code>. */ public boolean allowsScan() { return !this.emp; } /** * Gibt das Bild des Nebeltyps zurueck (als Pfad). * Der Pfad ist relativ zum data-Verzeichnis. * * @return Das Bild des Nebels als Pfad. */ public String getImage() { return "data/starmap/fog"+this.ordinal()+"/fog"+this.ordinal()+".png"; } /** * Damage the ship according to the nebula type. * * @param ship The ship to be damaged. */ public void damageShip(Ship ship, ConfigService config) { // Currently only damage nebula do damage and we only have one type of damage nebula // so no different effects if(this != DAMAGE) { return; } //gedockte Schiffe werden bereits ueber ihr Traegerschiff verarbeitet (siehe damageInternal()) if(ship.isDocked()) { return; } double shieldDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_SHIELD)/100.d; double ablativeDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_ABLATIVE)/100.d; double hullDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_HULL)/100.d; double subsystemDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_SUBSYSTEM)/100.d; damageInternal(ship, 1.0d, shieldDamageFactor, ablativeDamageFactor, hullDamageFactor, subsystemDamageFactor); } /** * Damage a ship for flying into a damage nebula. * * @param ship Ship to damage * @param globalDamageFactor Dampens initial damage to this ship (needed for docked ships, which should not take more damage than their carrier) */ private void damageInternal(Ship ship, double globalDamageFactor, double shieldDamageFactor, double ablativeDamageFactor, double hullDamageFactor, double subsystemDamageFactor) { /* Damage is applied according to the following formula ("ship type" always includes modules here): - Find the maximum shield of this ship type - Remove damage from shields - If ships shields are at zero find how much damage remains and apply it as percentage on the next level, e.g. We want to damage the shields for 1000, but only 900 shields remain, so we calculate the armor damage (according to the armor formula) and then only remove 10% (the remainder from shields) When shields are down externally attached ships (e.g. containers) start taking damage. */ double modifiedShieldDamageFactor = shieldDamageFactor * globalDamageFactor; ShipTypeData shipType = ship.getTypeData(); int shieldDamage = (int)Math.floor(shipType.getShields() * modifiedShieldDamageFactor); int shieldsRemaining = ship.getShields() - shieldDamage; //Damage we wanted to do, but couldn't cause there wasn't enough shield strength left int shieldOverflow = 0; if(shieldsRemaining < 0) { shieldOverflow = Math.abs(shieldsRemaining); shieldsRemaining = 0; } ship.setShields(shieldsRemaining); //No damage left after shields if(shieldOverflow == 0 && shipType.getShields() != 0) { return; } double shieldOverflowFactor = 1.0d; if(shipType.getShields() != 0) { shieldOverflowFactor = (double)shieldOverflow / (double)shieldDamage; } int ablativeDamage = (int)Math.floor(shipType.getAblativeArmor() * ablativeDamageFactor * shieldOverflowFactor); int ablativeRemaining = ship.getAblativeArmor() - ablativeDamage; int ablativeOverflow = 0; if(ablativeRemaining < 0) { ablativeOverflow = Math.abs(ablativeRemaining); ablativeRemaining = 0; } ship.setAblativeArmor(ablativeRemaining); // No more shields left to save them -> also damage docked ships for (Ship dockedShip : ship.getDockedShips()) { damageInternal(dockedShip, shieldOverflowFactor, shieldDamageFactor, ablativeDamageFactor, hullDamageFactor, subsystemDamageFactor); } //No damage left after ablative armor if(ablativeOverflow == 0 && shipType.getAblativeArmor() != 0) { return; } double ablativeOverflowFactor = 1.0d; if(shipType.getAblativeArmor() != 0) { ablativeOverflowFactor = (double)ablativeOverflow / (double)ablativeDamage; } int hullDamage = (int)Math.floor(shipType.getHull() * hullDamageFactor * ablativeOverflowFactor); int hullRemaining = ship.getHull() - hullDamage; if(hullRemaining <= 0) { ship.destroy(); return; } else { ship.setHull(hullRemaining); } //Damage each subsystem individually, so you don't get very good or bad results based on one roll damageSubsystem(subsystemDamageFactor, ship.getComm(), ship::setComm); damageSubsystem(subsystemDamageFactor, ship.getEngine(), ship::setEngine); damageSubsystem(subsystemDamageFactor, ship.getSensors(), ship::setSensors); damageSubsystem(subsystemDamageFactor, ship.getWeapons(), ship::setWeapons); } private void damageSubsystem(double subsystemDamageFactor, int subsystemBefore, IntConsumer subsystem) { double modifiedSubsystemDamageFactor = ThreadLocalRandom.current().nextDouble() * subsystemDamageFactor; int subsystemDamage = (int)Math.floor(100 * modifiedSubsystemDamageFactor); int subsystemRemaining = Math.max(0, subsystemBefore - subsystemDamage); subsystem.accept(subsystemRemaining); } } @EmbeddedId private MutableLocation loc; @Index(name="idx_nebulatype") @Enumerated @Column(nullable = false) private Typ type; public MutableLocation getLoc() { return loc; } public void setLoc(MutableLocation loc) { this.loc = loc; } /** * Konstruktor. * */ public Nebel() { // EMPTY } /** * Erstellt einen neuen Nebel. * @param loc Die Position des Nebels * @param type Der Typ */ public Nebel(MutableLocation loc, Typ type) { this.loc = loc; this.type = type; } /** * Gibt das System des Nebels zurueck. * @return Das System */ public int getSystem() { return loc.getSystem(); } /** * Gibt den Typ des Nebels zurueck. * @return Der Typ */ public Typ getType() { return this.type; } /** * Gibt die X-Koordinate zurueck. * @return Die X-Koordinate */ public int getX() { return loc.getX(); } /** * Gibt die Y-Koordinate zurueck. * @return Die Y-Koordinate */ public int getY() { return loc.getY(); } /** * Gibt die Position des Nebels zurueck. * @return Die Position */ @Override public Location getLocation() { return loc.getLocation(); } /** * Gibt an, ob Schiffe in diesem Feld scannen duerfen. * * @return <code>true</code>, wenn sie scannen duerfen, sonst <code>false</code>. */ public boolean allowsScan() { return this.type.allowsScan(); } /** * Gibt das Bild des Nebels zurueck (als Pfad). * Der Pfad ist relativ zum data-Verzeichnis. * * @return Das Bild des Nebels als Pfad. */ public String getImage() { return this.type.getImage(); } }
sgift/driftingsouls
game/src/main/java/net/driftingsouls/ds2/server/entities/Nebel.java
4,014
/** * Nebeltyp. */
block_comment
nl
/* * Drifting Souls 2 * Copyright (c) 2006 Christopher Jung * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package net.driftingsouls.ds2.server.entities; import net.driftingsouls.ds2.server.Locatable; import net.driftingsouls.ds2.server.Location; import net.driftingsouls.ds2.server.MutableLocation; import net.driftingsouls.ds2.server.WellKnownConfigValue; import net.driftingsouls.ds2.server.framework.ConfigService; import net.driftingsouls.ds2.server.framework.Context; import net.driftingsouls.ds2.server.framework.ContextMap; import net.driftingsouls.ds2.server.repositories.NebulaRepository; import net.driftingsouls.ds2.server.ships.Ship; import net.driftingsouls.ds2.server.ships.ShipTypeData; import net.driftingsouls.ds2.server.ships.Ships; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.Index; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.Table; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.IntConsumer; import java.util.stream.Collectors; /** * Ein Nebel. * @author Christopher Jung * */ @Entity @Table(name="nebel") @Immutable @BatchSize(size=50) public class Nebel implements Locatable { /** * Gibt den Nebeltyp an der angegebenen Position zurueck. Sollte sich an der Position kein * Nebel befinden, wird <code>null</code> zurueckgegeben. * @param loc Die Position * @return Der Nebeltyp oder <code>null</code> */ @SuppressWarnings("unchecked") public static synchronized Typ getNebula(Location loc) { return NebulaRepository.getInstance().getNebula(loc); } /** * Nebeltyp. <SUF>*/ public enum Typ { /** * Normaler Deutnebel. */ MEDIUM_DEUT(0, 7, false, 0, 0,"normaler Deuteriumnebel"), /** * Schwacher Deutnebel. */ LOW_DEUT(1, 5, false, -1, 0,"schwacher Deuteriumnebel"), /** * Dichter Deutnebel. */ STRONG_DEUT(2, 11, false, 1, 0,"starker Deuteriumnebel"), /** * Schwacher EMP-Nebel. */ LOW_EMP(3, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"schwacher EMP-Nebel"), /** * Normaler EMP-Nebel. */ MEDIUM_EMP(4, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"normaler EMP-Nebel"), /** * Dichter EMP-Nebel. */ STRONG_EMP(5, Integer.MAX_VALUE, true, Integer.MIN_VALUE, 0,"dichter EMP-Nebel" ), /** * Schadensnebel. */ DAMAGE(6, 7, false, Integer.MIN_VALUE, 0, "Schadensnebel"); private final int code; private final int minScansize; private final boolean emp; private final int deutfaktor; private final String beschreibung; Typ(int code, int minScansize, boolean emp, int deutfaktor, int minScanbareSchiffsgroesse, String beschreibung) { this.code = code; this.minScansize = minScansize; this.emp = emp; this.deutfaktor = deutfaktor; this.beschreibung = beschreibung; } /** * Erzeugt aus Typenids (Datenbank) enums. * * @param type Typenid. * @return Passendes enum. */ public static Typ getType(int type) { switch(type) { case 0: return MEDIUM_DEUT; case 1: return LOW_DEUT; case 2: return STRONG_DEUT; case 3: return LOW_EMP; case 4: return MEDIUM_EMP; case 5: return STRONG_EMP; case 6: return DAMAGE; default: throw new IllegalArgumentException("There's no nebula with type:" + type); } } /** * @return Die Beschreibung des Nebels. */ public String getDescription() { return this.beschreibung; } /** * @return Der Typcode des Nebels. */ public int getCode() { return this.code; } /** * @return Die Groesse ab der ein Schiff sichtbar ist in dem Nebel. */ public int getMinScansize() { return this.minScansize; } /** * Gibt zurueck, ob es sich um einen EMP-Nebel handelt. * @return <code>true</code> falls dem so ist */ public boolean isEmp() { return emp; } public boolean isDamage() { return getCode() == 6; } /** * Gibt zurueck, ob ein Nebel diesen Typs das Sammeln * von Deuterium ermoeglicht. * @return <code>true</code> falls dem so ist */ public boolean isDeuteriumNebel() { return this.deutfaktor > Integer.MIN_VALUE; } /** * Gibt den durch die Eigenschaften des Nebels modifizierten * Deuterium-Faktor beim Sammeln von Deuterium * in einem Nebel diesem Typs zurueck. Falls der modifizierte * Faktor <code>0</code> betraegt ist kein Sammeln moeglich. * Falls es sich nicht um einen Nebel handelt, * der das Sammeln von Deuterium erlaubt, wird * der Faktor immer auf <code>0</code> reduziert. * @param faktor Der zu modifizierende Faktor * @return Der modifizierte Deuteriumfaktor */ public long modifiziereDeutFaktor(long faktor) { if( faktor <= 0 ) { return 0; } long modfaktor = faktor + this.deutfaktor; if( modfaktor < 0 ) { return 0; } return modfaktor; } /** * Gibt alle Nebeltypen zurueck, die die Eigenschaft * EMP haben. * @return Die Liste * @see #isEmp() */ public static Set<Typ> getEmpNebula() { return Arrays.stream(values()) .filter(Typ::isEmp) .collect(Collectors.toCollection(HashSet::new)); } public static Set<Typ> getDamageNebula() { Set<Typ> nebula = new HashSet<>(); nebula.add(DAMAGE); return nebula; } /** * Gibt an, ob Schiffe in diesem Feld scannen duerfen. * * @return <code>true</code>, wenn sie scannen duerfen, sonst <code>false</code>. */ public boolean allowsScan() { return !this.emp; } /** * Gibt das Bild des Nebeltyps zurueck (als Pfad). * Der Pfad ist relativ zum data-Verzeichnis. * * @return Das Bild des Nebels als Pfad. */ public String getImage() { return "data/starmap/fog"+this.ordinal()+"/fog"+this.ordinal()+".png"; } /** * Damage the ship according to the nebula type. * * @param ship The ship to be damaged. */ public void damageShip(Ship ship, ConfigService config) { // Currently only damage nebula do damage and we only have one type of damage nebula // so no different effects if(this != DAMAGE) { return; } //gedockte Schiffe werden bereits ueber ihr Traegerschiff verarbeitet (siehe damageInternal()) if(ship.isDocked()) { return; } double shieldDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_SHIELD)/100.d; double ablativeDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_ABLATIVE)/100.d; double hullDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_HULL)/100.d; double subsystemDamageFactor = config.getValue(WellKnownConfigValue.NEBULA_DAMAGE_SUBSYSTEM)/100.d; damageInternal(ship, 1.0d, shieldDamageFactor, ablativeDamageFactor, hullDamageFactor, subsystemDamageFactor); } /** * Damage a ship for flying into a damage nebula. * * @param ship Ship to damage * @param globalDamageFactor Dampens initial damage to this ship (needed for docked ships, which should not take more damage than their carrier) */ private void damageInternal(Ship ship, double globalDamageFactor, double shieldDamageFactor, double ablativeDamageFactor, double hullDamageFactor, double subsystemDamageFactor) { /* Damage is applied according to the following formula ("ship type" always includes modules here): - Find the maximum shield of this ship type - Remove damage from shields - If ships shields are at zero find how much damage remains and apply it as percentage on the next level, e.g. We want to damage the shields for 1000, but only 900 shields remain, so we calculate the armor damage (according to the armor formula) and then only remove 10% (the remainder from shields) When shields are down externally attached ships (e.g. containers) start taking damage. */ double modifiedShieldDamageFactor = shieldDamageFactor * globalDamageFactor; ShipTypeData shipType = ship.getTypeData(); int shieldDamage = (int)Math.floor(shipType.getShields() * modifiedShieldDamageFactor); int shieldsRemaining = ship.getShields() - shieldDamage; //Damage we wanted to do, but couldn't cause there wasn't enough shield strength left int shieldOverflow = 0; if(shieldsRemaining < 0) { shieldOverflow = Math.abs(shieldsRemaining); shieldsRemaining = 0; } ship.setShields(shieldsRemaining); //No damage left after shields if(shieldOverflow == 0 && shipType.getShields() != 0) { return; } double shieldOverflowFactor = 1.0d; if(shipType.getShields() != 0) { shieldOverflowFactor = (double)shieldOverflow / (double)shieldDamage; } int ablativeDamage = (int)Math.floor(shipType.getAblativeArmor() * ablativeDamageFactor * shieldOverflowFactor); int ablativeRemaining = ship.getAblativeArmor() - ablativeDamage; int ablativeOverflow = 0; if(ablativeRemaining < 0) { ablativeOverflow = Math.abs(ablativeRemaining); ablativeRemaining = 0; } ship.setAblativeArmor(ablativeRemaining); // No more shields left to save them -> also damage docked ships for (Ship dockedShip : ship.getDockedShips()) { damageInternal(dockedShip, shieldOverflowFactor, shieldDamageFactor, ablativeDamageFactor, hullDamageFactor, subsystemDamageFactor); } //No damage left after ablative armor if(ablativeOverflow == 0 && shipType.getAblativeArmor() != 0) { return; } double ablativeOverflowFactor = 1.0d; if(shipType.getAblativeArmor() != 0) { ablativeOverflowFactor = (double)ablativeOverflow / (double)ablativeDamage; } int hullDamage = (int)Math.floor(shipType.getHull() * hullDamageFactor * ablativeOverflowFactor); int hullRemaining = ship.getHull() - hullDamage; if(hullRemaining <= 0) { ship.destroy(); return; } else { ship.setHull(hullRemaining); } //Damage each subsystem individually, so you don't get very good or bad results based on one roll damageSubsystem(subsystemDamageFactor, ship.getComm(), ship::setComm); damageSubsystem(subsystemDamageFactor, ship.getEngine(), ship::setEngine); damageSubsystem(subsystemDamageFactor, ship.getSensors(), ship::setSensors); damageSubsystem(subsystemDamageFactor, ship.getWeapons(), ship::setWeapons); } private void damageSubsystem(double subsystemDamageFactor, int subsystemBefore, IntConsumer subsystem) { double modifiedSubsystemDamageFactor = ThreadLocalRandom.current().nextDouble() * subsystemDamageFactor; int subsystemDamage = (int)Math.floor(100 * modifiedSubsystemDamageFactor); int subsystemRemaining = Math.max(0, subsystemBefore - subsystemDamage); subsystem.accept(subsystemRemaining); } } @EmbeddedId private MutableLocation loc; @Index(name="idx_nebulatype") @Enumerated @Column(nullable = false) private Typ type; public MutableLocation getLoc() { return loc; } public void setLoc(MutableLocation loc) { this.loc = loc; } /** * Konstruktor. * */ public Nebel() { // EMPTY } /** * Erstellt einen neuen Nebel. * @param loc Die Position des Nebels * @param type Der Typ */ public Nebel(MutableLocation loc, Typ type) { this.loc = loc; this.type = type; } /** * Gibt das System des Nebels zurueck. * @return Das System */ public int getSystem() { return loc.getSystem(); } /** * Gibt den Typ des Nebels zurueck. * @return Der Typ */ public Typ getType() { return this.type; } /** * Gibt die X-Koordinate zurueck. * @return Die X-Koordinate */ public int getX() { return loc.getX(); } /** * Gibt die Y-Koordinate zurueck. * @return Die Y-Koordinate */ public int getY() { return loc.getY(); } /** * Gibt die Position des Nebels zurueck. * @return Die Position */ @Override public Location getLocation() { return loc.getLocation(); } /** * Gibt an, ob Schiffe in diesem Feld scannen duerfen. * * @return <code>true</code>, wenn sie scannen duerfen, sonst <code>false</code>. */ public boolean allowsScan() { return this.type.allowsScan(); } /** * Gibt das Bild des Nebels zurueck (als Pfad). * Der Pfad ist relativ zum data-Verzeichnis. * * @return Das Bild des Nebels als Pfad. */ public String getImage() { return this.type.getImage(); } }
53981_33
package juloo.keyboard2; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.KeyEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import juloo.keyboard2.prefs.CustomExtraKeysPreference; import juloo.keyboard2.prefs.ExtraKeysPreference; import juloo.keyboard2.prefs.LayoutsPreference; public final class Config { private final SharedPreferences _prefs; // From resources public final float marginTop; public final float keyPadding; public final float labelTextSize; public final float sublabelTextSize; // From preferences /** [null] represent the [system] layout. */ public List<KeyboardData> layouts; public boolean show_numpad = false; // From the 'numpad_layout' option, also apply to the numeric pane. public boolean inverse_numpad = false; public boolean number_row; public float swipe_dist_px; public float slide_step_px; // Let the system handle vibration when false. public boolean vibrate_custom; // Control the vibration if [vibrate_custom] is true. public long vibrate_duration; public long longPressTimeout; public long longPressInterval; public float margin_bottom; public float keyHeight; public float horizontal_margin; public float key_vertical_margin; public float key_horizontal_margin; public int labelBrightness; // 0 - 255 public int keyboardOpacity; // 0 - 255 public float customBorderRadius; // 0 - 1 public float customBorderLineWidth; // dp public int keyOpacity; // 0 - 255 public int keyActivatedOpacity; // 0 - 255 public boolean double_tap_lock_shift; public float characterSize; // Ratio public int theme; // Values are R.style.* public boolean autocapitalisation; public boolean switch_input_immediate; public boolean pin_entry_enabled; public boolean borderConfig; // Dynamically set public boolean shouldOfferVoiceTyping; public String actionLabel; // Might be 'null' public int actionId; // Meaningful only when 'actionLabel' isn't 'null' public boolean swapEnterActionKey; // Swap the "enter" and "action" keys public ExtraKeys extra_keys_subtype; public Map<KeyValue, KeyboardData.PreferredPos> extra_keys_param; public Map<KeyValue, KeyboardData.PreferredPos> extra_keys_custom; public final IKeyEventHandler handler; public boolean orientation_landscape = false; /** Index in 'layouts' of the currently used layout. See [get_current_layout()] and [set_current_layout()]. */ int current_layout_portrait; int current_layout_landscape; private Config(SharedPreferences prefs, Resources res, IKeyEventHandler h) { _prefs = prefs; // static values marginTop = res.getDimension(R.dimen.margin_top); keyPadding = res.getDimension(R.dimen.key_padding); labelTextSize = 0.33f; sublabelTextSize = 0.22f; // from prefs refresh(res); // initialized later shouldOfferVoiceTyping = false; actionLabel = null; actionId = 0; swapEnterActionKey = false; extra_keys_subtype = null; handler = h; } /* ** Reload prefs */ public void refresh(Resources res) { DisplayMetrics dm = res.getDisplayMetrics(); orientation_landscape = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; // The height of the keyboard is relative to the height of the screen. // This is the height of the keyboard if it have 4 rows. int keyboardHeightPercent; float characterSizeScale = 1.f; String show_numpad_s = _prefs.getString("show_numpad", "never"); show_numpad = "always".equals(show_numpad_s); if (orientation_landscape) { if ("landscape".equals(show_numpad_s)) show_numpad = true; keyboardHeightPercent = _prefs.getInt("keyboard_height_landscape", 50); characterSizeScale = 1.25f; } else { keyboardHeightPercent = _prefs.getInt("keyboard_height", 35); } layouts = LayoutsPreference.load_from_preferences(res, _prefs); inverse_numpad = _prefs.getString("numpad_layout", "default").equals("low_first"); number_row = _prefs.getBoolean("number_row", false); // The baseline for the swipe distance correspond to approximately the // width of a key in portrait mode, as most layouts have 10 columns. // Multipled by the DPI ratio because most swipes are made in the diagonals. // The option value uses an unnamed scale where the baseline is around 25. float dpi_ratio = Math.max(dm.xdpi, dm.ydpi) / Math.min(dm.xdpi, dm.ydpi); float swipe_scaling = Math.min(dm.widthPixels, dm.heightPixels) / 10.f * dpi_ratio; float swipe_dist_value = Float.valueOf(_prefs.getString("swipe_dist", "15")); swipe_dist_px = swipe_dist_value / 25.f * swipe_scaling; slide_step_px = 0.2f * swipe_scaling; vibrate_custom = _prefs.getBoolean("vibrate_custom", false); vibrate_duration = _prefs.getInt("vibrate_duration", 20); longPressTimeout = _prefs.getInt("longpress_timeout", 600); longPressInterval = _prefs.getInt("longpress_interval", 65); margin_bottom = get_dip_pref_oriented(dm, "margin_bottom", 7, 3); key_vertical_margin = get_dip_pref(dm, "key_vertical_margin", 1.5f) / 100; key_horizontal_margin = get_dip_pref(dm, "key_horizontal_margin", 2) / 100; // Label brightness is used as the alpha channel labelBrightness = _prefs.getInt("label_brightness", 100) * 255 / 100; // Keyboard opacity keyboardOpacity = _prefs.getInt("keyboard_opacity", 100) * 255 / 100; keyOpacity = _prefs.getInt("key_opacity", 100) * 255 / 100; keyActivatedOpacity = _prefs.getInt("key_activated_opacity", 100) * 255 / 100; // keyboard border settings borderConfig = _prefs.getBoolean("border_config", false); customBorderRadius = _prefs.getInt("custom_border_radius", 0) / 100.f; customBorderLineWidth = get_dip_pref(dm, "custom_border_line_width", 0); // Do not substract key_vertical_margin from keyHeight because this is done // during rendering. keyHeight = dm.heightPixels * keyboardHeightPercent / 100 / 4; horizontal_margin = get_dip_pref_oriented(dm, "horizontal_margin", 3, 28); double_tap_lock_shift = _prefs.getBoolean("lock_double_tap", false); characterSize = _prefs.getFloat("character_size", 1.f) * characterSizeScale; theme = getThemeId(res, _prefs.getString("theme", "")); autocapitalisation = _prefs.getBoolean("autocapitalisation", true); switch_input_immediate = _prefs.getBoolean("switch_input_immediate", false); extra_keys_param = ExtraKeysPreference.get_extra_keys(_prefs); extra_keys_custom = CustomExtraKeysPreference.get(_prefs); pin_entry_enabled = _prefs.getBoolean("pin_entry_enabled", true); current_layout_portrait = _prefs.getInt("current_layout_portrait", 0); current_layout_landscape = _prefs.getInt("current_layout_landscape", 0); } public int get_current_layout() { return (orientation_landscape) ? current_layout_landscape : current_layout_portrait; } public void set_current_layout(int l) { if (orientation_landscape) current_layout_landscape = l; else current_layout_portrait = l; SharedPreferences.Editor e = _prefs.edit(); e.putInt("current_layout_portrait", current_layout_portrait); e.putInt("current_layout_landscape", current_layout_landscape); e.apply(); } KeyValue action_key() { // Update the name to avoid caching in KeyModifier return (actionLabel == null) ? null : KeyValue.getKeyByName("action").withSymbol(actionLabel); } /** Update the layout according to the configuration. * - Remove the switching key if it isn't needed * - Remove "localized" keys from other locales (not in 'extra_keys') * - Replace the action key to show the right label * - Swap the enter and action keys * - Add the optional numpad and number row * - Add the extra keys */ public KeyboardData modify_layout(KeyboardData kw) { final KeyValue action_key = action_key(); // Extra keys are removed from the set as they are encountered during the // first iteration then automatically added. final Map<KeyValue, KeyboardData.PreferredPos> extra_keys = new HashMap<KeyValue, KeyboardData.PreferredPos>(); final Set<KeyValue> remove_keys = new HashSet<KeyValue>(); // Make sure the config key is accessible to avoid being locked in a custom // layout. extra_keys.put(KeyValue.getKeyByName("config"), KeyboardData.PreferredPos.ANYWHERE); extra_keys.putAll(extra_keys_param); extra_keys.putAll(extra_keys_custom); if (extra_keys_subtype != null) { Set<KeyValue> present = new HashSet<KeyValue>(); present.addAll(kw.getKeys().keySet()); present.addAll(extra_keys_param.keySet()); present.addAll(extra_keys_custom.keySet()); extra_keys_subtype.compute(extra_keys, new ExtraKeys.Query(kw.script, present)); } KeyboardData.Row number_row = null; if (this.number_row && !show_numpad) number_row = modify_number_row(KeyboardData.number_row, kw); if (number_row != null) remove_keys.addAll(number_row.getKeys(0).keySet()); kw = kw.mapKeys(new KeyboardData.MapKeyValues() { public KeyValue apply(KeyValue key, boolean localized) { boolean is_extra_key = extra_keys.containsKey(key); if (is_extra_key) extra_keys.remove(key); if (localized && !is_extra_key) return null; if (remove_keys.contains(key)) return null; switch (key.getKind()) { case Event: switch (key.getEvent()) { case CHANGE_METHOD_PICKER: if (switch_input_immediate) return KeyValue.getKeyByName("change_method_prev"); return key; case ACTION: return (swapEnterActionKey && action_key != null) ? KeyValue.getKeyByName("enter") : action_key; case SWITCH_FORWARD: return (layouts.size() > 1) ? key : null; case SWITCH_BACKWARD: return (layouts.size() > 2) ? key : null; case SWITCH_VOICE_TYPING: case SWITCH_VOICE_TYPING_CHOOSER: return shouldOfferVoiceTyping ? key : null; } break; case Keyevent: switch (key.getKeyevent()) { case KeyEvent.KEYCODE_ENTER: return (swapEnterActionKey && action_key != null) ? action_key : key; } break; case Modifier: switch (key.getModifier()) { case SHIFT: if (double_tap_lock_shift) return key.withFlags(key.getFlags() | KeyValue.FLAG_LOCK); } break; } return key; } }); if (show_numpad) kw = kw.addNumPad(modify_numpad(KeyboardData.num_pad, kw)); if (number_row != null) kw = kw.addTopRow(number_row); if (extra_keys.size() > 0) kw = kw.addExtraKeys(extra_keys.entrySet().iterator()); return kw; } /** Handle the numpad layout. The [main_kw] is used to adapt the numpad to the main layout's script. */ public KeyboardData modify_numpad(KeyboardData kw, KeyboardData main_kw) { final KeyValue action_key = action_key(); final KeyModifier.Map_char map_digit = KeyModifier.modify_numpad_script(main_kw.numpad_script); return kw.mapKeys(new KeyboardData.MapKeyValues() { public KeyValue apply(KeyValue key, boolean localized) { switch (key.getKind()) { case Event: switch (key.getEvent()) { case ACTION: return (swapEnterActionKey && action_key != null) ? KeyValue.getKeyByName("enter") : action_key; } break; case Keyevent: switch (key.getKeyevent()) { case KeyEvent.KEYCODE_ENTER: return (swapEnterActionKey && action_key != null) ? action_key : key; } break; case Char: char prev_c = key.getChar(); char c = prev_c; if (inverse_numpad) c = inverse_numpad_char(c); String modified = map_digit.apply(c); if (modified != null) // Was modified by script return KeyValue.makeStringKey(modified); if (prev_c != c) // Was inverted return key.withChar(c); break; } return key; } }); } static KeyboardData.MapKeyValues numpad_script_map(String numpad_script) { final KeyModifier.Map_char map_digit = KeyModifier.modify_numpad_script(numpad_script); return new KeyboardData.MapKeyValues() { public KeyValue apply(KeyValue key, boolean localized) { switch (key.getKind()) { case Char: String modified = map_digit.apply(key.getChar()); if (modified != null) return KeyValue.makeStringKey(modified); break; } return key; } }; } /** Modify the pin entry layout. [main_kw] is used to map the digits into the same script. */ public KeyboardData modify_pinentry(KeyboardData kw, KeyboardData main_kw) { return kw.mapKeys(numpad_script_map(main_kw.numpad_script)); } /** Modify the number row according to [main_kw]'s script. */ public KeyboardData.Row modify_number_row(KeyboardData.Row row, KeyboardData main_kw) { return row.mapKeys(numpad_script_map(main_kw.numpad_script)); } private float get_dip_pref(DisplayMetrics dm, String pref_name, float def) { float value; try { value = _prefs.getInt(pref_name, -1); } catch (Exception e) { value = _prefs.getFloat(pref_name, -1f); } if (value < 0f) value = def; return (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm)); } /** [get_dip_pref] depending on orientation. */ float get_dip_pref_oriented(DisplayMetrics dm, String pref_base_name, float def_port, float def_land) { String suffix = orientation_landscape ? "_landscape" : "_portrait"; float def = orientation_landscape ? def_land : def_port; return get_dip_pref(dm, pref_base_name + suffix, def); } private int getThemeId(Resources res, String theme_name) { switch (theme_name) { case "light": return R.style.Light; case "black": return R.style.Black; case "altblack": return R.style.AltBlack; case "dark": return R.style.Dark; case "white": return R.style.White; case "epaper": return R.style.ePaper; case "desert": return R.style.Desert; case "jungle": return R.style.Jungle; default: case "system": int night_mode = res.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; if ((night_mode & Configuration.UI_MODE_NIGHT_NO) != 0) return R.style.Light; return R.style.Dark; } } char inverse_numpad_char(char c) { switch (c) { case '7': return '1'; case '8': return '2'; case '9': return '3'; case '1': return '7'; case '2': return '8'; case '3': return '9'; default: return c; } } private static Config _globalConfig = null; public static void initGlobalConfig(SharedPreferences prefs, Resources res, IKeyEventHandler handler) { migrate(prefs); _globalConfig = new Config(prefs, res, handler); } public static Config globalConfig() { return _globalConfig; } public static SharedPreferences globalPrefs() { return _globalConfig._prefs; } public static interface IKeyEventHandler { public void key_down(KeyValue value, boolean is_swipe); public void key_up(KeyValue value, Pointers.Modifiers mods); public void mods_changed(Pointers.Modifiers mods); } /** Config migrations. */ private static int CONFIG_VERSION = 1; public static void migrate(SharedPreferences prefs) { int saved_version = prefs.getInt("version", 0); Logs.debug_config_migration(saved_version, CONFIG_VERSION); if (saved_version == CONFIG_VERSION) return; SharedPreferences.Editor e = prefs.edit(); e.putInt("version", CONFIG_VERSION); // Migrations might run on an empty [prefs] for new installs, in this case // they set the default values of complex options. switch (saved_version) // Fallback switch { case 0: // Primary, secondary and custom layout options are merged into the new // Layouts option. This also sets the default value. List<LayoutsPreference.Layout> l = new ArrayList<LayoutsPreference.Layout>(); l.add(migrate_layout(prefs.getString("layout", "system"))); String snd_layout = prefs.getString("second_layout", "none"); if (snd_layout != null && !snd_layout.equals("none")) l.add(migrate_layout(snd_layout)); String custom_layout = prefs.getString("custom_layout", ""); if (custom_layout != null && !custom_layout.equals("")) l.add(LayoutsPreference.CustomLayout.parse(custom_layout)); LayoutsPreference.save_to_preferences(e, l); case 1: default: break; } e.apply(); } private static LayoutsPreference.Layout migrate_layout(String name) { if (name == null || name.equals("system")) return new LayoutsPreference.SystemLayout(); return new LayoutsPreference.NamedLayout(name); } }
Julow/Unexpected-Keyboard
srcs/juloo.keyboard2/Config.java
5,113
/** [get_dip_pref] depending on orientation. */
block_comment
nl
package juloo.keyboard2; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.KeyEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import juloo.keyboard2.prefs.CustomExtraKeysPreference; import juloo.keyboard2.prefs.ExtraKeysPreference; import juloo.keyboard2.prefs.LayoutsPreference; public final class Config { private final SharedPreferences _prefs; // From resources public final float marginTop; public final float keyPadding; public final float labelTextSize; public final float sublabelTextSize; // From preferences /** [null] represent the [system] layout. */ public List<KeyboardData> layouts; public boolean show_numpad = false; // From the 'numpad_layout' option, also apply to the numeric pane. public boolean inverse_numpad = false; public boolean number_row; public float swipe_dist_px; public float slide_step_px; // Let the system handle vibration when false. public boolean vibrate_custom; // Control the vibration if [vibrate_custom] is true. public long vibrate_duration; public long longPressTimeout; public long longPressInterval; public float margin_bottom; public float keyHeight; public float horizontal_margin; public float key_vertical_margin; public float key_horizontal_margin; public int labelBrightness; // 0 - 255 public int keyboardOpacity; // 0 - 255 public float customBorderRadius; // 0 - 1 public float customBorderLineWidth; // dp public int keyOpacity; // 0 - 255 public int keyActivatedOpacity; // 0 - 255 public boolean double_tap_lock_shift; public float characterSize; // Ratio public int theme; // Values are R.style.* public boolean autocapitalisation; public boolean switch_input_immediate; public boolean pin_entry_enabled; public boolean borderConfig; // Dynamically set public boolean shouldOfferVoiceTyping; public String actionLabel; // Might be 'null' public int actionId; // Meaningful only when 'actionLabel' isn't 'null' public boolean swapEnterActionKey; // Swap the "enter" and "action" keys public ExtraKeys extra_keys_subtype; public Map<KeyValue, KeyboardData.PreferredPos> extra_keys_param; public Map<KeyValue, KeyboardData.PreferredPos> extra_keys_custom; public final IKeyEventHandler handler; public boolean orientation_landscape = false; /** Index in 'layouts' of the currently used layout. See [get_current_layout()] and [set_current_layout()]. */ int current_layout_portrait; int current_layout_landscape; private Config(SharedPreferences prefs, Resources res, IKeyEventHandler h) { _prefs = prefs; // static values marginTop = res.getDimension(R.dimen.margin_top); keyPadding = res.getDimension(R.dimen.key_padding); labelTextSize = 0.33f; sublabelTextSize = 0.22f; // from prefs refresh(res); // initialized later shouldOfferVoiceTyping = false; actionLabel = null; actionId = 0; swapEnterActionKey = false; extra_keys_subtype = null; handler = h; } /* ** Reload prefs */ public void refresh(Resources res) { DisplayMetrics dm = res.getDisplayMetrics(); orientation_landscape = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; // The height of the keyboard is relative to the height of the screen. // This is the height of the keyboard if it have 4 rows. int keyboardHeightPercent; float characterSizeScale = 1.f; String show_numpad_s = _prefs.getString("show_numpad", "never"); show_numpad = "always".equals(show_numpad_s); if (orientation_landscape) { if ("landscape".equals(show_numpad_s)) show_numpad = true; keyboardHeightPercent = _prefs.getInt("keyboard_height_landscape", 50); characterSizeScale = 1.25f; } else { keyboardHeightPercent = _prefs.getInt("keyboard_height", 35); } layouts = LayoutsPreference.load_from_preferences(res, _prefs); inverse_numpad = _prefs.getString("numpad_layout", "default").equals("low_first"); number_row = _prefs.getBoolean("number_row", false); // The baseline for the swipe distance correspond to approximately the // width of a key in portrait mode, as most layouts have 10 columns. // Multipled by the DPI ratio because most swipes are made in the diagonals. // The option value uses an unnamed scale where the baseline is around 25. float dpi_ratio = Math.max(dm.xdpi, dm.ydpi) / Math.min(dm.xdpi, dm.ydpi); float swipe_scaling = Math.min(dm.widthPixels, dm.heightPixels) / 10.f * dpi_ratio; float swipe_dist_value = Float.valueOf(_prefs.getString("swipe_dist", "15")); swipe_dist_px = swipe_dist_value / 25.f * swipe_scaling; slide_step_px = 0.2f * swipe_scaling; vibrate_custom = _prefs.getBoolean("vibrate_custom", false); vibrate_duration = _prefs.getInt("vibrate_duration", 20); longPressTimeout = _prefs.getInt("longpress_timeout", 600); longPressInterval = _prefs.getInt("longpress_interval", 65); margin_bottom = get_dip_pref_oriented(dm, "margin_bottom", 7, 3); key_vertical_margin = get_dip_pref(dm, "key_vertical_margin", 1.5f) / 100; key_horizontal_margin = get_dip_pref(dm, "key_horizontal_margin", 2) / 100; // Label brightness is used as the alpha channel labelBrightness = _prefs.getInt("label_brightness", 100) * 255 / 100; // Keyboard opacity keyboardOpacity = _prefs.getInt("keyboard_opacity", 100) * 255 / 100; keyOpacity = _prefs.getInt("key_opacity", 100) * 255 / 100; keyActivatedOpacity = _prefs.getInt("key_activated_opacity", 100) * 255 / 100; // keyboard border settings borderConfig = _prefs.getBoolean("border_config", false); customBorderRadius = _prefs.getInt("custom_border_radius", 0) / 100.f; customBorderLineWidth = get_dip_pref(dm, "custom_border_line_width", 0); // Do not substract key_vertical_margin from keyHeight because this is done // during rendering. keyHeight = dm.heightPixels * keyboardHeightPercent / 100 / 4; horizontal_margin = get_dip_pref_oriented(dm, "horizontal_margin", 3, 28); double_tap_lock_shift = _prefs.getBoolean("lock_double_tap", false); characterSize = _prefs.getFloat("character_size", 1.f) * characterSizeScale; theme = getThemeId(res, _prefs.getString("theme", "")); autocapitalisation = _prefs.getBoolean("autocapitalisation", true); switch_input_immediate = _prefs.getBoolean("switch_input_immediate", false); extra_keys_param = ExtraKeysPreference.get_extra_keys(_prefs); extra_keys_custom = CustomExtraKeysPreference.get(_prefs); pin_entry_enabled = _prefs.getBoolean("pin_entry_enabled", true); current_layout_portrait = _prefs.getInt("current_layout_portrait", 0); current_layout_landscape = _prefs.getInt("current_layout_landscape", 0); } public int get_current_layout() { return (orientation_landscape) ? current_layout_landscape : current_layout_portrait; } public void set_current_layout(int l) { if (orientation_landscape) current_layout_landscape = l; else current_layout_portrait = l; SharedPreferences.Editor e = _prefs.edit(); e.putInt("current_layout_portrait", current_layout_portrait); e.putInt("current_layout_landscape", current_layout_landscape); e.apply(); } KeyValue action_key() { // Update the name to avoid caching in KeyModifier return (actionLabel == null) ? null : KeyValue.getKeyByName("action").withSymbol(actionLabel); } /** Update the layout according to the configuration. * - Remove the switching key if it isn't needed * - Remove "localized" keys from other locales (not in 'extra_keys') * - Replace the action key to show the right label * - Swap the enter and action keys * - Add the optional numpad and number row * - Add the extra keys */ public KeyboardData modify_layout(KeyboardData kw) { final KeyValue action_key = action_key(); // Extra keys are removed from the set as they are encountered during the // first iteration then automatically added. final Map<KeyValue, KeyboardData.PreferredPos> extra_keys = new HashMap<KeyValue, KeyboardData.PreferredPos>(); final Set<KeyValue> remove_keys = new HashSet<KeyValue>(); // Make sure the config key is accessible to avoid being locked in a custom // layout. extra_keys.put(KeyValue.getKeyByName("config"), KeyboardData.PreferredPos.ANYWHERE); extra_keys.putAll(extra_keys_param); extra_keys.putAll(extra_keys_custom); if (extra_keys_subtype != null) { Set<KeyValue> present = new HashSet<KeyValue>(); present.addAll(kw.getKeys().keySet()); present.addAll(extra_keys_param.keySet()); present.addAll(extra_keys_custom.keySet()); extra_keys_subtype.compute(extra_keys, new ExtraKeys.Query(kw.script, present)); } KeyboardData.Row number_row = null; if (this.number_row && !show_numpad) number_row = modify_number_row(KeyboardData.number_row, kw); if (number_row != null) remove_keys.addAll(number_row.getKeys(0).keySet()); kw = kw.mapKeys(new KeyboardData.MapKeyValues() { public KeyValue apply(KeyValue key, boolean localized) { boolean is_extra_key = extra_keys.containsKey(key); if (is_extra_key) extra_keys.remove(key); if (localized && !is_extra_key) return null; if (remove_keys.contains(key)) return null; switch (key.getKind()) { case Event: switch (key.getEvent()) { case CHANGE_METHOD_PICKER: if (switch_input_immediate) return KeyValue.getKeyByName("change_method_prev"); return key; case ACTION: return (swapEnterActionKey && action_key != null) ? KeyValue.getKeyByName("enter") : action_key; case SWITCH_FORWARD: return (layouts.size() > 1) ? key : null; case SWITCH_BACKWARD: return (layouts.size() > 2) ? key : null; case SWITCH_VOICE_TYPING: case SWITCH_VOICE_TYPING_CHOOSER: return shouldOfferVoiceTyping ? key : null; } break; case Keyevent: switch (key.getKeyevent()) { case KeyEvent.KEYCODE_ENTER: return (swapEnterActionKey && action_key != null) ? action_key : key; } break; case Modifier: switch (key.getModifier()) { case SHIFT: if (double_tap_lock_shift) return key.withFlags(key.getFlags() | KeyValue.FLAG_LOCK); } break; } return key; } }); if (show_numpad) kw = kw.addNumPad(modify_numpad(KeyboardData.num_pad, kw)); if (number_row != null) kw = kw.addTopRow(number_row); if (extra_keys.size() > 0) kw = kw.addExtraKeys(extra_keys.entrySet().iterator()); return kw; } /** Handle the numpad layout. The [main_kw] is used to adapt the numpad to the main layout's script. */ public KeyboardData modify_numpad(KeyboardData kw, KeyboardData main_kw) { final KeyValue action_key = action_key(); final KeyModifier.Map_char map_digit = KeyModifier.modify_numpad_script(main_kw.numpad_script); return kw.mapKeys(new KeyboardData.MapKeyValues() { public KeyValue apply(KeyValue key, boolean localized) { switch (key.getKind()) { case Event: switch (key.getEvent()) { case ACTION: return (swapEnterActionKey && action_key != null) ? KeyValue.getKeyByName("enter") : action_key; } break; case Keyevent: switch (key.getKeyevent()) { case KeyEvent.KEYCODE_ENTER: return (swapEnterActionKey && action_key != null) ? action_key : key; } break; case Char: char prev_c = key.getChar(); char c = prev_c; if (inverse_numpad) c = inverse_numpad_char(c); String modified = map_digit.apply(c); if (modified != null) // Was modified by script return KeyValue.makeStringKey(modified); if (prev_c != c) // Was inverted return key.withChar(c); break; } return key; } }); } static KeyboardData.MapKeyValues numpad_script_map(String numpad_script) { final KeyModifier.Map_char map_digit = KeyModifier.modify_numpad_script(numpad_script); return new KeyboardData.MapKeyValues() { public KeyValue apply(KeyValue key, boolean localized) { switch (key.getKind()) { case Char: String modified = map_digit.apply(key.getChar()); if (modified != null) return KeyValue.makeStringKey(modified); break; } return key; } }; } /** Modify the pin entry layout. [main_kw] is used to map the digits into the same script. */ public KeyboardData modify_pinentry(KeyboardData kw, KeyboardData main_kw) { return kw.mapKeys(numpad_script_map(main_kw.numpad_script)); } /** Modify the number row according to [main_kw]'s script. */ public KeyboardData.Row modify_number_row(KeyboardData.Row row, KeyboardData main_kw) { return row.mapKeys(numpad_script_map(main_kw.numpad_script)); } private float get_dip_pref(DisplayMetrics dm, String pref_name, float def) { float value; try { value = _prefs.getInt(pref_name, -1); } catch (Exception e) { value = _prefs.getFloat(pref_name, -1f); } if (value < 0f) value = def; return (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm)); } /** [get_dip_pref] depending on<SUF>*/ float get_dip_pref_oriented(DisplayMetrics dm, String pref_base_name, float def_port, float def_land) { String suffix = orientation_landscape ? "_landscape" : "_portrait"; float def = orientation_landscape ? def_land : def_port; return get_dip_pref(dm, pref_base_name + suffix, def); } private int getThemeId(Resources res, String theme_name) { switch (theme_name) { case "light": return R.style.Light; case "black": return R.style.Black; case "altblack": return R.style.AltBlack; case "dark": return R.style.Dark; case "white": return R.style.White; case "epaper": return R.style.ePaper; case "desert": return R.style.Desert; case "jungle": return R.style.Jungle; default: case "system": int night_mode = res.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; if ((night_mode & Configuration.UI_MODE_NIGHT_NO) != 0) return R.style.Light; return R.style.Dark; } } char inverse_numpad_char(char c) { switch (c) { case '7': return '1'; case '8': return '2'; case '9': return '3'; case '1': return '7'; case '2': return '8'; case '3': return '9'; default: return c; } } private static Config _globalConfig = null; public static void initGlobalConfig(SharedPreferences prefs, Resources res, IKeyEventHandler handler) { migrate(prefs); _globalConfig = new Config(prefs, res, handler); } public static Config globalConfig() { return _globalConfig; } public static SharedPreferences globalPrefs() { return _globalConfig._prefs; } public static interface IKeyEventHandler { public void key_down(KeyValue value, boolean is_swipe); public void key_up(KeyValue value, Pointers.Modifiers mods); public void mods_changed(Pointers.Modifiers mods); } /** Config migrations. */ private static int CONFIG_VERSION = 1; public static void migrate(SharedPreferences prefs) { int saved_version = prefs.getInt("version", 0); Logs.debug_config_migration(saved_version, CONFIG_VERSION); if (saved_version == CONFIG_VERSION) return; SharedPreferences.Editor e = prefs.edit(); e.putInt("version", CONFIG_VERSION); // Migrations might run on an empty [prefs] for new installs, in this case // they set the default values of complex options. switch (saved_version) // Fallback switch { case 0: // Primary, secondary and custom layout options are merged into the new // Layouts option. This also sets the default value. List<LayoutsPreference.Layout> l = new ArrayList<LayoutsPreference.Layout>(); l.add(migrate_layout(prefs.getString("layout", "system"))); String snd_layout = prefs.getString("second_layout", "none"); if (snd_layout != null && !snd_layout.equals("none")) l.add(migrate_layout(snd_layout)); String custom_layout = prefs.getString("custom_layout", ""); if (custom_layout != null && !custom_layout.equals("")) l.add(LayoutsPreference.CustomLayout.parse(custom_layout)); LayoutsPreference.save_to_preferences(e, l); case 1: default: break; } e.apply(); } private static LayoutsPreference.Layout migrate_layout(String name) { if (name == null || name.equals("system")) return new LayoutsPreference.SystemLayout(); return new LayoutsPreference.NamedLayout(name); } }
20477_1
package nl.enterbv.easion.View; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import nl.enterbv.easion.Model.Enquete; import nl.enterbv.easion.R; /** * Created by joepv on 15.jun.2016. */ public class TaskListAdapter extends ArrayAdapter<Enquete> { public TaskListAdapter(Context context, List<Enquete> objects) { super(context, -1, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_task_list, parent, false); } TextView title = (TextView) convertView.findViewById(R.id.tv_item_title); title.setText(getItem(position).getLabel()); TextView organization = (TextView) convertView.findViewById(R.id.tv_item_organization); organization.setText(getItem(position).getSender()); TextView date = (TextView) convertView.findViewById(R.id.tv_item_date); date.setText(getItem(position).getCreationDate()); View progress = convertView.findViewById(R.id.item_progress); //Progress of task: 0 = Nieuw, 1 = Bezig, 2 = Klaar switch (getItem(position).getProgress()) { case 0: progress.setBackgroundResource(R.drawable.nieuw); break; case 1: progress.setBackgroundResource(R.drawable.bezig); break; case 2: progress.setBackgroundResource(R.drawable.klaar); break; default: break; } return convertView; } }
SaxionHBO-ICT/parantion-enterbv
Easion/app/src/main/java/nl/enterbv/easion/View/TaskListAdapter.java
477
//Progress of task: 0 = Nieuw, 1 = Bezig, 2 = Klaar
line_comment
nl
package nl.enterbv.easion.View; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import nl.enterbv.easion.Model.Enquete; import nl.enterbv.easion.R; /** * Created by joepv on 15.jun.2016. */ public class TaskListAdapter extends ArrayAdapter<Enquete> { public TaskListAdapter(Context context, List<Enquete> objects) { super(context, -1, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_task_list, parent, false); } TextView title = (TextView) convertView.findViewById(R.id.tv_item_title); title.setText(getItem(position).getLabel()); TextView organization = (TextView) convertView.findViewById(R.id.tv_item_organization); organization.setText(getItem(position).getSender()); TextView date = (TextView) convertView.findViewById(R.id.tv_item_date); date.setText(getItem(position).getCreationDate()); View progress = convertView.findViewById(R.id.item_progress); //Progress of<SUF> switch (getItem(position).getProgress()) { case 0: progress.setBackgroundResource(R.drawable.nieuw); break; case 1: progress.setBackgroundResource(R.drawable.bezig); break; case 2: progress.setBackgroundResource(R.drawable.klaar); break; default: break; } return convertView; } }
54657_8
/* * Copyright 2015 - Per Wendel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.ssl; /** * SSL Stores */ public class SslStores { protected String keystoreFile; protected String keystorePassword; protected String certAlias; protected String truststoreFile; protected String truststorePassword; protected boolean needsClientCert; /** * Creates a Stores instance. * * @param keystoreFile the keystoreFile * @param keystorePassword the keystorePassword * @param truststoreFile the truststoreFile * @param truststorePassword the truststorePassword * @return the SslStores instance. */ public static SslStores create(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword) { return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); } public static SslStores create(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword) { return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); } public static SslStores create(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword, boolean needsClientCert) { return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); } public static SslStores create(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword, boolean needsClientCert) { return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); } private SslStores(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword, boolean needsClientCert) { this.keystoreFile = keystoreFile; this.keystorePassword = keystorePassword; this.certAlias = certAlias; this.truststoreFile = truststoreFile; this.truststorePassword = truststorePassword; this.needsClientCert = needsClientCert; } /** * @return keystoreFile */ public String keystoreFile() { return keystoreFile; } /** * @return keystorePassword */ public String keystorePassword() { return keystorePassword; } /** * @return certAlias */ public String certAlias() { return certAlias; } /** * @return trustStoreFile */ public String trustStoreFile() { return truststoreFile; } /** * @return trustStorePassword */ public String trustStorePassword() { return truststorePassword; } /** * @return needsClientCert */ public boolean needsClientCert() { return needsClientCert; } }
perwendel/spark
src/main/java/spark/ssl/SslStores.java
931
/** * @return needsClientCert */
block_comment
nl
/* * Copyright 2015 - Per Wendel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.ssl; /** * SSL Stores */ public class SslStores { protected String keystoreFile; protected String keystorePassword; protected String certAlias; protected String truststoreFile; protected String truststorePassword; protected boolean needsClientCert; /** * Creates a Stores instance. * * @param keystoreFile the keystoreFile * @param keystorePassword the keystorePassword * @param truststoreFile the truststoreFile * @param truststorePassword the truststorePassword * @return the SslStores instance. */ public static SslStores create(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword) { return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); } public static SslStores create(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword) { return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); } public static SslStores create(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword, boolean needsClientCert) { return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); } public static SslStores create(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword, boolean needsClientCert) { return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); } private SslStores(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword, boolean needsClientCert) { this.keystoreFile = keystoreFile; this.keystorePassword = keystorePassword; this.certAlias = certAlias; this.truststoreFile = truststoreFile; this.truststorePassword = truststorePassword; this.needsClientCert = needsClientCert; } /** * @return keystoreFile */ public String keystoreFile() { return keystoreFile; } /** * @return keystorePassword */ public String keystorePassword() { return keystorePassword; } /** * @return certAlias */ public String certAlias() { return certAlias; } /** * @return trustStoreFile */ public String trustStoreFile() { return truststoreFile; } /** * @return trustStorePassword */ public String trustStorePassword() { return truststorePassword; } /** * @return needsClientCert <SUF>*/ public boolean needsClientCert() { return needsClientCert; } }
7722_4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import java.util.ArrayList; import java.util.List; public class GeckoMenu extends LinearLayout implements Menu, GeckoMenuItem.OnShowAsActionChangedListener { private static final String LOGTAG = "GeckoMenu"; private Context mContext; public static interface ActionItemBarPresenter { public void addActionItem(View actionItem); public void removeActionItem(int index); public int getActionItemsCount(); } private static final int NO_ID = 0; // Default list of items. private List<GeckoMenuItem> mItems; // List of items in action-bar. private List<GeckoMenuItem> mActionItems; // Reference to action-items bar in action-bar. private ActionItemBarPresenter mActionItemBarPresenter; public GeckoMenu(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); setOrientation(VERTICAL); mItems = new ArrayList<GeckoMenuItem>(); mActionItems = new ArrayList<GeckoMenuItem>(); } @Override public MenuItem add(CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID); menuItem.setTitle(title); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order); menuItem.setTitle(titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID); menuItem.setTitle(titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order); menuItem.setTitle(title); addItem(menuItem); return menuItem; } private void addItem(GeckoMenuItem menuItem) { menuItem.setOnShowAsActionChangedListener(this); // Insert it in proper order. int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() > menuItem.getOrder()) { mItems.add(index, menuItem); // Account for the items in the action-bar. if (mActionItemBarPresenter != null) addView(menuItem.getLayout(), index - mActionItemBarPresenter.getActionItemsCount()); else addView(menuItem.getLayout(), index); return; } else { index++; } } // Add the menuItem at the end. mItems.add(menuItem); addView(menuItem.getLayout()); } private void addActionItem(GeckoMenuItem menuItem) { menuItem.setOnShowAsActionChangedListener(this); int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() <= menuItem.getOrder()) index++; else break; } mActionItems.add(menuItem); mItems.add(index, menuItem); mActionItemBarPresenter.addActionItem(menuItem.getLayout()); } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { return 0; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { return null; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { return null; } @Override public SubMenu addSubMenu(CharSequence title) { return null; } @Override public SubMenu addSubMenu(int titleRes) { return null; } @Override public void clear() { } @Override public void close() { } @Override public MenuItem findItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) return menuItem; } return null; } @Override public MenuItem getItem(int index) { if (index < mItems.size()) return mItems.get(index); return null; } @Override public boolean hasVisibleItems() { for (GeckoMenuItem menuItem : mItems) { if (menuItem.isVisible()) return true; } return false; } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return true; } @Override public boolean performIdentifierAction(int id, int flags) { return false; } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return false; } @Override public void removeGroup(int groupId) { } @Override public void removeItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) { if (mActionItems.contains(menuItem)) { if (mActionItemBarPresenter != null) mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(menuItem)); mActionItems.remove(menuItem); } else { removeView(findViewById(id)); } mItems.remove(menuItem); return; } } } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { } @Override public void setGroupEnabled(int group, boolean enabled) { } @Override public void setGroupVisible(int group, boolean visible) { } @Override public void setQwertyMode(boolean isQwerty) { } @Override public int size() { return mItems.size(); } @Override public boolean hasActionItemBar() { return (mActionItemBarPresenter != null); } @Override public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) { removeItem(item.getItemId()); if (isActionItem) addActionItem(item); else addItem(item); } public void setActionItemBarPresenter(ActionItemBarPresenter presenter) { mActionItemBarPresenter = presenter; } }
neonux/mozilla-all
mobile/android/base/GeckoMenu.java
1,763
// Insert it in proper order.
line_comment
nl
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import java.util.ArrayList; import java.util.List; public class GeckoMenu extends LinearLayout implements Menu, GeckoMenuItem.OnShowAsActionChangedListener { private static final String LOGTAG = "GeckoMenu"; private Context mContext; public static interface ActionItemBarPresenter { public void addActionItem(View actionItem); public void removeActionItem(int index); public int getActionItemsCount(); } private static final int NO_ID = 0; // Default list of items. private List<GeckoMenuItem> mItems; // List of items in action-bar. private List<GeckoMenuItem> mActionItems; // Reference to action-items bar in action-bar. private ActionItemBarPresenter mActionItemBarPresenter; public GeckoMenu(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); setOrientation(VERTICAL); mItems = new ArrayList<GeckoMenuItem>(); mActionItems = new ArrayList<GeckoMenuItem>(); } @Override public MenuItem add(CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID); menuItem.setTitle(title); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order); menuItem.setTitle(titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int titleRes) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID); menuItem.setTitle(titleRes); addItem(menuItem); return menuItem; } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order); menuItem.setTitle(title); addItem(menuItem); return menuItem; } private void addItem(GeckoMenuItem menuItem) { menuItem.setOnShowAsActionChangedListener(this); // Insert it<SUF> int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() > menuItem.getOrder()) { mItems.add(index, menuItem); // Account for the items in the action-bar. if (mActionItemBarPresenter != null) addView(menuItem.getLayout(), index - mActionItemBarPresenter.getActionItemsCount()); else addView(menuItem.getLayout(), index); return; } else { index++; } } // Add the menuItem at the end. mItems.add(menuItem); addView(menuItem.getLayout()); } private void addActionItem(GeckoMenuItem menuItem) { menuItem.setOnShowAsActionChangedListener(this); int index = 0; for (GeckoMenuItem item : mItems) { if (item.getOrder() <= menuItem.getOrder()) index++; else break; } mActionItems.add(menuItem); mItems.add(index, menuItem); mActionItemBarPresenter.addActionItem(menuItem.getLayout()); } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { return 0; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { return null; } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { return null; } @Override public SubMenu addSubMenu(CharSequence title) { return null; } @Override public SubMenu addSubMenu(int titleRes) { return null; } @Override public void clear() { } @Override public void close() { } @Override public MenuItem findItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) return menuItem; } return null; } @Override public MenuItem getItem(int index) { if (index < mItems.size()) return mItems.get(index); return null; } @Override public boolean hasVisibleItems() { for (GeckoMenuItem menuItem : mItems) { if (menuItem.isVisible()) return true; } return false; } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return true; } @Override public boolean performIdentifierAction(int id, int flags) { return false; } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return false; } @Override public void removeGroup(int groupId) { } @Override public void removeItem(int id) { for (GeckoMenuItem menuItem : mItems) { if (menuItem.getItemId() == id) { if (mActionItems.contains(menuItem)) { if (mActionItemBarPresenter != null) mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(menuItem)); mActionItems.remove(menuItem); } else { removeView(findViewById(id)); } mItems.remove(menuItem); return; } } } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { } @Override public void setGroupEnabled(int group, boolean enabled) { } @Override public void setGroupVisible(int group, boolean visible) { } @Override public void setQwertyMode(boolean isQwerty) { } @Override public int size() { return mItems.size(); } @Override public boolean hasActionItemBar() { return (mActionItemBarPresenter != null); } @Override public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) { removeItem(item.getItemId()); if (isActionItem) addActionItem(item); else addItem(item); } public void setActionItemBarPresenter(ActionItemBarPresenter presenter) { mActionItemBarPresenter = presenter; } }
76777_4
package mjava.util; import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ResolveJar { public static final String JAR_DIR_NAME = "apk2jar"; /** * parse apk into dex * @param apkPath * @param outputDir */ static public void zipDecompressing(String apkPath, String outputDir){ System.out.println("Starting decompress apk file ......"); long startTime=System.currentTimeMillis(); try { ZipInputStream Zin=new ZipInputStream(new FileInputStream(apkPath));//Input source zip path BufferedInputStream Bin=new BufferedInputStream(Zin); ZipEntry entry; try { while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){ if(!entry.getName().endsWith(".dex")){ continue; } File Fout=new File(outputDir,entry.getName()); if(!Fout.exists()){ (new File(Fout.getParent())).mkdirs(); } FileOutputStream out=new FileOutputStream(Fout); BufferedOutputStream Bout=new BufferedOutputStream(out); int b; while((b=Bin.read())!=-1){ Bout.write(b); } Bout.close(); out.close(); System.out.println(Fout+" decompressing succeeded."); } Bin.close(); Zin.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } long endTime=System.currentTimeMillis(); System.out.println("Apk decompression takes time: "+(endTime-startTime)+" ms."); } /** * parse dex into jar * @param inputDir */ static public void dexDecompressing(String inputDir){ System.out.println("Starting decompress dex file ......"); long startTime=System.currentTimeMillis(); File inputFileDir = new File(inputDir); if(!inputFileDir.exists()){ return; } String[] paramArr = new String[6]; paramArr[0] = "-f"; for(File f : inputFileDir.listFiles()){ if(f.getName().endsWith(".dex")){ paramArr[1] = "-o"; paramArr[2] = inputDir+"\\"+f.getName().replace(".dex","")+"-dex2jar.jar"; paramArr[3] = "-e"; paramArr[4] = inputDir+"\\"+f.getName().replace(".dex","")+"-error.zip"; paramArr[5] = f.getAbsolutePath(); //com.googlecode.dex2jar.tools.Dex2jarCmd.main(paramArr); //System.out.println("absPath: "+f.getAbsolutePath()); } } long endTime=System.currentTimeMillis(); System.out.println("Dex decompression takes time: "+(endTime-startTime)+" ms."); } /** * add the class path dynamically * */ private static void addURL(String classPath) { try{ Method addClass = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); addClass.setAccessible(true); ClassLoader cl = ClassLoader.getSystemClassLoader(); // load app's dependence jars File[] jarFiles = new File(classPath).listFiles(); for (File ff : jarFiles) { if(ff.getName().endsWith(".jar")){ addClass.invoke(cl, new Object[]{ff.toURL()}); System.out.println("FileName: "+ff.getName()); } } }catch (Exception e){ e.printStackTrace(); System.err.println(e.toString()); } } /** * parse apk into jar * @param apkPath */ public static void doApk2Jar(String apkPath){ if("".equals(apkPath)) return; File path = new File(apkPath); if(path.exists() && path.isDirectory()){ boolean flag = false; for(File f: path.listFiles()){ if(f.getName().endsWith(".apk")){ flag = true; File apk2jarDir = new File(apkPath+File.separator+JAR_DIR_NAME); if(!apk2jarDir.exists()){ apk2jarDir.mkdirs(); } zipDecompressing(f.getAbsolutePath(),apk2jarDir.getAbsolutePath()); dexDecompressing(apk2jarDir.getAbsolutePath()); } } if(!flag){ System.err.println("Can not find apk file. Parsing apk into jar failed."); } }else if(path.isFile()){ File apk2jarDir = new File(path.getParent()+File.separator+JAR_DIR_NAME); if(!apk2jarDir.exists()){ apk2jarDir.mkdirs(); } zipDecompressing(path.getAbsolutePath(),apk2jarDir.getAbsolutePath()); dexDecompressing(apk2jarDir.getAbsolutePath()); } else{ System.err.println("Can not find path ["+apkPath+"]. parsing apk into jar failed."); } } public static void main(String[] args){ //my testing //zipDecompressing("E:\\AndroidStudioProjects\\MyApplication\\app\\build\\outputs\\apk\\app-debug.apk","E:\\mutatorHome\\classes"); //zipDecompressing("E:\\andriod_project\\AnyMemo\\app\\build\\outputs\\apk\\debug\\AnyMemo-debug.apk","E:\\mutatorHome\\classes"); //dexDecompressing("E:\\mutatorHome\\classes"); addURL("E:\\mutatorHome\\classes"); String[] className = new String[]{"org.liberty.android.fantastischmemo.ui.CardEditor", "org.apache.commons.io.ByteOrderMark", "android.support.v7.app.AppCompatActivity", "org.jacoco.core.data.SessionInfo"}; try{ for(String name: className){ Class c = Class.forName(name); System.out.println("ClassName: "+c.getName()+ " superClass:"+c.getSuperclass().getName()); } }catch (ClassNotFoundException cnfe){ System.err.println(cnfe.toString()); } } }
SQS-JLiu/DroidMutator
src/main/java/mjava/util/ResolveJar.java
1,579
// load app's dependence jars
line_comment
nl
package mjava.util; import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ResolveJar { public static final String JAR_DIR_NAME = "apk2jar"; /** * parse apk into dex * @param apkPath * @param outputDir */ static public void zipDecompressing(String apkPath, String outputDir){ System.out.println("Starting decompress apk file ......"); long startTime=System.currentTimeMillis(); try { ZipInputStream Zin=new ZipInputStream(new FileInputStream(apkPath));//Input source zip path BufferedInputStream Bin=new BufferedInputStream(Zin); ZipEntry entry; try { while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){ if(!entry.getName().endsWith(".dex")){ continue; } File Fout=new File(outputDir,entry.getName()); if(!Fout.exists()){ (new File(Fout.getParent())).mkdirs(); } FileOutputStream out=new FileOutputStream(Fout); BufferedOutputStream Bout=new BufferedOutputStream(out); int b; while((b=Bin.read())!=-1){ Bout.write(b); } Bout.close(); out.close(); System.out.println(Fout+" decompressing succeeded."); } Bin.close(); Zin.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } long endTime=System.currentTimeMillis(); System.out.println("Apk decompression takes time: "+(endTime-startTime)+" ms."); } /** * parse dex into jar * @param inputDir */ static public void dexDecompressing(String inputDir){ System.out.println("Starting decompress dex file ......"); long startTime=System.currentTimeMillis(); File inputFileDir = new File(inputDir); if(!inputFileDir.exists()){ return; } String[] paramArr = new String[6]; paramArr[0] = "-f"; for(File f : inputFileDir.listFiles()){ if(f.getName().endsWith(".dex")){ paramArr[1] = "-o"; paramArr[2] = inputDir+"\\"+f.getName().replace(".dex","")+"-dex2jar.jar"; paramArr[3] = "-e"; paramArr[4] = inputDir+"\\"+f.getName().replace(".dex","")+"-error.zip"; paramArr[5] = f.getAbsolutePath(); //com.googlecode.dex2jar.tools.Dex2jarCmd.main(paramArr); //System.out.println("absPath: "+f.getAbsolutePath()); } } long endTime=System.currentTimeMillis(); System.out.println("Dex decompression takes time: "+(endTime-startTime)+" ms."); } /** * add the class path dynamically * */ private static void addURL(String classPath) { try{ Method addClass = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); addClass.setAccessible(true); ClassLoader cl = ClassLoader.getSystemClassLoader(); // load app's<SUF> File[] jarFiles = new File(classPath).listFiles(); for (File ff : jarFiles) { if(ff.getName().endsWith(".jar")){ addClass.invoke(cl, new Object[]{ff.toURL()}); System.out.println("FileName: "+ff.getName()); } } }catch (Exception e){ e.printStackTrace(); System.err.println(e.toString()); } } /** * parse apk into jar * @param apkPath */ public static void doApk2Jar(String apkPath){ if("".equals(apkPath)) return; File path = new File(apkPath); if(path.exists() && path.isDirectory()){ boolean flag = false; for(File f: path.listFiles()){ if(f.getName().endsWith(".apk")){ flag = true; File apk2jarDir = new File(apkPath+File.separator+JAR_DIR_NAME); if(!apk2jarDir.exists()){ apk2jarDir.mkdirs(); } zipDecompressing(f.getAbsolutePath(),apk2jarDir.getAbsolutePath()); dexDecompressing(apk2jarDir.getAbsolutePath()); } } if(!flag){ System.err.println("Can not find apk file. Parsing apk into jar failed."); } }else if(path.isFile()){ File apk2jarDir = new File(path.getParent()+File.separator+JAR_DIR_NAME); if(!apk2jarDir.exists()){ apk2jarDir.mkdirs(); } zipDecompressing(path.getAbsolutePath(),apk2jarDir.getAbsolutePath()); dexDecompressing(apk2jarDir.getAbsolutePath()); } else{ System.err.println("Can not find path ["+apkPath+"]. parsing apk into jar failed."); } } public static void main(String[] args){ //my testing //zipDecompressing("E:\\AndroidStudioProjects\\MyApplication\\app\\build\\outputs\\apk\\app-debug.apk","E:\\mutatorHome\\classes"); //zipDecompressing("E:\\andriod_project\\AnyMemo\\app\\build\\outputs\\apk\\debug\\AnyMemo-debug.apk","E:\\mutatorHome\\classes"); //dexDecompressing("E:\\mutatorHome\\classes"); addURL("E:\\mutatorHome\\classes"); String[] className = new String[]{"org.liberty.android.fantastischmemo.ui.CardEditor", "org.apache.commons.io.ByteOrderMark", "android.support.v7.app.AppCompatActivity", "org.jacoco.core.data.SessionInfo"}; try{ for(String name: className){ Class c = Class.forName(name); System.out.println("ClassName: "+c.getName()+ " superClass:"+c.getSuperclass().getName()); } }catch (ClassNotFoundException cnfe){ System.err.println(cnfe.toString()); } } }
25951_17
/** * $Revision: $ * $Date: $ * * Copyright (C) 2005-2008 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution, or a commercial license * agreement with Jive. */ package org.jivesoftware.openfire.resultsetmanager; import java.util.*; /** * A result set representation as described in XEP-0059. Note that this result * 'set' actually makes use of a List implementations, as the Java Set * definition disallows duplicate elements, while the List definition supplies * most of the required indexing operations. * * This ResultSet implementation loads all all results from the set into memory, * which might be undesirable for very large sets, or for sets where the * retrieval of a result is an expensive operation. sets. * * As most methods are backed by the {@link List#subList(int, int)} method, * non-structural changes in the returned lists are reflected in the ResultSet, * and vice-versa. * * @author Guus der Kinderen, [email protected] * * @param <E> * Each result set should be a collection of instances of the exact * same class. This class must implement the {@link Result} * interface. * @see java.util.List#subList(int, int) * */ /* * TODO: do we want changes to the returned Lists of methods in this class be * applied to the content of the ResultSet itself? Currently, because of the * usage of java.util.List#subList(int, int), it does. I'm thinking a * immodifiable solution would cause less problems. -Guus */ public class ResultSetImpl<E extends Result> extends ResultSet<E> { /** * A list of all results in this ResultSet */ public final List<E> resultList; /** * A mapping of the UIDs of all results in resultList, to the index of those * entries in that list. */ public final Map<String, Integer> uidToIndex; /** * Creates a new Result Set instance, based on a collection of Result * implementing objects. The collection should contain elements of the exact * same class only, and cannot contain 'null' elements. * * The order that's being used in the new ResultSet instance is the same * order in which {@link Collection#iterator()} iterates over the * collection. * * Note that this constructor throws an IllegalArgumentException if the * Collection that is provided contains Results that have duplicate UIDs. * * @param results * The collection of Results that make up this result set. */ public ResultSetImpl(Collection<E> results) { this(results, null); } /** * Creates a new Result Set instance, based on a collection of Result * implementing objects. The collection should contain elements of the exact * same class only, and cannot contain 'null' elements. * * The order that's being used in the new ResultSet instance is defined by * the supplied Comparator class. * * Note that this constructor throws an IllegalArgumentException if the * Collection that is provided contains Results that have duplicate UIDs. * * @param results * The collection of Results that make up this result set. * @param comparator * The Comparator that defines the order of the Results in this * result set. */ public ResultSetImpl(Collection<E> results, Comparator<E> comparator) { if (results == null) { throw new NullPointerException("Argument 'results' cannot be null."); } final int size = results.size(); resultList = new ArrayList<E>(size); uidToIndex = new Hashtable<String, Integer>(size); // sort the collection, if need be. List<E> sortedResults = null; if (comparator != null) { sortedResults = new ArrayList<E>(results); Collections.sort(sortedResults, comparator); } int index = 0; // iterate over either the sorted or unsorted collection for (final E result : (sortedResults != null ? sortedResults : results)) { if (result == null) { throw new NullPointerException( "The result set must not contain 'null' elements."); } final String uid = result.getUID(); if (uidToIndex.containsKey(uid)) { throw new IllegalArgumentException( "The result set can not contain elements that have the same UID."); } resultList.add(result); uidToIndex.put(uid, index); index++; } } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#size() */ @Override public int size() { return resultList.size(); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getAfter(E, int) */ @Override public List<E> getAfter(String uid, int maxAmount) { if (uid == null || uid.length() == 0) { throw new NullPointerException("Argument 'uid' cannot be null or an empty String."); } if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } // the result of this method is exclusive 'result' final int index = uidToIndex.get(uid) + 1; return get(index, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getBefore(E, int) */ @Override public List<E> getBefore(String uid, int maxAmount) { if (uid == null || uid.length() == 0) { throw new NullPointerException("Argument 'uid' cannot be null or an empty String."); } if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } // the result of this method is exclusive 'result' final int indexOfLastElement = uidToIndex.get(uid); final int indexOfFirstElement = indexOfLastElement - maxAmount; if (indexOfFirstElement < 0) { return get(0, indexOfLastElement); } return get(indexOfFirstElement, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#get(int) */ @Override public E get(int index) { return resultList.get(index); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getFirst(int) */ @Override public List<E> getFirst(int maxAmount) { if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } return get(0, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getLast(int) */ @Override public List<E> getLast(int maxAmount) { if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } final int indexOfFirstElement = size() - maxAmount; if (indexOfFirstElement < 0) { return get(0, maxAmount); } return get(indexOfFirstElement, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#get(int, int) */ @Override public List<E> get(int fromIndex, int maxAmount) { if (fromIndex < 0) { throw new IllegalArgumentException( "Argument 'fromIndex' must be zero or higher."); } if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } if (fromIndex >= size()) { return new ArrayList<E>(0); } // calculate the last index to return, or return up to the end of last // index if 'amount' surpasses the list length. final int absoluteTo = fromIndex + maxAmount; final int toIndex = (absoluteTo > size() ? size() : absoluteTo); return resultList.subList(fromIndex, toIndex); } /* * (non-Javadoc) * @see org.jivesoftware.util.resultsetmanager.ResultSet#indexOf(java.lang.String) */ @Override public int indexOf(String uid) { return uidToIndex.get(uid); } }
OpenJunction/Openfire
src/java/org/jivesoftware/openfire/resultsetmanager/ResultSetImpl.java
2,374
/* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#get(int, int) */
block_comment
nl
/** * $Revision: $ * $Date: $ * * Copyright (C) 2005-2008 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution, or a commercial license * agreement with Jive. */ package org.jivesoftware.openfire.resultsetmanager; import java.util.*; /** * A result set representation as described in XEP-0059. Note that this result * 'set' actually makes use of a List implementations, as the Java Set * definition disallows duplicate elements, while the List definition supplies * most of the required indexing operations. * * This ResultSet implementation loads all all results from the set into memory, * which might be undesirable for very large sets, or for sets where the * retrieval of a result is an expensive operation. sets. * * As most methods are backed by the {@link List#subList(int, int)} method, * non-structural changes in the returned lists are reflected in the ResultSet, * and vice-versa. * * @author Guus der Kinderen, [email protected] * * @param <E> * Each result set should be a collection of instances of the exact * same class. This class must implement the {@link Result} * interface. * @see java.util.List#subList(int, int) * */ /* * TODO: do we want changes to the returned Lists of methods in this class be * applied to the content of the ResultSet itself? Currently, because of the * usage of java.util.List#subList(int, int), it does. I'm thinking a * immodifiable solution would cause less problems. -Guus */ public class ResultSetImpl<E extends Result> extends ResultSet<E> { /** * A list of all results in this ResultSet */ public final List<E> resultList; /** * A mapping of the UIDs of all results in resultList, to the index of those * entries in that list. */ public final Map<String, Integer> uidToIndex; /** * Creates a new Result Set instance, based on a collection of Result * implementing objects. The collection should contain elements of the exact * same class only, and cannot contain 'null' elements. * * The order that's being used in the new ResultSet instance is the same * order in which {@link Collection#iterator()} iterates over the * collection. * * Note that this constructor throws an IllegalArgumentException if the * Collection that is provided contains Results that have duplicate UIDs. * * @param results * The collection of Results that make up this result set. */ public ResultSetImpl(Collection<E> results) { this(results, null); } /** * Creates a new Result Set instance, based on a collection of Result * implementing objects. The collection should contain elements of the exact * same class only, and cannot contain 'null' elements. * * The order that's being used in the new ResultSet instance is defined by * the supplied Comparator class. * * Note that this constructor throws an IllegalArgumentException if the * Collection that is provided contains Results that have duplicate UIDs. * * @param results * The collection of Results that make up this result set. * @param comparator * The Comparator that defines the order of the Results in this * result set. */ public ResultSetImpl(Collection<E> results, Comparator<E> comparator) { if (results == null) { throw new NullPointerException("Argument 'results' cannot be null."); } final int size = results.size(); resultList = new ArrayList<E>(size); uidToIndex = new Hashtable<String, Integer>(size); // sort the collection, if need be. List<E> sortedResults = null; if (comparator != null) { sortedResults = new ArrayList<E>(results); Collections.sort(sortedResults, comparator); } int index = 0; // iterate over either the sorted or unsorted collection for (final E result : (sortedResults != null ? sortedResults : results)) { if (result == null) { throw new NullPointerException( "The result set must not contain 'null' elements."); } final String uid = result.getUID(); if (uidToIndex.containsKey(uid)) { throw new IllegalArgumentException( "The result set can not contain elements that have the same UID."); } resultList.add(result); uidToIndex.put(uid, index); index++; } } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#size() */ @Override public int size() { return resultList.size(); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getAfter(E, int) */ @Override public List<E> getAfter(String uid, int maxAmount) { if (uid == null || uid.length() == 0) { throw new NullPointerException("Argument 'uid' cannot be null or an empty String."); } if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } // the result of this method is exclusive 'result' final int index = uidToIndex.get(uid) + 1; return get(index, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getBefore(E, int) */ @Override public List<E> getBefore(String uid, int maxAmount) { if (uid == null || uid.length() == 0) { throw new NullPointerException("Argument 'uid' cannot be null or an empty String."); } if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } // the result of this method is exclusive 'result' final int indexOfLastElement = uidToIndex.get(uid); final int indexOfFirstElement = indexOfLastElement - maxAmount; if (indexOfFirstElement < 0) { return get(0, indexOfLastElement); } return get(indexOfFirstElement, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#get(int) */ @Override public E get(int index) { return resultList.get(index); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getFirst(int) */ @Override public List<E> getFirst(int maxAmount) { if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } return get(0, maxAmount); } /* * (non-Javadoc) * * @see com.buzzaa.xmpp.resultsetmanager.ResultSet#getLast(int) */ @Override public List<E> getLast(int maxAmount) { if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } final int indexOfFirstElement = size() - maxAmount; if (indexOfFirstElement < 0) { return get(0, maxAmount); } return get(indexOfFirstElement, maxAmount); } /* * (non-Javadoc) <SUF>*/ @Override public List<E> get(int fromIndex, int maxAmount) { if (fromIndex < 0) { throw new IllegalArgumentException( "Argument 'fromIndex' must be zero or higher."); } if (maxAmount < 1) { throw new IllegalArgumentException( "Argument 'maxAmount' must be a integer higher than zero."); } if (fromIndex >= size()) { return new ArrayList<E>(0); } // calculate the last index to return, or return up to the end of last // index if 'amount' surpasses the list length. final int absoluteTo = fromIndex + maxAmount; final int toIndex = (absoluteTo > size() ? size() : absoluteTo); return resultList.subList(fromIndex, toIndex); } /* * (non-Javadoc) * @see org.jivesoftware.util.resultsetmanager.ResultSet#indexOf(java.lang.String) */ @Override public int indexOf(String uid) { return uidToIndex.get(uid); } }
38292_1
/* * Calendula - An assistant for personal medication management. * Copyright (C) 2014-2018 CiTIUS - University of Santiago de Compostela * * Calendula is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ package es.usc.citius.servando.calendula.database; import android.content.Context; import com.j256.ormlite.misc.TransactionManager; import java.util.concurrent.Callable; import es.usc.citius.servando.calendula.drugdb.model.database.DrugDBModule; import es.usc.citius.servando.calendula.util.LogUtil; public class DB { private static final String TAG = "DB"; // Database name public static String DB_NAME = "calendula.db"; // initialized flag public static boolean initialized = false; // DatabaseManeger reference private static DatabaseManager<DatabaseHelper> manager; // SQLite DB Helper private static DatabaseHelper db; // Medicines DAO private static MedicineDao Medicines; // Routines DAO private static RoutineDao Routines; // Schedules DAO private static ScheduleDao Schedules; // ScheduleItems DAO private static ScheduleItemDao ScheduleItems; // DailyScheduleItem DAO private static DailyScheduleItemDao DailyScheduleItems; // Pickups DAO private static PickupInfoDao Pickups; // Patients DAO private static PatientDao Patients; // Drug DB module private static DrugDBModule DrugDB; // Alerts DAO private static PatientAlertDao PatientAlerts; // Allergens DAO private static PatientAllergenDao PatientAllergens; // Allergy group DAO private static AllergyGroupDao AllergyGroups; /** * Initialize database and DAOs */ public synchronized static void init(Context context) { if (!initialized) { initialized = true; manager = new DatabaseManager<>(); db = manager.getHelper(context, DatabaseHelper.class); db.getReadableDatabase().enableWriteAheadLogging(); Medicines = new MedicineDao(db); Routines = new RoutineDao(db); Schedules = new ScheduleDao(db); ScheduleItems = new ScheduleItemDao(db); DailyScheduleItems = new DailyScheduleItemDao(db); Pickups = new PickupInfoDao(db); Patients = new PatientDao(db); DrugDB = DrugDBModule.getInstance(); PatientAlerts = new PatientAlertDao(db); PatientAllergens = new PatientAllergenDao(db); AllergyGroups = new AllergyGroupDao(db); LogUtil.v(TAG, "DB initialized " + DB.DB_NAME); } } /** * Dispose DB and DAOs */ public synchronized static void dispose() { initialized = false; db.close(); manager.releaseHelper(db); LogUtil.v(TAG, "DB disposed"); } public static DatabaseHelper helper() { return db; } public static Object transaction(Callable<?> callable) { try { return TransactionManager.callInTransaction(db.getConnectionSource(), callable); } catch (Exception e) { throw new RuntimeException(e); } } public static MedicineDao medicines() { return Medicines; } public static RoutineDao routines() { return Routines; } public static ScheduleDao schedules() { return Schedules; } public static ScheduleItemDao scheduleItems() { return ScheduleItems; } public static DailyScheduleItemDao dailyScheduleItems() { return DailyScheduleItems; } public static PickupInfoDao pickups() { return Pickups; } public static PatientDao patients() { return Patients; } public static DrugDBModule drugDB() { return DrugDB; } public static PatientAlertDao alerts() { return PatientAlerts; } public static PatientAllergenDao patientAllergens() { return PatientAllergens; } public static AllergyGroupDao allergyGroups() { return AllergyGroups; } public static void dropAndCreateDatabase() { db.dropAndCreateAllTables(); } }
citiususc/calendula
Calendula/src/main/java/es/usc/citius/servando/calendula/database/DB.java
1,162
// SQLite DB Helper
line_comment
nl
/* * Calendula - An assistant for personal medication management. * Copyright (C) 2014-2018 CiTIUS - University of Santiago de Compostela * * Calendula is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ package es.usc.citius.servando.calendula.database; import android.content.Context; import com.j256.ormlite.misc.TransactionManager; import java.util.concurrent.Callable; import es.usc.citius.servando.calendula.drugdb.model.database.DrugDBModule; import es.usc.citius.servando.calendula.util.LogUtil; public class DB { private static final String TAG = "DB"; // Database name public static String DB_NAME = "calendula.db"; // initialized flag public static boolean initialized = false; // DatabaseManeger reference private static DatabaseManager<DatabaseHelper> manager; // SQLite DB<SUF> private static DatabaseHelper db; // Medicines DAO private static MedicineDao Medicines; // Routines DAO private static RoutineDao Routines; // Schedules DAO private static ScheduleDao Schedules; // ScheduleItems DAO private static ScheduleItemDao ScheduleItems; // DailyScheduleItem DAO private static DailyScheduleItemDao DailyScheduleItems; // Pickups DAO private static PickupInfoDao Pickups; // Patients DAO private static PatientDao Patients; // Drug DB module private static DrugDBModule DrugDB; // Alerts DAO private static PatientAlertDao PatientAlerts; // Allergens DAO private static PatientAllergenDao PatientAllergens; // Allergy group DAO private static AllergyGroupDao AllergyGroups; /** * Initialize database and DAOs */ public synchronized static void init(Context context) { if (!initialized) { initialized = true; manager = new DatabaseManager<>(); db = manager.getHelper(context, DatabaseHelper.class); db.getReadableDatabase().enableWriteAheadLogging(); Medicines = new MedicineDao(db); Routines = new RoutineDao(db); Schedules = new ScheduleDao(db); ScheduleItems = new ScheduleItemDao(db); DailyScheduleItems = new DailyScheduleItemDao(db); Pickups = new PickupInfoDao(db); Patients = new PatientDao(db); DrugDB = DrugDBModule.getInstance(); PatientAlerts = new PatientAlertDao(db); PatientAllergens = new PatientAllergenDao(db); AllergyGroups = new AllergyGroupDao(db); LogUtil.v(TAG, "DB initialized " + DB.DB_NAME); } } /** * Dispose DB and DAOs */ public synchronized static void dispose() { initialized = false; db.close(); manager.releaseHelper(db); LogUtil.v(TAG, "DB disposed"); } public static DatabaseHelper helper() { return db; } public static Object transaction(Callable<?> callable) { try { return TransactionManager.callInTransaction(db.getConnectionSource(), callable); } catch (Exception e) { throw new RuntimeException(e); } } public static MedicineDao medicines() { return Medicines; } public static RoutineDao routines() { return Routines; } public static ScheduleDao schedules() { return Schedules; } public static ScheduleItemDao scheduleItems() { return ScheduleItems; } public static DailyScheduleItemDao dailyScheduleItems() { return DailyScheduleItems; } public static PickupInfoDao pickups() { return Pickups; } public static PatientDao patients() { return Patients; } public static DrugDBModule drugDB() { return DrugDB; } public static PatientAlertDao alerts() { return PatientAlerts; } public static PatientAllergenDao patientAllergens() { return PatientAllergens; } public static AllergyGroupDao allergyGroups() { return AllergyGroups; } public static void dropAndCreateDatabase() { db.dropAndCreateAllTables(); } }
100685_7
package com.example.jan.dabradio; import android.bluetooth.BluetoothSocket; import android.support.v7.app.AppCompatActivity; import java.io.IOException; import java. util. *; import java.io.InputStream; import java.io.DataInputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.DataOutputStream; import java.io.OutputStreamWriter; import java.io.IOException; import java.io.OutputStream; // // The "radioInterface" is the actual interface to the // socket of the bluetooth connector public class radioInterface extends Thread { // // keys for the outgoing messages private final int Q_QUIT = 0100; private final int Q_GAIN_SLIDER = 0101; private final int Q_SOUND_LEVEL = 0102; private final int Q_LNA_STATE = 0103; private final int Q_AUTOGAIN = 0104; private final int Q_SERVICE = 0106; private final int Q_RESET = 0107; private final int Q_SYSTEM_EXIT = 0110; // // keys for incoming messages private final int Q_INITIALS = 0100; private final int Q_DEVICE_NAME = 0101; private final int Q_ENSEMBLE = 0102; private final int Q_SERVICE_NAME = 0103; private final int Q_TEXT_MESSAGE = 0104; private final int Q_STATE = 0105; private final int Q_STEREO = 0106; private final int Q_NEW_ENSEMBLE = 0107; private final int Q_SOUND = 0110; // // For the connection we need private InputStream is; private OutputStream os; private DataOutputStream outputter; private DataInputStream inputter; private BluetoothSocket thePlug; // // for changing values in the GUI we need private AppCompatActivity the_gui; // // for signaling, we need private final List<Signals> listener = new ArrayList<>(); public void addServiceListener (Signals service) { listener. add (service); } public radioInterface (AppCompatActivity the_gui) { this. the_gui = the_gui; } public void startRadio (BluetoothSocket thePlug) throws IOException { this. thePlug = thePlug; is = thePlug. getInputStream (); os = thePlug. getOutputStream (); inputter = new DataInputStream (is); outputter = new DataOutputStream (os); start (); } @Override public void run () { char inBuffer[] = new char [2550]; byte header [] = new byte [300]; while (true) { int amount = 0; int length = 0; try { Thread.sleep (100); } catch (Exception e) {} if (!thePlug. isConnected ()) { toaster ("connection lost"); try { the_gui.runOnUiThread(new Runnable() { @Override public void run() { set_quit(); } }); } catch (Exception e) { } return; } try { for (int i = 0; i < 3; i ++) header [i] = inputter. readByte (); length = (int)(((header [1] & 0xFF) << 8) | (int)(header [2] & 0xFF)); // toaster ("Gelezen " + amount + " lengte is " + length); for (int i = 0; i < length; i ++) inBuffer [i] = (char) inputter. readByte (); Dispatcher (header [0], length, inBuffer); } catch (Exception e) { toaster ("connection lost"); try { the_gui.runOnUiThread(new Runnable() { @Override public void run() { set_quit(); } }); } catch (Exception e1) { } } } } // // This function is called from within the thread public void Dispatcher (byte key, int segSize, char [] inBuffer) { char buffer [] = new char [segSize + 1]; System. arraycopy (inBuffer, 0, buffer, 0, segSize); switch (key) { case Q_SOUND: // not yet implemented break; case Q_INITIALS: { final byte sysdata [] = new byte [segSize + 1]; for (int i = 0; i < segSize + 1; i ++) sysdata [i] = (byte)(inBuffer [i]); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { set_initialValues (sysdata); }}); } catch (Exception e) {} } break; case Q_DEVICE_NAME: { buffer [segSize] = 0; final String deviceLabel = String. valueOf (buffer); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_deviceName (deviceLabel); }}); } catch (Exception e) {} } break; case Q_ENSEMBLE: { buffer [segSize] = 0; final String ensembleLabel = String. valueOf (buffer); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_ensembleName (ensembleLabel, 0); }}); } catch (Exception e) {} } break; case Q_SERVICE_NAME: { buffer [segSize] = 0; final String serviceLabel = String. valueOf (buffer); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_serviceName (serviceLabel); }}); } catch (Exception e) {} } break; case Q_TEXT_MESSAGE: { buffer [segSize] = 0; final String dynamicLabel = String. valueOf (buffer); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_dynamicLabel (dynamicLabel); }}); } catch (Exception e) {} } break; case Q_STATE: { final byte vector [] = new byte [2]; vector [0] = (byte)(buffer [0]); vector [1] = (byte)(buffer [1]); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_state (vector); }}); } catch (Exception e) {} } break; case Q_NEW_ENSEMBLE: { try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { clearScreen (); }}); } catch (Exception e) {} } break; case Q_STEREO: { final boolean b = buffer [0] != 0; try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { set_stereoIndicator (b); }}); } catch (Exception e) {} } break; default:; } } public void set_quit () { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. set_quit (); } } public void show_deviceName (String Name) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_deviceName (Name); }; } public void set_initialValues (byte [] v) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. set_initialValues (v); }; } public void show_ensembleName (String Name, int Sid) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_ensembleName (Name, Sid); }; } public void show_serviceName (String s) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_serviceName (s); }; } public void show_dynamicLabel (String s) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_dynamicLabel (s); }; } public void show_state (byte [] v) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_state (v); } } public void clearScreen () { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. clearScreen (); }; } public void set_stereoIndicator (boolean b) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. set_stereoIndicator (b); }; } public void toaster (String s) { final String data = s; try { the_gui.runOnUiThread(new Runnable() { @Override public void run() { the_toaster (data); } }); } catch (Exception e) { } } public void the_toaster (String s) { for (int i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. toaster (s); } } // // and the transmitters public void setService (String s) { byte data [] = new byte [s. length () + 4]; data [0] = (byte)Q_SERVICE; data [1] = (byte)0; data [2] = (byte) (s. length () + 1); for (int i = 0; i < s. length (); i ++) data [3 + i] = (byte) s. charAt (i); data [3 + s. length ()] = 0; toaster ("Setting service for " + s); try { outputter. write (data, 0, s. length () + 4); outputter. flush (); } catch (Exception e) {} } public void reset () { byte data [] = new byte [4]; data [0] = (byte)Q_RESET; data [1] = (byte)0; data [2] = (byte) (1); data [3] = (byte)0; try { outputter. write (data, 0, 4); outputter. flush (); } catch (Exception e) {} } public void setLnaState (int lnaState) { byte data [] = new byte [3 + 2]; data [0] = (byte)Q_LNA_STATE; data [1] = (byte)0; data [2] = (byte)2; data [3] = (byte)lnaState; try { outputter. write (data, 0, 5); outputter. flush (); } catch (Exception e) {} } public void set_gainLevel (int val) { byte data [] = new byte [3 + 2]; data [0] = (byte)Q_GAIN_SLIDER; data [1] = (byte)0; data [2] = (byte)2; data [3] = (byte)val; try { outputter. write (data, 0, 5); outputter. flush (); } catch (Exception e) {} } public void set_soundLevel (int soundLevel) { byte data [] = new byte [3 + 2]; data [0] = (byte)Q_SOUND_LEVEL; data [1] = (byte)0; data [2] = (byte)2; data [3] = (byte)soundLevel; try { outputter. write (data, 0, 5); outputter. flush (); } catch (Exception e) {} } public void set_autoGain (Boolean b) { byte data [] = new byte [3 + 2]; data [0] = (byte)Q_AUTOGAIN; data [1] = (byte)0; data [2] = (byte)2; data [3] = (byte)(b ? 1 : 0); try { outputter. write (data, 0, 5); outputter. flush (); } catch (Exception e) {} } public void doReset () { byte data[] = new byte[4]; data[0] = Q_RESET; data[1] = 0; data[2] = (char) (1); data[3] = 0; try { outputter.write(data, 0, 4); outputter.flush(); } catch (Exception e) { } } public void do_systemExit () { byte data[] = new byte[4]; data[0] = Q_SYSTEM_EXIT; data[1] = 0; data[2] = (char) (1); data[3] = 0; try { outputter.write(data, 0, 4); outputter.flush(); } catch (Exception e) { } } };
JvanKatwijk/dab-server
10-inch/app/src/main/java/com/example/jan/dabradio/radioInterface.java
3,666
// toaster ("Gelezen " + amount + " lengte is " + length);
line_comment
nl
package com.example.jan.dabradio; import android.bluetooth.BluetoothSocket; import android.support.v7.app.AppCompatActivity; import java.io.IOException; import java. util. *; import java.io.InputStream; import java.io.DataInputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.DataOutputStream; import java.io.OutputStreamWriter; import java.io.IOException; import java.io.OutputStream; // // The "radioInterface" is the actual interface to the // socket of the bluetooth connector public class radioInterface extends Thread { // // keys for the outgoing messages private final int Q_QUIT = 0100; private final int Q_GAIN_SLIDER = 0101; private final int Q_SOUND_LEVEL = 0102; private final int Q_LNA_STATE = 0103; private final int Q_AUTOGAIN = 0104; private final int Q_SERVICE = 0106; private final int Q_RESET = 0107; private final int Q_SYSTEM_EXIT = 0110; // // keys for incoming messages private final int Q_INITIALS = 0100; private final int Q_DEVICE_NAME = 0101; private final int Q_ENSEMBLE = 0102; private final int Q_SERVICE_NAME = 0103; private final int Q_TEXT_MESSAGE = 0104; private final int Q_STATE = 0105; private final int Q_STEREO = 0106; private final int Q_NEW_ENSEMBLE = 0107; private final int Q_SOUND = 0110; // // For the connection we need private InputStream is; private OutputStream os; private DataOutputStream outputter; private DataInputStream inputter; private BluetoothSocket thePlug; // // for changing values in the GUI we need private AppCompatActivity the_gui; // // for signaling, we need private final List<Signals> listener = new ArrayList<>(); public void addServiceListener (Signals service) { listener. add (service); } public radioInterface (AppCompatActivity the_gui) { this. the_gui = the_gui; } public void startRadio (BluetoothSocket thePlug) throws IOException { this. thePlug = thePlug; is = thePlug. getInputStream (); os = thePlug. getOutputStream (); inputter = new DataInputStream (is); outputter = new DataOutputStream (os); start (); } @Override public void run () { char inBuffer[] = new char [2550]; byte header [] = new byte [300]; while (true) { int amount = 0; int length = 0; try { Thread.sleep (100); } catch (Exception e) {} if (!thePlug. isConnected ()) { toaster ("connection lost"); try { the_gui.runOnUiThread(new Runnable() { @Override public void run() { set_quit(); } }); } catch (Exception e) { } return; } try { for (int i = 0; i < 3; i ++) header [i] = inputter. readByte (); length = (int)(((header [1] & 0xFF) << 8) | (int)(header [2] & 0xFF)); // toaster ("Gelezen<SUF> for (int i = 0; i < length; i ++) inBuffer [i] = (char) inputter. readByte (); Dispatcher (header [0], length, inBuffer); } catch (Exception e) { toaster ("connection lost"); try { the_gui.runOnUiThread(new Runnable() { @Override public void run() { set_quit(); } }); } catch (Exception e1) { } } } } // // This function is called from within the thread public void Dispatcher (byte key, int segSize, char [] inBuffer) { char buffer [] = new char [segSize + 1]; System. arraycopy (inBuffer, 0, buffer, 0, segSize); switch (key) { case Q_SOUND: // not yet implemented break; case Q_INITIALS: { final byte sysdata [] = new byte [segSize + 1]; for (int i = 0; i < segSize + 1; i ++) sysdata [i] = (byte)(inBuffer [i]); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { set_initialValues (sysdata); }}); } catch (Exception e) {} } break; case Q_DEVICE_NAME: { buffer [segSize] = 0; final String deviceLabel = String. valueOf (buffer); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_deviceName (deviceLabel); }}); } catch (Exception e) {} } break; case Q_ENSEMBLE: { buffer [segSize] = 0; final String ensembleLabel = String. valueOf (buffer); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_ensembleName (ensembleLabel, 0); }}); } catch (Exception e) {} } break; case Q_SERVICE_NAME: { buffer [segSize] = 0; final String serviceLabel = String. valueOf (buffer); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_serviceName (serviceLabel); }}); } catch (Exception e) {} } break; case Q_TEXT_MESSAGE: { buffer [segSize] = 0; final String dynamicLabel = String. valueOf (buffer); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_dynamicLabel (dynamicLabel); }}); } catch (Exception e) {} } break; case Q_STATE: { final byte vector [] = new byte [2]; vector [0] = (byte)(buffer [0]); vector [1] = (byte)(buffer [1]); try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { show_state (vector); }}); } catch (Exception e) {} } break; case Q_NEW_ENSEMBLE: { try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { clearScreen (); }}); } catch (Exception e) {} } break; case Q_STEREO: { final boolean b = buffer [0] != 0; try { the_gui. runOnUiThread (new Runnable () { @Override public void run () { set_stereoIndicator (b); }}); } catch (Exception e) {} } break; default:; } } public void set_quit () { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. set_quit (); } } public void show_deviceName (String Name) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_deviceName (Name); }; } public void set_initialValues (byte [] v) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. set_initialValues (v); }; } public void show_ensembleName (String Name, int Sid) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_ensembleName (Name, Sid); }; } public void show_serviceName (String s) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_serviceName (s); }; } public void show_dynamicLabel (String s) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_dynamicLabel (s); }; } public void show_state (byte [] v) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. show_state (v); } } public void clearScreen () { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. clearScreen (); }; } public void set_stereoIndicator (boolean b) { int i; for (i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. set_stereoIndicator (b); }; } public void toaster (String s) { final String data = s; try { the_gui.runOnUiThread(new Runnable() { @Override public void run() { the_toaster (data); } }); } catch (Exception e) { } } public void the_toaster (String s) { for (int i = 0; i < listener. size (); i ++) { Signals handler = listener. get (i); handler. toaster (s); } } // // and the transmitters public void setService (String s) { byte data [] = new byte [s. length () + 4]; data [0] = (byte)Q_SERVICE; data [1] = (byte)0; data [2] = (byte) (s. length () + 1); for (int i = 0; i < s. length (); i ++) data [3 + i] = (byte) s. charAt (i); data [3 + s. length ()] = 0; toaster ("Setting service for " + s); try { outputter. write (data, 0, s. length () + 4); outputter. flush (); } catch (Exception e) {} } public void reset () { byte data [] = new byte [4]; data [0] = (byte)Q_RESET; data [1] = (byte)0; data [2] = (byte) (1); data [3] = (byte)0; try { outputter. write (data, 0, 4); outputter. flush (); } catch (Exception e) {} } public void setLnaState (int lnaState) { byte data [] = new byte [3 + 2]; data [0] = (byte)Q_LNA_STATE; data [1] = (byte)0; data [2] = (byte)2; data [3] = (byte)lnaState; try { outputter. write (data, 0, 5); outputter. flush (); } catch (Exception e) {} } public void set_gainLevel (int val) { byte data [] = new byte [3 + 2]; data [0] = (byte)Q_GAIN_SLIDER; data [1] = (byte)0; data [2] = (byte)2; data [3] = (byte)val; try { outputter. write (data, 0, 5); outputter. flush (); } catch (Exception e) {} } public void set_soundLevel (int soundLevel) { byte data [] = new byte [3 + 2]; data [0] = (byte)Q_SOUND_LEVEL; data [1] = (byte)0; data [2] = (byte)2; data [3] = (byte)soundLevel; try { outputter. write (data, 0, 5); outputter. flush (); } catch (Exception e) {} } public void set_autoGain (Boolean b) { byte data [] = new byte [3 + 2]; data [0] = (byte)Q_AUTOGAIN; data [1] = (byte)0; data [2] = (byte)2; data [3] = (byte)(b ? 1 : 0); try { outputter. write (data, 0, 5); outputter. flush (); } catch (Exception e) {} } public void doReset () { byte data[] = new byte[4]; data[0] = Q_RESET; data[1] = 0; data[2] = (char) (1); data[3] = 0; try { outputter.write(data, 0, 4); outputter.flush(); } catch (Exception e) { } } public void do_systemExit () { byte data[] = new byte[4]; data[0] = Q_SYSTEM_EXIT; data[1] = 0; data[2] = (char) (1); data[3] = 0; try { outputter.write(data, 0, 4); outputter.flush(); } catch (Exception e) { } } };
43042_1
package com.atakmap.comms; import android.os.Bundle; import com.atakmap.android.http.rest.ServerVersion; import com.atakmap.annotations.FortifyFinding; import com.atakmap.comms.app.CotPortListActivity; import com.atakmap.coremap.filesystem.FileSystemUtils; import com.atakmap.coremap.log.Log; /** * Metadata for a TAK server connection * Moved out of {@link CotPortListActivity.CotPort} */ public class TAKServer { private static final String TAG = "TAKServer"; public static final String CONNECT_STRING_KEY = "connectString"; public static final String DESCRIPTION_KEY = "description"; public static final String COMPRESSION_KEY = "compress"; public static final String ENABLED_KEY = "enabled"; public static final String CONNECTED_KEY = "connected"; public static final String ERROR_KEY = "error"; public static final String SERVER_VERSION_KEY = "serverVersion"; public static final String SERVER_API_KEY = "serverAPI"; public static final String USEAUTH_KEY = "useAuth"; public static final String USERNAME_KEY = "username"; public static final String ENROLL_FOR_CERT_KEY = "enrollForCertificateWithTrust"; public static final String EXPIRATION_KEY = "expiration"; @FortifyFinding(finding = "Password Management: Hardcoded Password", rational = "This is only a key and not a password") public static final String PASSWORD_KEY = "password"; public static final String CACHECREDS_KEY = "cacheCreds"; public static final String ISSTREAM_KEY = "isStream"; public static final String ISCHAT_KEY = "isChat"; private final Bundle data; public TAKServer(Bundle bundle) throws IllegalArgumentException { String connectString = bundle.getString(CONNECT_STRING_KEY); if (connectString == null || connectString.trim().length() == 0) { throw new IllegalArgumentException( "Cannot construct CotPort with empty/null connnectString"); } this.data = new Bundle(bundle); } public TAKServer(TAKServer other) { this(other.getData()); } @Override public boolean equals(Object other) { if (other instanceof TAKServer) return getConnectString().equalsIgnoreCase(((TAKServer) other) .getConnectString()); return false; } public String getConnectString() { return this.data.getString(CONNECT_STRING_KEY); } public String getURL(boolean includePort) { try { NetConnectString ncs = NetConnectString.fromString( getConnectString()); String proto = ncs.getProto(); if (proto.equalsIgnoreCase("ssl")) proto = "https"; else proto = "http"; String url = proto + "://" + ncs.getHost(); if (includePort) url += ":" + ncs.getPort(); return url; } catch (Exception e) { Log.e(TAG, "Failed to get server URL: " + this, e); } return null; } public void setServerVersion(ServerVersion version) { setServerVersion(version.getVersion()); this.data.putInt(SERVER_API_KEY, version.getApiVersion()); } public void setServerVersion(String version) { this.data.putString(SERVER_VERSION_KEY, version); } public String getServerVersion() { return this.data.getString(SERVER_VERSION_KEY); } public int getServerAPI() { return this.data.getInt(SERVER_API_KEY, -1); } public void setErrorString(String error) { appendString(this.data, ERROR_KEY, error); } public static void appendString(Bundle data, String key, String value) { String existing = data.getString(key); if (FileSystemUtils.isEmpty(existing)) data.putString(key, value); else if (!existing.contains(value)) { data.putString(key, existing + ", " + value); } } public String getErrorString() { return this.data.getString(ERROR_KEY); } public boolean isCompressed() { return this.data.getBoolean(COMPRESSION_KEY, false); } public boolean isUsingAuth() { return this.data.getBoolean(USEAUTH_KEY, false); } public boolean enrollForCert() { return this.data.getBoolean(ENROLL_FOR_CERT_KEY, false); } public boolean isStream() { return this.data.getBoolean(ISSTREAM_KEY, false); } public boolean isChat() { return this.data.getBoolean(ISCHAT_KEY, false); } public String getCacheCredentials() { String cacheCreds = this.data.getString(CACHECREDS_KEY); if (cacheCreds == null) { cacheCreds = ""; } return cacheCreds; } public String getDescription() { String description = this.data.getString(DESCRIPTION_KEY); if (description == null) { description = ""; } return description; } public String getUsername() { String s = this.data.getString(USERNAME_KEY); if (s == null) { s = ""; } return s; } public String getPassword() { String s = this.data.getString(PASSWORD_KEY); if (s == null) { s = ""; } return s; } @Override public int hashCode() { return this.getConnectString().hashCode(); } public boolean isEnabled() { return this.data.getBoolean(ENABLED_KEY, true); } public void setEnabled(boolean newValue) { this.data.putBoolean(ENABLED_KEY, newValue); } public boolean isConnected() { return this.data.getBoolean(CONNECTED_KEY, false); } public void setConnected(boolean newValue) { this.data.putBoolean(CONNECTED_KEY, newValue); if (newValue) this.data.remove(ERROR_KEY); } @Override public String toString() { if (data != null) { return "connect_string=" + data.getString(CONNECT_STRING_KEY) + " " + "description=" + data.getString(DESCRIPTION_KEY) + " " + "compression=" + data.getBoolean(COMPRESSION_KEY) + " " + "enabled=" + data.getBoolean(ENABLED_KEY) + " " + "connected=" + data.getBoolean(CONNECTED_KEY); } return super.toString(); } public Bundle getData() { return this.data; } }
paulmandal/AndroidTacticalAssaultKit-CIV
atak/ATAK/app/src/main/java/com/atakmap/comms/TAKServer.java
1,668
//" + ncs.getHost();
line_comment
nl
package com.atakmap.comms; import android.os.Bundle; import com.atakmap.android.http.rest.ServerVersion; import com.atakmap.annotations.FortifyFinding; import com.atakmap.comms.app.CotPortListActivity; import com.atakmap.coremap.filesystem.FileSystemUtils; import com.atakmap.coremap.log.Log; /** * Metadata for a TAK server connection * Moved out of {@link CotPortListActivity.CotPort} */ public class TAKServer { private static final String TAG = "TAKServer"; public static final String CONNECT_STRING_KEY = "connectString"; public static final String DESCRIPTION_KEY = "description"; public static final String COMPRESSION_KEY = "compress"; public static final String ENABLED_KEY = "enabled"; public static final String CONNECTED_KEY = "connected"; public static final String ERROR_KEY = "error"; public static final String SERVER_VERSION_KEY = "serverVersion"; public static final String SERVER_API_KEY = "serverAPI"; public static final String USEAUTH_KEY = "useAuth"; public static final String USERNAME_KEY = "username"; public static final String ENROLL_FOR_CERT_KEY = "enrollForCertificateWithTrust"; public static final String EXPIRATION_KEY = "expiration"; @FortifyFinding(finding = "Password Management: Hardcoded Password", rational = "This is only a key and not a password") public static final String PASSWORD_KEY = "password"; public static final String CACHECREDS_KEY = "cacheCreds"; public static final String ISSTREAM_KEY = "isStream"; public static final String ISCHAT_KEY = "isChat"; private final Bundle data; public TAKServer(Bundle bundle) throws IllegalArgumentException { String connectString = bundle.getString(CONNECT_STRING_KEY); if (connectString == null || connectString.trim().length() == 0) { throw new IllegalArgumentException( "Cannot construct CotPort with empty/null connnectString"); } this.data = new Bundle(bundle); } public TAKServer(TAKServer other) { this(other.getData()); } @Override public boolean equals(Object other) { if (other instanceof TAKServer) return getConnectString().equalsIgnoreCase(((TAKServer) other) .getConnectString()); return false; } public String getConnectString() { return this.data.getString(CONNECT_STRING_KEY); } public String getURL(boolean includePort) { try { NetConnectString ncs = NetConnectString.fromString( getConnectString()); String proto = ncs.getProto(); if (proto.equalsIgnoreCase("ssl")) proto = "https"; else proto = "http"; String url = proto + "://" +<SUF> if (includePort) url += ":" + ncs.getPort(); return url; } catch (Exception e) { Log.e(TAG, "Failed to get server URL: " + this, e); } return null; } public void setServerVersion(ServerVersion version) { setServerVersion(version.getVersion()); this.data.putInt(SERVER_API_KEY, version.getApiVersion()); } public void setServerVersion(String version) { this.data.putString(SERVER_VERSION_KEY, version); } public String getServerVersion() { return this.data.getString(SERVER_VERSION_KEY); } public int getServerAPI() { return this.data.getInt(SERVER_API_KEY, -1); } public void setErrorString(String error) { appendString(this.data, ERROR_KEY, error); } public static void appendString(Bundle data, String key, String value) { String existing = data.getString(key); if (FileSystemUtils.isEmpty(existing)) data.putString(key, value); else if (!existing.contains(value)) { data.putString(key, existing + ", " + value); } } public String getErrorString() { return this.data.getString(ERROR_KEY); } public boolean isCompressed() { return this.data.getBoolean(COMPRESSION_KEY, false); } public boolean isUsingAuth() { return this.data.getBoolean(USEAUTH_KEY, false); } public boolean enrollForCert() { return this.data.getBoolean(ENROLL_FOR_CERT_KEY, false); } public boolean isStream() { return this.data.getBoolean(ISSTREAM_KEY, false); } public boolean isChat() { return this.data.getBoolean(ISCHAT_KEY, false); } public String getCacheCredentials() { String cacheCreds = this.data.getString(CACHECREDS_KEY); if (cacheCreds == null) { cacheCreds = ""; } return cacheCreds; } public String getDescription() { String description = this.data.getString(DESCRIPTION_KEY); if (description == null) { description = ""; } return description; } public String getUsername() { String s = this.data.getString(USERNAME_KEY); if (s == null) { s = ""; } return s; } public String getPassword() { String s = this.data.getString(PASSWORD_KEY); if (s == null) { s = ""; } return s; } @Override public int hashCode() { return this.getConnectString().hashCode(); } public boolean isEnabled() { return this.data.getBoolean(ENABLED_KEY, true); } public void setEnabled(boolean newValue) { this.data.putBoolean(ENABLED_KEY, newValue); } public boolean isConnected() { return this.data.getBoolean(CONNECTED_KEY, false); } public void setConnected(boolean newValue) { this.data.putBoolean(CONNECTED_KEY, newValue); if (newValue) this.data.remove(ERROR_KEY); } @Override public String toString() { if (data != null) { return "connect_string=" + data.getString(CONNECT_STRING_KEY) + " " + "description=" + data.getString(DESCRIPTION_KEY) + " " + "compression=" + data.getBoolean(COMPRESSION_KEY) + " " + "enabled=" + data.getBoolean(ENABLED_KEY) + " " + "connected=" + data.getBoolean(CONNECTED_KEY); } return super.toString(); } public Bundle getData() { return this.data; } }
134880_1
/************************************************************************************ ** The MIT License (MIT) ** ** Copyright (c) 2016 Serg "EXL" Koles ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, 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: ** ** The above copyright notice and this permission notice shall be included in all ** copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** 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 ru.exlmoto.astrosmash; import java.util.Random; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Rect; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import ru.exlmoto.astrosmash.AstroSmashLauncher.AstroSmashSettings; import ru.exlmoto.astrosmash.AstroSmashEngine.GameWorld; import ru.exlmoto.astrosmash.AstroSmashEngine.Version; import ru.exlmoto.astrosmash.AstroSmashEngine.IGameWorldListener; @SuppressWarnings("unused") public class AstroSmashView extends SurfaceView implements SurfaceHolder.Callback, IGameWorldListener, Runnable { public static final int INITIAL_KEY_DELAY = 250; public static final int KEY_REPEAT_CYCLE = 75; private boolean m_bRunning = true; private boolean isGameOver = false; private Thread m_gameThread = null; private GameWorld m_gameWorld = null; private volatile boolean m_bKeyHeldDown = false; private volatile boolean m_bAfterInitialWait = false; private volatile int m_heldDownGameAction; private volatile long m_initialHoldDownTime; private boolean m_bFirstPaint = true; private long m_nStartTime; private long m_nPauseTime = 0L; private long m_nPausedTime = 0L; Thread m_currentThread = null; int m_nThreadSwitches = 0; long m_nLastMemoryUsageTime = 0L; private int screenWidth; private int screenHeight; private int screenHeightPercent; private Paint painter = null; private Canvas bitmapCanvas = null; private Canvas globalCanvas = null; private Bitmap gameScreen = null; private Bitmap touchArrowBitmap = null; private Canvas touchArrowCanvas = null; private Rect touchRect = null; private Rect bitmapRect = null; private Rect screenRect = null; private Rect screenRectPercent = null; private int px1 = 0; private int px5 = 0; private int px25 = 0; private int px25double = 0; private int arrow_Y0 = 0; private int arrow_Y1 = 0; private int arrow_Y2 = 0; private int arrow_X0 = 0; private int arrow_X1 = 0; private int screenRectChunkProcent = 0; private static Random m_random; private SurfaceHolder surfaceHolder = null; private AstroSmashActivity astroSmashActivity = null; public AstroSmashView(Context context) { super(context); astroSmashActivity = (AstroSmashActivity) context; m_random = new Random(System.currentTimeMillis()); switch (AstroSmashSettings.graphicsScale) { case AstroSmashLauncher.SCALE_120P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_120x146); break; case AstroSmashLauncher.SCALE_176P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_176x220); break; case AstroSmashLauncher.SCALE_240P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_240x320); break; case AstroSmashLauncher.SCALE_480P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_480x640); break; default: break; } surfaceHolder = getHolder(); surfaceHolder.addCallback(this); gameScreen = Bitmap.createBitmap(Version.getWidth(), Version.getHeight(), Bitmap.Config.ARGB_8888); bitmapCanvas = new Canvas(gameScreen); painter = new Paint(); m_gameWorld = new GameWorld(Version.getWidth(), Version.getHeight() - Version.getCommandHeightPixels(), this, context); this.m_bFirstPaint = true; restartGame(true); this.m_nStartTime = 0L; this.m_nPauseTime = 0L; this.m_nPausedTime = 0L; // Set screen on setKeepScreenOn(true); // Focus setFocusable(true); setFocusableInTouchMode(true); requestFocus(); } public void render(Canvas canvas) { if (canvas != null && bitmapCanvas != null) { if (this.m_bFirstPaint) { clearScreen(bitmapCanvas); this.m_bFirstPaint = false; } this.m_gameWorld.paint(bitmapCanvas, painter); if (gameScreen != null) { if (AstroSmashSettings.antialiasing) { painter.setFilterBitmap(true); } if (AstroSmashSettings.showTouchRect) { canvas.drawBitmap(gameScreen, bitmapRect, screenRectPercent, painter); canvas.drawBitmap(touchArrowBitmap, 0, screenRectChunkProcent, painter); } else { canvas.drawBitmap(gameScreen, bitmapRect, screenRect, painter); } } } } private int px(float dips) { float dp = getResources().getDisplayMetrics().density; return Math.round(dips * dp); } private void drawTouchArrow(Canvas canvas, Paint paint) { paint.setColor(Version.GREENCOLOR_DARK); canvas.drawRect(0, 0, screenWidth, screenHeightPercent, paint); paint.setStrokeCap(Cap.ROUND); paint.setAntiAlias(true); for (int i = 0; i < 2; ++i) { if (i == 0) { paint.setColor(Version.GRAYCOLOR); paint.setStrokeWidth(px5); } else { paint.setColor(Version.DARKCOLOR); paint.setStrokeWidth(px1); } canvas.drawLine(px25, arrow_Y0, arrow_X0, arrow_Y0, paint); canvas.drawLine(px25, arrow_Y0, px25double, arrow_Y1, paint); canvas.drawLine(px25, arrow_Y0, px25double, arrow_Y2, paint); canvas.drawLine(arrow_X0, arrow_Y0, arrow_X1, arrow_Y1, paint); canvas.drawLine(arrow_X0, arrow_Y0, arrow_X1, arrow_Y2, paint); } } public boolean isM_bRunning() { return m_bRunning; } public boolean isGameOver() { return isGameOver; } public void SetisGameOver(boolean gameOver) { isGameOver = gameOver; } public int getScreenHeightPercent() { return screenHeightPercent; } public void setScreenHeightPercent(int screenHeightPercent) { this.screenHeightPercent = screenHeightPercent; } public void resetStartTime() { this.m_nStartTime = System.currentTimeMillis(); this.m_nPauseTime = 0L; this.m_nPausedTime = 0L; } public void pause(boolean paused) { AstroSmashActivity.toDebug("Paused: " + paused); this.m_gameWorld.pause(paused); } public void exit() { this.m_bRunning = false; this.m_gameThread = null; } public void start() { if (Version.getDemoFlag()) { if (this.m_nPauseTime > 0L) { this.m_nPausedTime += System.currentTimeMillis() - this.m_nPauseTime; } this.m_nPauseTime = 0L; } this.m_bRunning = true; this.m_gameThread = new Thread(this); this.m_gameThread.start(); this.m_gameWorld.pause(false); } public int getPeakScore() { return this.m_gameWorld.getPeakScore(); } public void restartGame(boolean constructor) { resetStartTime(); this.m_gameWorld.reset(); this.m_bFirstPaint = true; if (!constructor) { init(); start(); } } public int getGameAction(int paramInt) { switch (paramInt) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_SPACE: case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_5: return 9; // Fire case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_W: case KeyEvent.KEYCODE_8: return 1; // Auto Fire case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_A: case KeyEvent.KEYCODE_4: return 2; // Left case KeyEvent.KEYCODE_DPAD_RIGHT: case KeyEvent.KEYCODE_D: case KeyEvent.KEYCODE_6: return 5; // Right case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_S: case KeyEvent.KEYCODE_2: return 6; // Hyper case KeyEvent.KEYCODE_Q: case KeyEvent.KEYCODE_E: case KeyEvent.KEYCODE_7: return 10; // Unknown } return 0; // return super.getGameAction(paramInt); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { this.m_bKeyHeldDown = false; return super.onKeyUp(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { try { int i = getGameAction(keyCode); if (this.m_bRunning) { this.m_gameWorld.handleAction(i); } this.m_heldDownGameAction = i; this.m_bKeyHeldDown = true; this.m_initialHoldDownTime = System.currentTimeMillis(); } catch (Exception localException) { System.out.println(localException.getMessage()); localException.printStackTrace(); } return super.onKeyDown(keyCode, event); } private int getPercentChunkHeight(int sideSize, int percent) { return Math.round(sideSize * percent / 100); } private void init() { screenHeightPercent = getPercentChunkHeight(screenHeight, 15); touchRect = new Rect(0, screenHeight - screenHeightPercent, screenWidth, screenHeight); bitmapRect = new Rect(0, 0, gameScreen.getWidth(), gameScreen.getHeight()); screenRect = new Rect(0, 0, screenWidth, screenHeight); screenRectPercent = new Rect(0, 0, screenWidth, screenHeight - screenHeightPercent); px1 = px(1); px5 = px(5); px25 = px(25); px25double = px25 * 2; arrow_Y0 = touchRect.height() / 2; arrow_Y1 = touchRect.height() / 4; arrow_Y2 = touchRect.height() / 4 * 3; arrow_X0 = screenWidth - px25; arrow_X1 = screenWidth - px25double; screenRectChunkProcent = screenHeight - screenHeightPercent; touchArrowBitmap = Bitmap.createBitmap(screenWidth, screenHeightPercent, Bitmap.Config.ARGB_8888); touchArrowCanvas = new Canvas(touchArrowBitmap); drawTouchArrow(touchArrowCanvas, painter); } @Override public void surfaceCreated(SurfaceHolder holder) { AstroSmashActivity.toDebug("Surface created"); screenWidth = holder.getSurfaceFrame().width(); screenHeight = holder.getSurfaceFrame().height(); init(); start(); if (AstroSmashActivity.paused) { pause(true); } if (isGameOver) { gameIsOver(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { AstroSmashActivity.toDebug("Surface changed: " + width + "x" + height + "|" + screenWidth + "x" + screenHeight); } @Override public void surfaceDestroyed(SurfaceHolder holder) { AstroSmashActivity.toDebug("Surface destroyed"); boolean shutdown = false; this.m_bRunning = false; while (!shutdown) { try { if (m_gameThread != null) { this.m_gameThread.join(); } shutdown = true; } catch (InterruptedException e) { AstroSmashActivity.toDebug("Error joining to Game Thread"); } } } public int getScorePosition(int score) { for (int i = 0; i < AstroSmashLauncher.HISCORE_PLAYERS; i++) { if (score > AstroSmashSettings.playerScores[i]) { return i; } } return -1; } public int addScore(int score, int restartGame) { int i = getScorePosition(score); if (i == -1) { return i; } Intent intent = new Intent(this.getContext(), AstroSmashHighScoreDialog.class); intent.putExtra("peakScore", score); intent.putExtra("indexScore", i); intent.putExtra("restartGame", restartGame); astroSmashActivity.startActivity(intent); return i; } public int checkHiScores(int restartGame) { int peakScore = m_gameWorld.getPeakScore(); AstroSmashActivity.toDebug("HiScore is: " + peakScore); return addScore(peakScore, restartGame); } public void setShipX(int xCoord) { this.m_gameWorld.getShip().setX(xCoord); } public void fire() { this.m_gameWorld.fireBullet(); } protected void clearScreen(Canvas canvas) { canvas.drawColor(Version.WHITECOLOR); } @Override public void gameIsOver() { isGameOver = true; AstroSmashActivity.toDebug("Game Over!"); AstroSmashLauncher.playGameOverSound(); this.m_bRunning = false; this.m_gameThread = null; } public static int getAbsRandomInt() { m_random.setSeed(System.currentTimeMillis() + m_random.nextInt()); return Math.abs(m_random.nextInt()); } public static int getRandomIntBetween(int min, int max) { return (int) ((Math.random() * (max - min)) + min); } public static int getRandomInt() { m_random.setSeed(System.currentTimeMillis() + m_random.nextInt()); return m_random.nextInt(); } public int getScreenWidth() { return screenWidth; } public int getScreenHeight() { return screenHeight; } public int getScreenRectChunkProcent() { return screenRectChunkProcent; } @Override public void run() { try { // long l1 = System.currentTimeMillis(); long l2 = System.currentTimeMillis(); long l5 = l2; this.m_nLastMemoryUsageTime = 0L; while (this.m_bRunning) { long l3 = System.currentTimeMillis(); long l4 = l3 - l2; // if (AstroSmashVersion.getDebugFlag()) { // if ((AstroSmashVersion.getDebugMemoryFlag()) && (l3 - this.m_nLastMemoryUsageTime > AstroSmashVersion.getDebugMemoryInterval())) { // // AstroSmashMidlet.printMemoryUsage("AstrosmashScreen.run (" + (l3 - l1) / 1000L + " secs)"); // this.m_nLastMemoryUsageTime = l3; // } // if (this.m_currentThread != Thread.currentThread()) { // this.m_currentThread = Thread.currentThread(); // this.m_nThreadSwitches += 1; // System.out.println("AstrosmashScreen.run: Game thread switch (" + this.m_nThreadSwitches + " total)"); // } // } // if ((AstroSmashVersion.getDemoFlag()) && (l3 - this.m_nStartTime - this.m_nPausedTime >= AstroSmashVersion.getDemoDuration() * 1000)) { // this.m_gameWorld.suspendEnemies(); // } if ((this.m_bKeyHeldDown) && (l3 - this.m_initialHoldDownTime > 250L) && (l3 - l5 > 75L)) { l5 = l3; this.m_gameWorld.handleAction(this.m_heldDownGameAction); } this.m_gameWorld.tick(l4); try { this.globalCanvas = surfaceHolder.lockCanvas(); synchronized (surfaceHolder) { render(this.globalCanvas); } } finally { if (this.globalCanvas != null) { surfaceHolder.unlockCanvasAndPost(this.globalCanvas); } } l2 = l3; } } catch (Exception localException) { System.out.println(localException.getMessage()); localException.printStackTrace(); } } }
EXL/AstroSmash
astrosmash/src/main/java/ru/exlmoto/astrosmash/AstroSmashView.java
4,666
// Set screen on
line_comment
nl
/************************************************************************************ ** The MIT License (MIT) ** ** Copyright (c) 2016 Serg "EXL" Koles ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, 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: ** ** The above copyright notice and this permission notice shall be included in all ** copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** 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 ru.exlmoto.astrosmash; import java.util.Random; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Rect; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import ru.exlmoto.astrosmash.AstroSmashLauncher.AstroSmashSettings; import ru.exlmoto.astrosmash.AstroSmashEngine.GameWorld; import ru.exlmoto.astrosmash.AstroSmashEngine.Version; import ru.exlmoto.astrosmash.AstroSmashEngine.IGameWorldListener; @SuppressWarnings("unused") public class AstroSmashView extends SurfaceView implements SurfaceHolder.Callback, IGameWorldListener, Runnable { public static final int INITIAL_KEY_DELAY = 250; public static final int KEY_REPEAT_CYCLE = 75; private boolean m_bRunning = true; private boolean isGameOver = false; private Thread m_gameThread = null; private GameWorld m_gameWorld = null; private volatile boolean m_bKeyHeldDown = false; private volatile boolean m_bAfterInitialWait = false; private volatile int m_heldDownGameAction; private volatile long m_initialHoldDownTime; private boolean m_bFirstPaint = true; private long m_nStartTime; private long m_nPauseTime = 0L; private long m_nPausedTime = 0L; Thread m_currentThread = null; int m_nThreadSwitches = 0; long m_nLastMemoryUsageTime = 0L; private int screenWidth; private int screenHeight; private int screenHeightPercent; private Paint painter = null; private Canvas bitmapCanvas = null; private Canvas globalCanvas = null; private Bitmap gameScreen = null; private Bitmap touchArrowBitmap = null; private Canvas touchArrowCanvas = null; private Rect touchRect = null; private Rect bitmapRect = null; private Rect screenRect = null; private Rect screenRectPercent = null; private int px1 = 0; private int px5 = 0; private int px25 = 0; private int px25double = 0; private int arrow_Y0 = 0; private int arrow_Y1 = 0; private int arrow_Y2 = 0; private int arrow_X0 = 0; private int arrow_X1 = 0; private int screenRectChunkProcent = 0; private static Random m_random; private SurfaceHolder surfaceHolder = null; private AstroSmashActivity astroSmashActivity = null; public AstroSmashView(Context context) { super(context); astroSmashActivity = (AstroSmashActivity) context; m_random = new Random(System.currentTimeMillis()); switch (AstroSmashSettings.graphicsScale) { case AstroSmashLauncher.SCALE_120P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_120x146); break; case AstroSmashLauncher.SCALE_176P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_176x220); break; case AstroSmashLauncher.SCALE_240P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_240x320); break; case AstroSmashLauncher.SCALE_480P: Version.setScreenSizes(Version.ANDROID_ORIGINAL_480x640); break; default: break; } surfaceHolder = getHolder(); surfaceHolder.addCallback(this); gameScreen = Bitmap.createBitmap(Version.getWidth(), Version.getHeight(), Bitmap.Config.ARGB_8888); bitmapCanvas = new Canvas(gameScreen); painter = new Paint(); m_gameWorld = new GameWorld(Version.getWidth(), Version.getHeight() - Version.getCommandHeightPixels(), this, context); this.m_bFirstPaint = true; restartGame(true); this.m_nStartTime = 0L; this.m_nPauseTime = 0L; this.m_nPausedTime = 0L; // Set screen<SUF> setKeepScreenOn(true); // Focus setFocusable(true); setFocusableInTouchMode(true); requestFocus(); } public void render(Canvas canvas) { if (canvas != null && bitmapCanvas != null) { if (this.m_bFirstPaint) { clearScreen(bitmapCanvas); this.m_bFirstPaint = false; } this.m_gameWorld.paint(bitmapCanvas, painter); if (gameScreen != null) { if (AstroSmashSettings.antialiasing) { painter.setFilterBitmap(true); } if (AstroSmashSettings.showTouchRect) { canvas.drawBitmap(gameScreen, bitmapRect, screenRectPercent, painter); canvas.drawBitmap(touchArrowBitmap, 0, screenRectChunkProcent, painter); } else { canvas.drawBitmap(gameScreen, bitmapRect, screenRect, painter); } } } } private int px(float dips) { float dp = getResources().getDisplayMetrics().density; return Math.round(dips * dp); } private void drawTouchArrow(Canvas canvas, Paint paint) { paint.setColor(Version.GREENCOLOR_DARK); canvas.drawRect(0, 0, screenWidth, screenHeightPercent, paint); paint.setStrokeCap(Cap.ROUND); paint.setAntiAlias(true); for (int i = 0; i < 2; ++i) { if (i == 0) { paint.setColor(Version.GRAYCOLOR); paint.setStrokeWidth(px5); } else { paint.setColor(Version.DARKCOLOR); paint.setStrokeWidth(px1); } canvas.drawLine(px25, arrow_Y0, arrow_X0, arrow_Y0, paint); canvas.drawLine(px25, arrow_Y0, px25double, arrow_Y1, paint); canvas.drawLine(px25, arrow_Y0, px25double, arrow_Y2, paint); canvas.drawLine(arrow_X0, arrow_Y0, arrow_X1, arrow_Y1, paint); canvas.drawLine(arrow_X0, arrow_Y0, arrow_X1, arrow_Y2, paint); } } public boolean isM_bRunning() { return m_bRunning; } public boolean isGameOver() { return isGameOver; } public void SetisGameOver(boolean gameOver) { isGameOver = gameOver; } public int getScreenHeightPercent() { return screenHeightPercent; } public void setScreenHeightPercent(int screenHeightPercent) { this.screenHeightPercent = screenHeightPercent; } public void resetStartTime() { this.m_nStartTime = System.currentTimeMillis(); this.m_nPauseTime = 0L; this.m_nPausedTime = 0L; } public void pause(boolean paused) { AstroSmashActivity.toDebug("Paused: " + paused); this.m_gameWorld.pause(paused); } public void exit() { this.m_bRunning = false; this.m_gameThread = null; } public void start() { if (Version.getDemoFlag()) { if (this.m_nPauseTime > 0L) { this.m_nPausedTime += System.currentTimeMillis() - this.m_nPauseTime; } this.m_nPauseTime = 0L; } this.m_bRunning = true; this.m_gameThread = new Thread(this); this.m_gameThread.start(); this.m_gameWorld.pause(false); } public int getPeakScore() { return this.m_gameWorld.getPeakScore(); } public void restartGame(boolean constructor) { resetStartTime(); this.m_gameWorld.reset(); this.m_bFirstPaint = true; if (!constructor) { init(); start(); } } public int getGameAction(int paramInt) { switch (paramInt) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_SPACE: case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_5: return 9; // Fire case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_W: case KeyEvent.KEYCODE_8: return 1; // Auto Fire case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_A: case KeyEvent.KEYCODE_4: return 2; // Left case KeyEvent.KEYCODE_DPAD_RIGHT: case KeyEvent.KEYCODE_D: case KeyEvent.KEYCODE_6: return 5; // Right case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_S: case KeyEvent.KEYCODE_2: return 6; // Hyper case KeyEvent.KEYCODE_Q: case KeyEvent.KEYCODE_E: case KeyEvent.KEYCODE_7: return 10; // Unknown } return 0; // return super.getGameAction(paramInt); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { this.m_bKeyHeldDown = false; return super.onKeyUp(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { try { int i = getGameAction(keyCode); if (this.m_bRunning) { this.m_gameWorld.handleAction(i); } this.m_heldDownGameAction = i; this.m_bKeyHeldDown = true; this.m_initialHoldDownTime = System.currentTimeMillis(); } catch (Exception localException) { System.out.println(localException.getMessage()); localException.printStackTrace(); } return super.onKeyDown(keyCode, event); } private int getPercentChunkHeight(int sideSize, int percent) { return Math.round(sideSize * percent / 100); } private void init() { screenHeightPercent = getPercentChunkHeight(screenHeight, 15); touchRect = new Rect(0, screenHeight - screenHeightPercent, screenWidth, screenHeight); bitmapRect = new Rect(0, 0, gameScreen.getWidth(), gameScreen.getHeight()); screenRect = new Rect(0, 0, screenWidth, screenHeight); screenRectPercent = new Rect(0, 0, screenWidth, screenHeight - screenHeightPercent); px1 = px(1); px5 = px(5); px25 = px(25); px25double = px25 * 2; arrow_Y0 = touchRect.height() / 2; arrow_Y1 = touchRect.height() / 4; arrow_Y2 = touchRect.height() / 4 * 3; arrow_X0 = screenWidth - px25; arrow_X1 = screenWidth - px25double; screenRectChunkProcent = screenHeight - screenHeightPercent; touchArrowBitmap = Bitmap.createBitmap(screenWidth, screenHeightPercent, Bitmap.Config.ARGB_8888); touchArrowCanvas = new Canvas(touchArrowBitmap); drawTouchArrow(touchArrowCanvas, painter); } @Override public void surfaceCreated(SurfaceHolder holder) { AstroSmashActivity.toDebug("Surface created"); screenWidth = holder.getSurfaceFrame().width(); screenHeight = holder.getSurfaceFrame().height(); init(); start(); if (AstroSmashActivity.paused) { pause(true); } if (isGameOver) { gameIsOver(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { AstroSmashActivity.toDebug("Surface changed: " + width + "x" + height + "|" + screenWidth + "x" + screenHeight); } @Override public void surfaceDestroyed(SurfaceHolder holder) { AstroSmashActivity.toDebug("Surface destroyed"); boolean shutdown = false; this.m_bRunning = false; while (!shutdown) { try { if (m_gameThread != null) { this.m_gameThread.join(); } shutdown = true; } catch (InterruptedException e) { AstroSmashActivity.toDebug("Error joining to Game Thread"); } } } public int getScorePosition(int score) { for (int i = 0; i < AstroSmashLauncher.HISCORE_PLAYERS; i++) { if (score > AstroSmashSettings.playerScores[i]) { return i; } } return -1; } public int addScore(int score, int restartGame) { int i = getScorePosition(score); if (i == -1) { return i; } Intent intent = new Intent(this.getContext(), AstroSmashHighScoreDialog.class); intent.putExtra("peakScore", score); intent.putExtra("indexScore", i); intent.putExtra("restartGame", restartGame); astroSmashActivity.startActivity(intent); return i; } public int checkHiScores(int restartGame) { int peakScore = m_gameWorld.getPeakScore(); AstroSmashActivity.toDebug("HiScore is: " + peakScore); return addScore(peakScore, restartGame); } public void setShipX(int xCoord) { this.m_gameWorld.getShip().setX(xCoord); } public void fire() { this.m_gameWorld.fireBullet(); } protected void clearScreen(Canvas canvas) { canvas.drawColor(Version.WHITECOLOR); } @Override public void gameIsOver() { isGameOver = true; AstroSmashActivity.toDebug("Game Over!"); AstroSmashLauncher.playGameOverSound(); this.m_bRunning = false; this.m_gameThread = null; } public static int getAbsRandomInt() { m_random.setSeed(System.currentTimeMillis() + m_random.nextInt()); return Math.abs(m_random.nextInt()); } public static int getRandomIntBetween(int min, int max) { return (int) ((Math.random() * (max - min)) + min); } public static int getRandomInt() { m_random.setSeed(System.currentTimeMillis() + m_random.nextInt()); return m_random.nextInt(); } public int getScreenWidth() { return screenWidth; } public int getScreenHeight() { return screenHeight; } public int getScreenRectChunkProcent() { return screenRectChunkProcent; } @Override public void run() { try { // long l1 = System.currentTimeMillis(); long l2 = System.currentTimeMillis(); long l5 = l2; this.m_nLastMemoryUsageTime = 0L; while (this.m_bRunning) { long l3 = System.currentTimeMillis(); long l4 = l3 - l2; // if (AstroSmashVersion.getDebugFlag()) { // if ((AstroSmashVersion.getDebugMemoryFlag()) && (l3 - this.m_nLastMemoryUsageTime > AstroSmashVersion.getDebugMemoryInterval())) { // // AstroSmashMidlet.printMemoryUsage("AstrosmashScreen.run (" + (l3 - l1) / 1000L + " secs)"); // this.m_nLastMemoryUsageTime = l3; // } // if (this.m_currentThread != Thread.currentThread()) { // this.m_currentThread = Thread.currentThread(); // this.m_nThreadSwitches += 1; // System.out.println("AstrosmashScreen.run: Game thread switch (" + this.m_nThreadSwitches + " total)"); // } // } // if ((AstroSmashVersion.getDemoFlag()) && (l3 - this.m_nStartTime - this.m_nPausedTime >= AstroSmashVersion.getDemoDuration() * 1000)) { // this.m_gameWorld.suspendEnemies(); // } if ((this.m_bKeyHeldDown) && (l3 - this.m_initialHoldDownTime > 250L) && (l3 - l5 > 75L)) { l5 = l3; this.m_gameWorld.handleAction(this.m_heldDownGameAction); } this.m_gameWorld.tick(l4); try { this.globalCanvas = surfaceHolder.lockCanvas(); synchronized (surfaceHolder) { render(this.globalCanvas); } } finally { if (this.globalCanvas != null) { surfaceHolder.unlockCanvasAndPost(this.globalCanvas); } } l2 = l3; } } catch (Exception localException) { System.out.println(localException.getMessage()); localException.printStackTrace(); } } }
29049_50
/* * Copyright (c) 2010-2020 Haifeng Li. All rights reserved. * * Smile is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Smile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Smile. If not, see <https://www.gnu.org/licenses/>. */ package dr.math.matrixAlgebra; import dr.math.MachineAccuracy; import java.util.Arrays; /** * The Lanczos algorithm is a direct algorithm devised by Cornelius Lanczos * that is an adaptation of power methods to find the most useful eigenvalues * and eigenvectors of an n<sup>th</sup> order linear system with a limited * number of operations, m, where m is much smaller than n. * <p> * Although computationally efficient in principle, the method as initially * formulated was not useful, due to its numerical instability. In this * implementation, we use partial reorthogonalization to make the method * numerically stable. * * @author Haifeng Li */ public class Lanczos { /** * Find k largest approximate eigen pairs of a symmetric matrix by the * Lanczos algorithm. * * @param A the matrix supporting matrix vector multiplication operation. * @param k the number of eigenvalues we wish to compute for the input matrix. * This number cannot exceed the size of A. * @return eigen value decomposition. */ public static double[] eigen(ReadableMatrix A, int k) { double[] res = eigen(A, k, 1.0E-8, 10 * A.getDim()); System.err.println(Arrays.toString(res)); return res; } /** * Find k largest approximate eigen pairs of a symmetric matrix by the * Lanczos algorithm. * * @param A the matrix supporting matrix vector multiplication operation. * @param k the number of eigenvalues we wish to compute for the input matrix. * This number cannot exceed the size of A. * @param kappa relative accuracy of ritz values acceptable as eigenvalues. * @param maxIter Maximum number of iterations. * @return eigen value decomposition. */ public static double[] eigen(ReadableMatrix A, int k, double kappa, int maxIter) { int n = A.getMajorDim(); int intro = 0; // roundoff estimate for dot product of two unit vectors double eps = MachineAccuracy.EPSILON * Math.sqrt(n); double reps = Math.sqrt(MachineAccuracy.EPSILON); double eps34 = reps * Math.sqrt(reps); kappa = Math.max(kappa, eps34); // Workspace // wptr[0] r[j] // wptr[1] q[j] // wptr[2] q[j-1] // wptr[3] p // wptr[4] p[j-1] // wptr[5] temporary worksapce double[][] wptr = new double[6][n]; // orthogonality estimate of Lanczos vectors at step j double[] eta = new double[n]; // orthogonality estimate of Lanczos vectors at step j-1 double[] oldeta = new double[n]; // the error bounds double[] bnd = new double[n]; // diagonal elements of T double[] alf = new double[n]; // off-diagonal elements of T double[] bet = new double[n + 1]; // basis vectors for the Krylov subspace double[][] q = new double[n][]; // initial Lanczos vectors double[][] p = new double[2][]; // arrays used in the QL decomposition double[] ritz = new double[n + 1]; // eigenvectors calculated in the QL decomposition WrappedMatrix z = null; // First step of the Lanczos algorithm. It also does a step of extended // local re-orthogonalization. // get initial vector; default is random double rnm = startv(A, q, wptr, 0); // normalize starting vector double t = 1.0 / rnm; scale(t, wptr[0], wptr[1]); scale(t, wptr[3]); // take the first step product(A, wptr[3], wptr[0]); //A.mv(wptr[3], wptr[0]); //todo: wptr[0] = A wptr[3] alf[0] = dot(wptr[0], wptr[3]); //alf[0] = MathEx.dot(wptr[0], wptr[3]); // todo: dot product axpy(-alf[0], wptr[1], wptr[0]); //MathEx.axpy(-alf[0], wptr[1], wptr[0]); // todo: (a,x,y) -> y = ax+y t = dot(wptr[0], wptr[3]); //t = MathEx.dot(wptr[0], wptr[3]); //todo: dot product axpy(-t, wptr[1], wptr[0]); alf[0] += t; System.arraycopy(wptr[0], 0, wptr[4], 0, n); rnm = norm(wptr[0]); double anorm = rnm + Math.abs(alf[0]); double tol = reps * anorm; if (0 == rnm) { throw new IllegalStateException("Lanczos method was unable to find a starting vector within range."); } eta[0] = eps; oldeta[0] = eps; // number of ritz values stabilized int neig = 0; // number of intitial Lanczos vectors in local orthog. (has value of 0, 1 or 2) int ll = 0; // start of index through loop int first = 1; // end of index through loop int last = Math.min(k + Math.max(8, k), n); // number of Lanczos steps actually taken int j = 0; // stop flag boolean enough = false; // algorithm iterations int iter = 0; for (; !enough && iter < maxIter; iter++) { if (rnm <= tol) { rnm = 0.0; } // a single Lanczos step for (j = first; j < last; j++) { swap(wptr, 1, 2); //todo: swap element i and j for x swap(wptr, 3, 4); store(q, j - 1, wptr[2]); if (j - 1 < 2) { p[j - 1] = wptr[4].clone(); } bet[j] = rnm; // restart if invariant subspace is found if (0 == bet[j]) { rnm = startv(A, q, wptr, j); if (rnm < 0.0) { rnm = 0.0; break; } if (rnm == 0) { enough = true; } } if (enough) { // These lines fix a bug that occurs with low-rank matrices swap(wptr, 1, 2); break; } // take a lanczos step t = 1.0 / rnm; scale(t, wptr[0], wptr[1]); scale(t, wptr[3]); product(A, wptr[3], wptr[0]); //A.mv(wptr[3], wptr[0]); axpy(-rnm, wptr[2], wptr[0]); alf[j] = dot(wptr[0], wptr[3]); axpy(-alf[j], wptr[1], wptr[0]); // orthogonalize against initial lanczos vectors if (j <= 2 && (Math.abs(alf[j - 1]) > 4.0 * Math.abs(alf[j]))) { ll = j; } for (int i = 0; i < Math.min(ll, j - 1); i++) { t = dot(p[i], wptr[0]); axpy(-t, q[i], wptr[0]); eta[i] = eps; oldeta[i] = eps; } // extended local reorthogonalization t = dot(wptr[0], wptr[4]); axpy(-t, wptr[2], wptr[0]); if (bet[j] > 0.0) { bet[j] = bet[j] + t; } t = dot(wptr[0], wptr[3]); axpy(-t, wptr[1], wptr[0]); alf[j] = alf[j] + t; System.arraycopy(wptr[0], 0, wptr[4], 0, n); rnm = norm(wptr[0]); anorm = bet[j] + Math.abs(alf[j]) + rnm; tol = reps * anorm; // update the orthogonality bounds ortbnd(alf, bet, eta, oldeta, j, rnm, eps); // restore the orthogonality state when needed rnm = purge(ll, q, wptr[0], wptr[1], wptr[4], wptr[3], eta, oldeta, j, rnm, tol, eps, reps); if (rnm <= tol) { rnm = 0.0; } } if (enough) { j = j - 1; } else { j = last - 1; } first = j + 1; bet[j + 1] = rnm; // analyze T System.arraycopy(alf, 0, ritz, 0, j + 1); System.arraycopy(bet, 0, wptr[5], 0, j + 1); z = new WrappedMatrix.Raw(new double[(j+1) * (j+1)], 0, j+1, j+1); for (int i = 0; i <= j; i++) { z.set(i, i, 1.0); } // compute the eigenvalues and eigenvectors of the // tridiagonal matrix tql2(z, ritz, wptr[5]); for (int i = 0; i <= j; i++) { bnd[i] = rnm * Math.abs(z.get(j, i)); } // massage error bounds for very close ritz values boolean[] ref_enough = {enough}; neig = error_bound(ref_enough, ritz, bnd, j, tol, eps34); enough = ref_enough[0]; // should we stop? if (neig < k) { if (0 == neig) { last = first + 9; intro = first; } else { last = first + Math.max(3, 1 + ((j - intro) * (k - neig)) / Math.max(3,neig)); } last = Math.min(last, n); } else { enough = true; } enough = enough || first >= n; } System.err.println("Lanczos: " + iter + " iterations for Matrix of size " + n); store(q, j, wptr[1]); k = Math.min(k, neig); double[] eigenvalues = new double[k]; // Matrix eigenvectors = new Matrix(n, k); for (int i = 0, index = 0; i <= j && index < k; i++) { if (bnd[i] <= kappa * Math.abs(ritz[i])) { // for (int row = 0; row < n; row++) { // for (int l = 0; l <= j; l++) { // eigenvectors.add(row, index, q[l][row] * z.get(l, i)); // } // } eigenvalues[index++] = ritz[i]; } } return eigenvalues; } /** * Generate a starting vector in r and returns |r|. It returns zero if the * range is spanned, and throws exception if no starting vector within range * of operator can be found. * @param step starting index for a Lanczos run */ private static double startv(ReadableMatrix A, double[][] q, double[][] wptr, int step) { // get initial vector; default is random double rnm = dot(wptr[0], wptr[0]); double[] r = wptr[0]; int n = r.length; for (int id = 0; id < 3; id++) { if (id > 0 || step > 0 || rnm == 0) { for (int i = 0; i < r.length; i++) { r[i] = Math.random() - 0.5; } } System.arraycopy(wptr[0], 0, wptr[3], 0, n); // apply operator to put r in range (essential if m singular) product(A, wptr[3], wptr[0]); System.arraycopy(wptr[0], 0, wptr[3], 0, n); rnm = dot(wptr[0], wptr[3]); if (rnm > 0.0) { break; } } // fatal error if (rnm <= 0.0) { System.err.println("Lanczos method was unable to find a starting vector within range."); return -1; } if (step > 0) { for (int i = 0; i < step; i++) { double t = dot(wptr[3], q[i]); axpy(-t, q[i], wptr[0]); } // make sure q[step] is orthogonal to q[step-1] double t = dot(wptr[4], wptr[0]); axpy(-t, wptr[2], wptr[0]); System.arraycopy(wptr[0], 0, wptr[3], 0, n); t = dot(wptr[3], wptr[0]); if (t <= MachineAccuracy.EPSILON * rnm) { t = 0.0; } rnm = t; } return Math.sqrt(rnm); } /** * Update the eta recurrence. * @param alf array to store diagonal of the tridiagonal matrix T * @param bet array to store off-diagonal of T * @param eta on input, orthogonality estimate of Lanczos vectors at step j. * On output, orthogonality estimate of Lanczos vectors at step j+1 . * @param oldeta on input, orthogonality estimate of Lanczos vectors at step j-1 * On output orthogonality estimate of Lanczos vectors at step j * @param step dimension of T * @param rnm norm of the next residual vector * @param eps roundoff estimate for dot product of two unit vectors */ private static void ortbnd(double[] alf, double[] bet, double[] eta, double[] oldeta, int step, double rnm, double eps) { if (step < 1) { return; } if (0 != rnm) { if (step > 1) { oldeta[0] = (bet[1] * eta[1] + (alf[0] - alf[step]) * eta[0] - bet[step] * oldeta[0]) / rnm + eps; } for (int i = 1; i <= step - 2; i++) { oldeta[i] = (bet[i + 1] * eta[i + 1] + (alf[i] - alf[step]) * eta[i] + bet[i] * eta[i - 1] - bet[step] * oldeta[i]) / rnm + eps; } } oldeta[step - 1] = eps; for (int i = 0; i < step; i++) { double swap = eta[i]; eta[i] = oldeta[i]; oldeta[i] = swap; } eta[step] = eps; } /** * Examine the state of orthogonality between the new Lanczos * vector and the previous ones to decide whether re-orthogonalization * should be performed. * @param ll number of intitial Lanczos vectors in local orthog. * @param r on input, residual vector to become next Lanczos vector. * On output, residual vector orthogonalized against previous Lanczos. * @param q on input, current Lanczos vector. On Output, current * Lanczos vector orthogonalized against previous ones. * @param ra previous Lanczos vector * @param qa previous Lanczos vector * @param eta state of orthogonality between r and prev. Lanczos vectors * @param oldeta state of orthogonality between q and prev. Lanczos vectors */ private static double purge(int ll, double[][] Q, double[] r, double[] q, double[] ra, double[] qa, double[] eta, double[] oldeta, int step, double rnm, double tol, double eps, double reps) { if (step < ll + 2) { return rnm; } double t, tq, tr; int k = idamax(step - (ll + 1), eta, ll, 1) + ll; if (Math.abs(eta[k]) > reps) { double reps1 = eps / reps; int iteration = 0; boolean flag = true; while (iteration < 2 && flag) { if (rnm > tol) { // bring in a lanczos vector t and orthogonalize both // r and q against it tq = 0.0; tr = 0.0; for (int i = ll; i < step; i++) { t = -dot(qa, Q[i]); tq += Math.abs(t); axpy(t, Q[i], q); t = -dot(ra, Q[i]); tr += Math.abs(t); axpy(t, Q[i], r); } System.arraycopy(q, 0, qa, 0, q.length); t = -dot(r, qa); tr += Math.abs(t); axpy(t, q, r); System.arraycopy(r, 0, ra, 0, r.length); rnm = Math.sqrt(dot(ra, r)); if (tq <= reps1 && tr <= reps1 * rnm) { flag = false; } } iteration++; } for (int i = ll; i <= step; i++) { eta[i] = eps; oldeta[i] = eps; } } return rnm; } /** * Find the index of element having maximum absolute value. */ private static int idamax(int n, double[] dx, int ix0, int incx) { int ix, imax; double dmax; if (n < 1) { return -1; } if (n == 1) { return 0; } if (incx == 0) { return -1; } ix = (incx < 0) ? ix0 + ((-n + 1) * incx) : ix0; imax = ix; dmax = Math.abs(dx[ix]); for (int i = 1; i < n; i++) { ix += incx; double dtemp = Math.abs(dx[ix]); if (dtemp > dmax) { dmax = dtemp; imax = ix; } } return imax; } /** * Massage error bounds for very close ritz values by placing a gap between * them. The error bounds are then refined to reflect this. * @param ritz array to store the ritz values * @param bnd array to store the error bounds * @param enough stop flag */ private static int error_bound(boolean[] enough, double[] ritz, double[] bnd, int step, double tol, double eps34) { double gapl, gap; // massage error bounds for very close ritz values int mid = idamax(step + 1, bnd, 0, 1); for (int i = ((step + 1) + (step - 1)) / 2; i >= mid + 1; i -= 1) { if (Math.abs(ritz[i - 1] - ritz[i]) < eps34 * Math.abs(ritz[i])) { if (bnd[i] > tol && bnd[i - 1] > tol) { bnd[i - 1] = Math.sqrt(bnd[i] * bnd[i] + bnd[i - 1] * bnd[i - 1]); bnd[i] = 0.0; } } } for (int i = ((step + 1) - (step - 1)) / 2; i <= mid - 1; i += 1) { if (Math.abs(ritz[i + 1] - ritz[i]) < eps34 * Math.abs(ritz[i])) { if (bnd[i] > tol && bnd[i + 1] > tol) { bnd[i + 1] = Math.sqrt(bnd[i] * bnd[i] + bnd[i + 1] * bnd[i + 1]); bnd[i] = 0.0; } } } // refine the error bounds int neig = 0; gapl = ritz[step] - ritz[0]; for (int i = 0; i <= step; i++) { gap = gapl; if (i < step) { gapl = ritz[i + 1] - ritz[i]; } gap = Math.min(gap, gapl); if (gap > bnd[i]) { bnd[i] = bnd[i] * (bnd[i] / gap); } if (bnd[i] <= 16.0 * MachineAccuracy.EPSILON * Math.abs(ritz[i])) { neig++; if (!enough[0]) { enough[0] = -MachineAccuracy.EPSILON < ritz[i] && ritz[i] < MachineAccuracy.EPSILON; } } } //logger.info("Lancozs method found {} converged eigenvalues of the {}-by-{} matrix", neig, step + 1, step + 1); if (neig != 0) { for (int i = 0; i <= step; i++) { if (bnd[i] <= 16.0 * MachineAccuracy.EPSILON * Math.abs(ritz[i])) { //logger.info("ritz[{}] = {}", i, ritz[i]); } } } return neig; } /** * Based on the input operation flag, stores to or retrieves from memory a vector. * @param s contains the vector to be stored */ private static void store(double[][] q, int j, double[] s) { if (null == q[j]) { q[j] = s.clone(); } else { System.arraycopy(s, 0, q[j], 0, s.length); } } /** * Tridiagonal QL Implicit routine for computing eigenvalues and eigenvectors of a symmetric, * real, tridiagonal matrix. * * The routine works extremely well in practice. The number of iterations for the first few * eigenvalues might be 4 or 5, say, but meanwhile the off-diagonal elements in the lower right-hand * corner have been reduced too. The later eigenvalues are liberated with very little work. The * average number of iterations per eigenvalue is typically 1.3 - 1.6. The operation count per * iteration is O(n), with a fairly large effective coefficient, say, ~20n. The total operation count * for the diagonalization is then ~20n * (1.3 - 1.6)n = ~30n<sup>2</sup>. If the eigenvectors are required, * there is an additional, much larger, workload of about O(3n<sup>3</sup>) operations. * * @param V on input, it contains the identity matrix. On output, the kth column * of V returns the normalized eigenvector corresponding to d[k]. * @param d on input, it contains the diagonal elements of the tridiagonal matrix. * On output, it contains the eigenvalues. * @param e on input, it contains the subdiagonal elements of the tridiagonal * matrix, with e[0] arbitrary. On output, its contents are destroyed. */ private static void tql2(WrappedMatrix V, double[] d, double[] e) { int n = V.getMajorDim(); for (int i = 1; i < n; i++) { e[i - 1] = e[i]; } e[n - 1] = 0.0; double f = 0.0; double tst1 = 0.0; for (int l = 0; l < n; l++) { // Find small subdiagonal element tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); int m = l; for (; m < n; m++) { if (Math.abs(e[m]) <= MachineAccuracy.EPSILON * tst1) { break; } } // If m == l, d[l] is an eigenvalue, // otherwise, iterate. if (m > l) { int iter = 0; do { if (++iter >= 30) { throw new RuntimeException("Too many iterations"); } // Compute implicit shift double g = d[l]; double p = (d[l + 1] - g) / (2.0 * e[l]); double r = Math.hypot(p, 1.0); if (p < 0) { r = -r; } d[l] = e[l] / (p + r); d[l + 1] = e[l] * (p + r); double dl1 = d[l + 1]; double h = g - d[l]; for (int i = l + 2; i < n; i++) { d[i] -= h; } f = f + h; // Implicit QL transformation. p = d[m]; double c = 1.0; double c2 = c; double c3 = c; double el1 = e[l + 1]; double s = 0.0; double s2 = 0.0; for (int i = m - 1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; r = Math.hypot(p, e[i]); e[i + 1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i + 1] = h + s * (c * g + s * d[i]); // Accumulate transformation. for (int k = 0; k < n; k++) { h = V.get(k, i + 1); V.set(k, i + 1, s * V.get(k, i) + c * h); V.set(k, i, c * V.get(k, i) - s * h); } } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; // Check for convergence. } while (Math.abs(e[l]) > MachineAccuracy.EPSILON * tst1); } d[l] = d[l] + f; e[l] = 0.0; } // Sort eigenvalues and corresponding vectors. for (int i = 0; i < n - 1; i++) { int k = i; double p = d[i]; for (int j = i + 1; j < n; j++) { if (d[j] > p) { k = j; p = d[j]; } } if (k != i) { d[k] = d[i]; d[i] = p; for (int j = 0; j < n; j++) { p = V.get(j, i); V.set(j, i, V.get(j, k)); V.set(j, k, p); } } } } public static void scale(double a, double[] x, double[] y) { for (int i = 0; i < x.length; i++) { y[i] = a * x[i]; } } public static void scale(double a, double[] x) { for (int i = 0; i < x.length; i++) { x[i] *= a; } } public static double dot(double[] x, double[] y) { double sum = 0; for (int i = 0; i < x.length; i++) { sum += x[i] * y[i]; } return sum; } public static void axpy(double a, double[] x, double[] y) { for (int i = 0; i < x.length; i++) { y[i] += a * x[i]; } } public static double norm(double[] x) { double norm = 0.0; for (int i = 0; i < x.length; i++) { norm += x[i] * x[i]; } return Math.sqrt(norm); } public static void swap(Object[] x, int i, int j) { Object tmp = x[i]; x[i] = x[j]; x[j] = tmp; } public static void product(ReadableMatrix A, double[] x, double[] y) { // y = Ax final int majorDim = A.getMajorDim(); final int minorDim = A.getMinorDim(); assert (x.length == minorDim); assert (y.length == minorDim); for (int row = 0; row < majorDim; ++row) { double sum = 0.0; for (int col = 0; col < minorDim; ++col) { sum += A.get(row, col) * x[col]; } y[row] = sum; } } }
jsigao/beast-mcmc
src/dr/math/matrixAlgebra/Lanczos.java
7,968
// get initial vector; default is random
line_comment
nl
/* * Copyright (c) 2010-2020 Haifeng Li. All rights reserved. * * Smile is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Smile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Smile. If not, see <https://www.gnu.org/licenses/>. */ package dr.math.matrixAlgebra; import dr.math.MachineAccuracy; import java.util.Arrays; /** * The Lanczos algorithm is a direct algorithm devised by Cornelius Lanczos * that is an adaptation of power methods to find the most useful eigenvalues * and eigenvectors of an n<sup>th</sup> order linear system with a limited * number of operations, m, where m is much smaller than n. * <p> * Although computationally efficient in principle, the method as initially * formulated was not useful, due to its numerical instability. In this * implementation, we use partial reorthogonalization to make the method * numerically stable. * * @author Haifeng Li */ public class Lanczos { /** * Find k largest approximate eigen pairs of a symmetric matrix by the * Lanczos algorithm. * * @param A the matrix supporting matrix vector multiplication operation. * @param k the number of eigenvalues we wish to compute for the input matrix. * This number cannot exceed the size of A. * @return eigen value decomposition. */ public static double[] eigen(ReadableMatrix A, int k) { double[] res = eigen(A, k, 1.0E-8, 10 * A.getDim()); System.err.println(Arrays.toString(res)); return res; } /** * Find k largest approximate eigen pairs of a symmetric matrix by the * Lanczos algorithm. * * @param A the matrix supporting matrix vector multiplication operation. * @param k the number of eigenvalues we wish to compute for the input matrix. * This number cannot exceed the size of A. * @param kappa relative accuracy of ritz values acceptable as eigenvalues. * @param maxIter Maximum number of iterations. * @return eigen value decomposition. */ public static double[] eigen(ReadableMatrix A, int k, double kappa, int maxIter) { int n = A.getMajorDim(); int intro = 0; // roundoff estimate for dot product of two unit vectors double eps = MachineAccuracy.EPSILON * Math.sqrt(n); double reps = Math.sqrt(MachineAccuracy.EPSILON); double eps34 = reps * Math.sqrt(reps); kappa = Math.max(kappa, eps34); // Workspace // wptr[0] r[j] // wptr[1] q[j] // wptr[2] q[j-1] // wptr[3] p // wptr[4] p[j-1] // wptr[5] temporary worksapce double[][] wptr = new double[6][n]; // orthogonality estimate of Lanczos vectors at step j double[] eta = new double[n]; // orthogonality estimate of Lanczos vectors at step j-1 double[] oldeta = new double[n]; // the error bounds double[] bnd = new double[n]; // diagonal elements of T double[] alf = new double[n]; // off-diagonal elements of T double[] bet = new double[n + 1]; // basis vectors for the Krylov subspace double[][] q = new double[n][]; // initial Lanczos vectors double[][] p = new double[2][]; // arrays used in the QL decomposition double[] ritz = new double[n + 1]; // eigenvectors calculated in the QL decomposition WrappedMatrix z = null; // First step of the Lanczos algorithm. It also does a step of extended // local re-orthogonalization. // get initial vector; default is random double rnm = startv(A, q, wptr, 0); // normalize starting vector double t = 1.0 / rnm; scale(t, wptr[0], wptr[1]); scale(t, wptr[3]); // take the first step product(A, wptr[3], wptr[0]); //A.mv(wptr[3], wptr[0]); //todo: wptr[0] = A wptr[3] alf[0] = dot(wptr[0], wptr[3]); //alf[0] = MathEx.dot(wptr[0], wptr[3]); // todo: dot product axpy(-alf[0], wptr[1], wptr[0]); //MathEx.axpy(-alf[0], wptr[1], wptr[0]); // todo: (a,x,y) -> y = ax+y t = dot(wptr[0], wptr[3]); //t = MathEx.dot(wptr[0], wptr[3]); //todo: dot product axpy(-t, wptr[1], wptr[0]); alf[0] += t; System.arraycopy(wptr[0], 0, wptr[4], 0, n); rnm = norm(wptr[0]); double anorm = rnm + Math.abs(alf[0]); double tol = reps * anorm; if (0 == rnm) { throw new IllegalStateException("Lanczos method was unable to find a starting vector within range."); } eta[0] = eps; oldeta[0] = eps; // number of ritz values stabilized int neig = 0; // number of intitial Lanczos vectors in local orthog. (has value of 0, 1 or 2) int ll = 0; // start of index through loop int first = 1; // end of index through loop int last = Math.min(k + Math.max(8, k), n); // number of Lanczos steps actually taken int j = 0; // stop flag boolean enough = false; // algorithm iterations int iter = 0; for (; !enough && iter < maxIter; iter++) { if (rnm <= tol) { rnm = 0.0; } // a single Lanczos step for (j = first; j < last; j++) { swap(wptr, 1, 2); //todo: swap element i and j for x swap(wptr, 3, 4); store(q, j - 1, wptr[2]); if (j - 1 < 2) { p[j - 1] = wptr[4].clone(); } bet[j] = rnm; // restart if invariant subspace is found if (0 == bet[j]) { rnm = startv(A, q, wptr, j); if (rnm < 0.0) { rnm = 0.0; break; } if (rnm == 0) { enough = true; } } if (enough) { // These lines fix a bug that occurs with low-rank matrices swap(wptr, 1, 2); break; } // take a lanczos step t = 1.0 / rnm; scale(t, wptr[0], wptr[1]); scale(t, wptr[3]); product(A, wptr[3], wptr[0]); //A.mv(wptr[3], wptr[0]); axpy(-rnm, wptr[2], wptr[0]); alf[j] = dot(wptr[0], wptr[3]); axpy(-alf[j], wptr[1], wptr[0]); // orthogonalize against initial lanczos vectors if (j <= 2 && (Math.abs(alf[j - 1]) > 4.0 * Math.abs(alf[j]))) { ll = j; } for (int i = 0; i < Math.min(ll, j - 1); i++) { t = dot(p[i], wptr[0]); axpy(-t, q[i], wptr[0]); eta[i] = eps; oldeta[i] = eps; } // extended local reorthogonalization t = dot(wptr[0], wptr[4]); axpy(-t, wptr[2], wptr[0]); if (bet[j] > 0.0) { bet[j] = bet[j] + t; } t = dot(wptr[0], wptr[3]); axpy(-t, wptr[1], wptr[0]); alf[j] = alf[j] + t; System.arraycopy(wptr[0], 0, wptr[4], 0, n); rnm = norm(wptr[0]); anorm = bet[j] + Math.abs(alf[j]) + rnm; tol = reps * anorm; // update the orthogonality bounds ortbnd(alf, bet, eta, oldeta, j, rnm, eps); // restore the orthogonality state when needed rnm = purge(ll, q, wptr[0], wptr[1], wptr[4], wptr[3], eta, oldeta, j, rnm, tol, eps, reps); if (rnm <= tol) { rnm = 0.0; } } if (enough) { j = j - 1; } else { j = last - 1; } first = j + 1; bet[j + 1] = rnm; // analyze T System.arraycopy(alf, 0, ritz, 0, j + 1); System.arraycopy(bet, 0, wptr[5], 0, j + 1); z = new WrappedMatrix.Raw(new double[(j+1) * (j+1)], 0, j+1, j+1); for (int i = 0; i <= j; i++) { z.set(i, i, 1.0); } // compute the eigenvalues and eigenvectors of the // tridiagonal matrix tql2(z, ritz, wptr[5]); for (int i = 0; i <= j; i++) { bnd[i] = rnm * Math.abs(z.get(j, i)); } // massage error bounds for very close ritz values boolean[] ref_enough = {enough}; neig = error_bound(ref_enough, ritz, bnd, j, tol, eps34); enough = ref_enough[0]; // should we stop? if (neig < k) { if (0 == neig) { last = first + 9; intro = first; } else { last = first + Math.max(3, 1 + ((j - intro) * (k - neig)) / Math.max(3,neig)); } last = Math.min(last, n); } else { enough = true; } enough = enough || first >= n; } System.err.println("Lanczos: " + iter + " iterations for Matrix of size " + n); store(q, j, wptr[1]); k = Math.min(k, neig); double[] eigenvalues = new double[k]; // Matrix eigenvectors = new Matrix(n, k); for (int i = 0, index = 0; i <= j && index < k; i++) { if (bnd[i] <= kappa * Math.abs(ritz[i])) { // for (int row = 0; row < n; row++) { // for (int l = 0; l <= j; l++) { // eigenvectors.add(row, index, q[l][row] * z.get(l, i)); // } // } eigenvalues[index++] = ritz[i]; } } return eigenvalues; } /** * Generate a starting vector in r and returns |r|. It returns zero if the * range is spanned, and throws exception if no starting vector within range * of operator can be found. * @param step starting index for a Lanczos run */ private static double startv(ReadableMatrix A, double[][] q, double[][] wptr, int step) { // get initial<SUF> double rnm = dot(wptr[0], wptr[0]); double[] r = wptr[0]; int n = r.length; for (int id = 0; id < 3; id++) { if (id > 0 || step > 0 || rnm == 0) { for (int i = 0; i < r.length; i++) { r[i] = Math.random() - 0.5; } } System.arraycopy(wptr[0], 0, wptr[3], 0, n); // apply operator to put r in range (essential if m singular) product(A, wptr[3], wptr[0]); System.arraycopy(wptr[0], 0, wptr[3], 0, n); rnm = dot(wptr[0], wptr[3]); if (rnm > 0.0) { break; } } // fatal error if (rnm <= 0.0) { System.err.println("Lanczos method was unable to find a starting vector within range."); return -1; } if (step > 0) { for (int i = 0; i < step; i++) { double t = dot(wptr[3], q[i]); axpy(-t, q[i], wptr[0]); } // make sure q[step] is orthogonal to q[step-1] double t = dot(wptr[4], wptr[0]); axpy(-t, wptr[2], wptr[0]); System.arraycopy(wptr[0], 0, wptr[3], 0, n); t = dot(wptr[3], wptr[0]); if (t <= MachineAccuracy.EPSILON * rnm) { t = 0.0; } rnm = t; } return Math.sqrt(rnm); } /** * Update the eta recurrence. * @param alf array to store diagonal of the tridiagonal matrix T * @param bet array to store off-diagonal of T * @param eta on input, orthogonality estimate of Lanczos vectors at step j. * On output, orthogonality estimate of Lanczos vectors at step j+1 . * @param oldeta on input, orthogonality estimate of Lanczos vectors at step j-1 * On output orthogonality estimate of Lanczos vectors at step j * @param step dimension of T * @param rnm norm of the next residual vector * @param eps roundoff estimate for dot product of two unit vectors */ private static void ortbnd(double[] alf, double[] bet, double[] eta, double[] oldeta, int step, double rnm, double eps) { if (step < 1) { return; } if (0 != rnm) { if (step > 1) { oldeta[0] = (bet[1] * eta[1] + (alf[0] - alf[step]) * eta[0] - bet[step] * oldeta[0]) / rnm + eps; } for (int i = 1; i <= step - 2; i++) { oldeta[i] = (bet[i + 1] * eta[i + 1] + (alf[i] - alf[step]) * eta[i] + bet[i] * eta[i - 1] - bet[step] * oldeta[i]) / rnm + eps; } } oldeta[step - 1] = eps; for (int i = 0; i < step; i++) { double swap = eta[i]; eta[i] = oldeta[i]; oldeta[i] = swap; } eta[step] = eps; } /** * Examine the state of orthogonality between the new Lanczos * vector and the previous ones to decide whether re-orthogonalization * should be performed. * @param ll number of intitial Lanczos vectors in local orthog. * @param r on input, residual vector to become next Lanczos vector. * On output, residual vector orthogonalized against previous Lanczos. * @param q on input, current Lanczos vector. On Output, current * Lanczos vector orthogonalized against previous ones. * @param ra previous Lanczos vector * @param qa previous Lanczos vector * @param eta state of orthogonality between r and prev. Lanczos vectors * @param oldeta state of orthogonality between q and prev. Lanczos vectors */ private static double purge(int ll, double[][] Q, double[] r, double[] q, double[] ra, double[] qa, double[] eta, double[] oldeta, int step, double rnm, double tol, double eps, double reps) { if (step < ll + 2) { return rnm; } double t, tq, tr; int k = idamax(step - (ll + 1), eta, ll, 1) + ll; if (Math.abs(eta[k]) > reps) { double reps1 = eps / reps; int iteration = 0; boolean flag = true; while (iteration < 2 && flag) { if (rnm > tol) { // bring in a lanczos vector t and orthogonalize both // r and q against it tq = 0.0; tr = 0.0; for (int i = ll; i < step; i++) { t = -dot(qa, Q[i]); tq += Math.abs(t); axpy(t, Q[i], q); t = -dot(ra, Q[i]); tr += Math.abs(t); axpy(t, Q[i], r); } System.arraycopy(q, 0, qa, 0, q.length); t = -dot(r, qa); tr += Math.abs(t); axpy(t, q, r); System.arraycopy(r, 0, ra, 0, r.length); rnm = Math.sqrt(dot(ra, r)); if (tq <= reps1 && tr <= reps1 * rnm) { flag = false; } } iteration++; } for (int i = ll; i <= step; i++) { eta[i] = eps; oldeta[i] = eps; } } return rnm; } /** * Find the index of element having maximum absolute value. */ private static int idamax(int n, double[] dx, int ix0, int incx) { int ix, imax; double dmax; if (n < 1) { return -1; } if (n == 1) { return 0; } if (incx == 0) { return -1; } ix = (incx < 0) ? ix0 + ((-n + 1) * incx) : ix0; imax = ix; dmax = Math.abs(dx[ix]); for (int i = 1; i < n; i++) { ix += incx; double dtemp = Math.abs(dx[ix]); if (dtemp > dmax) { dmax = dtemp; imax = ix; } } return imax; } /** * Massage error bounds for very close ritz values by placing a gap between * them. The error bounds are then refined to reflect this. * @param ritz array to store the ritz values * @param bnd array to store the error bounds * @param enough stop flag */ private static int error_bound(boolean[] enough, double[] ritz, double[] bnd, int step, double tol, double eps34) { double gapl, gap; // massage error bounds for very close ritz values int mid = idamax(step + 1, bnd, 0, 1); for (int i = ((step + 1) + (step - 1)) / 2; i >= mid + 1; i -= 1) { if (Math.abs(ritz[i - 1] - ritz[i]) < eps34 * Math.abs(ritz[i])) { if (bnd[i] > tol && bnd[i - 1] > tol) { bnd[i - 1] = Math.sqrt(bnd[i] * bnd[i] + bnd[i - 1] * bnd[i - 1]); bnd[i] = 0.0; } } } for (int i = ((step + 1) - (step - 1)) / 2; i <= mid - 1; i += 1) { if (Math.abs(ritz[i + 1] - ritz[i]) < eps34 * Math.abs(ritz[i])) { if (bnd[i] > tol && bnd[i + 1] > tol) { bnd[i + 1] = Math.sqrt(bnd[i] * bnd[i] + bnd[i + 1] * bnd[i + 1]); bnd[i] = 0.0; } } } // refine the error bounds int neig = 0; gapl = ritz[step] - ritz[0]; for (int i = 0; i <= step; i++) { gap = gapl; if (i < step) { gapl = ritz[i + 1] - ritz[i]; } gap = Math.min(gap, gapl); if (gap > bnd[i]) { bnd[i] = bnd[i] * (bnd[i] / gap); } if (bnd[i] <= 16.0 * MachineAccuracy.EPSILON * Math.abs(ritz[i])) { neig++; if (!enough[0]) { enough[0] = -MachineAccuracy.EPSILON < ritz[i] && ritz[i] < MachineAccuracy.EPSILON; } } } //logger.info("Lancozs method found {} converged eigenvalues of the {}-by-{} matrix", neig, step + 1, step + 1); if (neig != 0) { for (int i = 0; i <= step; i++) { if (bnd[i] <= 16.0 * MachineAccuracy.EPSILON * Math.abs(ritz[i])) { //logger.info("ritz[{}] = {}", i, ritz[i]); } } } return neig; } /** * Based on the input operation flag, stores to or retrieves from memory a vector. * @param s contains the vector to be stored */ private static void store(double[][] q, int j, double[] s) { if (null == q[j]) { q[j] = s.clone(); } else { System.arraycopy(s, 0, q[j], 0, s.length); } } /** * Tridiagonal QL Implicit routine for computing eigenvalues and eigenvectors of a symmetric, * real, tridiagonal matrix. * * The routine works extremely well in practice. The number of iterations for the first few * eigenvalues might be 4 or 5, say, but meanwhile the off-diagonal elements in the lower right-hand * corner have been reduced too. The later eigenvalues are liberated with very little work. The * average number of iterations per eigenvalue is typically 1.3 - 1.6. The operation count per * iteration is O(n), with a fairly large effective coefficient, say, ~20n. The total operation count * for the diagonalization is then ~20n * (1.3 - 1.6)n = ~30n<sup>2</sup>. If the eigenvectors are required, * there is an additional, much larger, workload of about O(3n<sup>3</sup>) operations. * * @param V on input, it contains the identity matrix. On output, the kth column * of V returns the normalized eigenvector corresponding to d[k]. * @param d on input, it contains the diagonal elements of the tridiagonal matrix. * On output, it contains the eigenvalues. * @param e on input, it contains the subdiagonal elements of the tridiagonal * matrix, with e[0] arbitrary. On output, its contents are destroyed. */ private static void tql2(WrappedMatrix V, double[] d, double[] e) { int n = V.getMajorDim(); for (int i = 1; i < n; i++) { e[i - 1] = e[i]; } e[n - 1] = 0.0; double f = 0.0; double tst1 = 0.0; for (int l = 0; l < n; l++) { // Find small subdiagonal element tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); int m = l; for (; m < n; m++) { if (Math.abs(e[m]) <= MachineAccuracy.EPSILON * tst1) { break; } } // If m == l, d[l] is an eigenvalue, // otherwise, iterate. if (m > l) { int iter = 0; do { if (++iter >= 30) { throw new RuntimeException("Too many iterations"); } // Compute implicit shift double g = d[l]; double p = (d[l + 1] - g) / (2.0 * e[l]); double r = Math.hypot(p, 1.0); if (p < 0) { r = -r; } d[l] = e[l] / (p + r); d[l + 1] = e[l] * (p + r); double dl1 = d[l + 1]; double h = g - d[l]; for (int i = l + 2; i < n; i++) { d[i] -= h; } f = f + h; // Implicit QL transformation. p = d[m]; double c = 1.0; double c2 = c; double c3 = c; double el1 = e[l + 1]; double s = 0.0; double s2 = 0.0; for (int i = m - 1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; r = Math.hypot(p, e[i]); e[i + 1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i + 1] = h + s * (c * g + s * d[i]); // Accumulate transformation. for (int k = 0; k < n; k++) { h = V.get(k, i + 1); V.set(k, i + 1, s * V.get(k, i) + c * h); V.set(k, i, c * V.get(k, i) - s * h); } } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; // Check for convergence. } while (Math.abs(e[l]) > MachineAccuracy.EPSILON * tst1); } d[l] = d[l] + f; e[l] = 0.0; } // Sort eigenvalues and corresponding vectors. for (int i = 0; i < n - 1; i++) { int k = i; double p = d[i]; for (int j = i + 1; j < n; j++) { if (d[j] > p) { k = j; p = d[j]; } } if (k != i) { d[k] = d[i]; d[i] = p; for (int j = 0; j < n; j++) { p = V.get(j, i); V.set(j, i, V.get(j, k)); V.set(j, k, p); } } } } public static void scale(double a, double[] x, double[] y) { for (int i = 0; i < x.length; i++) { y[i] = a * x[i]; } } public static void scale(double a, double[] x) { for (int i = 0; i < x.length; i++) { x[i] *= a; } } public static double dot(double[] x, double[] y) { double sum = 0; for (int i = 0; i < x.length; i++) { sum += x[i] * y[i]; } return sum; } public static void axpy(double a, double[] x, double[] y) { for (int i = 0; i < x.length; i++) { y[i] += a * x[i]; } } public static double norm(double[] x) { double norm = 0.0; for (int i = 0; i < x.length; i++) { norm += x[i] * x[i]; } return Math.sqrt(norm); } public static void swap(Object[] x, int i, int j) { Object tmp = x[i]; x[i] = x[j]; x[j] = tmp; } public static void product(ReadableMatrix A, double[] x, double[] y) { // y = Ax final int majorDim = A.getMajorDim(); final int minorDim = A.getMinorDim(); assert (x.length == minorDim); assert (y.length == minorDim); for (int row = 0; row < majorDim; ++row) { double sum = 0.0; for (int col = 0; col < minorDim; ++col) { sum += A.get(row, col) * x[col]; } y[row] = sum; } } }
167328_0
package com.awssamples.cbor; import com.aws.samples.cdk.constructs.iam.policies.LambdaPolicies; import com.aws.samples.cdk.helpers.*; import com.aws.samples.cdk.stacktypes.JavaGradleStack; import io.vavr.collection.HashMap; import io.vavr.collection.List; import io.vavr.collection.Map; import io.vavr.control.Option; import software.amazon.awscdk.core.Construct; import software.amazon.awscdk.core.Duration; import software.amazon.awscdk.services.iam.Role; import software.amazon.awscdk.services.iot.CfnTopicRule; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.lambda.FunctionProps; import software.amazon.awscdk.services.lambda.Runtime; public class CborStack extends software.amazon.awscdk.core.Stack implements JavaGradleStack { public static final String CBOR_MESSAGE = "CborMessage"; public static final String JSON_MESSAGE = "JsonMessage"; private static final String HANDLER_PACKAGE = "com.awssamples.iot.cbor.handler.handlers"; private static final String OUTPUT_TOPIC = "OutputTopic"; private static final String CBOR_INPUT_TOPIC = String.join("/", "cbor", "input"); private static final String CBOR_OUTPUT_TOPIC = String.join("/", "json", "output"); private static final String JSON_INPUT_TOPIC = String.join("/", "json", "input"); private static final String JSON_OUTPUT_TOPIC = String.join("/", "cbor", "output"); // Amazon Ion event handler private static final String CBOR_EVENT_HANDLER = String.join(".", HANDLER_PACKAGE, "HandleCborEvent"); // JSON event handler private static final String JSON_EVENT_HANDLER = String.join(".", HANDLER_PACKAGE, "HandleJsonEvent"); private static final Duration LAMBDA_FUNCTION_TIMEOUT = Duration.seconds(10); private final String projectDirectory; private final String outputArtifactName; public static void main(String[] args) { new CborStack(CdkHelper.getApp(), CdkHelper.getStackName()); CdkHelper.getApp().synth(); } public CborStack(final Construct parent, final String name) { super(parent, name); projectDirectory = "../" + name + "/"; outputArtifactName = name + "-all.jar"; // Build all of the necessary JARs build(); // Build the properties required for both Lambda functions FunctionProps.Builder lambdaFunctionPropsBuilder = FunctionProps.builder() .runtime(Runtime.JAVA_11) .memorySize(1024) .timeout(Duration.seconds(10)); // Resources to convert an Amazon Ion message to JSON Role cborMessageRole = RoleHelper.buildPublishToTopicRole(this, CBOR_MESSAGE, CBOR_OUTPUT_TOPIC, List.empty(), List.empty(), LambdaPolicies.LAMBDA_SERVICE_PRINCIPAL); Map<String, String> cborLambdaEnvironment = getCborLambdaEnvironment(); Function cborMessageFunction = LambdaHelper.buildLambda(this, CBOR_MESSAGE, cborMessageRole, cborLambdaEnvironment, getAssetCode(), CBOR_EVENT_HANDLER, Option.of(lambdaFunctionPropsBuilder)); CfnTopicRule cborMessageTopicRule = RulesEngineSqlHelper.buildSelectAllBinaryIotEventRule(this, CBOR_MESSAGE, cborMessageFunction, CBOR_INPUT_TOPIC); IotHelper.allowIotTopicRuleToInvokeLambdaFunction(this, cborMessageTopicRule, cborMessageFunction, CBOR_MESSAGE); // Resources to convert a JSON message to Amazon Ion Role jsonMessageRole = RoleHelper.buildPublishToTopicRole(this, JSON_MESSAGE, JSON_OUTPUT_TOPIC, List.empty(), List.empty(), LambdaPolicies.LAMBDA_SERVICE_PRINCIPAL); Map<String, String> jsonLambdaEnvironment = getJsonLambdaEnvironment(); Function jsonMessageFunction = LambdaHelper.buildLambda(this, JSON_MESSAGE, jsonMessageRole, jsonLambdaEnvironment, getAssetCode(), JSON_EVENT_HANDLER, Option.of(lambdaFunctionPropsBuilder)); CfnTopicRule jsonMessageTopicRule = RulesEngineSqlHelper.buildSelectAllIotEventRule(this, JSON_MESSAGE, jsonMessageFunction, JSON_INPUT_TOPIC); IotHelper.allowIotTopicRuleToInvokeLambdaFunction(this, jsonMessageTopicRule, jsonMessageFunction, JSON_MESSAGE); } private Map<String, String> getCborLambdaEnvironment() { return HashMap.of(OUTPUT_TOPIC, CBOR_OUTPUT_TOPIC); } private Map<String, String> getJsonLambdaEnvironment() { return HashMap.of(OUTPUT_TOPIC, JSON_OUTPUT_TOPIC); } @Override public String getProjectDirectory() { return projectDirectory; } @Override public String getOutputArtifactName() { return outputArtifactName; } }
aws-iot-builder-tools/iot-reference-architectures
cbor-stack/src/main/java/com/awssamples/cbor/CborStack.java
1,204
// Amazon Ion event handler
line_comment
nl
package com.awssamples.cbor; import com.aws.samples.cdk.constructs.iam.policies.LambdaPolicies; import com.aws.samples.cdk.helpers.*; import com.aws.samples.cdk.stacktypes.JavaGradleStack; import io.vavr.collection.HashMap; import io.vavr.collection.List; import io.vavr.collection.Map; import io.vavr.control.Option; import software.amazon.awscdk.core.Construct; import software.amazon.awscdk.core.Duration; import software.amazon.awscdk.services.iam.Role; import software.amazon.awscdk.services.iot.CfnTopicRule; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.lambda.FunctionProps; import software.amazon.awscdk.services.lambda.Runtime; public class CborStack extends software.amazon.awscdk.core.Stack implements JavaGradleStack { public static final String CBOR_MESSAGE = "CborMessage"; public static final String JSON_MESSAGE = "JsonMessage"; private static final String HANDLER_PACKAGE = "com.awssamples.iot.cbor.handler.handlers"; private static final String OUTPUT_TOPIC = "OutputTopic"; private static final String CBOR_INPUT_TOPIC = String.join("/", "cbor", "input"); private static final String CBOR_OUTPUT_TOPIC = String.join("/", "json", "output"); private static final String JSON_INPUT_TOPIC = String.join("/", "json", "input"); private static final String JSON_OUTPUT_TOPIC = String.join("/", "cbor", "output"); // Amazon Ion<SUF> private static final String CBOR_EVENT_HANDLER = String.join(".", HANDLER_PACKAGE, "HandleCborEvent"); // JSON event handler private static final String JSON_EVENT_HANDLER = String.join(".", HANDLER_PACKAGE, "HandleJsonEvent"); private static final Duration LAMBDA_FUNCTION_TIMEOUT = Duration.seconds(10); private final String projectDirectory; private final String outputArtifactName; public static void main(String[] args) { new CborStack(CdkHelper.getApp(), CdkHelper.getStackName()); CdkHelper.getApp().synth(); } public CborStack(final Construct parent, final String name) { super(parent, name); projectDirectory = "../" + name + "/"; outputArtifactName = name + "-all.jar"; // Build all of the necessary JARs build(); // Build the properties required for both Lambda functions FunctionProps.Builder lambdaFunctionPropsBuilder = FunctionProps.builder() .runtime(Runtime.JAVA_11) .memorySize(1024) .timeout(Duration.seconds(10)); // Resources to convert an Amazon Ion message to JSON Role cborMessageRole = RoleHelper.buildPublishToTopicRole(this, CBOR_MESSAGE, CBOR_OUTPUT_TOPIC, List.empty(), List.empty(), LambdaPolicies.LAMBDA_SERVICE_PRINCIPAL); Map<String, String> cborLambdaEnvironment = getCborLambdaEnvironment(); Function cborMessageFunction = LambdaHelper.buildLambda(this, CBOR_MESSAGE, cborMessageRole, cborLambdaEnvironment, getAssetCode(), CBOR_EVENT_HANDLER, Option.of(lambdaFunctionPropsBuilder)); CfnTopicRule cborMessageTopicRule = RulesEngineSqlHelper.buildSelectAllBinaryIotEventRule(this, CBOR_MESSAGE, cborMessageFunction, CBOR_INPUT_TOPIC); IotHelper.allowIotTopicRuleToInvokeLambdaFunction(this, cborMessageTopicRule, cborMessageFunction, CBOR_MESSAGE); // Resources to convert a JSON message to Amazon Ion Role jsonMessageRole = RoleHelper.buildPublishToTopicRole(this, JSON_MESSAGE, JSON_OUTPUT_TOPIC, List.empty(), List.empty(), LambdaPolicies.LAMBDA_SERVICE_PRINCIPAL); Map<String, String> jsonLambdaEnvironment = getJsonLambdaEnvironment(); Function jsonMessageFunction = LambdaHelper.buildLambda(this, JSON_MESSAGE, jsonMessageRole, jsonLambdaEnvironment, getAssetCode(), JSON_EVENT_HANDLER, Option.of(lambdaFunctionPropsBuilder)); CfnTopicRule jsonMessageTopicRule = RulesEngineSqlHelper.buildSelectAllIotEventRule(this, JSON_MESSAGE, jsonMessageFunction, JSON_INPUT_TOPIC); IotHelper.allowIotTopicRuleToInvokeLambdaFunction(this, jsonMessageTopicRule, jsonMessageFunction, JSON_MESSAGE); } private Map<String, String> getCborLambdaEnvironment() { return HashMap.of(OUTPUT_TOPIC, CBOR_OUTPUT_TOPIC); } private Map<String, String> getJsonLambdaEnvironment() { return HashMap.of(OUTPUT_TOPIC, JSON_OUTPUT_TOPIC); } @Override public String getProjectDirectory() { return projectDirectory; } @Override public String getOutputArtifactName() { return outputArtifactName; } }
93755_4
/* * Copyright 2019 Web3 Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.web3j.crypto; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.Provider; import java.security.SecureRandomSpi; import java.security.Security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation from <a * href="https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/crypto/LinuxSecureRandom.java">BitcoinJ * implementation</a> * * <p>A SecureRandom implementation that is able to override the standard JVM provided * implementation, and which simply serves random numbers by reading /dev/urandom. That is, it * delegates to the kernel on UNIX systems and is unusable on other platforms. Attempts to manually * set the seed are ignored. There is no difference between seed bytes and non-seed bytes, they are * all from the same source. */ public class LinuxSecureRandom extends SecureRandomSpi { private static final FileInputStream urandom; private static class LinuxSecureRandomProvider extends Provider { public LinuxSecureRandomProvider() { super( "LinuxSecureRandom", 1.0, "A Linux specific random number provider that uses /dev/urandom"); put("SecureRandom.LinuxSecureRandom", LinuxSecureRandom.class.getName()); } } private static final Logger log = LoggerFactory.getLogger(LinuxSecureRandom.class); static { try { File file = new File("/dev/urandom"); // This stream is deliberately leaked. urandom = new FileInputStream(file); if (urandom.read() == -1) { throw new RuntimeException("/dev/urandom not readable?"); } // Now override the default SecureRandom implementation with this one. int position = Security.insertProviderAt(new LinuxSecureRandomProvider(), 1); if (position != -1) { log.info("Secure randomness will be read from {} only.", file); } else { log.info("Randomness is already secure."); } } catch (FileNotFoundException e) { // Should never happen. log.error("/dev/urandom does not appear to exist or is not openable"); throw new RuntimeException(e); } catch (IOException e) { log.error("/dev/urandom does not appear to be readable"); throw new RuntimeException(e); } } private final DataInputStream dis; public LinuxSecureRandom() { // DataInputStream is not thread safe, so each random object has its own. dis = new DataInputStream(urandom); } @Override protected void engineSetSeed(byte[] bytes) { // Ignore. } @Override protected void engineNextBytes(byte[] bytes) { try { dis.readFully(bytes); // This will block until all the bytes can be read. } catch (IOException e) { throw new RuntimeException(e); // Fatal error. Do not attempt to recover from this. } } @Override protected byte[] engineGenerateSeed(int i) { byte[] bits = new byte[i]; engineNextBytes(bits); return bits; } }
hyperledger/web3j
crypto/src/main/java/org/web3j/crypto/LinuxSecureRandom.java
946
// Should never happen.
line_comment
nl
/* * Copyright 2019 Web3 Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.web3j.crypto; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.Provider; import java.security.SecureRandomSpi; import java.security.Security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation from <a * href="https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/crypto/LinuxSecureRandom.java">BitcoinJ * implementation</a> * * <p>A SecureRandom implementation that is able to override the standard JVM provided * implementation, and which simply serves random numbers by reading /dev/urandom. That is, it * delegates to the kernel on UNIX systems and is unusable on other platforms. Attempts to manually * set the seed are ignored. There is no difference between seed bytes and non-seed bytes, they are * all from the same source. */ public class LinuxSecureRandom extends SecureRandomSpi { private static final FileInputStream urandom; private static class LinuxSecureRandomProvider extends Provider { public LinuxSecureRandomProvider() { super( "LinuxSecureRandom", 1.0, "A Linux specific random number provider that uses /dev/urandom"); put("SecureRandom.LinuxSecureRandom", LinuxSecureRandom.class.getName()); } } private static final Logger log = LoggerFactory.getLogger(LinuxSecureRandom.class); static { try { File file = new File("/dev/urandom"); // This stream is deliberately leaked. urandom = new FileInputStream(file); if (urandom.read() == -1) { throw new RuntimeException("/dev/urandom not readable?"); } // Now override the default SecureRandom implementation with this one. int position = Security.insertProviderAt(new LinuxSecureRandomProvider(), 1); if (position != -1) { log.info("Secure randomness will be read from {} only.", file); } else { log.info("Randomness is already secure."); } } catch (FileNotFoundException e) { // Should never<SUF> log.error("/dev/urandom does not appear to exist or is not openable"); throw new RuntimeException(e); } catch (IOException e) { log.error("/dev/urandom does not appear to be readable"); throw new RuntimeException(e); } } private final DataInputStream dis; public LinuxSecureRandom() { // DataInputStream is not thread safe, so each random object has its own. dis = new DataInputStream(urandom); } @Override protected void engineSetSeed(byte[] bytes) { // Ignore. } @Override protected void engineNextBytes(byte[] bytes) { try { dis.readFully(bytes); // This will block until all the bytes can be read. } catch (IOException e) { throw new RuntimeException(e); // Fatal error. Do not attempt to recover from this. } } @Override protected byte[] engineGenerateSeed(int i) { byte[] bits = new byte[i]; engineNextBytes(bits); return bits; } }
38258_5
package com.mdimension.jchronic.numerizer; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Numerizer { protected static class DirectNum { private Pattern _name; private String _number; public DirectNum(String name, String number) { _name = Pattern.compile(name, Pattern.CASE_INSENSITIVE); _number = number; } public Pattern getName() { return _name; } public String getNumber() { return _number; } } protected static class Prefix { private Pattern _name; private long _number; public Prefix(Pattern name, long number) { _name = name; _number = number; } public Pattern getName() { return _name; } public long getNumber() { return _number; } } protected static class TenPrefix extends Prefix { public TenPrefix(String name, long number) { super(Pattern.compile("(?:" + name + ")( *\\d(?=\\D|$))*", Pattern.CASE_INSENSITIVE), number); } } protected static class BigPrefix extends Prefix { public BigPrefix(String name, long number) { super(Pattern.compile("(\\d*) *" + name, Pattern.CASE_INSENSITIVE), number); } } protected static DirectNum[] DIRECT_NUMS; protected static TenPrefix[] TEN_PREFIXES; protected static BigPrefix[] BIG_PREFIXES; static { List<DirectNum> directNums = new LinkedList<DirectNum>(); directNums.add(new DirectNum("eleven", "11")); directNums.add(new DirectNum("twelve", "12")); directNums.add(new DirectNum("thirteen", "13")); directNums.add(new DirectNum("fourteen", "14")); directNums.add(new DirectNum("fifteen", "15")); directNums.add(new DirectNum("sixteen", "16")); directNums.add(new DirectNum("seventeen", "17")); directNums.add(new DirectNum("eighteen", "18")); directNums.add(new DirectNum("nineteen", "19")); directNums.add(new DirectNum("ninteen", "19")); // Common mis-spelling directNums.add(new DirectNum("zero", "0")); directNums.add(new DirectNum("one", "1")); directNums.add(new DirectNum("two", "2")); directNums.add(new DirectNum("three", "3")); directNums.add(new DirectNum("four(\\W|$)", "4$1")); // The weird regex is so that it matches four but not fourty directNums.add(new DirectNum("five", "5")); directNums.add(new DirectNum("six(\\W|$)", "6$1")); directNums.add(new DirectNum("seven(\\W|$)", "7$1")); directNums.add(new DirectNum("eight(\\W|$)", "8$1")); directNums.add(new DirectNum("nine(\\W|$)", "9$1")); directNums.add(new DirectNum("ten", "10")); directNums.add(new DirectNum("\\ba\\b", "1")); Numerizer.DIRECT_NUMS = directNums.toArray(new DirectNum[directNums.size()]); List<TenPrefix> tenPrefixes = new LinkedList<TenPrefix>(); tenPrefixes.add(new TenPrefix("twenty", 20)); tenPrefixes.add(new TenPrefix("thirty", 30)); tenPrefixes.add(new TenPrefix("fourty", 40)); tenPrefixes.add(new TenPrefix("fifty", 50)); tenPrefixes.add(new TenPrefix("sixty", 60)); tenPrefixes.add(new TenPrefix("seventy", 70)); tenPrefixes.add(new TenPrefix("eighty", 80)); tenPrefixes.add(new TenPrefix("ninety", 90)); tenPrefixes.add(new TenPrefix("ninty", 90)); // Common mis-spelling Numerizer.TEN_PREFIXES = tenPrefixes.toArray(new TenPrefix[tenPrefixes.size()]); List<BigPrefix> bigPrefixes = new LinkedList<BigPrefix>(); bigPrefixes.add(new BigPrefix("hundred", 100L)); bigPrefixes.add(new BigPrefix("thousand", 1000L)); bigPrefixes.add(new BigPrefix("million", 1000000L)); bigPrefixes.add(new BigPrefix("billion", 1000000000L)); bigPrefixes.add(new BigPrefix("trillion", 1000000000000L)); Numerizer.BIG_PREFIXES = bigPrefixes.toArray(new BigPrefix[bigPrefixes.size()]); } private static final Pattern DEHYPHENATOR = Pattern.compile(" +|(\\D)-(\\D)"); private static final Pattern DEHALFER = Pattern.compile("a half", Pattern.CASE_INSENSITIVE); private static final Pattern DEHAALFER = Pattern.compile("(\\d+)(?: | and |-)*haAlf", Pattern.CASE_INSENSITIVE); private static final Pattern ANDITION_PATTERN = Pattern.compile("(\\d+)( | and )(\\d+)(?=\\W|$)"); // FIXES //string.gsub!(/ +|([^\d])-([^d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction //string.gsub!(/ +|([^\d])-([^\\d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction public static String numerize(String str) { String numerizedStr = str; // preprocess numerizedStr = Numerizer.DEHYPHENATOR.matcher(numerizedStr).replaceAll("$1 $2"); // will mutilate hyphenated-words but shouldn't matter for date extraction numerizedStr = Numerizer.DEHALFER.matcher(numerizedStr).replaceAll("haAlf"); // take the 'a' out so it doesn't turn into a 1, save the half for the end // easy/direct replacements for (DirectNum dn : Numerizer.DIRECT_NUMS) { numerizedStr = dn.getName().matcher(numerizedStr).replaceAll(dn.getNumber()); } // ten, twenty, etc. for (Prefix tp : Numerizer.TEN_PREFIXES) { Matcher matcher = tp.getName().matcher(numerizedStr); if (matcher.find()) { StringBuffer matcherBuffer = new StringBuffer(); do { if (matcher.group(1) == null) { matcher.appendReplacement(matcherBuffer, String.valueOf(tp.getNumber())); } else { matcher.appendReplacement(matcherBuffer, String.valueOf(tp.getNumber() + Long.parseLong(matcher.group(1).trim()))); } } while (matcher.find()); matcher.appendTail(matcherBuffer); numerizedStr = matcherBuffer.toString(); } } // hundreds, thousands, millions, etc. for (Prefix bp : Numerizer.BIG_PREFIXES) { Matcher matcher = bp.getName().matcher(numerizedStr); if (matcher.find()) { StringBuffer matcherBuffer = new StringBuffer(); do { if (matcher.group(1) == null) { matcher.appendReplacement(matcherBuffer, String.valueOf(bp.getNumber())); } else { matcher.appendReplacement(matcherBuffer, String.valueOf(bp.getNumber() * Long.parseLong(matcher.group(1).trim()))); } } while (matcher.find()); matcher.appendTail(matcherBuffer); numerizedStr = matcherBuffer.toString(); numerizedStr = Numerizer.andition(numerizedStr); // combine_numbers(string) // Should to be more efficient way to do this } } // fractional addition // I'm not combining this with the previous block as using float addition complicates the strings // (with extraneous .0's and such ) Matcher matcher = Numerizer.DEHAALFER.matcher(numerizedStr); if (matcher.find()) { StringBuffer matcherBuffer = new StringBuffer(); do { matcher.appendReplacement(matcherBuffer, String.valueOf(Float.parseFloat(matcher.group(1).trim()) + 0.5f)); } while (matcher.find()); matcher.appendTail(matcherBuffer); numerizedStr = matcherBuffer.toString(); } //string.gsub!(/(\d+)(?: | and |-)*haAlf/i) { ($1.to_f + 0.5).to_s } return numerizedStr; } public static String andition(String str) { StringBuffer anditionStr = new StringBuffer(str); Matcher matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr); while (matcher.find()) { if (matcher.group(2).equalsIgnoreCase(" and ") || matcher.group(1).length() > matcher.group(3).length()) { anditionStr.replace(matcher.start(), matcher.end(), String.valueOf(Integer.parseInt(matcher.group(1).trim()) + Integer.parseInt(matcher.group(3).trim()))); matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr); } } return anditionStr.toString(); } }
jedld/jchronic
src/main/java/com/mdimension/jchronic/numerizer/Numerizer.java
2,386
// ten, twenty, etc.
line_comment
nl
package com.mdimension.jchronic.numerizer; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Numerizer { protected static class DirectNum { private Pattern _name; private String _number; public DirectNum(String name, String number) { _name = Pattern.compile(name, Pattern.CASE_INSENSITIVE); _number = number; } public Pattern getName() { return _name; } public String getNumber() { return _number; } } protected static class Prefix { private Pattern _name; private long _number; public Prefix(Pattern name, long number) { _name = name; _number = number; } public Pattern getName() { return _name; } public long getNumber() { return _number; } } protected static class TenPrefix extends Prefix { public TenPrefix(String name, long number) { super(Pattern.compile("(?:" + name + ")( *\\d(?=\\D|$))*", Pattern.CASE_INSENSITIVE), number); } } protected static class BigPrefix extends Prefix { public BigPrefix(String name, long number) { super(Pattern.compile("(\\d*) *" + name, Pattern.CASE_INSENSITIVE), number); } } protected static DirectNum[] DIRECT_NUMS; protected static TenPrefix[] TEN_PREFIXES; protected static BigPrefix[] BIG_PREFIXES; static { List<DirectNum> directNums = new LinkedList<DirectNum>(); directNums.add(new DirectNum("eleven", "11")); directNums.add(new DirectNum("twelve", "12")); directNums.add(new DirectNum("thirteen", "13")); directNums.add(new DirectNum("fourteen", "14")); directNums.add(new DirectNum("fifteen", "15")); directNums.add(new DirectNum("sixteen", "16")); directNums.add(new DirectNum("seventeen", "17")); directNums.add(new DirectNum("eighteen", "18")); directNums.add(new DirectNum("nineteen", "19")); directNums.add(new DirectNum("ninteen", "19")); // Common mis-spelling directNums.add(new DirectNum("zero", "0")); directNums.add(new DirectNum("one", "1")); directNums.add(new DirectNum("two", "2")); directNums.add(new DirectNum("three", "3")); directNums.add(new DirectNum("four(\\W|$)", "4$1")); // The weird regex is so that it matches four but not fourty directNums.add(new DirectNum("five", "5")); directNums.add(new DirectNum("six(\\W|$)", "6$1")); directNums.add(new DirectNum("seven(\\W|$)", "7$1")); directNums.add(new DirectNum("eight(\\W|$)", "8$1")); directNums.add(new DirectNum("nine(\\W|$)", "9$1")); directNums.add(new DirectNum("ten", "10")); directNums.add(new DirectNum("\\ba\\b", "1")); Numerizer.DIRECT_NUMS = directNums.toArray(new DirectNum[directNums.size()]); List<TenPrefix> tenPrefixes = new LinkedList<TenPrefix>(); tenPrefixes.add(new TenPrefix("twenty", 20)); tenPrefixes.add(new TenPrefix("thirty", 30)); tenPrefixes.add(new TenPrefix("fourty", 40)); tenPrefixes.add(new TenPrefix("fifty", 50)); tenPrefixes.add(new TenPrefix("sixty", 60)); tenPrefixes.add(new TenPrefix("seventy", 70)); tenPrefixes.add(new TenPrefix("eighty", 80)); tenPrefixes.add(new TenPrefix("ninety", 90)); tenPrefixes.add(new TenPrefix("ninty", 90)); // Common mis-spelling Numerizer.TEN_PREFIXES = tenPrefixes.toArray(new TenPrefix[tenPrefixes.size()]); List<BigPrefix> bigPrefixes = new LinkedList<BigPrefix>(); bigPrefixes.add(new BigPrefix("hundred", 100L)); bigPrefixes.add(new BigPrefix("thousand", 1000L)); bigPrefixes.add(new BigPrefix("million", 1000000L)); bigPrefixes.add(new BigPrefix("billion", 1000000000L)); bigPrefixes.add(new BigPrefix("trillion", 1000000000000L)); Numerizer.BIG_PREFIXES = bigPrefixes.toArray(new BigPrefix[bigPrefixes.size()]); } private static final Pattern DEHYPHENATOR = Pattern.compile(" +|(\\D)-(\\D)"); private static final Pattern DEHALFER = Pattern.compile("a half", Pattern.CASE_INSENSITIVE); private static final Pattern DEHAALFER = Pattern.compile("(\\d+)(?: | and |-)*haAlf", Pattern.CASE_INSENSITIVE); private static final Pattern ANDITION_PATTERN = Pattern.compile("(\\d+)( | and )(\\d+)(?=\\W|$)"); // FIXES //string.gsub!(/ +|([^\d])-([^d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction //string.gsub!(/ +|([^\d])-([^\\d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction public static String numerize(String str) { String numerizedStr = str; // preprocess numerizedStr = Numerizer.DEHYPHENATOR.matcher(numerizedStr).replaceAll("$1 $2"); // will mutilate hyphenated-words but shouldn't matter for date extraction numerizedStr = Numerizer.DEHALFER.matcher(numerizedStr).replaceAll("haAlf"); // take the 'a' out so it doesn't turn into a 1, save the half for the end // easy/direct replacements for (DirectNum dn : Numerizer.DIRECT_NUMS) { numerizedStr = dn.getName().matcher(numerizedStr).replaceAll(dn.getNumber()); } // ten, twenty,<SUF> for (Prefix tp : Numerizer.TEN_PREFIXES) { Matcher matcher = tp.getName().matcher(numerizedStr); if (matcher.find()) { StringBuffer matcherBuffer = new StringBuffer(); do { if (matcher.group(1) == null) { matcher.appendReplacement(matcherBuffer, String.valueOf(tp.getNumber())); } else { matcher.appendReplacement(matcherBuffer, String.valueOf(tp.getNumber() + Long.parseLong(matcher.group(1).trim()))); } } while (matcher.find()); matcher.appendTail(matcherBuffer); numerizedStr = matcherBuffer.toString(); } } // hundreds, thousands, millions, etc. for (Prefix bp : Numerizer.BIG_PREFIXES) { Matcher matcher = bp.getName().matcher(numerizedStr); if (matcher.find()) { StringBuffer matcherBuffer = new StringBuffer(); do { if (matcher.group(1) == null) { matcher.appendReplacement(matcherBuffer, String.valueOf(bp.getNumber())); } else { matcher.appendReplacement(matcherBuffer, String.valueOf(bp.getNumber() * Long.parseLong(matcher.group(1).trim()))); } } while (matcher.find()); matcher.appendTail(matcherBuffer); numerizedStr = matcherBuffer.toString(); numerizedStr = Numerizer.andition(numerizedStr); // combine_numbers(string) // Should to be more efficient way to do this } } // fractional addition // I'm not combining this with the previous block as using float addition complicates the strings // (with extraneous .0's and such ) Matcher matcher = Numerizer.DEHAALFER.matcher(numerizedStr); if (matcher.find()) { StringBuffer matcherBuffer = new StringBuffer(); do { matcher.appendReplacement(matcherBuffer, String.valueOf(Float.parseFloat(matcher.group(1).trim()) + 0.5f)); } while (matcher.find()); matcher.appendTail(matcherBuffer); numerizedStr = matcherBuffer.toString(); } //string.gsub!(/(\d+)(?: | and |-)*haAlf/i) { ($1.to_f + 0.5).to_s } return numerizedStr; } public static String andition(String str) { StringBuffer anditionStr = new StringBuffer(str); Matcher matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr); while (matcher.find()) { if (matcher.group(2).equalsIgnoreCase(" and ") || matcher.group(1).length() > matcher.group(3).length()) { anditionStr.replace(matcher.start(), matcher.end(), String.valueOf(Integer.parseInt(matcher.group(1).trim()) + Integer.parseInt(matcher.group(3).trim()))); matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr); } } return anditionStr.toString(); } }
141674_10
/*************************************************************************** * (C) Copyright 2003-2011 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.core.rp.achievement.factory; import java.util.Collection; import java.util.LinkedList; import java.util.List; import games.stendhal.common.parser.Sentence; import games.stendhal.server.core.rp.achievement.Achievement; import games.stendhal.server.core.rp.achievement.Category; import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.npc.ChatCondition; import games.stendhal.server.entity.npc.condition.AndCondition; import games.stendhal.server.entity.npc.condition.QuestActiveCondition; import games.stendhal.server.entity.npc.condition.QuestCompletedCondition; import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition; import games.stendhal.server.entity.npc.condition.QuestStartedCondition; import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition; import games.stendhal.server.entity.player.Player; /** * Factory for quest achievements * * @author kymara */ public class FriendAchievementFactory extends AbstractAchievementFactory { public static final String ID_CHILD_FRIEND = "friend.quests.children"; public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find"; public static final String ID_GOOD_SAMARITAN = "friend.karma.250"; public static final String ID_STILL_BELIEVING = "friend.meet.seasonal"; @Override protected Category getCategory() { return Category.FRIEND; } @Override public Collection<Achievement> createAchievements() { List<Achievement> achievements = new LinkedList<Achievement>(); // TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time) // Befriend Susi and complete quests for all children achievements.add(createAchievement( ID_CHILD_FRIEND, "Childrens' Friend", "Complete quests for all children", Achievement.MEDIUM_BASE_SCORE, true, new AndCondition( // Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java) new QuestStartedCondition("susi"), // Help Tad, Semos Town Hall (Medicine for Tad) new QuestCompletedCondition("introduce_players"), // Plink, Semos Plains North new QuestCompletedCondition("plinks_toy"), // Anna, in Ados new QuestCompletedCondition("toys_collector"), // Sally, Orril River // 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT)); new AndCondition(new QuestActiveCondition("campfire"), new QuestNotInStateCondition("campfire", "start")), // Annie, Kalavan city gardens new QuestStateStartsWithCondition("icecream_for_annie","eating;"), // Elisabeth, Kirdneh new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"), // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom"), // Hughie, Ados farmhouse new AndCondition(new QuestActiveCondition("fishsoup_for_hughie"), new QuestNotInStateCondition("fishsoup_for_hughie", "start")), // Finn Farmer, George new QuestCompletedCondition("coded_message"), // Marianne, Deniran City S new AndCondition( new QuestActiveCondition("eggs_for_marianne"), new QuestNotInStateCondition("eggs_for_marianne", "start") ) ))); // quests about finding people achievements.add(createAchievement( ID_PRIVATE_DETECTIVE, "Private Detective", "Find all lost and hidden people", Achievement.HARD_BASE_SCORE, true, new AndCondition( // Rat Children (Agnus) new QuestCompletedCondition("find_rat_kids"), // Find Ghosts (Carena) new QuestCompletedCondition("find_ghosts"), // Meet Angels (any of the cherubs) new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { if (!player.hasQuest("seven_cherubs")) { return false; } final String npcDoneText = player.getQuest("seven_cherubs"); final String[] done = npcDoneText.split(";"); final int left = 7 - done.length; return left < 0; } }))); // earn over 250 karma achievements.add(createAchievement( ID_GOOD_SAMARITAN, "Good Samaritan", "Earn a very good karma", Achievement.MEDIUM_BASE_SCORE, true, new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { return player.getKarma() > 250; } })); // meet Santa Claus and Easter Bunny achievements.add(createAchievement( ID_STILL_BELIEVING, "Still Believing", "Meet Santa Claus and Easter Bunny", Achievement.EASY_BASE_SCORE, true, new AndCondition( new QuestWithPrefixCompletedCondition("meet_santa_"), new QuestWithPrefixCompletedCondition("meet_bunny_")))); return achievements; } }
Gnefil/Stendhal-Game
src/games/stendhal/server/core/rp/achievement/factory/FriendAchievementFactory.java
1,491
// Annie, Kalavan city gardens
line_comment
nl
/*************************************************************************** * (C) Copyright 2003-2011 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.core.rp.achievement.factory; import java.util.Collection; import java.util.LinkedList; import java.util.List; import games.stendhal.common.parser.Sentence; import games.stendhal.server.core.rp.achievement.Achievement; import games.stendhal.server.core.rp.achievement.Category; import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.npc.ChatCondition; import games.stendhal.server.entity.npc.condition.AndCondition; import games.stendhal.server.entity.npc.condition.QuestActiveCondition; import games.stendhal.server.entity.npc.condition.QuestCompletedCondition; import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition; import games.stendhal.server.entity.npc.condition.QuestStartedCondition; import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition; import games.stendhal.server.entity.player.Player; /** * Factory for quest achievements * * @author kymara */ public class FriendAchievementFactory extends AbstractAchievementFactory { public static final String ID_CHILD_FRIEND = "friend.quests.children"; public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find"; public static final String ID_GOOD_SAMARITAN = "friend.karma.250"; public static final String ID_STILL_BELIEVING = "friend.meet.seasonal"; @Override protected Category getCategory() { return Category.FRIEND; } @Override public Collection<Achievement> createAchievements() { List<Achievement> achievements = new LinkedList<Achievement>(); // TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time) // Befriend Susi and complete quests for all children achievements.add(createAchievement( ID_CHILD_FRIEND, "Childrens' Friend", "Complete quests for all children", Achievement.MEDIUM_BASE_SCORE, true, new AndCondition( // Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java) new QuestStartedCondition("susi"), // Help Tad, Semos Town Hall (Medicine for Tad) new QuestCompletedCondition("introduce_players"), // Plink, Semos Plains North new QuestCompletedCondition("plinks_toy"), // Anna, in Ados new QuestCompletedCondition("toys_collector"), // Sally, Orril River // 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT)); new AndCondition(new QuestActiveCondition("campfire"), new QuestNotInStateCondition("campfire", "start")), // Annie, Kalavan<SUF> new QuestStateStartsWithCondition("icecream_for_annie","eating;"), // Elisabeth, Kirdneh new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"), // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom"), // Hughie, Ados farmhouse new AndCondition(new QuestActiveCondition("fishsoup_for_hughie"), new QuestNotInStateCondition("fishsoup_for_hughie", "start")), // Finn Farmer, George new QuestCompletedCondition("coded_message"), // Marianne, Deniran City S new AndCondition( new QuestActiveCondition("eggs_for_marianne"), new QuestNotInStateCondition("eggs_for_marianne", "start") ) ))); // quests about finding people achievements.add(createAchievement( ID_PRIVATE_DETECTIVE, "Private Detective", "Find all lost and hidden people", Achievement.HARD_BASE_SCORE, true, new AndCondition( // Rat Children (Agnus) new QuestCompletedCondition("find_rat_kids"), // Find Ghosts (Carena) new QuestCompletedCondition("find_ghosts"), // Meet Angels (any of the cherubs) new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { if (!player.hasQuest("seven_cherubs")) { return false; } final String npcDoneText = player.getQuest("seven_cherubs"); final String[] done = npcDoneText.split(";"); final int left = 7 - done.length; return left < 0; } }))); // earn over 250 karma achievements.add(createAchievement( ID_GOOD_SAMARITAN, "Good Samaritan", "Earn a very good karma", Achievement.MEDIUM_BASE_SCORE, true, new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { return player.getKarma() > 250; } })); // meet Santa Claus and Easter Bunny achievements.add(createAchievement( ID_STILL_BELIEVING, "Still Believing", "Meet Santa Claus and Easter Bunny", Achievement.EASY_BASE_SCORE, true, new AndCondition( new QuestWithPrefixCompletedCondition("meet_santa_"), new QuestWithPrefixCompletedCondition("meet_bunny_")))); return achievements; } }
174472_0
package org.starloco.locos.other; import org.starloco.locos.client.Player; import org.starloco.locos.common.Formulas; import org.starloco.locos.common.SocketManager; import org.starloco.locos.game.world.World; import org.starloco.locos.object.GameObject; public class Loterie { public static void startLoterie(Player perso, int args) { switch (args) { case 1: if (perso.hasItemTemplate(15001, 1)) { int objIdWin = getCadeau1(); //ObjectTemplate objWin = World.world.getObjTemplate(objIdWin); //String objName = objWin.getName(); //SocketManager.GAME_SEND_cMK_PACKET_TO_MAP(perso.getCurMap(), "", -5, "Roulette", "Félicitation "+perso.getName()+" ! Tu viens de gagné : '"+objName+"'."); perso.removeByTemplateID(15001, 1); SocketManager.GAME_SEND_Im_PACKET(perso, "022;" + 1 + "~" + 15001); SocketManager.GAME_SEND_Im_PACKET(perso, "021;" + 1 + "~" + objIdWin); GameObject newObjAdded = World.world.getObjTemplate(objIdWin).createNewItem(1, false); if(perso.addObjet(newObjAdded, true)) World.world.addGameObject(newObjAdded, true); } else { SocketManager.GAME_SEND_Im_PACKET(perso, "14|43"); } break; case 2: if (perso.hasItemTemplate(19072, 1)) { int objIdWin = getCadeau2(); //ObjectTemplate objWin = World.world.getObjTemplate(objIdWin); //String objName = objWin.getName(); //SocketManager.GAME_SEND_cMK_PACKET_TO_MAP(perso.getCurMap(), "", -5, "Roulette", "Félicitation "+perso.getName()+" ! Tu viens de gagné : '"+objName+"'."); perso.removeByTemplateID(19072, 1); SocketManager.GAME_SEND_Im_PACKET(perso, "022;" + 1 + "~" + 19072); SocketManager.GAME_SEND_Im_PACKET(perso, "021;" + 1 + "~" + objIdWin); GameObject newObjAdded = World.world.getObjTemplate(objIdWin).createNewItem(1, false); if(perso.addObjet(newObjAdded, true)) World.world.addGameObject(newObjAdded, true); } else { SocketManager.GAME_SEND_Im_PACKET(perso, "14|43"); } break; } } public static void startLoteriePioute(Player perso) { int objIdWin = getCadeauPioute(); SocketManager.GAME_SEND_Im_PACKET(perso, "021;" + 1 + "~" + objIdWin); GameObject newObjAdded = World.world.getObjTemplate(objIdWin).createNewItem(1, false); if(perso.addObjet(newObjAdded, true)) World.world.addGameObject(newObjAdded, true); } public static int getCadeau1() { int Chance = Formulas.getRandomValue(1, 18); switch (Chance) { case 1: return 10338; case 2: return 8899; case 3: return 8903; case 4: return 9339; case 5: return 9348; case 6: return 9500; case 7: return 9583; case 8: return 9889; case 9: return 9893; case 10: return 10150; case 11: return 8817; case 12: return 8912; case 13: return 8983; case 14: return 9353; case 15: return 9354; case 16: return 9356; case 17: return 9358; case 18: return 9184; } return Chance; } public static int getCadeau2() { int Chance = Formulas.getRandomValue(1, 26); switch (Chance) { case 1: return 9643; case 2: return 9642; case 3: return 9641; case 4: return 9640; case 5: return 9639; case 6: return 9638; case 7: return 9637; case 8: return 9636; case 9: return 9635; case 10: return 8955; case 11: return 8954; case 12: return 8953; case 13: return 8952; case 14: return 8951; case 15: return 8950; case 16: return 8949; case 17: return 8948; case 18: return 7804; case 19: return 7803; case 20: return 7802; case 21: return 2333; case 22: return 2332; case 23: return 992; case 24: return 991; case 25: return 990; case 26: return 989; } return Chance; } public static int getCadeauPioute() { int Chance = Formulas.getRandomValue(1, 6); switch (Chance) { case 1: return 7708; case 2: return 7709; case 3: return 7710; case 4: return 7711; case 5: return 7712; case 6: return 7713; } return Chance; } public static int getCadeauBworker() { int Chance = Formulas.getRandomValue(1, 8); switch (Chance) { case 1: return 6799; case 2: return 6804; case 3: return 6805; case 4: return 6807; case 5: return 6811; case 6: return 6812; case 7: return 6813; case 8: return 6904; } return Chance; } }
iR3SH/HelpGame
src/org/starloco/locos/other/Loterie.java
1,923
//ObjectTemplate objWin = World.world.getObjTemplate(objIdWin);
line_comment
nl
package org.starloco.locos.other; import org.starloco.locos.client.Player; import org.starloco.locos.common.Formulas; import org.starloco.locos.common.SocketManager; import org.starloco.locos.game.world.World; import org.starloco.locos.object.GameObject; public class Loterie { public static void startLoterie(Player perso, int args) { switch (args) { case 1: if (perso.hasItemTemplate(15001, 1)) { int objIdWin = getCadeau1(); //ObjectTemplate objWin<SUF> //String objName = objWin.getName(); //SocketManager.GAME_SEND_cMK_PACKET_TO_MAP(perso.getCurMap(), "", -5, "Roulette", "Félicitation "+perso.getName()+" ! Tu viens de gagné : '"+objName+"'."); perso.removeByTemplateID(15001, 1); SocketManager.GAME_SEND_Im_PACKET(perso, "022;" + 1 + "~" + 15001); SocketManager.GAME_SEND_Im_PACKET(perso, "021;" + 1 + "~" + objIdWin); GameObject newObjAdded = World.world.getObjTemplate(objIdWin).createNewItem(1, false); if(perso.addObjet(newObjAdded, true)) World.world.addGameObject(newObjAdded, true); } else { SocketManager.GAME_SEND_Im_PACKET(perso, "14|43"); } break; case 2: if (perso.hasItemTemplate(19072, 1)) { int objIdWin = getCadeau2(); //ObjectTemplate objWin = World.world.getObjTemplate(objIdWin); //String objName = objWin.getName(); //SocketManager.GAME_SEND_cMK_PACKET_TO_MAP(perso.getCurMap(), "", -5, "Roulette", "Félicitation "+perso.getName()+" ! Tu viens de gagné : '"+objName+"'."); perso.removeByTemplateID(19072, 1); SocketManager.GAME_SEND_Im_PACKET(perso, "022;" + 1 + "~" + 19072); SocketManager.GAME_SEND_Im_PACKET(perso, "021;" + 1 + "~" + objIdWin); GameObject newObjAdded = World.world.getObjTemplate(objIdWin).createNewItem(1, false); if(perso.addObjet(newObjAdded, true)) World.world.addGameObject(newObjAdded, true); } else { SocketManager.GAME_SEND_Im_PACKET(perso, "14|43"); } break; } } public static void startLoteriePioute(Player perso) { int objIdWin = getCadeauPioute(); SocketManager.GAME_SEND_Im_PACKET(perso, "021;" + 1 + "~" + objIdWin); GameObject newObjAdded = World.world.getObjTemplate(objIdWin).createNewItem(1, false); if(perso.addObjet(newObjAdded, true)) World.world.addGameObject(newObjAdded, true); } public static int getCadeau1() { int Chance = Formulas.getRandomValue(1, 18); switch (Chance) { case 1: return 10338; case 2: return 8899; case 3: return 8903; case 4: return 9339; case 5: return 9348; case 6: return 9500; case 7: return 9583; case 8: return 9889; case 9: return 9893; case 10: return 10150; case 11: return 8817; case 12: return 8912; case 13: return 8983; case 14: return 9353; case 15: return 9354; case 16: return 9356; case 17: return 9358; case 18: return 9184; } return Chance; } public static int getCadeau2() { int Chance = Formulas.getRandomValue(1, 26); switch (Chance) { case 1: return 9643; case 2: return 9642; case 3: return 9641; case 4: return 9640; case 5: return 9639; case 6: return 9638; case 7: return 9637; case 8: return 9636; case 9: return 9635; case 10: return 8955; case 11: return 8954; case 12: return 8953; case 13: return 8952; case 14: return 8951; case 15: return 8950; case 16: return 8949; case 17: return 8948; case 18: return 7804; case 19: return 7803; case 20: return 7802; case 21: return 2333; case 22: return 2332; case 23: return 992; case 24: return 991; case 25: return 990; case 26: return 989; } return Chance; } public static int getCadeauPioute() { int Chance = Formulas.getRandomValue(1, 6); switch (Chance) { case 1: return 7708; case 2: return 7709; case 3: return 7710; case 4: return 7711; case 5: return 7712; case 6: return 7713; } return Chance; } public static int getCadeauBworker() { int Chance = Formulas.getRandomValue(1, 8); switch (Chance) { case 1: return 6799; case 2: return 6804; case 3: return 6805; case 4: return 6807; case 5: return 6811; case 6: return 6812; case 7: return 6813; case 8: return 6904; } return Chance; } }
18319_25
/******************************************************************************* * BusinessHorizon2 * * Copyright (C) * 2012-2013 Christian Gahlert, Florian Stier, Kai Westerholz, * Timo Belz, Daniel Dengler, Katharina Huber, Christian Scherer, Julius Hacker * 2013-2014 Marcel Rosenberger, Mirko Göpfrich, Annika Weis, Katharina Narlock, * Volker Meier * * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package dhbw.ka.mwi.businesshorizon2.models; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeSet; import com.vaadin.ui.Label; import dhbw.ka.mwi.businesshorizon2.methods.AbstractDeterministicMethod; import dhbw.ka.mwi.businesshorizon2.methods.AbstractStochasticMethod; import dhbw.ka.mwi.businesshorizon2.models.Period.Period; import dhbw.ka.mwi.businesshorizon2.models.PeriodContainer.AbstractPeriodContainer; import dhbw.ka.mwi.businesshorizon2.services.persistence.ProjectAlreadyExistsException; /** * Bei dieser Klasse handelt es sich um eine Art Container-Objekt. Dieses Objekt * wird via Spring einmal pro Session erstellt und bleibt somit bestehen. Sollte * z.B. vorher gespeicherte Daten geladen werden, dann muessen diese an dieses * Objekt uebergeben werden (d.h. es ist nicht moeglich, dieses Objekt zu * ersetzen). * * @author Christian Gahlert * */ public class Project implements Serializable { /** * */ private static final long serialVersionUID = 9199799755347070847L; protected TreeSet<? extends Period> periods = new TreeSet<>(); private Date lastChanged; private User createdFrom; private String name; private String typ; private String description; private AbstractPeriodContainer stochasticPeriods, deterministicPeriods; public AbstractPeriodContainer getStochasticPeriods() { return stochasticPeriods; } public void setStochasticPeriods(AbstractPeriodContainer stochasticPeriods) { this.stochasticPeriods = stochasticPeriods; } public AbstractPeriodContainer getDeterministicPeriods() { return deterministicPeriods; } public void setDeterministicPeriods(AbstractPeriodContainer deterministicPeriods) { this.deterministicPeriods = deterministicPeriods; } private double CashFlowProbabilityOfRise; private double CashFlowStepRange; private double BorrowedCapitalProbabilityOfRise; private double BorrowedCapitalStepRange; private int periodsToForecast; private int periodsToForecast_deterministic;//Annika Weis private int specifiedPastPeriods; private int relevantPastPeriods; private int iterations; private int basisYear; private ProjectInputType projectInputType; private SortedSet<AbstractStochasticMethod> methods; //Annika Weis private SortedSet<AbstractDeterministicMethod> methods_deterministic; protected List<Szenario> scenarios = new ArrayList<Szenario>(); /** * Konstruktor des Projekts, mit dessen der Name gesetzt wird. * Außerdem werden analog zum Fachkonzept die Default-Werte der Parameter gesetzt. * * @author Christian Scherer, Marcel Rosenberger * @param Der * Name des Projekts */ public Project(String name, String description) { this.name = name; this.setDescription(description); this.projectInputType = new ProjectInputType(); this.iterations = 10000; this.specifiedPastPeriods = 6; this.relevantPastPeriods = 5; this.periodsToForecast = 3; } /** * Standardkonstruktor des Projekt * * @author Christian Scherer */ public Project() { this.projectInputType = new ProjectInputType(); } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowProbabilityOfRise() { return CashFlowProbabilityOfRise; } /** * Setzt die Erhöhungswahrscheinlichkeit des CashFlows. * * @author Kai Westerholz * @param cashFlowProbabilityOfRise */ public void setCashFlowProbabilityOfRise(double cashFlowProbabilityOfRise) { CashFlowProbabilityOfRise = cashFlowProbabilityOfRise; } /** * Gibt die Schrittweise des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowStepRange() { return CashFlowStepRange; } /** * Setzt die Schrittweise vom CashFlow. * * @author Kai Westerholz * @param cashFlowStepRange */ public void setCashFlowStepRange(double cashFlowStepRange) { CashFlowStepRange = cashFlowStepRange; } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return Erhöhungswahrscheinlichkeit CashFlow */ public double getBorrowedCapitalProbabilityOfRise() { return BorrowedCapitalProbabilityOfRise; } /** * Setzt die Wahrscheinlichkeit der Erhoehung des Fremdkapitals. * * @author Kai Westerholz * * @param borrowedCapitalProbabilityOfRise */ public void setBorrowedCapitalProbabilityOfRise(double borrowedCapitalProbabilityOfRise) { BorrowedCapitalProbabilityOfRise = borrowedCapitalProbabilityOfRise; } /** * Gibt die Schrittweite des Fremdkapitals an. * * @author Kai Westerholz * * @return Schrittweite */ public double getBorrowedCapitalStepRange() { return BorrowedCapitalStepRange; } /** * Setzt die Schrittweite des Fremdkapitals. * * @author Kai Westerholz * @param borrowedCapitalStepRange */ public void setBorrowedCapitalStepRange(double borrowedCapitalStepRange) { BorrowedCapitalStepRange = borrowedCapitalStepRange; } /** * Gibt die Perioden in einem sortierten NavigableSet zurueck. * * @author Christian Gahlert * @return Die Perioden */ public NavigableSet<? extends Period> getPeriods() { return periods; } /** * @deprecated Bitte getter für die stochastiPeriods und DeterministicPeriods * verwenden Ueberschreibt die bisher verwendeten Methoden. Die * Perioden muessen in Form eines sortierten NavigableSet * vorliegen. * * @param periods * Die Perioden */ @Deprecated public void setPeriods(TreeSet<? extends Period> periods) { this.periods = periods; } /** * Diese Methode soll lediglich eine Liste von verfuegbaren Jahren * zurueckgeben. Ein Jahr ist verfuegbar, wenn noch keine Periode fuer das * Jahr existiert. Es wird beim aktuellen Jahr begonnen und dann * schrittweise ein Jahr runtergezaehlt. Dabei sollte z.B. nach 10 oder 20 * Jahren schluss sein (mehr Jahre wird wohl niemand eingeben wollen). * * @author Christian Gahlert * @return Die verfuegbaren Jahre absteigend sortiert */ public List<Integer> getAvailableYears() { ArrayList<Integer> years = new ArrayList<Integer>(); int start = Calendar.getInstance().get(Calendar.YEAR); boolean contains; for (int i = start; i > start - 5; i--) { contains = false; for (Period period : periods) { if (period.getYear() == i) { contains = true; break; } } if (!contains) { years.add(i); } } return years; } /** * Liesst das Datum der letzten Bearbeitung aus. Wird benötigt für die * Anwenderinformation auf dem Auswahl-screen für Projekte. * * @author Christian Scherer * @return Datum der letzten Aenderung */ public Date getLastChanged() { return lastChanged; } /** * Wird aufgerufen, wenn Aenderungen am Projekt vorgenommen wurden und * aktualisiert dann das bisherige Aenderungsdatum. * * @author Christian Scherer * @param heutiges * Datum (Aenderungszeitpunkt) */ public void setLastChanged(Date lastChanged) { this.lastChanged = lastChanged; } /** * Gibt den Namen des Projekts zurück. * * @author Christian Scherer * @return Name des Projekts */ public String getName() { return name; } public void setMethods(SortedSet<AbstractStochasticMethod> methods) { this.methods = methods; } public SortedSet<AbstractStochasticMethod> getMethods() { return methods; } //Annika Weis public void setMethods_deterministic(SortedSet<AbstractDeterministicMethod> methods_deterministic) { this.methods_deterministic = methods_deterministic; } //Annika Weis public SortedSet<AbstractDeterministicMethod> getMethods_deterministic() { return methods_deterministic; } public ProjectInputType getProjectInputType() { return projectInputType; } public void setProjectInputType(ProjectInputType projectInputType) { this.projectInputType = projectInputType; } /** * Setzt den Namen des Projekts. * * @author Christian Scherer * @param name * Name des Projekts */ public void setName(String name) { this.name = name; } /** * Gibt die Anzahl vorherzusagender Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast() { return periodsToForecast; } /** * Setzt die Anzahl vorherzusagender Perioden des Projekts. * * @author Christian Scherer * @param periodsToForecast * Anzahl vorherzusagender Perioden */ public void setPeriodsToForecast(int periodsToForecast) { this.periodsToForecast = periodsToForecast; } /** * Gibt die Anzahl vorherzusagender deterinistischer Perioden des Projekts zurück. * * @author Annika Weis * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast_deterministic() { return periodsToForecast_deterministic; } /** * Setzt die Anzahl vorherzusagender deterministischer Perioden des Projekts. * * @author Annika Weis * @param periodsToForecast_deterministic * Anzahl vorherzusagender Perioden (deterministisch) */ public void setPeriodsToForecast_deterministic(int periodsToForecast_deterministic) { this.periodsToForecast_deterministic = periodsToForecast_deterministic; } /** * Setzt die Anzahl der anzugebenden vergangenen Perioden des Projekts. * * @author Marcel Rosenberger * @param specifiedPastPeriods * Anzahl der anzugebenden vergangenen Perioden */ public void setSpecifiedPastPeriods(int specifiedPastPeriods) { this.specifiedPastPeriods = specifiedPastPeriods; } /** * Gibt die Anzahl der anzugebenden vergangenen Perioden des Projekts zurück. * * @author Marcel Rosenberger * @return Anzahl der anzugebenden vergangenen Perioden */ public int getSpecifiedPastPeriods() { return specifiedPastPeriods; } /** * Setzt die Anzahl der vergangenen relevanten Perioden des Projekts. * * @author Christian Scherer * @param relevantPastPeriods * Anzahl der vergangenen relevanten Perioden */ public void setRelevantPastPeriods(int relevantPastPeriods) { this.relevantPastPeriods = relevantPastPeriods; } /** * Gibt die Anzahl der vergangenen relevanten Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl der vergangenen relevanten Perioden */ public int getRelevantPastPeriods() { return relevantPastPeriods; } /** * Gibt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts zurück. * * @author Christian Scherer * @return Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public int getIterations() { return iterations; } /** * Setzt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts. * * @author Christian Scherer * @param iterations * Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public void setIterations(int iterations) { this.iterations = iterations; } /** * Setzt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen. * * @author Christian Scherer * @param basisYear * Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public void setBasisYear(int basisYear) { this.basisYear = basisYear; } /** * Gibt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen zurück. * * @author Christian Scherer * @return Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public int getBasisYear() { return basisYear; } public List<Szenario> getScenarios() { return this.scenarios; } /** * Gibt nur die einbezogenen Szenarios eines Projektes zurück. * * @author Marcel Rosenberger * * @return alle einbezogenen Szenarios */ public List<Szenario> getIncludedScenarios() { List<Szenario> includedScenarios = new ArrayList<Szenario>(); for (Szenario szenario : this.scenarios){ if(szenario.isIncludeInCalculation()){ includedScenarios.add(szenario); } } return includedScenarios; } public void addScenario(Szenario scenario) { this.scenarios.add(scenario); } public User getCreatedFrom() { return createdFrom; } public void setCreatedFrom(User user) { createdFrom = user; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } public int getTotalPeriods (){ if (projectInputType.isDeterministic()==true){ return periodsToForecast_deterministic; } return specifiedPastPeriods ; } public String getTypMethod(){ if (projectInputType.isDeterministic()==true){ typ = "Deterministische Eingabe"; } else { typ = "Stochastische Eingabe"; } return typ; } }
DHBW-Karlsruhe/businesshorizon2_old
src/main/java/dhbw/ka/mwi/businesshorizon2/models/Project.java
3,990
/** * Setzt die Anzahl der vergangenen relevanten Perioden des Projekts. * * @author Christian Scherer * @param relevantPastPeriods * Anzahl der vergangenen relevanten Perioden */
block_comment
nl
/******************************************************************************* * BusinessHorizon2 * * Copyright (C) * 2012-2013 Christian Gahlert, Florian Stier, Kai Westerholz, * Timo Belz, Daniel Dengler, Katharina Huber, Christian Scherer, Julius Hacker * 2013-2014 Marcel Rosenberger, Mirko Göpfrich, Annika Weis, Katharina Narlock, * Volker Meier * * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package dhbw.ka.mwi.businesshorizon2.models; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeSet; import com.vaadin.ui.Label; import dhbw.ka.mwi.businesshorizon2.methods.AbstractDeterministicMethod; import dhbw.ka.mwi.businesshorizon2.methods.AbstractStochasticMethod; import dhbw.ka.mwi.businesshorizon2.models.Period.Period; import dhbw.ka.mwi.businesshorizon2.models.PeriodContainer.AbstractPeriodContainer; import dhbw.ka.mwi.businesshorizon2.services.persistence.ProjectAlreadyExistsException; /** * Bei dieser Klasse handelt es sich um eine Art Container-Objekt. Dieses Objekt * wird via Spring einmal pro Session erstellt und bleibt somit bestehen. Sollte * z.B. vorher gespeicherte Daten geladen werden, dann muessen diese an dieses * Objekt uebergeben werden (d.h. es ist nicht moeglich, dieses Objekt zu * ersetzen). * * @author Christian Gahlert * */ public class Project implements Serializable { /** * */ private static final long serialVersionUID = 9199799755347070847L; protected TreeSet<? extends Period> periods = new TreeSet<>(); private Date lastChanged; private User createdFrom; private String name; private String typ; private String description; private AbstractPeriodContainer stochasticPeriods, deterministicPeriods; public AbstractPeriodContainer getStochasticPeriods() { return stochasticPeriods; } public void setStochasticPeriods(AbstractPeriodContainer stochasticPeriods) { this.stochasticPeriods = stochasticPeriods; } public AbstractPeriodContainer getDeterministicPeriods() { return deterministicPeriods; } public void setDeterministicPeriods(AbstractPeriodContainer deterministicPeriods) { this.deterministicPeriods = deterministicPeriods; } private double CashFlowProbabilityOfRise; private double CashFlowStepRange; private double BorrowedCapitalProbabilityOfRise; private double BorrowedCapitalStepRange; private int periodsToForecast; private int periodsToForecast_deterministic;//Annika Weis private int specifiedPastPeriods; private int relevantPastPeriods; private int iterations; private int basisYear; private ProjectInputType projectInputType; private SortedSet<AbstractStochasticMethod> methods; //Annika Weis private SortedSet<AbstractDeterministicMethod> methods_deterministic; protected List<Szenario> scenarios = new ArrayList<Szenario>(); /** * Konstruktor des Projekts, mit dessen der Name gesetzt wird. * Außerdem werden analog zum Fachkonzept die Default-Werte der Parameter gesetzt. * * @author Christian Scherer, Marcel Rosenberger * @param Der * Name des Projekts */ public Project(String name, String description) { this.name = name; this.setDescription(description); this.projectInputType = new ProjectInputType(); this.iterations = 10000; this.specifiedPastPeriods = 6; this.relevantPastPeriods = 5; this.periodsToForecast = 3; } /** * Standardkonstruktor des Projekt * * @author Christian Scherer */ public Project() { this.projectInputType = new ProjectInputType(); } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowProbabilityOfRise() { return CashFlowProbabilityOfRise; } /** * Setzt die Erhöhungswahrscheinlichkeit des CashFlows. * * @author Kai Westerholz * @param cashFlowProbabilityOfRise */ public void setCashFlowProbabilityOfRise(double cashFlowProbabilityOfRise) { CashFlowProbabilityOfRise = cashFlowProbabilityOfRise; } /** * Gibt die Schrittweise des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowStepRange() { return CashFlowStepRange; } /** * Setzt die Schrittweise vom CashFlow. * * @author Kai Westerholz * @param cashFlowStepRange */ public void setCashFlowStepRange(double cashFlowStepRange) { CashFlowStepRange = cashFlowStepRange; } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return Erhöhungswahrscheinlichkeit CashFlow */ public double getBorrowedCapitalProbabilityOfRise() { return BorrowedCapitalProbabilityOfRise; } /** * Setzt die Wahrscheinlichkeit der Erhoehung des Fremdkapitals. * * @author Kai Westerholz * * @param borrowedCapitalProbabilityOfRise */ public void setBorrowedCapitalProbabilityOfRise(double borrowedCapitalProbabilityOfRise) { BorrowedCapitalProbabilityOfRise = borrowedCapitalProbabilityOfRise; } /** * Gibt die Schrittweite des Fremdkapitals an. * * @author Kai Westerholz * * @return Schrittweite */ public double getBorrowedCapitalStepRange() { return BorrowedCapitalStepRange; } /** * Setzt die Schrittweite des Fremdkapitals. * * @author Kai Westerholz * @param borrowedCapitalStepRange */ public void setBorrowedCapitalStepRange(double borrowedCapitalStepRange) { BorrowedCapitalStepRange = borrowedCapitalStepRange; } /** * Gibt die Perioden in einem sortierten NavigableSet zurueck. * * @author Christian Gahlert * @return Die Perioden */ public NavigableSet<? extends Period> getPeriods() { return periods; } /** * @deprecated Bitte getter für die stochastiPeriods und DeterministicPeriods * verwenden Ueberschreibt die bisher verwendeten Methoden. Die * Perioden muessen in Form eines sortierten NavigableSet * vorliegen. * * @param periods * Die Perioden */ @Deprecated public void setPeriods(TreeSet<? extends Period> periods) { this.periods = periods; } /** * Diese Methode soll lediglich eine Liste von verfuegbaren Jahren * zurueckgeben. Ein Jahr ist verfuegbar, wenn noch keine Periode fuer das * Jahr existiert. Es wird beim aktuellen Jahr begonnen und dann * schrittweise ein Jahr runtergezaehlt. Dabei sollte z.B. nach 10 oder 20 * Jahren schluss sein (mehr Jahre wird wohl niemand eingeben wollen). * * @author Christian Gahlert * @return Die verfuegbaren Jahre absteigend sortiert */ public List<Integer> getAvailableYears() { ArrayList<Integer> years = new ArrayList<Integer>(); int start = Calendar.getInstance().get(Calendar.YEAR); boolean contains; for (int i = start; i > start - 5; i--) { contains = false; for (Period period : periods) { if (period.getYear() == i) { contains = true; break; } } if (!contains) { years.add(i); } } return years; } /** * Liesst das Datum der letzten Bearbeitung aus. Wird benötigt für die * Anwenderinformation auf dem Auswahl-screen für Projekte. * * @author Christian Scherer * @return Datum der letzten Aenderung */ public Date getLastChanged() { return lastChanged; } /** * Wird aufgerufen, wenn Aenderungen am Projekt vorgenommen wurden und * aktualisiert dann das bisherige Aenderungsdatum. * * @author Christian Scherer * @param heutiges * Datum (Aenderungszeitpunkt) */ public void setLastChanged(Date lastChanged) { this.lastChanged = lastChanged; } /** * Gibt den Namen des Projekts zurück. * * @author Christian Scherer * @return Name des Projekts */ public String getName() { return name; } public void setMethods(SortedSet<AbstractStochasticMethod> methods) { this.methods = methods; } public SortedSet<AbstractStochasticMethod> getMethods() { return methods; } //Annika Weis public void setMethods_deterministic(SortedSet<AbstractDeterministicMethod> methods_deterministic) { this.methods_deterministic = methods_deterministic; } //Annika Weis public SortedSet<AbstractDeterministicMethod> getMethods_deterministic() { return methods_deterministic; } public ProjectInputType getProjectInputType() { return projectInputType; } public void setProjectInputType(ProjectInputType projectInputType) { this.projectInputType = projectInputType; } /** * Setzt den Namen des Projekts. * * @author Christian Scherer * @param name * Name des Projekts */ public void setName(String name) { this.name = name; } /** * Gibt die Anzahl vorherzusagender Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast() { return periodsToForecast; } /** * Setzt die Anzahl vorherzusagender Perioden des Projekts. * * @author Christian Scherer * @param periodsToForecast * Anzahl vorherzusagender Perioden */ public void setPeriodsToForecast(int periodsToForecast) { this.periodsToForecast = periodsToForecast; } /** * Gibt die Anzahl vorherzusagender deterinistischer Perioden des Projekts zurück. * * @author Annika Weis * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast_deterministic() { return periodsToForecast_deterministic; } /** * Setzt die Anzahl vorherzusagender deterministischer Perioden des Projekts. * * @author Annika Weis * @param periodsToForecast_deterministic * Anzahl vorherzusagender Perioden (deterministisch) */ public void setPeriodsToForecast_deterministic(int periodsToForecast_deterministic) { this.periodsToForecast_deterministic = periodsToForecast_deterministic; } /** * Setzt die Anzahl der anzugebenden vergangenen Perioden des Projekts. * * @author Marcel Rosenberger * @param specifiedPastPeriods * Anzahl der anzugebenden vergangenen Perioden */ public void setSpecifiedPastPeriods(int specifiedPastPeriods) { this.specifiedPastPeriods = specifiedPastPeriods; } /** * Gibt die Anzahl der anzugebenden vergangenen Perioden des Projekts zurück. * * @author Marcel Rosenberger * @return Anzahl der anzugebenden vergangenen Perioden */ public int getSpecifiedPastPeriods() { return specifiedPastPeriods; } /** * Setzt die Anzahl<SUF>*/ public void setRelevantPastPeriods(int relevantPastPeriods) { this.relevantPastPeriods = relevantPastPeriods; } /** * Gibt die Anzahl der vergangenen relevanten Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl der vergangenen relevanten Perioden */ public int getRelevantPastPeriods() { return relevantPastPeriods; } /** * Gibt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts zurück. * * @author Christian Scherer * @return Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public int getIterations() { return iterations; } /** * Setzt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts. * * @author Christian Scherer * @param iterations * Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public void setIterations(int iterations) { this.iterations = iterations; } /** * Setzt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen. * * @author Christian Scherer * @param basisYear * Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public void setBasisYear(int basisYear) { this.basisYear = basisYear; } /** * Gibt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen zurück. * * @author Christian Scherer * @return Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public int getBasisYear() { return basisYear; } public List<Szenario> getScenarios() { return this.scenarios; } /** * Gibt nur die einbezogenen Szenarios eines Projektes zurück. * * @author Marcel Rosenberger * * @return alle einbezogenen Szenarios */ public List<Szenario> getIncludedScenarios() { List<Szenario> includedScenarios = new ArrayList<Szenario>(); for (Szenario szenario : this.scenarios){ if(szenario.isIncludeInCalculation()){ includedScenarios.add(szenario); } } return includedScenarios; } public void addScenario(Szenario scenario) { this.scenarios.add(scenario); } public User getCreatedFrom() { return createdFrom; } public void setCreatedFrom(User user) { createdFrom = user; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } public int getTotalPeriods (){ if (projectInputType.isDeterministic()==true){ return periodsToForecast_deterministic; } return specifiedPastPeriods ; } public String getTypMethod(){ if (projectInputType.isDeterministic()==true){ typ = "Deterministische Eingabe"; } else { typ = "Stochastische Eingabe"; } return typ; } }
177427_3
package gtPlusPlus.xmod.gregtech.common.tileentities.generators; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import gregtech.api.enums.Textures; import gregtech.api.interfaces.ITexture; import gregtech.api.interfaces.tileentity.IGregTechTileEntity; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.implementations.GT_MetaTileEntity_BasicGenerator; import gregtech.api.objects.GT_RenderedTexture; import gregtech.api.util.GT_Recipe; import gregtech.api.util.GT_Utility; import gregtech.api.util.Recipe_GT; import gtPlusPlus.api.objects.Logger; import gtPlusPlus.core.lib.CORE; import gtPlusPlus.core.util.math.MathUtils; import gtPlusPlus.core.util.minecraft.gregtech.PollutionUtils; import gtPlusPlus.core.util.reflect.ReflectionUtils; import gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList; import net.minecraftforge.fluids.FluidStack; public class GregtechMetaTileEntity_RTG extends GT_MetaTileEntity_BasicGenerator { public int mEfficiency; private int mDays; private long mTicksToBurnFor; private int mVoltage = 0; private GT_Recipe mCurrentRecipe; private int mDaysRemaining = 0; private int mDayTick = 0; private byte mNewTier = 0; public int removeDayOfTime(){ if (this.mDaysRemaining > 0){ return this.mDaysRemaining--; } return this.mDaysRemaining; } //Generates fuel value based on MC days public static int convertDaysToTicks(float days){ int value = 0; value = MathUtils.roundToClosestInt(20*86400*days); return value; } public static long getTotalEUGenerated(int ticks, int voltage){ return ticks*voltage; } @Override public void saveNBTData(NBTTagCompound aNBT) { super.saveNBTData(aNBT); aNBT.setLong("mTicksToBurnFor", this.mTicksToBurnFor); aNBT.setInteger("mVoltage", this.mVoltage); aNBT.setInteger("mDaysRemaining", this.mDaysRemaining); aNBT.setInteger("mDayTick", this.mDayTick); aNBT.setByte("mNewTier", this.mNewTier); if (this.mCurrentRecipe != null){ final NBTTagList list = new NBTTagList(); final ItemStack stack = this.mCurrentRecipe.mInputs[0]; if(stack != null){ final NBTTagCompound data = new NBTTagCompound(); stack.writeToNBT(data); data.setInteger("mSlot", 0); list.appendTag(data); } aNBT.setTag("mRecipeItem", list); } } @Override public void loadNBTData(NBTTagCompound aNBT) { super.loadNBTData(aNBT); //this.mMachineBlock = aNBT.getByte("mMachineBlock"); this.mTicksToBurnFor = aNBT.getLong("mTicksToBurnFor"); this.mVoltage = aNBT.getInteger("mVoltage"); this.mDaysRemaining = aNBT.getInteger("mDaysRemaining"); this.mDayTick = aNBT.getInteger("mDayTick"); this.mNewTier = aNBT.getByte("mNewTier"); try { ReflectionUtils.setByte(this, "mTier", this.mNewTier); } catch (Exception e) { if (this.getBaseMetaTileEntity() != null){ IGregTechTileEntity thisTile = this.getBaseMetaTileEntity(); if (thisTile.isAllowedToWork() || thisTile.isActive()){ thisTile.setActive(false); } } } final NBTTagList list = aNBT.getTagList("mRecipeItem", 10); final NBTTagCompound data = list.getCompoundTagAt(0); ItemStack lastUsedFuel = ItemStack.loadItemStackFromNBT(data); if (lastUsedFuel != null){ this.mCurrentRecipe = getRecipes().findRecipe(getBaseMetaTileEntity(), false, 9223372036854775807L, null, new ItemStack[] { lastUsedFuel }); } } @Override public void onPostTick(IGregTechTileEntity aBaseMetaTileEntity, long aTick) { if (aBaseMetaTileEntity.isServerSide()){ if (this.mDayTick < 24000){ this.mDayTick++; } else if (this.mDayTick >= 24000){ this.mDayTick = 0; this.mDaysRemaining = this.removeDayOfTime(); } } if ((aBaseMetaTileEntity.isServerSide()) && (aBaseMetaTileEntity.isAllowedToWork()) && (aTick % 10L == 0L)) { long tProducedEU = 0L; if (this.mFluid == null) { if (aBaseMetaTileEntity.getUniversalEnergyStored() < maxEUOutput() + getMinimumStoredEU()) { this.mInventory[getStackDisplaySlot()] = null; } else { if (this.mInventory[getStackDisplaySlot()] == null) this.mInventory[getStackDisplaySlot()] = new ItemStack(Blocks.fire, 1); this.mInventory[getStackDisplaySlot()].setStackDisplayName("Generating: " + (aBaseMetaTileEntity.getUniversalEnergyStored() - getMinimumStoredEU()) + " EU"); } } else { int tFuelValue = getFuelValue(this.mFluid); int tConsumed = consumedFluidPerOperation(this.mFluid); if ((tFuelValue > 0) && (tConsumed > 0) && (this.mFluid.amount > tConsumed)) { long tFluidAmountToUse = Math.min(this.mFluid.amount / tConsumed, (maxEUStore() - aBaseMetaTileEntity.getUniversalEnergyStored()) / tFuelValue); if ((tFluidAmountToUse > 0L) && (aBaseMetaTileEntity.increaseStoredEnergyUnits(tFluidAmountToUse * tFuelValue, true))) { tProducedEU = tFluidAmountToUse * tFuelValue; FluidStack tmp260_257 = this.mFluid; tmp260_257.amount = (int) (tmp260_257.amount - (tFluidAmountToUse * tConsumed)); } } } if ((this.mInventory[getInputSlot()] != null) && (aBaseMetaTileEntity.getUniversalEnergyStored() < maxEUOutput() * 20L + getMinimumStoredEU()) && (GT_Utility.getFluidForFilledItem(this.mInventory[getInputSlot()], true) == null)) { int tFuelValue = getFuelValue(this.mInventory[getInputSlot()]); if (tFuelValue > 0) { ItemStack tEmptyContainer = getEmptyContainer(this.mInventory[getInputSlot()]); if (aBaseMetaTileEntity.addStackToSlot(getOutputSlot(), tEmptyContainer)) { aBaseMetaTileEntity.increaseStoredEnergyUnits(tFuelValue, true); aBaseMetaTileEntity.decrStackSize(getInputSlot(), 1); tProducedEU = tFuelValue; } } } if ((tProducedEU > 0L) && (getPollution() > 0)) { PollutionUtils.addPollution(aBaseMetaTileEntity, (int) (tProducedEU * getPollution() / 500 * this.mTier + 1L)); } } if (aBaseMetaTileEntity.isServerSide()) aBaseMetaTileEntity.setActive((aBaseMetaTileEntity.isAllowedToWork()) && (aBaseMetaTileEntity.getUniversalEnergyStored() >= maxEUOutput() + getMinimumStoredEU())); } @Override public String[] getDescription() { return new String[]{this.mDescription, "Fuel is measured in minecraft days (Check with Scanner)", "RTG changes output voltage depending on fuel", "Generates power at " + this.getEfficiency() + "% Efficiency per tick", "Output Voltage: "+this.getOutputTier()+" EU/t", }; } public GregtechMetaTileEntity_RTG(int aID, String aName, String aNameRegional, int aTier) { super(aID, aName, aNameRegional, aTier, "Requires RTG Pellets", new ITexture[0]); } private byte getTier(){ int voltage = this.mVoltage; if (voltage >= 512){ return 4; } else if (voltage >= 128){ return 3; } else if (voltage >= 32){ return 2; } else if (voltage >= 8){ return 1; } return 0; } public GregtechMetaTileEntity_RTG(String aName, int aTier, String aDescription, ITexture[][][] aTextures) { super(aName, aTier, aDescription, aTextures); } @Override public boolean isOutputFacing(byte aSide) { return ((aSide > 1) && (aSide != getBaseMetaTileEntity().getFrontFacing()) && (aSide != getBaseMetaTileEntity().getBackFacing())); } @Override public MetaTileEntity newMetaEntity(IGregTechTileEntity aTileEntity) { return new GregtechMetaTileEntity_RTG(this.mName, this.mTier, this.mDescription, this.mTextures); } @Override public GT_Recipe.GT_Recipe_Map getRecipes() { return Recipe_GT.Gregtech_Recipe_Map.sRTGFuels; } @Override public int getCapacity() { return 0; } @Override public int getEfficiency() { return this.mEfficiency = 100; } @Override public ITexture[] getFront(byte aColor) { return new ITexture[] { super.getFront(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP), new GT_RenderedTexture(Textures.BlockIcons.OVERLAY_FRONT_MASSFAB) }; } @Override public ITexture[] getBack(byte aColor) { return new ITexture[] { super.getBack(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP) }; } @Override public ITexture[] getBottom(byte aColor) { return new ITexture[] { super.getBottom(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP) }; } @Override public ITexture[] getTop(byte aColor) { return new ITexture[] { super.getTop(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP), new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_FLUID_SIDE) }; } @Override public ITexture[] getSides(byte aColor) { return new ITexture[]{ gregtech.api.enums.Textures.BlockIcons.MACHINE_CASINGS[this.mTier][(0)], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE), gregtech.api.enums.Textures.BlockIcons.OVERLAYS_ENERGY_OUT_MULTI[getTier()]}; } @Override public ITexture[] getFrontActive(byte aColor) { return new ITexture[] { super.getFrontActive(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE), new GT_RenderedTexture(Textures.BlockIcons.OVERLAY_FRONT_MASSFAB_ACTIVE) }; } @Override public ITexture[] getBackActive(byte aColor) { return new ITexture[] { super.getBackActive(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE) }; } @Override public ITexture[] getBottomActive(byte aColor) { return new ITexture[] { super.getBottomActive(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE) }; } @Override public ITexture[] getTopActive(byte aColor) { return new ITexture[] { super.getTopActive(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE), new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_FLUID_SIDE_ACTIVE) }; } @Override public ITexture[] getSidesActive(byte aColor) { return new ITexture[]{ gregtech.api.enums.Textures.BlockIcons.MACHINE_CASINGS[this.mTier][(0)], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE), gregtech.api.enums.Textures.BlockIcons.OVERLAYS_ENERGY_OUT_MULTI[getTier()]}; } public int getPollution() { return 0; } @Override public int getFuelValue(ItemStack aStack) { if ((GT_Utility.isStackInvalid(aStack)) || (getRecipes() == null)) return 0; GT_Recipe tFuel = getRecipes().findRecipe(getBaseMetaTileEntity(), false, 9223372036854775807L, null, new ItemStack[] { aStack }); if (tFuel != null){ this.mCurrentRecipe = tFuel; int voltage = tFuel.mEUt; this.mVoltage = voltage; int sfsf = this.mTier; //this.mDaysRemaining = tFuel.mSpecialValue*365; //Do some voodoo. byte mTier2; //mTier2 = ReflectionUtils.getField(this.getClass(), "mTier"); try { if (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_AM241.get(1))){ mTier2 = 1; } else if (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_PO210.get(1))){ mTier2 = 3; } else if (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_PU238.get(1))){ mTier2 = 2; } else if (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_SR90.get(1))){ mTier2 = 1; } else { //Utils.LOG_INFO("test:"+tFuel.mInputs[0].getDisplayName() + " | " + (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_PU238.get(1)))); mTier2 = 0; } ReflectionUtils.setByte(this, "mTier", mTier2); this.mNewTier = mTier2; //ReflectionUtils.setFinalStatic(mTier2, GT_Values.V[0]); } catch (Exception e) { Logger.WARNING("Failed setting mTier."); e.printStackTrace(); } this.mTicksToBurnFor = getTotalEUGenerated(convertDaysToTicks(tFuel.mSpecialValue), voltage); if (mTicksToBurnFor >= Integer.MAX_VALUE){ mTicksToBurnFor = Integer.MAX_VALUE; Logger.WARNING("Fuel went over Int limit, setting to MAX_VALUE."); } this.mDaysRemaining = MathUtils.roundToClosestInt(mTicksToBurnFor/20/60/3); Logger.WARNING("step | "+(int) (mTicksToBurnFor * getEfficiency() / 100L)); return (int) (mTicksToBurnFor * getEfficiency() / 100L); //return (int) (tFuel.mSpecialValue * 365L * getEfficiency() / 100L); //return tFuel.mEUt; } Logger.WARNING("Not sure"); return 0; } @Override public long maxEUOutput() { return ((getBaseMetaTileEntity().isAllowedToWork()) ? this.mVoltage : 0L); } @Override public long getOutputTier() { if (this.mCurrentRecipe != null){ return this.mVoltage = this.mCurrentRecipe.mEUt; } return 0; } @Override public boolean isGivingInformation() { return true; } @Override public String[] getInfoData() { return new String[] { "RTG - Running at tier "+this.mTier, "Active: "+this.getBaseMetaTileEntity().isActive(), "Current Output: " + this.mVoltage + " EU/t", "Days of Fuel remaining: "+(mTicksToBurnFor/20/60/20), "Hours of Fuel remaining: "+(mTicksToBurnFor/20/60/60), "Ticks of "+this.mVoltage+"v remaining: "+(mTicksToBurnFor), "Current Recipe input: "+ this.mCurrentRecipe != null ? this.mCurrentRecipe.mInputs[0].getDisplayName() + " x1" : "NUll" }; } }
huajijam/GTplusplus
src/Java/gtPlusPlus/xmod/gregtech/common/tileentities/generators/GregtechMetaTileEntity_RTG.java
4,479
//Do some voodoo.
line_comment
nl
package gtPlusPlus.xmod.gregtech.common.tileentities.generators; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import gregtech.api.enums.Textures; import gregtech.api.interfaces.ITexture; import gregtech.api.interfaces.tileentity.IGregTechTileEntity; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.implementations.GT_MetaTileEntity_BasicGenerator; import gregtech.api.objects.GT_RenderedTexture; import gregtech.api.util.GT_Recipe; import gregtech.api.util.GT_Utility; import gregtech.api.util.Recipe_GT; import gtPlusPlus.api.objects.Logger; import gtPlusPlus.core.lib.CORE; import gtPlusPlus.core.util.math.MathUtils; import gtPlusPlus.core.util.minecraft.gregtech.PollutionUtils; import gtPlusPlus.core.util.reflect.ReflectionUtils; import gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList; import net.minecraftforge.fluids.FluidStack; public class GregtechMetaTileEntity_RTG extends GT_MetaTileEntity_BasicGenerator { public int mEfficiency; private int mDays; private long mTicksToBurnFor; private int mVoltage = 0; private GT_Recipe mCurrentRecipe; private int mDaysRemaining = 0; private int mDayTick = 0; private byte mNewTier = 0; public int removeDayOfTime(){ if (this.mDaysRemaining > 0){ return this.mDaysRemaining--; } return this.mDaysRemaining; } //Generates fuel value based on MC days public static int convertDaysToTicks(float days){ int value = 0; value = MathUtils.roundToClosestInt(20*86400*days); return value; } public static long getTotalEUGenerated(int ticks, int voltage){ return ticks*voltage; } @Override public void saveNBTData(NBTTagCompound aNBT) { super.saveNBTData(aNBT); aNBT.setLong("mTicksToBurnFor", this.mTicksToBurnFor); aNBT.setInteger("mVoltage", this.mVoltage); aNBT.setInteger("mDaysRemaining", this.mDaysRemaining); aNBT.setInteger("mDayTick", this.mDayTick); aNBT.setByte("mNewTier", this.mNewTier); if (this.mCurrentRecipe != null){ final NBTTagList list = new NBTTagList(); final ItemStack stack = this.mCurrentRecipe.mInputs[0]; if(stack != null){ final NBTTagCompound data = new NBTTagCompound(); stack.writeToNBT(data); data.setInteger("mSlot", 0); list.appendTag(data); } aNBT.setTag("mRecipeItem", list); } } @Override public void loadNBTData(NBTTagCompound aNBT) { super.loadNBTData(aNBT); //this.mMachineBlock = aNBT.getByte("mMachineBlock"); this.mTicksToBurnFor = aNBT.getLong("mTicksToBurnFor"); this.mVoltage = aNBT.getInteger("mVoltage"); this.mDaysRemaining = aNBT.getInteger("mDaysRemaining"); this.mDayTick = aNBT.getInteger("mDayTick"); this.mNewTier = aNBT.getByte("mNewTier"); try { ReflectionUtils.setByte(this, "mTier", this.mNewTier); } catch (Exception e) { if (this.getBaseMetaTileEntity() != null){ IGregTechTileEntity thisTile = this.getBaseMetaTileEntity(); if (thisTile.isAllowedToWork() || thisTile.isActive()){ thisTile.setActive(false); } } } final NBTTagList list = aNBT.getTagList("mRecipeItem", 10); final NBTTagCompound data = list.getCompoundTagAt(0); ItemStack lastUsedFuel = ItemStack.loadItemStackFromNBT(data); if (lastUsedFuel != null){ this.mCurrentRecipe = getRecipes().findRecipe(getBaseMetaTileEntity(), false, 9223372036854775807L, null, new ItemStack[] { lastUsedFuel }); } } @Override public void onPostTick(IGregTechTileEntity aBaseMetaTileEntity, long aTick) { if (aBaseMetaTileEntity.isServerSide()){ if (this.mDayTick < 24000){ this.mDayTick++; } else if (this.mDayTick >= 24000){ this.mDayTick = 0; this.mDaysRemaining = this.removeDayOfTime(); } } if ((aBaseMetaTileEntity.isServerSide()) && (aBaseMetaTileEntity.isAllowedToWork()) && (aTick % 10L == 0L)) { long tProducedEU = 0L; if (this.mFluid == null) { if (aBaseMetaTileEntity.getUniversalEnergyStored() < maxEUOutput() + getMinimumStoredEU()) { this.mInventory[getStackDisplaySlot()] = null; } else { if (this.mInventory[getStackDisplaySlot()] == null) this.mInventory[getStackDisplaySlot()] = new ItemStack(Blocks.fire, 1); this.mInventory[getStackDisplaySlot()].setStackDisplayName("Generating: " + (aBaseMetaTileEntity.getUniversalEnergyStored() - getMinimumStoredEU()) + " EU"); } } else { int tFuelValue = getFuelValue(this.mFluid); int tConsumed = consumedFluidPerOperation(this.mFluid); if ((tFuelValue > 0) && (tConsumed > 0) && (this.mFluid.amount > tConsumed)) { long tFluidAmountToUse = Math.min(this.mFluid.amount / tConsumed, (maxEUStore() - aBaseMetaTileEntity.getUniversalEnergyStored()) / tFuelValue); if ((tFluidAmountToUse > 0L) && (aBaseMetaTileEntity.increaseStoredEnergyUnits(tFluidAmountToUse * tFuelValue, true))) { tProducedEU = tFluidAmountToUse * tFuelValue; FluidStack tmp260_257 = this.mFluid; tmp260_257.amount = (int) (tmp260_257.amount - (tFluidAmountToUse * tConsumed)); } } } if ((this.mInventory[getInputSlot()] != null) && (aBaseMetaTileEntity.getUniversalEnergyStored() < maxEUOutput() * 20L + getMinimumStoredEU()) && (GT_Utility.getFluidForFilledItem(this.mInventory[getInputSlot()], true) == null)) { int tFuelValue = getFuelValue(this.mInventory[getInputSlot()]); if (tFuelValue > 0) { ItemStack tEmptyContainer = getEmptyContainer(this.mInventory[getInputSlot()]); if (aBaseMetaTileEntity.addStackToSlot(getOutputSlot(), tEmptyContainer)) { aBaseMetaTileEntity.increaseStoredEnergyUnits(tFuelValue, true); aBaseMetaTileEntity.decrStackSize(getInputSlot(), 1); tProducedEU = tFuelValue; } } } if ((tProducedEU > 0L) && (getPollution() > 0)) { PollutionUtils.addPollution(aBaseMetaTileEntity, (int) (tProducedEU * getPollution() / 500 * this.mTier + 1L)); } } if (aBaseMetaTileEntity.isServerSide()) aBaseMetaTileEntity.setActive((aBaseMetaTileEntity.isAllowedToWork()) && (aBaseMetaTileEntity.getUniversalEnergyStored() >= maxEUOutput() + getMinimumStoredEU())); } @Override public String[] getDescription() { return new String[]{this.mDescription, "Fuel is measured in minecraft days (Check with Scanner)", "RTG changes output voltage depending on fuel", "Generates power at " + this.getEfficiency() + "% Efficiency per tick", "Output Voltage: "+this.getOutputTier()+" EU/t", }; } public GregtechMetaTileEntity_RTG(int aID, String aName, String aNameRegional, int aTier) { super(aID, aName, aNameRegional, aTier, "Requires RTG Pellets", new ITexture[0]); } private byte getTier(){ int voltage = this.mVoltage; if (voltage >= 512){ return 4; } else if (voltage >= 128){ return 3; } else if (voltage >= 32){ return 2; } else if (voltage >= 8){ return 1; } return 0; } public GregtechMetaTileEntity_RTG(String aName, int aTier, String aDescription, ITexture[][][] aTextures) { super(aName, aTier, aDescription, aTextures); } @Override public boolean isOutputFacing(byte aSide) { return ((aSide > 1) && (aSide != getBaseMetaTileEntity().getFrontFacing()) && (aSide != getBaseMetaTileEntity().getBackFacing())); } @Override public MetaTileEntity newMetaEntity(IGregTechTileEntity aTileEntity) { return new GregtechMetaTileEntity_RTG(this.mName, this.mTier, this.mDescription, this.mTextures); } @Override public GT_Recipe.GT_Recipe_Map getRecipes() { return Recipe_GT.Gregtech_Recipe_Map.sRTGFuels; } @Override public int getCapacity() { return 0; } @Override public int getEfficiency() { return this.mEfficiency = 100; } @Override public ITexture[] getFront(byte aColor) { return new ITexture[] { super.getFront(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP), new GT_RenderedTexture(Textures.BlockIcons.OVERLAY_FRONT_MASSFAB) }; } @Override public ITexture[] getBack(byte aColor) { return new ITexture[] { super.getBack(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP) }; } @Override public ITexture[] getBottom(byte aColor) { return new ITexture[] { super.getBottom(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP) }; } @Override public ITexture[] getTop(byte aColor) { return new ITexture[] { super.getTop(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP), new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_FLUID_SIDE) }; } @Override public ITexture[] getSides(byte aColor) { return new ITexture[]{ gregtech.api.enums.Textures.BlockIcons.MACHINE_CASINGS[this.mTier][(0)], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE), gregtech.api.enums.Textures.BlockIcons.OVERLAYS_ENERGY_OUT_MULTI[getTier()]}; } @Override public ITexture[] getFrontActive(byte aColor) { return new ITexture[] { super.getFrontActive(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE), new GT_RenderedTexture(Textures.BlockIcons.OVERLAY_FRONT_MASSFAB_ACTIVE) }; } @Override public ITexture[] getBackActive(byte aColor) { return new ITexture[] { super.getBackActive(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE) }; } @Override public ITexture[] getBottomActive(byte aColor) { return new ITexture[] { super.getBottomActive(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE) }; } @Override public ITexture[] getTopActive(byte aColor) { return new ITexture[] { super.getTopActive(aColor)[0], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE), new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_FLUID_SIDE_ACTIVE) }; } @Override public ITexture[] getSidesActive(byte aColor) { return new ITexture[]{ gregtech.api.enums.Textures.BlockIcons.MACHINE_CASINGS[this.mTier][(0)], new GT_RenderedTexture(Textures.BlockIcons.NAQUADAH_REACTOR_SOLID_TOP_ACTIVE), gregtech.api.enums.Textures.BlockIcons.OVERLAYS_ENERGY_OUT_MULTI[getTier()]}; } public int getPollution() { return 0; } @Override public int getFuelValue(ItemStack aStack) { if ((GT_Utility.isStackInvalid(aStack)) || (getRecipes() == null)) return 0; GT_Recipe tFuel = getRecipes().findRecipe(getBaseMetaTileEntity(), false, 9223372036854775807L, null, new ItemStack[] { aStack }); if (tFuel != null){ this.mCurrentRecipe = tFuel; int voltage = tFuel.mEUt; this.mVoltage = voltage; int sfsf = this.mTier; //this.mDaysRemaining = tFuel.mSpecialValue*365; //Do some<SUF> byte mTier2; //mTier2 = ReflectionUtils.getField(this.getClass(), "mTier"); try { if (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_AM241.get(1))){ mTier2 = 1; } else if (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_PO210.get(1))){ mTier2 = 3; } else if (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_PU238.get(1))){ mTier2 = 2; } else if (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_SR90.get(1))){ mTier2 = 1; } else { //Utils.LOG_INFO("test:"+tFuel.mInputs[0].getDisplayName() + " | " + (ItemStack.areItemStacksEqual(tFuel.mInputs[0], GregtechItemList.Pellet_RTG_PU238.get(1)))); mTier2 = 0; } ReflectionUtils.setByte(this, "mTier", mTier2); this.mNewTier = mTier2; //ReflectionUtils.setFinalStatic(mTier2, GT_Values.V[0]); } catch (Exception e) { Logger.WARNING("Failed setting mTier."); e.printStackTrace(); } this.mTicksToBurnFor = getTotalEUGenerated(convertDaysToTicks(tFuel.mSpecialValue), voltage); if (mTicksToBurnFor >= Integer.MAX_VALUE){ mTicksToBurnFor = Integer.MAX_VALUE; Logger.WARNING("Fuel went over Int limit, setting to MAX_VALUE."); } this.mDaysRemaining = MathUtils.roundToClosestInt(mTicksToBurnFor/20/60/3); Logger.WARNING("step | "+(int) (mTicksToBurnFor * getEfficiency() / 100L)); return (int) (mTicksToBurnFor * getEfficiency() / 100L); //return (int) (tFuel.mSpecialValue * 365L * getEfficiency() / 100L); //return tFuel.mEUt; } Logger.WARNING("Not sure"); return 0; } @Override public long maxEUOutput() { return ((getBaseMetaTileEntity().isAllowedToWork()) ? this.mVoltage : 0L); } @Override public long getOutputTier() { if (this.mCurrentRecipe != null){ return this.mVoltage = this.mCurrentRecipe.mEUt; } return 0; } @Override public boolean isGivingInformation() { return true; } @Override public String[] getInfoData() { return new String[] { "RTG - Running at tier "+this.mTier, "Active: "+this.getBaseMetaTileEntity().isActive(), "Current Output: " + this.mVoltage + " EU/t", "Days of Fuel remaining: "+(mTicksToBurnFor/20/60/20), "Hours of Fuel remaining: "+(mTicksToBurnFor/20/60/60), "Ticks of "+this.mVoltage+"v remaining: "+(mTicksToBurnFor), "Current Recipe input: "+ this.mCurrentRecipe != null ? this.mCurrentRecipe.mInputs[0].getDisplayName() + " x1" : "NUll" }; } }
67718_5
import java.util.jar.Attributes.Name; public class DivideAndConquer { public static void printArray(int arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void mergeSort(int arr[], int si, int ei) { // base case if (si >= ei) { return; } // kaam int mid = (si + ei) / 2; // int mid = si + (ei - si) / 2; // calling innerfunction mergeSort(arr, si, mid);// sortting for left mergeSort(arr, mid + 1, ei);// sortting for right // merging both left& right part merge(arr, si, mid, ei); } public static void merge(int arr[], int si, int mid, int ei) { int temp[] = new int[ei - si + 1]; int i = si; int j = mid + 1; int k = 0;// temp array while (i <= mid && j <= ei) { if (arr[i] < arr[j]) { temp[k] = arr[i]; i++; k++; // i ko temp mei store kar dunga } else { temp[k] = arr[j]; j++; k++; } // k++; } // leeft over element while (i <= mid) { temp[k++] = arr[i++]; } // right part while (j <= ei) { temp[k++] = arr[j++]; } // copy temp to orignal array for (k = 0, i = si; k < temp.length; k++, i++) { arr[i] = temp[k]; } } public static void Name() { int n = 50, k = 5; for (int i = 0; i < n; i = i + k) { for (int j = i + 1; j <= k; j++) { System.out.print("i = " + i + " "); System.out.print("j= " + j + " "); } } } public static int power(int a, int n) { if (n == 0) { return 1; } return a * power(a, n - 1); } public static void main(String[] args) { int arr[] = { 6, 3, 9, 10, 2, 18, 1 }; // System.out.println("before"); // printArray(arr); mergeSort(arr, 0, arr.length - 1); // System.out.println("After "); // printArray(arr); // int a = 3; // int b = 2; // int c = (a + b) / 2; // System.out.println("addition is " + c); // Name(); // System.out.println(power(2, 5)); // int a=3; // System.out.println(a/2); } }
mihirkate/DSA-IN-AVA
21.Divide &Conquer/DivideAndConquer.java
827
// leeft over element
line_comment
nl
import java.util.jar.Attributes.Name; public class DivideAndConquer { public static void printArray(int arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void mergeSort(int arr[], int si, int ei) { // base case if (si >= ei) { return; } // kaam int mid = (si + ei) / 2; // int mid = si + (ei - si) / 2; // calling innerfunction mergeSort(arr, si, mid);// sortting for left mergeSort(arr, mid + 1, ei);// sortting for right // merging both left& right part merge(arr, si, mid, ei); } public static void merge(int arr[], int si, int mid, int ei) { int temp[] = new int[ei - si + 1]; int i = si; int j = mid + 1; int k = 0;// temp array while (i <= mid && j <= ei) { if (arr[i] < arr[j]) { temp[k] = arr[i]; i++; k++; // i ko temp mei store kar dunga } else { temp[k] = arr[j]; j++; k++; } // k++; } // leeft over<SUF> while (i <= mid) { temp[k++] = arr[i++]; } // right part while (j <= ei) { temp[k++] = arr[j++]; } // copy temp to orignal array for (k = 0, i = si; k < temp.length; k++, i++) { arr[i] = temp[k]; } } public static void Name() { int n = 50, k = 5; for (int i = 0; i < n; i = i + k) { for (int j = i + 1; j <= k; j++) { System.out.print("i = " + i + " "); System.out.print("j= " + j + " "); } } } public static int power(int a, int n) { if (n == 0) { return 1; } return a * power(a, n - 1); } public static void main(String[] args) { int arr[] = { 6, 3, 9, 10, 2, 18, 1 }; // System.out.println("before"); // printArray(arr); mergeSort(arr, 0, arr.length - 1); // System.out.println("After "); // printArray(arr); // int a = 3; // int b = 2; // int c = (a + b) / 2; // System.out.println("addition is " + c); // Name(); // System.out.println(power(2, 5)); // int a=3; // System.out.println(a/2); } }
73843_15
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joor; import android.os.Build; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** * A wrapper for an {@link Object} or {@link Class} upon which reflective calls * can be made. * <p> * An example of using <code>Reflect</code> is <code><pre> * // Static import all reflection methods to decrease verbosity * import static org.joor.Reflect.*; * * // Wrap an Object / Class / class name with the on() method: * on("java.lang.String") * // Invoke constructors using the create() method: * .create("Hello World") * // Invoke methods using the call() method: * .call("toString") * // Retrieve the wrapped object * * @author Lukas Eder * @author Irek Matysiewicz * @author Thomas Darimont */ public class Reflect { // --------------------------------------------------------------------- // Static API used as entrance points to the fluent API // --------------------------------------------------------------------- /** * Wrap a class name. * <p> * This is the same as calling <code>on(Class.forName(name))</code> * * @param name A fully qualified class name * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name) throws ReflectException { return on(forName(name)); } /** * Wrap a class name, loading it via a given class loader. * <p> * This is the same as calling * <code>on(Class.forName(name, classLoader))</code> * * @param name A fully qualified class name. * @param classLoader The class loader in whose context the class should be * loaded. * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name, ClassLoader classLoader) throws ReflectException { return on(forName(name, classLoader)); } /** * Wrap a class. * <p> * Use this when you want to access static fields and methods on a * {@link Class} object, or as a basis for constructing objects of that * class using {@link #create(Object...)} * * @param clazz The class to be wrapped * @return A wrapped class object, to be used for further reflection. */ public static Reflect on(Class<?> clazz) { return new Reflect(clazz); } /** * Wrap an object. * <p> * Use this when you want to access instance fields and methods on any * {@link Object} * * @param object The object to be wrapped * @return A wrapped object, to be used for further reflection. */ public static Reflect on(Object object) { return new Reflect(object == null ? Object.class : object.getClass(), object); } private static Reflect on(Class<?> type, Object object) { return new Reflect(type, object); } /** * Conveniently render an {@link AccessibleObject} accessible. * <p> * To prevent {@link SecurityException}, this is only done if the argument * object and its declaring class are non-public. * * @param accessible The object to render accessible * @return The argument object rendered accessible */ public static <T extends AccessibleObject> T accessible(T accessible) { if (accessible == null) { return null; } if (accessible instanceof Member) { Member member = (Member) accessible; if (Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return accessible; } } // [jOOQ #3392] The accessible flag is set to false by default, also for public members. if (!accessible.isAccessible()) { accessible.setAccessible(true); } return accessible; } // --------------------------------------------------------------------- // Members // --------------------------------------------------------------------- /** * The type of the wrapped object. */ private final Class<?> type; /** * The wrapped object. */ private final Object object; // --------------------------------------------------------------------- // Constructors // --------------------------------------------------------------------- private Reflect(Class<?> type) { this(type, type); } private Reflect(Class<?> type, Object object) { this.type = type; this.object = object; } // --------------------------------------------------------------------- // Fluent Reflection API // --------------------------------------------------------------------- /** * Get the wrapped object * * @param <T> A convenience generic parameter for automatic unsafe casting */ @SuppressWarnings("unchecked") public <T> T get() { return (T) object; } /** * Set a field value. * <p> * This is roughly equivalent to {@link Field#set(Object, Object)}. If the * wrapped object is a {@link Class}, then this will set a value to a static * member field. If the wrapped object is any other {@link Object}, then * this will set a value to an instance member field. * <p> * This method is also capable of setting the value of (static) final * fields. This may be convenient in situations where no * {@link SecurityManager} is expected to prevent this, but do note that * (especially static) final fields may already have been inlined by the * javac and/or JIT and relevant code deleted from the runtime verison of * your program, so setting these fields might not have any effect on your * execution. * <p> * For restrictions of usage regarding setting values on final fields check: * <a href= * "http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection">http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection</a> * ... and <a href= * "http://pveentjer.blogspot.co.at/2017/01/final-static-boolean-jit.html">http://pveentjer.blogspot.co.at/2017/01/final-static-boolean-jit.html</a> * * @param name The field name * @param value The new field value * @return The same wrapped object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect set(String name, Object value) throws ReflectException { try { Field field = field0(name); if ((field.getModifiers() & Modifier.FINAL) == Modifier.FINAL) { // Note (d4vidi): this is an important change, compared to the original implementation!!! // See here: https://stackoverflow.com/a/64378131/453052 // Field modifiersField = Field.class.getDeclaredField("modifiers"); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Field modifiersField = Field.class.getDeclaredField("accessFlags"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } } field.set(object, unwrap(value)); return this; } catch (Exception e) { throw new ReflectException(e); } } /** * Get a field value. * <p> * This is roughly equivalent to {@link Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will get a value from a static * member field. If the wrapped object is any other {@link Object}, then * this will get a value from an instance member field. * <p> * If you want to "navigate" to a wrapped version of the field, use * {@link #field(String)} instead. * * @param name The field name * @return The field value * @throws ReflectException If any reflection exception occurred. * @see #field(String) */ public <T> T get(String name) throws ReflectException { return field(name).<T>get(); } /** * Get a wrapped field. * <p> * This is roughly equivalent to {@link Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will wrap a static member field. If * the wrapped object is any other {@link Object}, then this wrap an * instance member field. * * @param name The field name * @return The wrapped field * @throws ReflectException If any reflection exception occurred. */ public Reflect field(String name) throws ReflectException { try { Field field = field0(name); return on(field.getType(), field.get(object)); } catch (Exception e) { throw new ReflectException(e); } } private Field field0(String name) throws ReflectException { Class<?> t = type(); // Try getting a public field try { return accessible(t.getField(name)); } // Try again, getting a non-public field catch (NoSuchFieldException e) { do { try { return accessible(t.getDeclaredField(name)); } catch (NoSuchFieldException ignore) {} t = t.getSuperclass(); } while (t != null); throw new ReflectException(e); } } /** * Get a Map containing field names and wrapped values for the fields' * values. * <p> * If the wrapped object is a {@link Class}, then this will return static * fields. If the wrapped object is any other {@link Object}, then this will * return instance fields. * <p> * These two calls are equivalent <code><pre> * on(object).field("myField"); * on(object).fields().get("myField"); * </pre></code> * * @return A map containing field names and wrapped values. */ public Map<String, Reflect> fields() { Map<String, Reflect> result = new LinkedHashMap<String, Reflect>(); Class<?> t = type(); do { for (Field field : t.getDeclaredFields()) { if (type != object ^ Modifier.isStatic(field.getModifiers())) { String name = field.getName(); if (!result.containsKey(name)) result.put(name, field(name)); } } t = t.getSuperclass(); } while (t != null); return result; } /** * Call a method by its name. * <p> * This is a convenience method for calling * <code>call(name, new Object[0])</code> * * @param name The method name * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. * @see #call(String, Object...) */ public Reflect call(String name) throws ReflectException { return call(name, new Object[0]); } /** * Call a method by its name. * <p> * This is roughly equivalent to {@link Method#invoke(Object, Object...)}. * If the wrapped object is a {@link Class}, then this will invoke a static * method. If the wrapped object is any other {@link Object}, then this will * invoke an instance method. * <p> * Just like {@link Method#invoke(Object, Object...)}, this will try to wrap * primitive types or unwrap primitive type wrappers if applicable. If * several methods are applicable, by that rule, the first one encountered * is called. i.e. when calling <code><pre> * on(...).call("method", 1, 1); * </pre></code> The first of the following methods will be called: * <code><pre> * public void method(int param1, Integer param2); * public void method(Integer param1, int param2); * public void method(Number param1, Number param2); * public void method(Number param1, Object param2); * public void method(int param1, Object param2); * </pre></code> * <p> * The best matching method is searched for with the following strategy: * <ol> * <li>public method with exact signature match in class hierarchy</li> * <li>non-public method with exact signature match on declaring class</li> * <li>public method with similar signature in class hierarchy</li> * <li>non-public method with similar signature on declaring class</li> * </ol> * * @param name The method name * @param args The method arguments * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect call(String name, Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" method, i.e. the one with exact // matching argument types try { Method method = exactMethod(name, types); return on(method, object, args); } // If there is no exact match, try to find a method that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { try { Method method = similarMethod(name, types); return on(method, object, args); } catch (NoSuchMethodException e1) { throw new ReflectException(e1); } } } /** * Searches a method with the exact same signature as desired. * <p> * If a public method is found in the class hierarchy, this method is returned. * Otherwise a private method with the exact same signature is returned. * If no exact match could be found, we let the {@code NoSuchMethodException} pass through. */ private Method exactMethod(String name, Class<?>[] types) throws NoSuchMethodException { Class<?> t = type(); // first priority: find a public method with exact signature match in class hierarchy try { return t.getMethod(name, types); } // second priority: find a private method with exact signature match on declaring class catch (NoSuchMethodException e) { do { try { return t.getDeclaredMethod(name, types); } catch (NoSuchMethodException ignore) {} t = t.getSuperclass(); } while (t != null); throw new NoSuchMethodException(); } } /** * Searches a method with a similar signature as desired using * {@link #isSimilarSignature(java.lang.reflect.Method, String, Class[])}. * <p> * First public methods are searched in the class hierarchy, then private * methods on the declaring class. If a method could be found, it is * returned, otherwise a {@code NoSuchMethodException} is thrown. */ private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException { Class<?> t = type(); // first priority: find a public method with a "similar" signature in class hierarchy // similar interpreted in when primitive argument types are converted to their wrappers for (Method method : t.getMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } // second priority: find a non-public method with a "similar" signature on declaring class do { for (Method method : t.getDeclaredMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } t = t.getSuperclass(); } while (t != null); throw new NoSuchMethodException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found on type " + type() + "."); } /** * Determines if a method has a "similar" signature, especially if wrapping * primitive argument types would result in an exactly matching signature. */ private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) { return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes); } /** * Call a constructor. * <p> * This is a convenience method for calling * <code>create(new Object[0])</code> * * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #create(Object...) */ public Reflect create() throws ReflectException { return create(new Object[0]); } /** * Call a constructor. * <p> * This is roughly equivalent to {@link Constructor#newInstance(Object...)}. * If the wrapped object is a {@link Class}, then this will create a new * object of that class. If the wrapped object is any other {@link Object}, * then this will create a new object of the same type. * <p> * Just like {@link Constructor#newInstance(Object...)}, this will try to * wrap primitive types or unwrap primitive type wrappers if applicable. If * several constructors are applicable, by that rule, the first one * encountered is called. i.e. when calling <code><pre> * on(C.class).create(1, 1); * </pre></code> The first of the following constructors will be applied: * <code><pre> * public C(int param1, Integer param2); * public C(Integer param1, int param2); * public C(Number param1, Number param2); * public C(Number param1, Object param2); * public C(int param1, Object param2); * </pre></code> * * @param args The constructor arguments * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect create(Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" constructor, i.e. the one with exact // matching argument types try { Constructor<?> constructor = type().getDeclaredConstructor(types); return on(constructor, args); } // If there is no exact match, try to find one that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { for (Constructor<?> constructor : type().getDeclaredConstructors()) { if (match(constructor.getParameterTypes(), types)) { return on(constructor, args); } } throw new ReflectException(e); } } /** * Create a proxy for the wrapped object allowing to typesafely invoke * methods on it using a custom interface * * @param proxyType The interface type that is implemented by the proxy * @return A proxy for the wrapped object */ @SuppressWarnings("unchecked") public <P> P as(final Class<P> proxyType) { final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @SuppressWarnings("null") @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); // Actual method name matches always come first try { return on(type, object).call(name, args).get(); } // [#14] Emulate POJO behaviour on wrapped map objects catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler); } /** * Get the POJO property name of an getter/setter */ private static String property(String string) { int length = string.length(); if (length == 0) { return ""; } else if (length == 1) { return string.toLowerCase(Locale.ROOT); } else { return string.substring(0, 1).toLowerCase(Locale.ROOT) + string.substring(1); } } // --------------------------------------------------------------------- // Object API // --------------------------------------------------------------------- /** * Check whether two arrays of types match, converting primitive types to * their corresponding wrappers. */ private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) { if (declaredTypes.length == actualTypes.length) { for (int i = 0; i < actualTypes.length; i++) { if (actualTypes[i] == NULL.class) continue; if (wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i]))) continue; return false; } return true; } else { return false; } } /** * {@inheritDoc} */ @Override public int hashCode() { return object.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof Reflect) { return object.equals(((Reflect) obj).get()); } return false; } /** * {@inheritDoc} */ @Override public String toString() { return object.toString(); } // --------------------------------------------------------------------- // Utility methods // --------------------------------------------------------------------- /** * Wrap an object created from a constructor */ private static Reflect on(Constructor<?> constructor, Object... args) throws ReflectException { try { return on(constructor.getDeclaringClass(), accessible(constructor).newInstance(args)); } catch (Exception e) { throw new ReflectException(e); } } /** * Wrap an object returned from a method */ private static Reflect on(Method method, Object object, Object... args) throws ReflectException { try { accessible(method); if (method.getReturnType() == void.class) { method.invoke(object, args); return on(object); } else { return on(method.invoke(object, args)); } } catch (Exception e) { throw new ReflectException(e); } } /** * Unwrap an object */ private static Object unwrap(Object object) { if (object instanceof Reflect) { return ((Reflect) object).get(); } return object; } /** * Get an array of types for an array of objects * * @see Object#getClass() */ private static Class<?>[] types(Object... values) { if (values == null) { return new Class[0]; } Class<?>[] result = new Class[values.length]; for (int i = 0; i < values.length; i++) { Object value = values[i]; result[i] = value == null ? NULL.class : value.getClass(); } return result; } /** * Load a class * * @see Class#forName(String) */ private static Class<?> forName(String name) throws ReflectException { try { return Class.forName(name); } catch (Exception e) { throw new ReflectException(e); } } private static Class<?> forName(String name, ClassLoader classLoader) throws ReflectException { try { return Class.forName(name, true, classLoader); } catch (Exception e) { throw new ReflectException(e); } } /** * Get the type of the wrapped object. * * @see Object#getClass() */ public Class<?> type() { return type; } /** * Get a wrapper type for a primitive type, or the argument type itself, if * it is not a primitive type. */ public static Class<?> wrapper(Class<?> type) { if (type == null) { return null; } else if (type.isPrimitive()) { if (boolean.class == type) { return Boolean.class; } else if (int.class == type) { return Integer.class; } else if (long.class == type) { return Long.class; } else if (short.class == type) { return Short.class; } else if (byte.class == type) { return Byte.class; } else if (double.class == type) { return Double.class; } else if (float.class == type) { return Float.class; } else if (char.class == type) { return Character.class; } else if (void.class == type) { return Void.class; } } return type; } private static class NULL {} }
wix/Detox
detox/android/detox/src/main/java/org/joor/Reflect.java
6,756
// See here: https://stackoverflow.com/a/64378131/453052
line_comment
nl
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joor; import android.os.Build; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** * A wrapper for an {@link Object} or {@link Class} upon which reflective calls * can be made. * <p> * An example of using <code>Reflect</code> is <code><pre> * // Static import all reflection methods to decrease verbosity * import static org.joor.Reflect.*; * * // Wrap an Object / Class / class name with the on() method: * on("java.lang.String") * // Invoke constructors using the create() method: * .create("Hello World") * // Invoke methods using the call() method: * .call("toString") * // Retrieve the wrapped object * * @author Lukas Eder * @author Irek Matysiewicz * @author Thomas Darimont */ public class Reflect { // --------------------------------------------------------------------- // Static API used as entrance points to the fluent API // --------------------------------------------------------------------- /** * Wrap a class name. * <p> * This is the same as calling <code>on(Class.forName(name))</code> * * @param name A fully qualified class name * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name) throws ReflectException { return on(forName(name)); } /** * Wrap a class name, loading it via a given class loader. * <p> * This is the same as calling * <code>on(Class.forName(name, classLoader))</code> * * @param name A fully qualified class name. * @param classLoader The class loader in whose context the class should be * loaded. * @return A wrapped class object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #on(Class) */ public static Reflect on(String name, ClassLoader classLoader) throws ReflectException { return on(forName(name, classLoader)); } /** * Wrap a class. * <p> * Use this when you want to access static fields and methods on a * {@link Class} object, or as a basis for constructing objects of that * class using {@link #create(Object...)} * * @param clazz The class to be wrapped * @return A wrapped class object, to be used for further reflection. */ public static Reflect on(Class<?> clazz) { return new Reflect(clazz); } /** * Wrap an object. * <p> * Use this when you want to access instance fields and methods on any * {@link Object} * * @param object The object to be wrapped * @return A wrapped object, to be used for further reflection. */ public static Reflect on(Object object) { return new Reflect(object == null ? Object.class : object.getClass(), object); } private static Reflect on(Class<?> type, Object object) { return new Reflect(type, object); } /** * Conveniently render an {@link AccessibleObject} accessible. * <p> * To prevent {@link SecurityException}, this is only done if the argument * object and its declaring class are non-public. * * @param accessible The object to render accessible * @return The argument object rendered accessible */ public static <T extends AccessibleObject> T accessible(T accessible) { if (accessible == null) { return null; } if (accessible instanceof Member) { Member member = (Member) accessible; if (Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return accessible; } } // [jOOQ #3392] The accessible flag is set to false by default, also for public members. if (!accessible.isAccessible()) { accessible.setAccessible(true); } return accessible; } // --------------------------------------------------------------------- // Members // --------------------------------------------------------------------- /** * The type of the wrapped object. */ private final Class<?> type; /** * The wrapped object. */ private final Object object; // --------------------------------------------------------------------- // Constructors // --------------------------------------------------------------------- private Reflect(Class<?> type) { this(type, type); } private Reflect(Class<?> type, Object object) { this.type = type; this.object = object; } // --------------------------------------------------------------------- // Fluent Reflection API // --------------------------------------------------------------------- /** * Get the wrapped object * * @param <T> A convenience generic parameter for automatic unsafe casting */ @SuppressWarnings("unchecked") public <T> T get() { return (T) object; } /** * Set a field value. * <p> * This is roughly equivalent to {@link Field#set(Object, Object)}. If the * wrapped object is a {@link Class}, then this will set a value to a static * member field. If the wrapped object is any other {@link Object}, then * this will set a value to an instance member field. * <p> * This method is also capable of setting the value of (static) final * fields. This may be convenient in situations where no * {@link SecurityManager} is expected to prevent this, but do note that * (especially static) final fields may already have been inlined by the * javac and/or JIT and relevant code deleted from the runtime verison of * your program, so setting these fields might not have any effect on your * execution. * <p> * For restrictions of usage regarding setting values on final fields check: * <a href= * "http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection">http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection</a> * ... and <a href= * "http://pveentjer.blogspot.co.at/2017/01/final-static-boolean-jit.html">http://pveentjer.blogspot.co.at/2017/01/final-static-boolean-jit.html</a> * * @param name The field name * @param value The new field value * @return The same wrapped object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect set(String name, Object value) throws ReflectException { try { Field field = field0(name); if ((field.getModifiers() & Modifier.FINAL) == Modifier.FINAL) { // Note (d4vidi): this is an important change, compared to the original implementation!!! // See here:<SUF> // Field modifiersField = Field.class.getDeclaredField("modifiers"); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Field modifiersField = Field.class.getDeclaredField("accessFlags"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } } field.set(object, unwrap(value)); return this; } catch (Exception e) { throw new ReflectException(e); } } /** * Get a field value. * <p> * This is roughly equivalent to {@link Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will get a value from a static * member field. If the wrapped object is any other {@link Object}, then * this will get a value from an instance member field. * <p> * If you want to "navigate" to a wrapped version of the field, use * {@link #field(String)} instead. * * @param name The field name * @return The field value * @throws ReflectException If any reflection exception occurred. * @see #field(String) */ public <T> T get(String name) throws ReflectException { return field(name).<T>get(); } /** * Get a wrapped field. * <p> * This is roughly equivalent to {@link Field#get(Object)}. If the wrapped * object is a {@link Class}, then this will wrap a static member field. If * the wrapped object is any other {@link Object}, then this wrap an * instance member field. * * @param name The field name * @return The wrapped field * @throws ReflectException If any reflection exception occurred. */ public Reflect field(String name) throws ReflectException { try { Field field = field0(name); return on(field.getType(), field.get(object)); } catch (Exception e) { throw new ReflectException(e); } } private Field field0(String name) throws ReflectException { Class<?> t = type(); // Try getting a public field try { return accessible(t.getField(name)); } // Try again, getting a non-public field catch (NoSuchFieldException e) { do { try { return accessible(t.getDeclaredField(name)); } catch (NoSuchFieldException ignore) {} t = t.getSuperclass(); } while (t != null); throw new ReflectException(e); } } /** * Get a Map containing field names and wrapped values for the fields' * values. * <p> * If the wrapped object is a {@link Class}, then this will return static * fields. If the wrapped object is any other {@link Object}, then this will * return instance fields. * <p> * These two calls are equivalent <code><pre> * on(object).field("myField"); * on(object).fields().get("myField"); * </pre></code> * * @return A map containing field names and wrapped values. */ public Map<String, Reflect> fields() { Map<String, Reflect> result = new LinkedHashMap<String, Reflect>(); Class<?> t = type(); do { for (Field field : t.getDeclaredFields()) { if (type != object ^ Modifier.isStatic(field.getModifiers())) { String name = field.getName(); if (!result.containsKey(name)) result.put(name, field(name)); } } t = t.getSuperclass(); } while (t != null); return result; } /** * Call a method by its name. * <p> * This is a convenience method for calling * <code>call(name, new Object[0])</code> * * @param name The method name * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. * @see #call(String, Object...) */ public Reflect call(String name) throws ReflectException { return call(name, new Object[0]); } /** * Call a method by its name. * <p> * This is roughly equivalent to {@link Method#invoke(Object, Object...)}. * If the wrapped object is a {@link Class}, then this will invoke a static * method. If the wrapped object is any other {@link Object}, then this will * invoke an instance method. * <p> * Just like {@link Method#invoke(Object, Object...)}, this will try to wrap * primitive types or unwrap primitive type wrappers if applicable. If * several methods are applicable, by that rule, the first one encountered * is called. i.e. when calling <code><pre> * on(...).call("method", 1, 1); * </pre></code> The first of the following methods will be called: * <code><pre> * public void method(int param1, Integer param2); * public void method(Integer param1, int param2); * public void method(Number param1, Number param2); * public void method(Number param1, Object param2); * public void method(int param1, Object param2); * </pre></code> * <p> * The best matching method is searched for with the following strategy: * <ol> * <li>public method with exact signature match in class hierarchy</li> * <li>non-public method with exact signature match on declaring class</li> * <li>public method with similar signature in class hierarchy</li> * <li>non-public method with similar signature on declaring class</li> * </ol> * * @param name The method name * @param args The method arguments * @return The wrapped method result or the same wrapped object if the * method returns <code>void</code>, to be used for further * reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect call(String name, Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" method, i.e. the one with exact // matching argument types try { Method method = exactMethod(name, types); return on(method, object, args); } // If there is no exact match, try to find a method that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { try { Method method = similarMethod(name, types); return on(method, object, args); } catch (NoSuchMethodException e1) { throw new ReflectException(e1); } } } /** * Searches a method with the exact same signature as desired. * <p> * If a public method is found in the class hierarchy, this method is returned. * Otherwise a private method with the exact same signature is returned. * If no exact match could be found, we let the {@code NoSuchMethodException} pass through. */ private Method exactMethod(String name, Class<?>[] types) throws NoSuchMethodException { Class<?> t = type(); // first priority: find a public method with exact signature match in class hierarchy try { return t.getMethod(name, types); } // second priority: find a private method with exact signature match on declaring class catch (NoSuchMethodException e) { do { try { return t.getDeclaredMethod(name, types); } catch (NoSuchMethodException ignore) {} t = t.getSuperclass(); } while (t != null); throw new NoSuchMethodException(); } } /** * Searches a method with a similar signature as desired using * {@link #isSimilarSignature(java.lang.reflect.Method, String, Class[])}. * <p> * First public methods are searched in the class hierarchy, then private * methods on the declaring class. If a method could be found, it is * returned, otherwise a {@code NoSuchMethodException} is thrown. */ private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException { Class<?> t = type(); // first priority: find a public method with a "similar" signature in class hierarchy // similar interpreted in when primitive argument types are converted to their wrappers for (Method method : t.getMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } // second priority: find a non-public method with a "similar" signature on declaring class do { for (Method method : t.getDeclaredMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } t = t.getSuperclass(); } while (t != null); throw new NoSuchMethodException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found on type " + type() + "."); } /** * Determines if a method has a "similar" signature, especially if wrapping * primitive argument types would result in an exactly matching signature. */ private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) { return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes); } /** * Call a constructor. * <p> * This is a convenience method for calling * <code>create(new Object[0])</code> * * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. * @see #create(Object...) */ public Reflect create() throws ReflectException { return create(new Object[0]); } /** * Call a constructor. * <p> * This is roughly equivalent to {@link Constructor#newInstance(Object...)}. * If the wrapped object is a {@link Class}, then this will create a new * object of that class. If the wrapped object is any other {@link Object}, * then this will create a new object of the same type. * <p> * Just like {@link Constructor#newInstance(Object...)}, this will try to * wrap primitive types or unwrap primitive type wrappers if applicable. If * several constructors are applicable, by that rule, the first one * encountered is called. i.e. when calling <code><pre> * on(C.class).create(1, 1); * </pre></code> The first of the following constructors will be applied: * <code><pre> * public C(int param1, Integer param2); * public C(Integer param1, int param2); * public C(Number param1, Number param2); * public C(Number param1, Object param2); * public C(int param1, Object param2); * </pre></code> * * @param args The constructor arguments * @return The wrapped new object, to be used for further reflection. * @throws ReflectException If any reflection exception occurred. */ public Reflect create(Object... args) throws ReflectException { Class<?>[] types = types(args); // Try invoking the "canonical" constructor, i.e. the one with exact // matching argument types try { Constructor<?> constructor = type().getDeclaredConstructor(types); return on(constructor, args); } // If there is no exact match, try to find one that has a "similar" // signature if primitive argument types are converted to their wrappers catch (NoSuchMethodException e) { for (Constructor<?> constructor : type().getDeclaredConstructors()) { if (match(constructor.getParameterTypes(), types)) { return on(constructor, args); } } throw new ReflectException(e); } } /** * Create a proxy for the wrapped object allowing to typesafely invoke * methods on it using a custom interface * * @param proxyType The interface type that is implemented by the proxy * @return A proxy for the wrapped object */ @SuppressWarnings("unchecked") public <P> P as(final Class<P> proxyType) { final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @SuppressWarnings("null") @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); // Actual method name matches always come first try { return on(type, object).call(name, args).get(); } // [#14] Emulate POJO behaviour on wrapped map objects catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler); } /** * Get the POJO property name of an getter/setter */ private static String property(String string) { int length = string.length(); if (length == 0) { return ""; } else if (length == 1) { return string.toLowerCase(Locale.ROOT); } else { return string.substring(0, 1).toLowerCase(Locale.ROOT) + string.substring(1); } } // --------------------------------------------------------------------- // Object API // --------------------------------------------------------------------- /** * Check whether two arrays of types match, converting primitive types to * their corresponding wrappers. */ private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) { if (declaredTypes.length == actualTypes.length) { for (int i = 0; i < actualTypes.length; i++) { if (actualTypes[i] == NULL.class) continue; if (wrapper(declaredTypes[i]).isAssignableFrom(wrapper(actualTypes[i]))) continue; return false; } return true; } else { return false; } } /** * {@inheritDoc} */ @Override public int hashCode() { return object.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof Reflect) { return object.equals(((Reflect) obj).get()); } return false; } /** * {@inheritDoc} */ @Override public String toString() { return object.toString(); } // --------------------------------------------------------------------- // Utility methods // --------------------------------------------------------------------- /** * Wrap an object created from a constructor */ private static Reflect on(Constructor<?> constructor, Object... args) throws ReflectException { try { return on(constructor.getDeclaringClass(), accessible(constructor).newInstance(args)); } catch (Exception e) { throw new ReflectException(e); } } /** * Wrap an object returned from a method */ private static Reflect on(Method method, Object object, Object... args) throws ReflectException { try { accessible(method); if (method.getReturnType() == void.class) { method.invoke(object, args); return on(object); } else { return on(method.invoke(object, args)); } } catch (Exception e) { throw new ReflectException(e); } } /** * Unwrap an object */ private static Object unwrap(Object object) { if (object instanceof Reflect) { return ((Reflect) object).get(); } return object; } /** * Get an array of types for an array of objects * * @see Object#getClass() */ private static Class<?>[] types(Object... values) { if (values == null) { return new Class[0]; } Class<?>[] result = new Class[values.length]; for (int i = 0; i < values.length; i++) { Object value = values[i]; result[i] = value == null ? NULL.class : value.getClass(); } return result; } /** * Load a class * * @see Class#forName(String) */ private static Class<?> forName(String name) throws ReflectException { try { return Class.forName(name); } catch (Exception e) { throw new ReflectException(e); } } private static Class<?> forName(String name, ClassLoader classLoader) throws ReflectException { try { return Class.forName(name, true, classLoader); } catch (Exception e) { throw new ReflectException(e); } } /** * Get the type of the wrapped object. * * @see Object#getClass() */ public Class<?> type() { return type; } /** * Get a wrapper type for a primitive type, or the argument type itself, if * it is not a primitive type. */ public static Class<?> wrapper(Class<?> type) { if (type == null) { return null; } else if (type.isPrimitive()) { if (boolean.class == type) { return Boolean.class; } else if (int.class == type) { return Integer.class; } else if (long.class == type) { return Long.class; } else if (short.class == type) { return Short.class; } else if (byte.class == type) { return Byte.class; } else if (double.class == type) { return Double.class; } else if (float.class == type) { return Float.class; } else if (char.class == type) { return Character.class; } else if (void.class == type) { return Void.class; } } return type; } private static class NULL {} }
137061_2
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.turbo; import org.openide.util.Lookup; import org.openide.ErrorManager; import java.util.*; import java.lang.ref.WeakReference; import org.netbeans.modules.versioning.util.Utils; /** * Turbo is general purpose entries/attributes dictionary with pluggable * layer enabling high scalability disk swaping implementations. * It allows to store several name identified values * for an entity identified by a key. * * <p>All methods take a <b><code>key</code></b> parameter. It * identifies entity to which attribute values are associated. * It must have properly implemented <code>equals()</code>, * <code>hashcode()</code> and <code>toString()</code> (returning * unique string) methods. Key lifetime must be well * understood to set cache strategy effeciently: * <ul> * <li>MAXIMUM: The implementation monitors key instance lifetime and does * not release data from memory until max. size limit reached or * key instance garbage collected whichever comes sooner. For * unbound caches the key must not be hard referenced from stored * value. * * <li>MINIMUM: For value lookups key's value based equalence is used. * Key's instance lifetime is monitored by instance based equalence. * Reasonable min limit must be set because there can be several * value equalent key instances but only one used key instance * actually stored in cache and lifetime monitored. * </ul> * * <p>Entry <b>name</b> fully indentifies contract between * consumers and providers. Contracts are described elsewhere. * * <p>The dictionary does not support storing <code>null</code> * <b>values</b>. Writing <code>null</code> value means that given * entry should be invalidated and removed (it actualy depends * on externally negotiated contract identified by name). Getting * <code>null</code> as requets result means that given value * is not (yet) known or does not exist at all. * * @author Petr Kuzel */ public final class Turbo { /** Default providers registry. */ private static Lookup.Result providers; /** Custom providers 'registry'. */ private final CustomProviders customProviders; private static WeakReference defaultInstance; private List listeners = new ArrayList(100); /** memory layer */ private final Memory memory; private final Statistics statistics; private static Environment env; /** * Returns default instance. It's size is driven by * keys lifetime. It shrinks on keys become unreferenced * and grows without bounds on inserting keys. */ public static synchronized Turbo getDefault() { Turbo turbo = null; if (defaultInstance != null) { turbo = (Turbo) defaultInstance.get(); } if (turbo == null) { turbo = new Turbo(null, 47, -1); defaultInstance = new WeakReference(turbo); } return turbo; } /** * Creates new instance with customized providers layer. * @param providers never <code>null</null> * @param min minimum number of entries held by the cache * @param max maximum size or <code>-1</code> for unbound size * (defined just by key instance lifetime) */ public static synchronized Turbo createCustom(CustomProviders providers, int min, int max) { return new Turbo(providers, min, max); } private Turbo(CustomProviders customProviders, int min, int max) { statistics = Statistics.createInstance(); memory = new Memory(statistics, min, max); this.customProviders = customProviders; if (customProviders == null && providers == null) { Lookup.Template t = new Lookup.Template(TurboProvider.class); synchronized(Turbo.class) { if (env == null) env = new Environment(); } providers = env.getLookup().lookup(t); } } /** Tests can set different environment. Must be called before {@link #getDefault}. */ static synchronized void initEnvironment(Environment environment) { assert env == null; env = environment; providers = null; } /** Logs cache statistics data. */ protected void finalize() throws Throwable { super.finalize(); statistics.shutdown(); } /** * Reads given attribute for given entity key. * @param key a entity key, never <code>null</code> * @param name identifies requested entry, never <code>null</code> * @return entry value or <code>null</code> if it does not exist or unknown. */ public Object readEntry(Object key, String name) { statistics.attributeRequest(); // check memory cache if (memory.existsEntry(key, name)) { Object value = memory.get(key, name); statistics.memoryHit(); return value; } // iterate over providers List speculative = new ArrayList(57); Object value = loadEntry(key, name, speculative); memory.put(key, name, value != null ? value : Memory.NULL); // XXX should fire here? yes if name avalability changes should be // dispatched to clients that have not called prepare otherwise NO. // refire speculative results, can be optinized later on to fire // them lazilly on prepareAttribute or isPrepared calls Iterator it = speculative.iterator(); while (it.hasNext()) { Object[] next = (Object[]) it.next(); Object sKey = next[0]; String sName = (String) next[1]; Object sValue = next[2]; assert sKey != null; assert sName != null; fireEntryChange(sKey, sName, sValue); } return value; } private Iterator providers() { if (customProviders == null) { Collection plugins = providers.allInstances(); List all = new ArrayList(plugins.size() +1); all.addAll(plugins); all.add(DefaultTurboProvider.getDefault()); return all.iterator(); } else { return customProviders.providers(); } } /** * Iterate over providers asking for attribute values */ private Object loadEntry(Object key, String name, List speculative) { TurboProvider provider; Iterator it = providers(); while (it.hasNext()) { provider = (TurboProvider) it.next(); try { if (provider.recognizesAttribute(name) && provider.recognizesEntity(key)) { TurboProvider.MemoryCache cache = TurboProvider.MemoryCache.createDefault(memory, speculative); Object value = provider.readEntry(key, name, cache); statistics.providerHit(); return value; } } catch (ThreadDeath td) { throw td; } catch (Throwable t) { // error in provider ErrorManager.getDefault().annotate(t, "Error in provider " + provider + ", skipping... "); // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, t); // XXX in Junit mode writes to stdout ommiting annotation!!! } } return null; } /** * Writes given attribute, value pair and notifies all listeners. * Written value is stored both into memory and providers layer. * The call speed depends on actually used provider. However do not * rely on synchronous provider call. In future it may return and * fire immediately on writing into memory layer, populating providers * asychronously on background. * * <p>A client calling this method is reponsible for passing * valid value that is accepted by attribute serving providers. * * @param key identifies target, never <code>null</code> * @param name identifies attribute, never <code>null</code> * @param value actual attribute value to be stored, <code>null</code> behaviour * is defined specificaly for each name. It always invalidates memory entry * and it either invalidates or removes value from providers layer * (mening: value unknown versus value is known to not exist). * * <p>Client should consider a size of stored value. It must be corelated * with Turbo memory layer limits to avoid running ouf of memory. * * @return <ul> * <li><code>false</code> on write failure caused by a provider denying the value. * It means attribute contract violation and must be handled e.g.: * <p><code> * boolean success = faq.writeAttribute(fo, name, value);<br> * assert success : "Unexpected name[" + name + "] value[" + value + "] denial for " + key + "!"; * </code> * <li><code>true</code> in all other cases includins I/O error. * After all it's just best efford cache. All values can be recomputed. * </ul> */ public boolean writeEntry(Object key, String name, Object value) { if (value != null) { Object oldValue = memory.get(key, name); if (oldValue != null && oldValue.equals(value)) return true; // XXX assuming provider has the same value, assert it! } int result = storeEntry(key, name, value); if (result >= 0) { // no one denied keep at least in memory cache memory.put(key, name, value); fireEntryChange(key, name, value); return true; } else { return false; } } /** * Stores directly to providers. * @return 0 success, -1 contract failure, 1 other failure */ int storeEntry(Object key, String name, Object value) { TurboProvider provider; Iterator it = providers(); while (it.hasNext()) { provider = (TurboProvider) it.next(); try { if (provider.recognizesAttribute(name) && provider.recognizesEntity(key)) { if (provider.writeEntry(key, name, value)) { return 0; } else { // for debugging purposes log which provider rejected defined name contract IllegalArgumentException ex = new IllegalArgumentException("Attribute[" + name + "] value rejected by " + provider); ErrorManager.getDefault().notify(ErrorManager.WARNING, ex); return -1; } } } catch (ThreadDeath td) { throw td; } catch (Throwable t) { // error in provider ErrorManager.getDefault().annotate(t, "Error in provider " + provider + ", skipping... "); // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, t); } } return 1; } /** * Checks value instant availability and possibly schedules its background * loading. It's designed to be called from UI tread. * * @return <ul> * <li><code>false</code> if not ready and providers must be consulted. It * asynchronously fires event possibly with <code>null</code> value * if given attribute does not exist. * * <li> * If <code>true</code> it's * ready and stays ready at least until next {@link #prepareEntry}, * {@link #isPrepared}, {@link #writeEntry} <code>null</code> call * or {@link #readEntry} from the same thread. * </ul> */ public boolean prepareEntry(Object key, String name) { statistics.attributeRequest(); // check memory cache if (memory.existsEntry(key, name)) { statistics.memoryHit(); return true; } // start asynchronous providers queriing scheduleLoad(key, name); return false; } /** * Checks name instant availability. Note that actual * value may be still <code>null</code>, in case * that it's known that value does not exist. * * @return <ul> * <li><code>false</code> if not present in memory for instant access. * * <li><code>true</code> when it's * ready and stays ready at least until next {@link #prepareEntry}, * {@link #isPrepared}, {@link #writeEntry} <code>null</code> call * or {@link #readEntry} from the same thread. * </ul> */ public boolean isPrepared(Object key, String name) { return memory.existsEntry(key, name); } /** * Gets key instance that it actually used in memory layer. * Client should keep reference to it if it wants to use * key lifetime monitoring cache size strategy. * * @param key key never <code>null</code> * @return key instance that is value-equalent or <code>null</code> * if monitored instance does not exist. */ public Object getMonitoredKey(Object key) { return memory.getMonitoredKey(key); } public void addTurboListener(TurboListener l) { synchronized(listeners) { List copy = new ArrayList(listeners); copy.add(l); listeners = copy; } } public void removeTurboListener(TurboListener l) { synchronized(listeners) { List copy = new ArrayList(listeners); copy.remove(l); listeners = copy; } } protected void fireEntryChange(Object key, String name, Object value) { Iterator it = listeners.iterator(); while (it.hasNext()) { TurboListener next = (TurboListener) it.next(); next.entryChanged(key, name, value); } } /** For debugging purposes only. */ public String toString() { StringBuffer sb = new StringBuffer("Turbo delegating to:"); // NOI18N Iterator it = providers(); while (it.hasNext()) { TurboProvider provider = (TurboProvider) it.next(); sb.append(" [" + provider + "]"); // NOI18N } return sb.toString(); } /** Defines binding to external world. Used by tests. */ static class Environment { /** Lookup that serves providers. */ public Lookup getLookup() { return Lookup.getDefault(); } } // Background loading ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** Holds keys that were requested for background status retrieval. */ private final Set prepareRequests = Collections.synchronizedSet(new LinkedHashSet(27)); private static PreparationTask preparationTask; /** Tries to locate meta on disk on failure it forward to repository */ private void scheduleLoad(Object key, String name) { synchronized(prepareRequests) { if (preparationTask == null) { preparationTask = new PreparationTask(prepareRequests); Utils.postParallel(preparationTask, 0); statistics.backgroundThread(); } preparationTask.notifyNewRequest(new Request(key, name)); } } /** Requests queue entry featuring value based identity. */ private final static class Request { private final Object key; private final String name; public Request(Object key, String name) { this.name = name; this.key = key; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Request)) return false; final Request request = (Request) o; if (name != null ? !name.equals(request.name) : request.name != null) return false; if (key != null ? !key.equals(request.key) : request.key != null) return false; return true; } public int hashCode() { int result; result = (key != null ? key.hashCode() : 0); result = 29 * result + (name != null ? name.hashCode() : 0); return result; } public String toString() { return "Request[key=" + key + ", attr=" + name + "]"; } } /** * On background fetches data from providers layer. */ private final class PreparationTask implements Runnable { private final Set requests; private static final int INACTIVITY_TIMEOUT = 123 * 1000; // 123 sec public PreparationTask(Set requests) { this.requests = requests; } public void run() { try { Thread.currentThread().setName("Turbo Async Fetcher"); // NOI18N while (waitForRequests()) { Request request; synchronized (requests) { request = (Request) requests.iterator().next(); requests.remove(request); } Object key = request.key; String name = request.name; Object value; boolean fire; if (memory.existsEntry(key, name)) { synchronized(Memory.class) { fire = memory.existsEntry(key, name) == false; value = memory.get(key, name); } if (fire) { statistics.providerHit(); // from our perpective we achieved hit } } else { value = loadEntry(key, name, null); // possible thread switch, so atomic fire test must be used synchronized(Memory.class) { fire = memory.existsEntry(key, name) == false; Object oldValue = memory.get(key, name); memory.put(key, name, value != null ? value : Memory.NULL); fire |= (oldValue != null && !oldValue.equals(value)) || (oldValue == null && value != null); } } // some one was faster, probably previous disk read that silently fetched whole directory // our contract was to fire event once loading, stick to it. Note that get() // silently populates stable memory area // if (fire) { ALWAYS because of above loadAttribute(key, name, null); fireEntryChange(key, name, value); // notify as soon as available in memory // } } } catch (InterruptedException ex) { synchronized(requests) { // forget about recent requests requests.clear(); } } finally { synchronized(requests) { preparationTask = null; } } } /** * Wait for requests, it no request comes until timeout * it ommits suicide. It's respawned on next request however. */ private boolean waitForRequests() throws InterruptedException { synchronized(requests) { if (requests.size() == 0) { requests.wait(INACTIVITY_TIMEOUT); } return requests.size() > 0; } } public void notifyNewRequest(Request request) { synchronized(requests) { if (requests.add(request)) { statistics.queueSize(requests.size()); requests.notify(); } else { statistics.duplicate(); statistics.providerHit(); } } } public String toString() { return "Turbo.PreparationTask queue=[" + requests +"]"; // NOI18N } } }
rtaneja1/netbeans
ide/versioning.util/src/org/netbeans/modules/turbo/Turbo.java
4,768
/** Default providers registry. */
block_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.turbo; import org.openide.util.Lookup; import org.openide.ErrorManager; import java.util.*; import java.lang.ref.WeakReference; import org.netbeans.modules.versioning.util.Utils; /** * Turbo is general purpose entries/attributes dictionary with pluggable * layer enabling high scalability disk swaping implementations. * It allows to store several name identified values * for an entity identified by a key. * * <p>All methods take a <b><code>key</code></b> parameter. It * identifies entity to which attribute values are associated. * It must have properly implemented <code>equals()</code>, * <code>hashcode()</code> and <code>toString()</code> (returning * unique string) methods. Key lifetime must be well * understood to set cache strategy effeciently: * <ul> * <li>MAXIMUM: The implementation monitors key instance lifetime and does * not release data from memory until max. size limit reached or * key instance garbage collected whichever comes sooner. For * unbound caches the key must not be hard referenced from stored * value. * * <li>MINIMUM: For value lookups key's value based equalence is used. * Key's instance lifetime is monitored by instance based equalence. * Reasonable min limit must be set because there can be several * value equalent key instances but only one used key instance * actually stored in cache and lifetime monitored. * </ul> * * <p>Entry <b>name</b> fully indentifies contract between * consumers and providers. Contracts are described elsewhere. * * <p>The dictionary does not support storing <code>null</code> * <b>values</b>. Writing <code>null</code> value means that given * entry should be invalidated and removed (it actualy depends * on externally negotiated contract identified by name). Getting * <code>null</code> as requets result means that given value * is not (yet) known or does not exist at all. * * @author Petr Kuzel */ public final class Turbo { /** Default providers registry.<SUF>*/ private static Lookup.Result providers; /** Custom providers 'registry'. */ private final CustomProviders customProviders; private static WeakReference defaultInstance; private List listeners = new ArrayList(100); /** memory layer */ private final Memory memory; private final Statistics statistics; private static Environment env; /** * Returns default instance. It's size is driven by * keys lifetime. It shrinks on keys become unreferenced * and grows without bounds on inserting keys. */ public static synchronized Turbo getDefault() { Turbo turbo = null; if (defaultInstance != null) { turbo = (Turbo) defaultInstance.get(); } if (turbo == null) { turbo = new Turbo(null, 47, -1); defaultInstance = new WeakReference(turbo); } return turbo; } /** * Creates new instance with customized providers layer. * @param providers never <code>null</null> * @param min minimum number of entries held by the cache * @param max maximum size or <code>-1</code> for unbound size * (defined just by key instance lifetime) */ public static synchronized Turbo createCustom(CustomProviders providers, int min, int max) { return new Turbo(providers, min, max); } private Turbo(CustomProviders customProviders, int min, int max) { statistics = Statistics.createInstance(); memory = new Memory(statistics, min, max); this.customProviders = customProviders; if (customProviders == null && providers == null) { Lookup.Template t = new Lookup.Template(TurboProvider.class); synchronized(Turbo.class) { if (env == null) env = new Environment(); } providers = env.getLookup().lookup(t); } } /** Tests can set different environment. Must be called before {@link #getDefault}. */ static synchronized void initEnvironment(Environment environment) { assert env == null; env = environment; providers = null; } /** Logs cache statistics data. */ protected void finalize() throws Throwable { super.finalize(); statistics.shutdown(); } /** * Reads given attribute for given entity key. * @param key a entity key, never <code>null</code> * @param name identifies requested entry, never <code>null</code> * @return entry value or <code>null</code> if it does not exist or unknown. */ public Object readEntry(Object key, String name) { statistics.attributeRequest(); // check memory cache if (memory.existsEntry(key, name)) { Object value = memory.get(key, name); statistics.memoryHit(); return value; } // iterate over providers List speculative = new ArrayList(57); Object value = loadEntry(key, name, speculative); memory.put(key, name, value != null ? value : Memory.NULL); // XXX should fire here? yes if name avalability changes should be // dispatched to clients that have not called prepare otherwise NO. // refire speculative results, can be optinized later on to fire // them lazilly on prepareAttribute or isPrepared calls Iterator it = speculative.iterator(); while (it.hasNext()) { Object[] next = (Object[]) it.next(); Object sKey = next[0]; String sName = (String) next[1]; Object sValue = next[2]; assert sKey != null; assert sName != null; fireEntryChange(sKey, sName, sValue); } return value; } private Iterator providers() { if (customProviders == null) { Collection plugins = providers.allInstances(); List all = new ArrayList(plugins.size() +1); all.addAll(plugins); all.add(DefaultTurboProvider.getDefault()); return all.iterator(); } else { return customProviders.providers(); } } /** * Iterate over providers asking for attribute values */ private Object loadEntry(Object key, String name, List speculative) { TurboProvider provider; Iterator it = providers(); while (it.hasNext()) { provider = (TurboProvider) it.next(); try { if (provider.recognizesAttribute(name) && provider.recognizesEntity(key)) { TurboProvider.MemoryCache cache = TurboProvider.MemoryCache.createDefault(memory, speculative); Object value = provider.readEntry(key, name, cache); statistics.providerHit(); return value; } } catch (ThreadDeath td) { throw td; } catch (Throwable t) { // error in provider ErrorManager.getDefault().annotate(t, "Error in provider " + provider + ", skipping... "); // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, t); // XXX in Junit mode writes to stdout ommiting annotation!!! } } return null; } /** * Writes given attribute, value pair and notifies all listeners. * Written value is stored both into memory and providers layer. * The call speed depends on actually used provider. However do not * rely on synchronous provider call. In future it may return and * fire immediately on writing into memory layer, populating providers * asychronously on background. * * <p>A client calling this method is reponsible for passing * valid value that is accepted by attribute serving providers. * * @param key identifies target, never <code>null</code> * @param name identifies attribute, never <code>null</code> * @param value actual attribute value to be stored, <code>null</code> behaviour * is defined specificaly for each name. It always invalidates memory entry * and it either invalidates or removes value from providers layer * (mening: value unknown versus value is known to not exist). * * <p>Client should consider a size of stored value. It must be corelated * with Turbo memory layer limits to avoid running ouf of memory. * * @return <ul> * <li><code>false</code> on write failure caused by a provider denying the value. * It means attribute contract violation and must be handled e.g.: * <p><code> * boolean success = faq.writeAttribute(fo, name, value);<br> * assert success : "Unexpected name[" + name + "] value[" + value + "] denial for " + key + "!"; * </code> * <li><code>true</code> in all other cases includins I/O error. * After all it's just best efford cache. All values can be recomputed. * </ul> */ public boolean writeEntry(Object key, String name, Object value) { if (value != null) { Object oldValue = memory.get(key, name); if (oldValue != null && oldValue.equals(value)) return true; // XXX assuming provider has the same value, assert it! } int result = storeEntry(key, name, value); if (result >= 0) { // no one denied keep at least in memory cache memory.put(key, name, value); fireEntryChange(key, name, value); return true; } else { return false; } } /** * Stores directly to providers. * @return 0 success, -1 contract failure, 1 other failure */ int storeEntry(Object key, String name, Object value) { TurboProvider provider; Iterator it = providers(); while (it.hasNext()) { provider = (TurboProvider) it.next(); try { if (provider.recognizesAttribute(name) && provider.recognizesEntity(key)) { if (provider.writeEntry(key, name, value)) { return 0; } else { // for debugging purposes log which provider rejected defined name contract IllegalArgumentException ex = new IllegalArgumentException("Attribute[" + name + "] value rejected by " + provider); ErrorManager.getDefault().notify(ErrorManager.WARNING, ex); return -1; } } } catch (ThreadDeath td) { throw td; } catch (Throwable t) { // error in provider ErrorManager.getDefault().annotate(t, "Error in provider " + provider + ", skipping... "); // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, t); } } return 1; } /** * Checks value instant availability and possibly schedules its background * loading. It's designed to be called from UI tread. * * @return <ul> * <li><code>false</code> if not ready and providers must be consulted. It * asynchronously fires event possibly with <code>null</code> value * if given attribute does not exist. * * <li> * If <code>true</code> it's * ready and stays ready at least until next {@link #prepareEntry}, * {@link #isPrepared}, {@link #writeEntry} <code>null</code> call * or {@link #readEntry} from the same thread. * </ul> */ public boolean prepareEntry(Object key, String name) { statistics.attributeRequest(); // check memory cache if (memory.existsEntry(key, name)) { statistics.memoryHit(); return true; } // start asynchronous providers queriing scheduleLoad(key, name); return false; } /** * Checks name instant availability. Note that actual * value may be still <code>null</code>, in case * that it's known that value does not exist. * * @return <ul> * <li><code>false</code> if not present in memory for instant access. * * <li><code>true</code> when it's * ready and stays ready at least until next {@link #prepareEntry}, * {@link #isPrepared}, {@link #writeEntry} <code>null</code> call * or {@link #readEntry} from the same thread. * </ul> */ public boolean isPrepared(Object key, String name) { return memory.existsEntry(key, name); } /** * Gets key instance that it actually used in memory layer. * Client should keep reference to it if it wants to use * key lifetime monitoring cache size strategy. * * @param key key never <code>null</code> * @return key instance that is value-equalent or <code>null</code> * if monitored instance does not exist. */ public Object getMonitoredKey(Object key) { return memory.getMonitoredKey(key); } public void addTurboListener(TurboListener l) { synchronized(listeners) { List copy = new ArrayList(listeners); copy.add(l); listeners = copy; } } public void removeTurboListener(TurboListener l) { synchronized(listeners) { List copy = new ArrayList(listeners); copy.remove(l); listeners = copy; } } protected void fireEntryChange(Object key, String name, Object value) { Iterator it = listeners.iterator(); while (it.hasNext()) { TurboListener next = (TurboListener) it.next(); next.entryChanged(key, name, value); } } /** For debugging purposes only. */ public String toString() { StringBuffer sb = new StringBuffer("Turbo delegating to:"); // NOI18N Iterator it = providers(); while (it.hasNext()) { TurboProvider provider = (TurboProvider) it.next(); sb.append(" [" + provider + "]"); // NOI18N } return sb.toString(); } /** Defines binding to external world. Used by tests. */ static class Environment { /** Lookup that serves providers. */ public Lookup getLookup() { return Lookup.getDefault(); } } // Background loading ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** Holds keys that were requested for background status retrieval. */ private final Set prepareRequests = Collections.synchronizedSet(new LinkedHashSet(27)); private static PreparationTask preparationTask; /** Tries to locate meta on disk on failure it forward to repository */ private void scheduleLoad(Object key, String name) { synchronized(prepareRequests) { if (preparationTask == null) { preparationTask = new PreparationTask(prepareRequests); Utils.postParallel(preparationTask, 0); statistics.backgroundThread(); } preparationTask.notifyNewRequest(new Request(key, name)); } } /** Requests queue entry featuring value based identity. */ private final static class Request { private final Object key; private final String name; public Request(Object key, String name) { this.name = name; this.key = key; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Request)) return false; final Request request = (Request) o; if (name != null ? !name.equals(request.name) : request.name != null) return false; if (key != null ? !key.equals(request.key) : request.key != null) return false; return true; } public int hashCode() { int result; result = (key != null ? key.hashCode() : 0); result = 29 * result + (name != null ? name.hashCode() : 0); return result; } public String toString() { return "Request[key=" + key + ", attr=" + name + "]"; } } /** * On background fetches data from providers layer. */ private final class PreparationTask implements Runnable { private final Set requests; private static final int INACTIVITY_TIMEOUT = 123 * 1000; // 123 sec public PreparationTask(Set requests) { this.requests = requests; } public void run() { try { Thread.currentThread().setName("Turbo Async Fetcher"); // NOI18N while (waitForRequests()) { Request request; synchronized (requests) { request = (Request) requests.iterator().next(); requests.remove(request); } Object key = request.key; String name = request.name; Object value; boolean fire; if (memory.existsEntry(key, name)) { synchronized(Memory.class) { fire = memory.existsEntry(key, name) == false; value = memory.get(key, name); } if (fire) { statistics.providerHit(); // from our perpective we achieved hit } } else { value = loadEntry(key, name, null); // possible thread switch, so atomic fire test must be used synchronized(Memory.class) { fire = memory.existsEntry(key, name) == false; Object oldValue = memory.get(key, name); memory.put(key, name, value != null ? value : Memory.NULL); fire |= (oldValue != null && !oldValue.equals(value)) || (oldValue == null && value != null); } } // some one was faster, probably previous disk read that silently fetched whole directory // our contract was to fire event once loading, stick to it. Note that get() // silently populates stable memory area // if (fire) { ALWAYS because of above loadAttribute(key, name, null); fireEntryChange(key, name, value); // notify as soon as available in memory // } } } catch (InterruptedException ex) { synchronized(requests) { // forget about recent requests requests.clear(); } } finally { synchronized(requests) { preparationTask = null; } } } /** * Wait for requests, it no request comes until timeout * it ommits suicide. It's respawned on next request however. */ private boolean waitForRequests() throws InterruptedException { synchronized(requests) { if (requests.size() == 0) { requests.wait(INACTIVITY_TIMEOUT); } return requests.size() > 0; } } public void notifyNewRequest(Request request) { synchronized(requests) { if (requests.add(request)) { statistics.queueSize(requests.size()); requests.notify(); } else { statistics.duplicate(); statistics.providerHit(); } } } public String toString() { return "Turbo.PreparationTask queue=[" + requests +"]"; // NOI18N } } }
126156_0
public class ArchiveerContractUseCaseHandler implements UseCaseHandler<ArchiveerContractUseCase> { private readonly Mediator mediator; public ArchiveerContractUseCase(Mediator mediator) { this.mediator = mediator; } public void handle(RegistreerVerkoopUseCase useCase) { var aanvraag = mediator.ask(new GeefBorgstellingAanvraag(useCase.borgstellingId)); var maakContract = new MaakContract(); maakContract.BorgstellingId = aanvraag.BorgstellingId; maakContract.Kenmerk = aanvraag.Kenmerk; maakContractv.Bedrag = aanvraag.BrutoKredietsom; maakContract.Datum = new Date(); maakContract.EindDatum = port.Datum.plusMonths(36); maakContract.Kredietbank = aanvraag.Kredietbank; var contract = mediator.ask(maakContract); var archiveerDocument = new ArchiveerBorgstellingDocument(); archiveerDocument.DocumentId = useCase.ContractId; archiveerDocument.KredietbankId = aanvraag.KredietbankId; archiveerDocument.Onderwerp = String.format("Borgstelling contract %s met kenmerk %s.", aanvraag.BorgstellingId, aanvraag.Kenmerk); archiveerDocument.VerlooptOp = port.Datum.plusYears(7); archiveerDocument.Kenmerken = [ aanvraag.BorgstellingId, "Borgstelling contract", aanvraag.KredietbankId, aanvraag.Kenmerk ]; archiveerDocument.Bestand = new Bestand(); archiveerDocument.Bestand.Naam = String.format("borgstelling-contract-%s.pdf", aanvraag.BorgstellingId);; archiveerDocument.Bestand.Data = contract.toBase64String(); mediator.send(archiveerDocument); } } public class ExactService implements PortHandler<ArchiveerBorgstellingDocument> { private readonly ExactApi api; public ExactService(ExactApi api) { this.api = api; } public void handle(RegistreerVerkoop port) { var accountId = api.getAccountId(port.KredietbankId); const document = new Document(); document.ID = port.DocumentId; document.Account = accountId; document.Subject = port.Omschrijving; document.ExpiryDate = port.VerlooptOp; //TODO: uitzoeken hoe kenmerken toe te voegen? api.createDocument(document); const documentAttachment = new DocumentAttachment(); documentAttachment.Attachment = port.Bestand.Data; documentAttachment.Document = port.DocumentId; documentAttachment.FileName = port.Bestand.Naam; api.createDocumentAttachment(documentAttachment); } }
sbnnl/documentatie
docs/100_producten/100_borgstelling/010_aanvragen-borgstelling/010_afhandelen-aanvraag-borgstelling/ArchiveerContractUseCase.java
675
//TODO: uitzoeken hoe kenmerken toe te voegen?
line_comment
nl
public class ArchiveerContractUseCaseHandler implements UseCaseHandler<ArchiveerContractUseCase> { private readonly Mediator mediator; public ArchiveerContractUseCase(Mediator mediator) { this.mediator = mediator; } public void handle(RegistreerVerkoopUseCase useCase) { var aanvraag = mediator.ask(new GeefBorgstellingAanvraag(useCase.borgstellingId)); var maakContract = new MaakContract(); maakContract.BorgstellingId = aanvraag.BorgstellingId; maakContract.Kenmerk = aanvraag.Kenmerk; maakContractv.Bedrag = aanvraag.BrutoKredietsom; maakContract.Datum = new Date(); maakContract.EindDatum = port.Datum.plusMonths(36); maakContract.Kredietbank = aanvraag.Kredietbank; var contract = mediator.ask(maakContract); var archiveerDocument = new ArchiveerBorgstellingDocument(); archiveerDocument.DocumentId = useCase.ContractId; archiveerDocument.KredietbankId = aanvraag.KredietbankId; archiveerDocument.Onderwerp = String.format("Borgstelling contract %s met kenmerk %s.", aanvraag.BorgstellingId, aanvraag.Kenmerk); archiveerDocument.VerlooptOp = port.Datum.plusYears(7); archiveerDocument.Kenmerken = [ aanvraag.BorgstellingId, "Borgstelling contract", aanvraag.KredietbankId, aanvraag.Kenmerk ]; archiveerDocument.Bestand = new Bestand(); archiveerDocument.Bestand.Naam = String.format("borgstelling-contract-%s.pdf", aanvraag.BorgstellingId);; archiveerDocument.Bestand.Data = contract.toBase64String(); mediator.send(archiveerDocument); } } public class ExactService implements PortHandler<ArchiveerBorgstellingDocument> { private readonly ExactApi api; public ExactService(ExactApi api) { this.api = api; } public void handle(RegistreerVerkoop port) { var accountId = api.getAccountId(port.KredietbankId); const document = new Document(); document.ID = port.DocumentId; document.Account = accountId; document.Subject = port.Omschrijving; document.ExpiryDate = port.VerlooptOp; //TODO: uitzoeken<SUF> api.createDocument(document); const documentAttachment = new DocumentAttachment(); documentAttachment.Attachment = port.Bestand.Data; documentAttachment.Document = port.DocumentId; documentAttachment.FileName = port.Bestand.Naam; api.createDocumentAttachment(documentAttachment); } }
174705_13
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eclserver; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /** * * @author rbalsewich */ public class BESList extends JPanel implements ListSelectionListener { private JList list; private DefaultListModel listModel; private static final String addString = "+"; private static final String removeString = "-"; private JButton removeButton; private JTextField serverName; public BESList() { super(new BorderLayout()); listModel = new DefaultListModel(); listModel.addElement("TBD"); // listModel.addElement("server2:8080"); // listModel.addElement("server3:8080"); //Create the list and put it in a scroll pane. list = new JList(listModel); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectedIndex(0); list.addListSelectionListener(this); list.setVisibleRowCount(5); JScrollPane listScrollPane = new JScrollPane(list); JButton addButton = new JButton(addString); AddListener addListener = new AddListener(addButton); addButton.setActionCommand(addString); addButton.addActionListener(addListener); addButton.setEnabled(false); removeButton = new JButton(removeString); removeButton.setActionCommand(removeString); removeButton.addActionListener(new RemoveListener()); serverName = new JTextField(10); serverName.addActionListener(addListener); serverName.getDocument().addDocumentListener(addListener); String name = listModel.getElementAt( list.getSelectedIndex()).toString(); //Create a panel that uses BoxLayout. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.add(removeButton); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(new JSeparator(SwingConstants.VERTICAL)); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(serverName); buttonPane.add(addButton); buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); add(listScrollPane, BorderLayout.CENTER); add(buttonPane, BorderLayout.PAGE_END); } class RemoveListener implements ActionListener { public void actionPerformed(ActionEvent e) { //This method can be called only if //there's a valid selection //so go ahead and remove whatever's selected. int index = list.getSelectedIndex(); listModel.remove(index); int size = listModel.getSize(); if (size == 0) { //Nobody's left, disable remove. removeButton.setEnabled(false); } else { //Select an index. if (index == listModel.getSize()) { //removed item in last position index--; } list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } } } //This listener is shared by the text field and the add button. class AddListener implements ActionListener, DocumentListener { private boolean alreadyEnabled = false; private JButton button; public AddListener(JButton button) { this.button = button; } //Required by ActionListener. public void actionPerformed(ActionEvent e) { String name = serverName.getText(); //User didn't type in a unique name... if (name.equals("") || alreadyInList(name)) { Toolkit.getDefaultToolkit().beep(); serverName.requestFocusInWindow(); serverName.selectAll(); return; } int index = list.getSelectedIndex(); //get selected index if (index == -1) { //no selection, so insert at beginning index = 0; } else { //add after the selected item index++; } listModel.insertElementAt(serverName.getText(), index); //If we just wanted to add to the end, we'd do this: //listModel.addElement(serverName.getText()); //Reset the text field. serverName.requestFocusInWindow(); serverName.setText(""); //Select the new item and make it visible. list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } //This method tests for string equality. protected boolean alreadyInList(String name) { return listModel.contains(name.trim()); } //Required by DocumentListener. public void insertUpdate(DocumentEvent e) { enableButton(); } //Required by DocumentListener. public void removeUpdate(DocumentEvent e) { handleEmptyTextField(e); } //Required by DocumentListener. public void changedUpdate(DocumentEvent e) { if (!handleEmptyTextField(e)) { enableButton(); } } private void enableButton() { if (!alreadyEnabled) { button.setEnabled(true); } } private boolean handleEmptyTextField(DocumentEvent e) { if (e.getDocument().getLength() <= 0) { button.setEnabled(false); alreadyEnabled = false; return true; } return false; } } //This method is required by ListSelectionListener. public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (list.getSelectedIndex() == -1) { //No selection, disable fire button. removeButton.setEnabled(false); } else { //Selection, enable the fire button. removeButton.setEnabled(true); } } } }
jmutter/Enterprise-Application-Samples
CCA/Server/Java/ECLServer/src/eclserver/BESList.java
1,416
//get selected index
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eclserver; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /** * * @author rbalsewich */ public class BESList extends JPanel implements ListSelectionListener { private JList list; private DefaultListModel listModel; private static final String addString = "+"; private static final String removeString = "-"; private JButton removeButton; private JTextField serverName; public BESList() { super(new BorderLayout()); listModel = new DefaultListModel(); listModel.addElement("TBD"); // listModel.addElement("server2:8080"); // listModel.addElement("server3:8080"); //Create the list and put it in a scroll pane. list = new JList(listModel); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setSelectedIndex(0); list.addListSelectionListener(this); list.setVisibleRowCount(5); JScrollPane listScrollPane = new JScrollPane(list); JButton addButton = new JButton(addString); AddListener addListener = new AddListener(addButton); addButton.setActionCommand(addString); addButton.addActionListener(addListener); addButton.setEnabled(false); removeButton = new JButton(removeString); removeButton.setActionCommand(removeString); removeButton.addActionListener(new RemoveListener()); serverName = new JTextField(10); serverName.addActionListener(addListener); serverName.getDocument().addDocumentListener(addListener); String name = listModel.getElementAt( list.getSelectedIndex()).toString(); //Create a panel that uses BoxLayout. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.add(removeButton); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(new JSeparator(SwingConstants.VERTICAL)); buttonPane.add(Box.createHorizontalStrut(5)); buttonPane.add(serverName); buttonPane.add(addButton); buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); add(listScrollPane, BorderLayout.CENTER); add(buttonPane, BorderLayout.PAGE_END); } class RemoveListener implements ActionListener { public void actionPerformed(ActionEvent e) { //This method can be called only if //there's a valid selection //so go ahead and remove whatever's selected. int index = list.getSelectedIndex(); listModel.remove(index); int size = listModel.getSize(); if (size == 0) { //Nobody's left, disable remove. removeButton.setEnabled(false); } else { //Select an index. if (index == listModel.getSize()) { //removed item in last position index--; } list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } } } //This listener is shared by the text field and the add button. class AddListener implements ActionListener, DocumentListener { private boolean alreadyEnabled = false; private JButton button; public AddListener(JButton button) { this.button = button; } //Required by ActionListener. public void actionPerformed(ActionEvent e) { String name = serverName.getText(); //User didn't type in a unique name... if (name.equals("") || alreadyInList(name)) { Toolkit.getDefaultToolkit().beep(); serverName.requestFocusInWindow(); serverName.selectAll(); return; } int index = list.getSelectedIndex(); //get selected<SUF> if (index == -1) { //no selection, so insert at beginning index = 0; } else { //add after the selected item index++; } listModel.insertElementAt(serverName.getText(), index); //If we just wanted to add to the end, we'd do this: //listModel.addElement(serverName.getText()); //Reset the text field. serverName.requestFocusInWindow(); serverName.setText(""); //Select the new item and make it visible. list.setSelectedIndex(index); list.ensureIndexIsVisible(index); } //This method tests for string equality. protected boolean alreadyInList(String name) { return listModel.contains(name.trim()); } //Required by DocumentListener. public void insertUpdate(DocumentEvent e) { enableButton(); } //Required by DocumentListener. public void removeUpdate(DocumentEvent e) { handleEmptyTextField(e); } //Required by DocumentListener. public void changedUpdate(DocumentEvent e) { if (!handleEmptyTextField(e)) { enableButton(); } } private void enableButton() { if (!alreadyEnabled) { button.setEnabled(true); } } private boolean handleEmptyTextField(DocumentEvent e) { if (e.getDocument().getLength() <= 0) { button.setEnabled(false); alreadyEnabled = false; return true; } return false; } } //This method is required by ListSelectionListener. public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (list.getSelectedIndex() == -1) { //No selection, disable fire button. removeButton.setEnabled(false); } else { //Selection, enable the fire button. removeButton.setEnabled(true); } } } }
162837_9
package util.twitter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.regex.*; import java.util.Arrays; import java.util.List; import java.util.ArrayList; /** * Twokenize -- a tokenizer designed for Twitter text in English and some other European languages. * This is the Java version. If you want the old Python version, see: http://github.com/brendano/tweetmotif * * This tokenizer code has gone through a long history: * * (1) Brendan O'Connor wrote original version in Python, http://github.com/brendano/tweetmotif * TweetMotif: Exploratory Search and Topic Summarization for Twitter. * Brendan O'Connor, Michel Krieger, and David Ahn. * ICWSM-2010 (demo track), http://brenocon.com/oconnor_krieger_ahn.icwsm2010.tweetmotif.pdf * (2a) Kevin Gimpel and Daniel Mills modified it for POS tagging for the CMU ARK Twitter POS Tagger * (2b) Jason Baldridge and David Snyder ported it to Scala * (3) Brendan bugfixed the Scala port and merged with POS-specific changes * for the CMU ARK Twitter POS Tagger * (4) Tobi Owoputi ported it back to Java and added many improvements (2012-06) * * Current home is http://github.com/brendano/ark-tweet-nlp and http://www.ark.cs.cmu.edu/TweetNLP * * There have been at least 2 other Java ports, but they are not in the lineage for the code here. */ public class Twokenize { static Pattern Contractions = Pattern.compile("(?i)(\\w+)(n['’′]t|['’′]ve|['’′]ll|['’′]d|['’′]re|['’′]s|['’′]m)$"); static Pattern Whitespace = Pattern.compile("[\\s\\p{Zs}]+"); static String punctChars = "['\"“”‘’.?!…,:;]"; //static String punctSeq = punctChars+"+"; //'anthem'. => ' anthem '. static String punctSeq = "['\"“”‘’]+|[.?!,…]+|[:;]+"; //'anthem'. => ' anthem ' . static String entity = "&(?:amp|lt|gt|quot);"; // URLs // BTO 2012-06: everyone thinks the daringfireball regex should be better, but they're wrong. // If you actually empirically test it the results are bad. // Please see https://github.com/brendano/ark-tweet-nlp/pull/9 static String urlStart1 = "(?:https?://|\\bwww\\.)"; static String commonTLDs = "(?:com|org|edu|gov|net|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|pro|tel|travel|xxx)"; static String ccTLDs = "(?:ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|" + "bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|" + "er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|" + "hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|" + "lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|" + "nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|" + "sl|sm|sn|so|sr|ss|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|" + "va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)"; //TODO: remove obscure country domains? static String urlStart2 = "\\b(?:[A-Za-z\\d-])+(?:\\.[A-Za-z0-9]+){0,3}\\." + "(?:"+commonTLDs+"|"+ccTLDs+")"+"(?:\\."+ccTLDs+")?(?=\\W|$)"; static String urlBody = "(?:[^\\.\\s<>][^\\s<>]*?)?"; static String urlExtraCrapBeforeEnd = "(?:"+punctChars+"|"+entity+")+?"; static String urlEnd = "(?:\\.\\.+|[<>]|\\s|$)"; public static String url = "(?:"+urlStart1+"|"+urlStart2+")"+urlBody+"(?=(?:"+urlExtraCrapBeforeEnd+")?"+urlEnd+")"; // Numeric static String timeLike = "\\d+(?::\\d+){1,2}"; //static String numNum = "\\d+\\.\\d+"; static String numberWithCommas = "(?:(?<!\\d)\\d{1,3},)+?\\d{3}" + "(?=(?:[^,\\d]|$))"; static String numComb = "\\p{Sc}?\\d+(?:\\.\\d+)+%?"; // Abbreviations static String boundaryNotDot = "(?:$|\\s|[“\\u0022?!,:;]|" + entity + ")"; static String aa1 = "(?:[A-Za-z]\\.){2,}(?=" + boundaryNotDot + ")"; static String aa2 = "[^A-Za-z](?:[A-Za-z]\\.){1,}[A-Za-z](?=" + boundaryNotDot + ")"; static String standardAbbreviations = "\\b(?:[Mm]r|[Mm]rs|[Mm]s|[Dd]r|[Ss]r|[Jj]r|[Rr]ep|[Ss]en|[Ss]t)\\."; static String arbitraryAbbrev = "(?:" + aa1 +"|"+ aa2 + "|" + standardAbbreviations + ")"; static String separators = "(?:--+|―|—|~|–|=)"; static String decorations = "(?:[♫♪]+|[★☆]+|[♥❤♡]+|[\\u2639-\\u263b]+|[\\ue001-\\uebbb]+)"; static String thingsThatSplitWords = "[^\\s\\.,?\"]"; static String embeddedApostrophe = thingsThatSplitWords+"+['’′]" + thingsThatSplitWords + "*"; public static String OR(String... parts) { String prefix="(?:"; StringBuilder sb = new StringBuilder(); for (String s:parts){ sb.append(prefix); prefix="|"; sb.append(s); } sb.append(")"); return sb.toString(); } // Emoticons static String normalEyes = "(?iu)[:=]"; // 8 and x are eyes but cause problems static String wink = "[;]"; static String noseArea = "(?:|-|[^a-zA-Z0-9 ])"; // doesn't get :'-( static String happyMouths = "[D\\)\\]\\}]+"; static String sadMouths = "[\\(\\[\\{]+"; static String tongue = "[pPd3]+"; static String otherMouths = "(?:[oO]+|[/\\\\]+|[vV]+|[Ss]+|[|]+)"; // remove forward slash if http://'s aren't cleaned // mouth repetition examples: // @aliciakeys Put it in a love song :-)) // @hellocalyclops =))=))=)) Oh well static String bfLeft = "(♥|0|o|°|v|\\$|t|x|;|\\u0CA0|@|ʘ|•|・|◕|\\^|¬|\\*)"; static String bfCenter = "(?:[\\.]|[_-]+)"; static String bfRight = "\\2"; static String s3 = "(?:--['\"])"; static String s4 = "(?:<|&lt;|>|&gt;)[\\._-]+(?:<|&lt;|>|&gt;)"; static String s5 = "(?:[.][_]+[.])"; static String basicface = "(?:(?i)" +bfLeft+bfCenter+bfRight+ ")|" +s3+ "|" +s4+ "|" + s5; static String eeLeft = "[\\\\\ƪԄ\\((<>;ヽ\\-=~\\*]+"; static String eeRight= "[\\-=\\);'\\u0022<>ʃ)//ノノ丿╯σっµ~\\*]+"; static String eeSymbol = "[^A-Za-z0-9\\s\\(\\)\\*:=-]"; static String eastEmote = eeLeft + "(?:"+basicface+"|" +eeSymbol+")+" + eeRight; public static String emoticon = OR( // Standard version :) :( :] :D :P "(?:>|&gt;)?" + OR(normalEyes, wink) + OR(noseArea,"[Oo]") + OR(tongue+"(?=\\W|$|RT|rt|Rt)", otherMouths+"(?=\\W|$|RT|rt|Rt)", sadMouths, happyMouths), // reversed version (: D: use positive lookbehind to remove "(word):" // because eyes on the right side is more ambiguous with the standard usage of : ; "(?<=(?: |^))" + OR(sadMouths,happyMouths,otherMouths) + noseArea + OR(normalEyes, wink) + "(?:<|&lt;)?", //inspired by http://en.wikipedia.org/wiki/User:Scapler/emoticons#East_Asian_style eastEmote.replaceFirst("2", "1"), basicface // iOS 'emoji' characters (some smileys, some symbols) [\ue001-\uebbb] // TODO should try a big precompiled lexicon from Wikipedia, Dan Ramage told me (BTO) he does this ); static String Hearts = "(?:<+/?3+)+"; //the other hearts are in decorations static String Arrows = "(?:<*[-―—=]*>+|<+[-―—=]*>*)|\\p{InArrows}+"; // BTO 2011-06: restored Hashtag, AtMention protection (dropped in original scala port) because it fixes // "hello (#hashtag)" ==> "hello (#hashtag )" WRONG // "hello (#hashtag)" ==> "hello ( #hashtag )" RIGHT // "hello (@person)" ==> "hello (@person )" WRONG // "hello (@person)" ==> "hello ( @person )" RIGHT // ... Some sort of weird interaction with edgepunct I guess, because edgepunct // has poor content-symbol detection. // This also gets #1 #40 which probably aren't hashtags .. but good as tokens. // If you want good hashtag identification, use a different regex. static String Hashtag = "#[a-zA-Z0-9_]+"; //optional: lookbehind for \b //optional: lookbehind for \b, max length 15 static String AtMention = "[@@][a-zA-Z0-9_]+"; // I was worried this would conflict with at-mentions // but seems ok in sample of 5800: 7 changes all email fixes // http://www.regular-expressions.info/email.html static String Bound = "(?:\\W|^|$)"; public static String Email = "(?<=" +Bound+ ")[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}(?=" +Bound+")"; // We will be tokenizing using these regexps as delimiters // Additionally, these things are "protected", meaning they shouldn't be further split themselves. static Pattern Protected = Pattern.compile( OR( Hearts, url, Email, timeLike, //numNum, numberWithCommas, numComb, emoticon, Arrows, entity, punctSeq, arbitraryAbbrev, separators, decorations, embeddedApostrophe, Hashtag, AtMention )); // Edge punctuation // Want: 'foo' => ' foo ' // While also: don't => don't // the first is considered "edge punctuation". // the second is word-internal punctuation -- don't want to mess with it. // BTO (2011-06): the edgepunct system seems to be the #1 source of problems these days. // I remember it causing lots of trouble in the past as well. Would be good to revisit or eliminate. // Note the 'smart quotes' (http://en.wikipedia.org/wiki/Smart_quotes) static String edgePunctChars = "'\"“”‘’«»{}\\(\\)\\[\\]\\*&"; //add \\p{So}? (symbols) static String edgePunct = "[" + edgePunctChars + "]"; static String notEdgePunct = "[a-zA-Z0-9]"; // content characters static String offEdge = "(^|$|:|;|\\s|\\.|,)"; // colon here gets "(hello):" ==> "( hello ):" static Pattern EdgePunctLeft = Pattern.compile(offEdge + "("+edgePunct+"+)("+notEdgePunct+")"); static Pattern EdgePunctRight = Pattern.compile("("+notEdgePunct+")("+edgePunct+"+)" + offEdge); public static String splitEdgePunct (String input) { Matcher m1 = EdgePunctLeft.matcher(input); input = m1.replaceAll("$1$2 $3"); m1 = EdgePunctRight.matcher(input); input = m1.replaceAll("$1 $2$3"); return input; } private static class Pair<T1, T2> { public T1 first; public T2 second; public Pair(T1 x, T2 y) { first=x; second=y; } } // The main work of tokenizing a tweet. private static List<String> simpleTokenize (String text) { // Do the no-brainers first String splitPunctText = splitEdgePunct(text); int textLength = splitPunctText.length(); // BTO: the logic here got quite convoluted via the Scala porting detour // It would be good to switch back to a nice simple procedural style like in the Python version // ... Scala is such a pain. Never again. // Find the matches for subsequences that should be protected, // e.g. URLs, 1.0, U.N.K.L.E., 12:53 Matcher matches = Protected.matcher(splitPunctText); //Storing as List[List[String]] to make zip easier later on List<List<String>> bads = new ArrayList<List<String>>(); //linked list? List<Pair<Integer,Integer>> badSpans = new ArrayList<Pair<Integer,Integer>>(); while(matches.find()){ // The spans of the "bads" should not be split. if (matches.start() != matches.end()){ //unnecessary? List<String> bad = new ArrayList<String>(1); bad.add(splitPunctText.substring(matches.start(),matches.end())); bads.add(bad); badSpans.add(new Pair<Integer, Integer>(matches.start(),matches.end())); } } // Create a list of indices to create the "goods", which can be // split. We are taking "bad" spans like // List((2,5), (8,10)) // to create /// List(0, 2, 5, 8, 10, 12) // where, e.g., "12" here would be the textLength // has an even length and no indices are the same List<Integer> indices = new ArrayList<Integer>(2+2*badSpans.size()); indices.add(0); for(Pair<Integer,Integer> p:badSpans){ indices.add(p.first); indices.add(p.second); } indices.add(textLength); // Group the indices and map them to their respective portion of the string List<List<String>> splitGoods = new ArrayList<List<String>>(indices.size()/2); for (int i=0; i<indices.size(); i+=2) { String goodstr = splitPunctText.substring(indices.get(i),indices.get(i+1)); List<String> splitstr = Arrays.asList(goodstr.trim().split(" ")); splitGoods.add(splitstr); } // Reinterpolate the 'good' and 'bad' Lists, ensuring that // additonal tokens from last good item get included List<String> zippedStr= new ArrayList<String>(); int i; for(i=0; i < bads.size(); i++) { zippedStr = addAllnonempty(zippedStr,splitGoods.get(i)); zippedStr = addAllnonempty(zippedStr,bads.get(i)); } zippedStr = addAllnonempty(zippedStr,splitGoods.get(i)); // BTO: our POS tagger wants "ur" and "you're" to both be one token. // Uncomment to get "you 're" /*ArrayList<String> splitStr = new ArrayList<String>(zippedStr.size()); for(String tok:zippedStr) splitStr.addAll(splitToken(tok)); zippedStr=splitStr;*/ return zippedStr; } private static List<String> addAllnonempty(List<String> master, List<String> smaller){ for (String s : smaller){ String strim = s.trim(); if (strim.length() > 0) master.add(strim); } return master; } /** "foo bar " => "foo bar" */ public static String squeezeWhitespace (String input){ return Whitespace.matcher(input).replaceAll(" ").trim(); } // Final pass tokenization based on special patterns private static List<String> splitToken (String token) { Matcher m = Contractions.matcher(token); if (m.find()){ String[] contract = {m.group(1), m.group(2)}; return Arrays.asList(contract); } String[] contract = {token}; return Arrays.asList(contract); } /** Assume 'text' has no HTML escaping. **/ public static List<String> tokenize(String text){ return simpleTokenize(squeezeWhitespace(text)); } }
wlin12/JNN
src/util/twitter/Twokenize.java
4,875
// doesn't get :'-(
line_comment
nl
package util.twitter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.regex.*; import java.util.Arrays; import java.util.List; import java.util.ArrayList; /** * Twokenize -- a tokenizer designed for Twitter text in English and some other European languages. * This is the Java version. If you want the old Python version, see: http://github.com/brendano/tweetmotif * * This tokenizer code has gone through a long history: * * (1) Brendan O'Connor wrote original version in Python, http://github.com/brendano/tweetmotif * TweetMotif: Exploratory Search and Topic Summarization for Twitter. * Brendan O'Connor, Michel Krieger, and David Ahn. * ICWSM-2010 (demo track), http://brenocon.com/oconnor_krieger_ahn.icwsm2010.tweetmotif.pdf * (2a) Kevin Gimpel and Daniel Mills modified it for POS tagging for the CMU ARK Twitter POS Tagger * (2b) Jason Baldridge and David Snyder ported it to Scala * (3) Brendan bugfixed the Scala port and merged with POS-specific changes * for the CMU ARK Twitter POS Tagger * (4) Tobi Owoputi ported it back to Java and added many improvements (2012-06) * * Current home is http://github.com/brendano/ark-tweet-nlp and http://www.ark.cs.cmu.edu/TweetNLP * * There have been at least 2 other Java ports, but they are not in the lineage for the code here. */ public class Twokenize { static Pattern Contractions = Pattern.compile("(?i)(\\w+)(n['’′]t|['’′]ve|['’′]ll|['’′]d|['’′]re|['’′]s|['’′]m)$"); static Pattern Whitespace = Pattern.compile("[\\s\\p{Zs}]+"); static String punctChars = "['\"“”‘’.?!…,:;]"; //static String punctSeq = punctChars+"+"; //'anthem'. => ' anthem '. static String punctSeq = "['\"“”‘’]+|[.?!,…]+|[:;]+"; //'anthem'. => ' anthem ' . static String entity = "&(?:amp|lt|gt|quot);"; // URLs // BTO 2012-06: everyone thinks the daringfireball regex should be better, but they're wrong. // If you actually empirically test it the results are bad. // Please see https://github.com/brendano/ark-tweet-nlp/pull/9 static String urlStart1 = "(?:https?://|\\bwww\\.)"; static String commonTLDs = "(?:com|org|edu|gov|net|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|pro|tel|travel|xxx)"; static String ccTLDs = "(?:ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|" + "bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|" + "er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|" + "hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|" + "lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|" + "nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|" + "sl|sm|sn|so|sr|ss|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|" + "va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)"; //TODO: remove obscure country domains? static String urlStart2 = "\\b(?:[A-Za-z\\d-])+(?:\\.[A-Za-z0-9]+){0,3}\\." + "(?:"+commonTLDs+"|"+ccTLDs+")"+"(?:\\."+ccTLDs+")?(?=\\W|$)"; static String urlBody = "(?:[^\\.\\s<>][^\\s<>]*?)?"; static String urlExtraCrapBeforeEnd = "(?:"+punctChars+"|"+entity+")+?"; static String urlEnd = "(?:\\.\\.+|[<>]|\\s|$)"; public static String url = "(?:"+urlStart1+"|"+urlStart2+")"+urlBody+"(?=(?:"+urlExtraCrapBeforeEnd+")?"+urlEnd+")"; // Numeric static String timeLike = "\\d+(?::\\d+){1,2}"; //static String numNum = "\\d+\\.\\d+"; static String numberWithCommas = "(?:(?<!\\d)\\d{1,3},)+?\\d{3}" + "(?=(?:[^,\\d]|$))"; static String numComb = "\\p{Sc}?\\d+(?:\\.\\d+)+%?"; // Abbreviations static String boundaryNotDot = "(?:$|\\s|[“\\u0022?!,:;]|" + entity + ")"; static String aa1 = "(?:[A-Za-z]\\.){2,}(?=" + boundaryNotDot + ")"; static String aa2 = "[^A-Za-z](?:[A-Za-z]\\.){1,}[A-Za-z](?=" + boundaryNotDot + ")"; static String standardAbbreviations = "\\b(?:[Mm]r|[Mm]rs|[Mm]s|[Dd]r|[Ss]r|[Jj]r|[Rr]ep|[Ss]en|[Ss]t)\\."; static String arbitraryAbbrev = "(?:" + aa1 +"|"+ aa2 + "|" + standardAbbreviations + ")"; static String separators = "(?:--+|―|—|~|–|=)"; static String decorations = "(?:[♫♪]+|[★☆]+|[♥❤♡]+|[\\u2639-\\u263b]+|[\\ue001-\\uebbb]+)"; static String thingsThatSplitWords = "[^\\s\\.,?\"]"; static String embeddedApostrophe = thingsThatSplitWords+"+['’′]" + thingsThatSplitWords + "*"; public static String OR(String... parts) { String prefix="(?:"; StringBuilder sb = new StringBuilder(); for (String s:parts){ sb.append(prefix); prefix="|"; sb.append(s); } sb.append(")"); return sb.toString(); } // Emoticons static String normalEyes = "(?iu)[:=]"; // 8 and x are eyes but cause problems static String wink = "[;]"; static String noseArea = "(?:|-|[^a-zA-Z0-9 ])"; // doesn't get<SUF> static String happyMouths = "[D\\)\\]\\}]+"; static String sadMouths = "[\\(\\[\\{]+"; static String tongue = "[pPd3]+"; static String otherMouths = "(?:[oO]+|[/\\\\]+|[vV]+|[Ss]+|[|]+)"; // remove forward slash if http://'s aren't cleaned // mouth repetition examples: // @aliciakeys Put it in a love song :-)) // @hellocalyclops =))=))=)) Oh well static String bfLeft = "(♥|0|o|°|v|\\$|t|x|;|\\u0CA0|@|ʘ|•|・|◕|\\^|¬|\\*)"; static String bfCenter = "(?:[\\.]|[_-]+)"; static String bfRight = "\\2"; static String s3 = "(?:--['\"])"; static String s4 = "(?:<|&lt;|>|&gt;)[\\._-]+(?:<|&lt;|>|&gt;)"; static String s5 = "(?:[.][_]+[.])"; static String basicface = "(?:(?i)" +bfLeft+bfCenter+bfRight+ ")|" +s3+ "|" +s4+ "|" + s5; static String eeLeft = "[\\\\\ƪԄ\\((<>;ヽ\\-=~\\*]+"; static String eeRight= "[\\-=\\);'\\u0022<>ʃ)//ノノ丿╯σっµ~\\*]+"; static String eeSymbol = "[^A-Za-z0-9\\s\\(\\)\\*:=-]"; static String eastEmote = eeLeft + "(?:"+basicface+"|" +eeSymbol+")+" + eeRight; public static String emoticon = OR( // Standard version :) :( :] :D :P "(?:>|&gt;)?" + OR(normalEyes, wink) + OR(noseArea,"[Oo]") + OR(tongue+"(?=\\W|$|RT|rt|Rt)", otherMouths+"(?=\\W|$|RT|rt|Rt)", sadMouths, happyMouths), // reversed version (: D: use positive lookbehind to remove "(word):" // because eyes on the right side is more ambiguous with the standard usage of : ; "(?<=(?: |^))" + OR(sadMouths,happyMouths,otherMouths) + noseArea + OR(normalEyes, wink) + "(?:<|&lt;)?", //inspired by http://en.wikipedia.org/wiki/User:Scapler/emoticons#East_Asian_style eastEmote.replaceFirst("2", "1"), basicface // iOS 'emoji' characters (some smileys, some symbols) [\ue001-\uebbb] // TODO should try a big precompiled lexicon from Wikipedia, Dan Ramage told me (BTO) he does this ); static String Hearts = "(?:<+/?3+)+"; //the other hearts are in decorations static String Arrows = "(?:<*[-―—=]*>+|<+[-―—=]*>*)|\\p{InArrows}+"; // BTO 2011-06: restored Hashtag, AtMention protection (dropped in original scala port) because it fixes // "hello (#hashtag)" ==> "hello (#hashtag )" WRONG // "hello (#hashtag)" ==> "hello ( #hashtag )" RIGHT // "hello (@person)" ==> "hello (@person )" WRONG // "hello (@person)" ==> "hello ( @person )" RIGHT // ... Some sort of weird interaction with edgepunct I guess, because edgepunct // has poor content-symbol detection. // This also gets #1 #40 which probably aren't hashtags .. but good as tokens. // If you want good hashtag identification, use a different regex. static String Hashtag = "#[a-zA-Z0-9_]+"; //optional: lookbehind for \b //optional: lookbehind for \b, max length 15 static String AtMention = "[@@][a-zA-Z0-9_]+"; // I was worried this would conflict with at-mentions // but seems ok in sample of 5800: 7 changes all email fixes // http://www.regular-expressions.info/email.html static String Bound = "(?:\\W|^|$)"; public static String Email = "(?<=" +Bound+ ")[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}(?=" +Bound+")"; // We will be tokenizing using these regexps as delimiters // Additionally, these things are "protected", meaning they shouldn't be further split themselves. static Pattern Protected = Pattern.compile( OR( Hearts, url, Email, timeLike, //numNum, numberWithCommas, numComb, emoticon, Arrows, entity, punctSeq, arbitraryAbbrev, separators, decorations, embeddedApostrophe, Hashtag, AtMention )); // Edge punctuation // Want: 'foo' => ' foo ' // While also: don't => don't // the first is considered "edge punctuation". // the second is word-internal punctuation -- don't want to mess with it. // BTO (2011-06): the edgepunct system seems to be the #1 source of problems these days. // I remember it causing lots of trouble in the past as well. Would be good to revisit or eliminate. // Note the 'smart quotes' (http://en.wikipedia.org/wiki/Smart_quotes) static String edgePunctChars = "'\"“”‘’«»{}\\(\\)\\[\\]\\*&"; //add \\p{So}? (symbols) static String edgePunct = "[" + edgePunctChars + "]"; static String notEdgePunct = "[a-zA-Z0-9]"; // content characters static String offEdge = "(^|$|:|;|\\s|\\.|,)"; // colon here gets "(hello):" ==> "( hello ):" static Pattern EdgePunctLeft = Pattern.compile(offEdge + "("+edgePunct+"+)("+notEdgePunct+")"); static Pattern EdgePunctRight = Pattern.compile("("+notEdgePunct+")("+edgePunct+"+)" + offEdge); public static String splitEdgePunct (String input) { Matcher m1 = EdgePunctLeft.matcher(input); input = m1.replaceAll("$1$2 $3"); m1 = EdgePunctRight.matcher(input); input = m1.replaceAll("$1 $2$3"); return input; } private static class Pair<T1, T2> { public T1 first; public T2 second; public Pair(T1 x, T2 y) { first=x; second=y; } } // The main work of tokenizing a tweet. private static List<String> simpleTokenize (String text) { // Do the no-brainers first String splitPunctText = splitEdgePunct(text); int textLength = splitPunctText.length(); // BTO: the logic here got quite convoluted via the Scala porting detour // It would be good to switch back to a nice simple procedural style like in the Python version // ... Scala is such a pain. Never again. // Find the matches for subsequences that should be protected, // e.g. URLs, 1.0, U.N.K.L.E., 12:53 Matcher matches = Protected.matcher(splitPunctText); //Storing as List[List[String]] to make zip easier later on List<List<String>> bads = new ArrayList<List<String>>(); //linked list? List<Pair<Integer,Integer>> badSpans = new ArrayList<Pair<Integer,Integer>>(); while(matches.find()){ // The spans of the "bads" should not be split. if (matches.start() != matches.end()){ //unnecessary? List<String> bad = new ArrayList<String>(1); bad.add(splitPunctText.substring(matches.start(),matches.end())); bads.add(bad); badSpans.add(new Pair<Integer, Integer>(matches.start(),matches.end())); } } // Create a list of indices to create the "goods", which can be // split. We are taking "bad" spans like // List((2,5), (8,10)) // to create /// List(0, 2, 5, 8, 10, 12) // where, e.g., "12" here would be the textLength // has an even length and no indices are the same List<Integer> indices = new ArrayList<Integer>(2+2*badSpans.size()); indices.add(0); for(Pair<Integer,Integer> p:badSpans){ indices.add(p.first); indices.add(p.second); } indices.add(textLength); // Group the indices and map them to their respective portion of the string List<List<String>> splitGoods = new ArrayList<List<String>>(indices.size()/2); for (int i=0; i<indices.size(); i+=2) { String goodstr = splitPunctText.substring(indices.get(i),indices.get(i+1)); List<String> splitstr = Arrays.asList(goodstr.trim().split(" ")); splitGoods.add(splitstr); } // Reinterpolate the 'good' and 'bad' Lists, ensuring that // additonal tokens from last good item get included List<String> zippedStr= new ArrayList<String>(); int i; for(i=0; i < bads.size(); i++) { zippedStr = addAllnonempty(zippedStr,splitGoods.get(i)); zippedStr = addAllnonempty(zippedStr,bads.get(i)); } zippedStr = addAllnonempty(zippedStr,splitGoods.get(i)); // BTO: our POS tagger wants "ur" and "you're" to both be one token. // Uncomment to get "you 're" /*ArrayList<String> splitStr = new ArrayList<String>(zippedStr.size()); for(String tok:zippedStr) splitStr.addAll(splitToken(tok)); zippedStr=splitStr;*/ return zippedStr; } private static List<String> addAllnonempty(List<String> master, List<String> smaller){ for (String s : smaller){ String strim = s.trim(); if (strim.length() > 0) master.add(strim); } return master; } /** "foo bar " => "foo bar" */ public static String squeezeWhitespace (String input){ return Whitespace.matcher(input).replaceAll(" ").trim(); } // Final pass tokenization based on special patterns private static List<String> splitToken (String token) { Matcher m = Contractions.matcher(token); if (m.find()){ String[] contract = {m.group(1), m.group(2)}; return Arrays.asList(contract); } String[] contract = {token}; return Arrays.asList(contract); } /** Assume 'text' has no HTML escaping. **/ public static List<String> tokenize(String text){ return simpleTokenize(squeezeWhitespace(text)); } }
151635_0
package mthread; public class SynchronizeFbLike { public static void main( String[] args ) { /* Facebook Page: Everest, Current Likes: 500 */ final FacebookLike everestFbPagePiclike = new FacebookLike( 500 ); Thread user1 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user2 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user3 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user4 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; /* User1,2,3,4 hit like button in Everest Facebook Page */ user1.start( ); user2.start( ); user3.start( ); user4.start( ); } }
yrojha4ever/JavaStud
src/mthread/SynchronizeFbLike.java
283
/* Facebook Page: Everest, Current Likes: 500 */
block_comment
nl
package mthread; public class SynchronizeFbLike { public static void main( String[] args ) { /* Facebook Page: Everest,<SUF>*/ final FacebookLike everestFbPagePiclike = new FacebookLike( 500 ); Thread user1 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user2 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user3 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; Thread user4 = new Thread( ) { public void run( ) { everestFbPagePiclike.plusOne( ); } }; /* User1,2,3,4 hit like button in Everest Facebook Page */ user1.start( ); user2.start( ); user3.start( ); user4.start( ); } }
204413_45
/* * Copyright (c) 2016 Martin Davis. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.locationtech.jts.operation.buffer; import org.locationtech.jts.algorithm.Angle; import org.locationtech.jts.algorithm.HCoordinate; import org.locationtech.jts.algorithm.Intersection; import org.locationtech.jts.algorithm.LineIntersector; import org.locationtech.jts.algorithm.NotRepresentableException; import org.locationtech.jts.algorithm.Orientation; import org.locationtech.jts.algorithm.RobustLineIntersector; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.LineSegment; import org.locationtech.jts.geom.PrecisionModel; import org.locationtech.jts.geomgraph.Position; /** * Generates segments which form an offset curve. * Supports all end cap and join options * provided for buffering. * This algorithm implements various heuristics to * produce smoother, simpler curves which are * still within a reasonable tolerance of the * true curve. * * @author Martin Davis * */ class OffsetSegmentGenerator { /** * Factor which controls how close offset segments can be to * skip adding a filler or mitre. */ private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices on inside turns can be to be snapped */ private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices can be to be snapped */ private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6; /** * Factor which determines how short closing segs can be for round buffers */ private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80; /** * the max error of approximation (distance) between a quad segment and the true fillet curve */ private double maxCurveSegmentError = 0.0; /** * The angle quantum with which to approximate a fillet curve * (based on the input # of quadrant segments) */ private double filletAngleQuantum; /** * The Closing Segment Length Factor controls how long * "closing segments" are. Closing segments are added * at the middle of inside corners to ensure a smoother * boundary for the buffer offset curve. * In some cases (particularly for round joins with default-or-better * quantization) the closing segments can be made quite short. * This substantially improves performance (due to fewer intersections being created). * * A closingSegFactor of 0 results in lines to the corner vertex * A closingSegFactor of 1 results in lines halfway to the corner vertex * A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex * (this option is reasonable for the very common default situation of round joins * and quadrantSegs >= 8) */ private int closingSegLengthFactor = 1; private OffsetSegmentString segList; private double distance = 0.0; private PrecisionModel precisionModel; private BufferParameters bufParams; private LineIntersector li; private Coordinate s0, s1, s2; private LineSegment seg0 = new LineSegment(); private LineSegment seg1 = new LineSegment(); private LineSegment offset0 = new LineSegment(); private LineSegment offset1 = new LineSegment(); private int side = 0; private boolean hasNarrowConcaveAngle = false; public OffsetSegmentGenerator(PrecisionModel precisionModel, BufferParameters bufParams, double distance) { this.precisionModel = precisionModel; this.bufParams = bufParams; // compute intersections in full precision, to provide accuracy // the points are rounded as they are inserted into the curve line li = new RobustLineIntersector(); filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments(); /** * Non-round joins cause issues with short closing segments, so don't use * them. In any case, non-round joins only really make sense for relatively * small buffer distances. */ if (bufParams.getQuadrantSegments() >= 8 && bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR; init(distance); } /** * Tests whether the input has a narrow concave angle * (relative to the offset distance). * In this case the generated offset curve will contain self-intersections * and heuristic closing segments. * This is expected behaviour in the case of Buffer curves. * For pure Offset Curves, * the output needs to be further treated * before it can be used. * * @return true if the input has a narrow concave angle */ public boolean hasNarrowConcaveAngle() { return hasNarrowConcaveAngle; } private void init(double distance) { this.distance = distance; maxCurveSegmentError = distance * (1 - Math.cos(filletAngleQuantum / 2.0)); segList = new OffsetSegmentString(); segList.setPrecisionModel(precisionModel); /** * Choose the min vertex separation as a small fraction of the offset distance. */ segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR); } public void initSideSegments(Coordinate s1, Coordinate s2, int side) { this.s1 = s1; this.s2 = s2; this.side = side; seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); } public Coordinate[] getCoordinates() { Coordinate[] pts = segList.getCoordinates(); return pts; } public void closeRing() { segList.closeRing(); } public void addSegments(Coordinate[] pt, boolean isForward) { segList.addPts(pt, isForward); } public void addFirstSegment() { segList.addPt(offset1.p0); } /** * Add last offset point */ public void addLastSegment() { segList.addPt(offset1.p1); } //private static double MAX_CLOSING_SEG_LEN = 3.0; public void addNextSegment(Coordinate p, boolean addStartPoint) { // s0-s1-s2 are the coordinates of the previous segment and the current one s0 = s1; s1 = s2; s2 = p; seg0.setCoordinates(s0, s1); computeOffsetSegment(seg0, side, distance, offset0); seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); // do nothing if points are equal if (s1.equals(s2)) return; int orientation = Orientation.index(s0, s1, s2); boolean outsideTurn = (orientation == Orientation.CLOCKWISE && side == Position.LEFT) || (orientation == Orientation.COUNTERCLOCKWISE && side == Position.RIGHT); if (orientation == 0) { // lines are collinear addCollinear(addStartPoint); } else if (outsideTurn) { addOutsideTurn(orientation, addStartPoint); } else { // inside turn addInsideTurn(orientation, addStartPoint); } } private void addCollinear(boolean addStartPoint) { /** * This test could probably be done more efficiently, * but the situation of exact collinearity should be fairly rare. */ li.computeIntersection(s0, s1, s1, s2); int numInt = li.getIntersectionNum(); /** * if numInt is < 2, the lines are parallel and in the same direction. In * this case the point can be ignored, since the offset lines will also be * parallel. */ if (numInt >= 2) { /** * segments are collinear but reversing. * Add an "end-cap" fillet * all the way around to other direction This case should ONLY happen * for LineStrings, so the orientation is always CW. (Polygons can never * have two consecutive segments which are parallel but reversed, * because that would be a self intersection. * */ if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL || bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { if (addStartPoint) segList.addPt(offset0.p1); segList.addPt(offset1.p0); } else { addCornerFillet(s1, offset0.p1, offset1.p0, Orientation.CLOCKWISE, distance); } } } /** * Adds the offset points for an outside (convex) turn * * @param orientation * @param addStartPoint */ private void addOutsideTurn(int orientation, boolean addStartPoint) { /** * Heuristic: If offset endpoints are very close together, * just use one of them as the corner vertex. * This avoids problems with computing mitre corners in the case * where the two segments are almost parallel * (which is hard to compute a robust intersection for). */ if (offset0.p1.distance(offset1.p0) < distance * OFFSET_SEGMENT_SEPARATION_FACTOR) { segList.addPt(offset0.p1); return; } if (bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { addMitreJoin(s1, offset0, offset1, distance); } else if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL){ addBevelJoin(offset0, offset1); } else { // add a circular fillet connecting the endpoints of the offset segments if (addStartPoint) segList.addPt(offset0.p1); // TESTING - comment out to produce beveled joins addCornerFillet(s1, offset0.p1, offset1.p0, orientation, distance); segList.addPt(offset1.p0); } } /** * Adds the offset points for an inside (concave) turn. * * @param orientation * @param addStartPoint */ private void addInsideTurn(int orientation, boolean addStartPoint) { /** * add intersection point of offset segments (if any) */ li.computeIntersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (li.hasIntersection()) { segList.addPt(li.getIntersection(0)); } else { /** * If no intersection is detected, * it means the angle is so small and/or the offset so * large that the offsets segments don't intersect. * In this case we must * add a "closing segment" to make sure the buffer curve is continuous, * fairly smooth (e.g. no sharp reversals in direction) * and tracks the buffer correctly around the corner. The curve connects * the endpoints of the segment offsets to points * which lie toward the centre point of the corner. * The joining curve will not appear in the final buffer outline, since it * is completely internal to the buffer polygon. * * In complex buffer cases the closing segment may cut across many other * segments in the generated offset curve. In order to improve the * performance of the noding, the closing segment should be kept as short as possible. * (But not too short, since that would defeat its purpose). * This is the purpose of the closingSegFactor heuristic value. */ /** * The intersection test above is vulnerable to robustness errors; i.e. it * may be that the offsets should intersect very close to their endpoints, * but aren't reported as such due to rounding. To handle this situation * appropriately, we use the following test: If the offset points are very * close, don't add closing segments but simply use one of the offset * points */ hasNarrowConcaveAngle = true; //System.out.println("NARROW ANGLE - distance = " + distance); if (offset0.p1.distance(offset1.p0) < distance * INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) { segList.addPt(offset0.p1); } else { // add endpoint of this segment offset segList.addPt(offset0.p1); /** * Add "closing segment" of required length. */ if (closingSegLengthFactor > 0) { Coordinate mid0 = new Coordinate((closingSegLengthFactor * offset0.p1.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset0.p1.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid0); Coordinate mid1 = new Coordinate((closingSegLengthFactor*offset1.p0.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset1.p0.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid1); } else { /** * This branch is not expected to be used except for testing purposes. * It is equivalent to the JTS 1.9 logic for closing segments * (which results in very poor performance for large buffer distances) */ segList.addPt(s1); } //*/ // add start point of next segment offset segList.addPt(offset1.p0); } } } /** * Compute an offset segment for an input segment on a given side and at a given distance. * The offset points are computed in full double precision, for accuracy. * * @param seg the segment to offset * @param side the side of the segment ({@link Position}) the offset lies on * @param distance the offset distance * @param offset the points computed for the offset segment */ private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) { int sideSign = side == Position.LEFT ? 1 : -1; double dx = seg.p1.x - seg.p0.x; double dy = seg.p1.y - seg.p0.y; double len = Math.sqrt(dx * dx + dy * dy); // u is the vector that is the length of the offset, in the direction of the segment double ux = sideSign * distance * dx / len; double uy = sideSign * distance * dy / len; offset.p0.x = seg.p0.x - uy; offset.p0.y = seg.p0.y + ux; offset.p1.x = seg.p1.x - uy; offset.p1.y = seg.p1.y + ux; } /** * Add an end cap around point p1, terminating a line segment coming from p0 */ public void addLineEndCap(Coordinate p0, Coordinate p1) { LineSegment seg = new LineSegment(p0, p1); LineSegment offsetL = new LineSegment(); computeOffsetSegment(seg, Position.LEFT, distance, offsetL); LineSegment offsetR = new LineSegment(); computeOffsetSegment(seg, Position.RIGHT, distance, offsetR); double dx = p1.x - p0.x; double dy = p1.y - p0.y; double angle = Math.atan2(dy, dx); switch (bufParams.getEndCapStyle()) { case BufferParameters.CAP_ROUND: // add offset seg points with a fillet between them segList.addPt(offsetL.p1); addDirectedFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, Orientation.CLOCKWISE, distance); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_FLAT: // only offset segment points are added segList.addPt(offsetL.p1); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_SQUARE: // add a square defined by extensions of the offset segment endpoints Coordinate squareCapSideOffset = new Coordinate(); squareCapSideOffset.x = Math.abs(distance) * Math.cos(angle); squareCapSideOffset.y = Math.abs(distance) * Math.sin(angle); Coordinate squareCapLOffset = new Coordinate( offsetL.p1.x + squareCapSideOffset.x, offsetL.p1.y + squareCapSideOffset.y); Coordinate squareCapROffset = new Coordinate( offsetR.p1.x + squareCapSideOffset.x, offsetR.p1.y + squareCapSideOffset.y); segList.addPt(squareCapLOffset); segList.addPt(squareCapROffset); break; } } /** * Adds a mitre join connecting the two reflex offset segments. * The mitre will be beveled if it exceeds the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance */ private void addMitreJoin(Coordinate p, LineSegment offset0, LineSegment offset1, double distance) { /** * This computation is unstable if the offset segments are nearly collinear. * However, this situation should have been eliminated earlier by the check * for whether the offset segment endpoints are almost coincident */ Coordinate intPt = Intersection.intersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (intPt != null) { double mitreRatio = distance <= 0.0 ? 1.0 : intPt.distance(p) / Math.abs(distance); if (mitreRatio <= bufParams.getMitreLimit()) { segList.addPt(intPt); return; } } // at this point either intersection failed or mitre limit was exceeded addLimitedMitreJoin(offset0, offset1, distance, bufParams.getMitreLimit()); // addBevelJoin(offset0, offset1); } /** * Adds a limited mitre join connecting the two reflex offset segments. * A limited mitre is a mitre which is beveled at the distance * determined by the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance * @param mitreLimit the mitre limit ratio */ private void addLimitedMitreJoin( LineSegment offset0, LineSegment offset1, double distance, double mitreLimit) { Coordinate basePt = seg0.p1; double ang0 = Angle.angle(basePt, seg0.p0); // oriented angle between segments double angDiff = Angle.angleBetweenOriented(seg0.p0, basePt, seg1.p1); // half of the interior angle double angDiffHalf = angDiff / 2; // angle for bisector of the interior angle between the segments double midAng = Angle.normalize(ang0 + angDiffHalf); // rotating this by PI gives the bisector of the reflex angle double mitreMidAng = Angle.normalize(midAng + Math.PI); // the miterLimit determines the distance to the mitre bevel double mitreDist = mitreLimit * distance; // the bevel delta is the difference between the buffer distance // and half of the length of the bevel segment double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf)); double bevelHalfLen = distance - bevelDelta; // compute the midpoint of the bevel segment double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng); double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng); Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY); // compute the mitre midline segment from the corner point to the bevel segment midpoint LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt); // finally the bevel segment endpoints are computed as offsets from // the mitre midline Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen); Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen); if (side == Position.LEFT) { segList.addPt(bevelEndLeft); segList.addPt(bevelEndRight); } else { segList.addPt(bevelEndRight); segList.addPt(bevelEndLeft); } } /** * Adds a bevel join connecting the two offset segments * around a reflex corner. * * @param offset0 the first offset segment * @param offset1 the second offset segment */ private void addBevelJoin( LineSegment offset0, LineSegment offset1) { segList.addPt(offset0.p1); segList.addPt(offset1.p0); } /** * Add points for a circular fillet around a reflex corner. * Adds the start and end points * * @param p base point of curve * @param p0 start point of fillet curve * @param p1 endpoint of fillet curve * @param direction the orientation of the fillet * @param radius the radius of the fillet */ private void addCornerFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) { double dx0 = p0.x - p.x; double dy0 = p0.y - p.y; double startAngle = Math.atan2(dy0, dx0); double dx1 = p1.x - p.x; double dy1 = p1.y - p.y; double endAngle = Math.atan2(dy1, dx1); if (direction == Orientation.CLOCKWISE) { if (startAngle <= endAngle) startAngle += 2.0 * Math.PI; } else { // direction == COUNTERCLOCKWISE if (startAngle >= endAngle) startAngle -= 2.0 * Math.PI; } segList.addPt(p0); addDirectedFillet(p, startAngle, endAngle, direction, radius); segList.addPt(p1); } /** * Adds points for a circular fillet arc * between two specified angles. * The start and end point for the fillet are not added - * the caller must add them if required. * * @param direction is -1 for a CW angle, 1 for a CCW angle * @param radius the radius of the fillet */ private void addDirectedFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) { int directionFactor = direction == Orientation.CLOCKWISE ? -1 : 1; double totalAngle = Math.abs(startAngle - endAngle); int nSegs = (int) (totalAngle / filletAngleQuantum + 0.5); if (nSegs < 1) return; // no segments because angle is less than increment - nothing to do! // choose angle increment so that each segment has equal length double angleInc = totalAngle / nSegs; Coordinate pt = new Coordinate(); for (int i = 0; i < nSegs; i++) { double angle = startAngle + directionFactor * i * angleInc; pt.x = p.x + radius * Math.cos(angle); pt.y = p.y + radius * Math.sin(angle); segList.addPt(pt); } } /** * Creates a CW circle around a point */ public void createCircle(Coordinate p) { // add start point Coordinate pt = new Coordinate(p.x + distance, p.y); segList.addPt(pt); addDirectedFillet(p, 0.0, 2.0 * Math.PI, -1, distance); segList.closeRing(); } /** * Creates a CW square around a point */ public void createSquare(Coordinate p) { segList.addPt(new Coordinate(p.x + distance, p.y + distance)); segList.addPt(new Coordinate(p.x + distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y + distance)); segList.closeRing(); } }
jnh5y/jts
modules/core/src/main/java/org/locationtech/jts/operation/buffer/OffsetSegmentGenerator.java
6,468
// oriented angle between segments
line_comment
nl
/* * Copyright (c) 2016 Martin Davis. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.locationtech.jts.operation.buffer; import org.locationtech.jts.algorithm.Angle; import org.locationtech.jts.algorithm.HCoordinate; import org.locationtech.jts.algorithm.Intersection; import org.locationtech.jts.algorithm.LineIntersector; import org.locationtech.jts.algorithm.NotRepresentableException; import org.locationtech.jts.algorithm.Orientation; import org.locationtech.jts.algorithm.RobustLineIntersector; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.LineSegment; import org.locationtech.jts.geom.PrecisionModel; import org.locationtech.jts.geomgraph.Position; /** * Generates segments which form an offset curve. * Supports all end cap and join options * provided for buffering. * This algorithm implements various heuristics to * produce smoother, simpler curves which are * still within a reasonable tolerance of the * true curve. * * @author Martin Davis * */ class OffsetSegmentGenerator { /** * Factor which controls how close offset segments can be to * skip adding a filler or mitre. */ private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices on inside turns can be to be snapped */ private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices can be to be snapped */ private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6; /** * Factor which determines how short closing segs can be for round buffers */ private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80; /** * the max error of approximation (distance) between a quad segment and the true fillet curve */ private double maxCurveSegmentError = 0.0; /** * The angle quantum with which to approximate a fillet curve * (based on the input # of quadrant segments) */ private double filletAngleQuantum; /** * The Closing Segment Length Factor controls how long * "closing segments" are. Closing segments are added * at the middle of inside corners to ensure a smoother * boundary for the buffer offset curve. * In some cases (particularly for round joins with default-or-better * quantization) the closing segments can be made quite short. * This substantially improves performance (due to fewer intersections being created). * * A closingSegFactor of 0 results in lines to the corner vertex * A closingSegFactor of 1 results in lines halfway to the corner vertex * A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex * (this option is reasonable for the very common default situation of round joins * and quadrantSegs >= 8) */ private int closingSegLengthFactor = 1; private OffsetSegmentString segList; private double distance = 0.0; private PrecisionModel precisionModel; private BufferParameters bufParams; private LineIntersector li; private Coordinate s0, s1, s2; private LineSegment seg0 = new LineSegment(); private LineSegment seg1 = new LineSegment(); private LineSegment offset0 = new LineSegment(); private LineSegment offset1 = new LineSegment(); private int side = 0; private boolean hasNarrowConcaveAngle = false; public OffsetSegmentGenerator(PrecisionModel precisionModel, BufferParameters bufParams, double distance) { this.precisionModel = precisionModel; this.bufParams = bufParams; // compute intersections in full precision, to provide accuracy // the points are rounded as they are inserted into the curve line li = new RobustLineIntersector(); filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments(); /** * Non-round joins cause issues with short closing segments, so don't use * them. In any case, non-round joins only really make sense for relatively * small buffer distances. */ if (bufParams.getQuadrantSegments() >= 8 && bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR; init(distance); } /** * Tests whether the input has a narrow concave angle * (relative to the offset distance). * In this case the generated offset curve will contain self-intersections * and heuristic closing segments. * This is expected behaviour in the case of Buffer curves. * For pure Offset Curves, * the output needs to be further treated * before it can be used. * * @return true if the input has a narrow concave angle */ public boolean hasNarrowConcaveAngle() { return hasNarrowConcaveAngle; } private void init(double distance) { this.distance = distance; maxCurveSegmentError = distance * (1 - Math.cos(filletAngleQuantum / 2.0)); segList = new OffsetSegmentString(); segList.setPrecisionModel(precisionModel); /** * Choose the min vertex separation as a small fraction of the offset distance. */ segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR); } public void initSideSegments(Coordinate s1, Coordinate s2, int side) { this.s1 = s1; this.s2 = s2; this.side = side; seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); } public Coordinate[] getCoordinates() { Coordinate[] pts = segList.getCoordinates(); return pts; } public void closeRing() { segList.closeRing(); } public void addSegments(Coordinate[] pt, boolean isForward) { segList.addPts(pt, isForward); } public void addFirstSegment() { segList.addPt(offset1.p0); } /** * Add last offset point */ public void addLastSegment() { segList.addPt(offset1.p1); } //private static double MAX_CLOSING_SEG_LEN = 3.0; public void addNextSegment(Coordinate p, boolean addStartPoint) { // s0-s1-s2 are the coordinates of the previous segment and the current one s0 = s1; s1 = s2; s2 = p; seg0.setCoordinates(s0, s1); computeOffsetSegment(seg0, side, distance, offset0); seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); // do nothing if points are equal if (s1.equals(s2)) return; int orientation = Orientation.index(s0, s1, s2); boolean outsideTurn = (orientation == Orientation.CLOCKWISE && side == Position.LEFT) || (orientation == Orientation.COUNTERCLOCKWISE && side == Position.RIGHT); if (orientation == 0) { // lines are collinear addCollinear(addStartPoint); } else if (outsideTurn) { addOutsideTurn(orientation, addStartPoint); } else { // inside turn addInsideTurn(orientation, addStartPoint); } } private void addCollinear(boolean addStartPoint) { /** * This test could probably be done more efficiently, * but the situation of exact collinearity should be fairly rare. */ li.computeIntersection(s0, s1, s1, s2); int numInt = li.getIntersectionNum(); /** * if numInt is < 2, the lines are parallel and in the same direction. In * this case the point can be ignored, since the offset lines will also be * parallel. */ if (numInt >= 2) { /** * segments are collinear but reversing. * Add an "end-cap" fillet * all the way around to other direction This case should ONLY happen * for LineStrings, so the orientation is always CW. (Polygons can never * have two consecutive segments which are parallel but reversed, * because that would be a self intersection. * */ if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL || bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { if (addStartPoint) segList.addPt(offset0.p1); segList.addPt(offset1.p0); } else { addCornerFillet(s1, offset0.p1, offset1.p0, Orientation.CLOCKWISE, distance); } } } /** * Adds the offset points for an outside (convex) turn * * @param orientation * @param addStartPoint */ private void addOutsideTurn(int orientation, boolean addStartPoint) { /** * Heuristic: If offset endpoints are very close together, * just use one of them as the corner vertex. * This avoids problems with computing mitre corners in the case * where the two segments are almost parallel * (which is hard to compute a robust intersection for). */ if (offset0.p1.distance(offset1.p0) < distance * OFFSET_SEGMENT_SEPARATION_FACTOR) { segList.addPt(offset0.p1); return; } if (bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { addMitreJoin(s1, offset0, offset1, distance); } else if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL){ addBevelJoin(offset0, offset1); } else { // add a circular fillet connecting the endpoints of the offset segments if (addStartPoint) segList.addPt(offset0.p1); // TESTING - comment out to produce beveled joins addCornerFillet(s1, offset0.p1, offset1.p0, orientation, distance); segList.addPt(offset1.p0); } } /** * Adds the offset points for an inside (concave) turn. * * @param orientation * @param addStartPoint */ private void addInsideTurn(int orientation, boolean addStartPoint) { /** * add intersection point of offset segments (if any) */ li.computeIntersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (li.hasIntersection()) { segList.addPt(li.getIntersection(0)); } else { /** * If no intersection is detected, * it means the angle is so small and/or the offset so * large that the offsets segments don't intersect. * In this case we must * add a "closing segment" to make sure the buffer curve is continuous, * fairly smooth (e.g. no sharp reversals in direction) * and tracks the buffer correctly around the corner. The curve connects * the endpoints of the segment offsets to points * which lie toward the centre point of the corner. * The joining curve will not appear in the final buffer outline, since it * is completely internal to the buffer polygon. * * In complex buffer cases the closing segment may cut across many other * segments in the generated offset curve. In order to improve the * performance of the noding, the closing segment should be kept as short as possible. * (But not too short, since that would defeat its purpose). * This is the purpose of the closingSegFactor heuristic value. */ /** * The intersection test above is vulnerable to robustness errors; i.e. it * may be that the offsets should intersect very close to their endpoints, * but aren't reported as such due to rounding. To handle this situation * appropriately, we use the following test: If the offset points are very * close, don't add closing segments but simply use one of the offset * points */ hasNarrowConcaveAngle = true; //System.out.println("NARROW ANGLE - distance = " + distance); if (offset0.p1.distance(offset1.p0) < distance * INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) { segList.addPt(offset0.p1); } else { // add endpoint of this segment offset segList.addPt(offset0.p1); /** * Add "closing segment" of required length. */ if (closingSegLengthFactor > 0) { Coordinate mid0 = new Coordinate((closingSegLengthFactor * offset0.p1.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset0.p1.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid0); Coordinate mid1 = new Coordinate((closingSegLengthFactor*offset1.p0.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset1.p0.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid1); } else { /** * This branch is not expected to be used except for testing purposes. * It is equivalent to the JTS 1.9 logic for closing segments * (which results in very poor performance for large buffer distances) */ segList.addPt(s1); } //*/ // add start point of next segment offset segList.addPt(offset1.p0); } } } /** * Compute an offset segment for an input segment on a given side and at a given distance. * The offset points are computed in full double precision, for accuracy. * * @param seg the segment to offset * @param side the side of the segment ({@link Position}) the offset lies on * @param distance the offset distance * @param offset the points computed for the offset segment */ private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) { int sideSign = side == Position.LEFT ? 1 : -1; double dx = seg.p1.x - seg.p0.x; double dy = seg.p1.y - seg.p0.y; double len = Math.sqrt(dx * dx + dy * dy); // u is the vector that is the length of the offset, in the direction of the segment double ux = sideSign * distance * dx / len; double uy = sideSign * distance * dy / len; offset.p0.x = seg.p0.x - uy; offset.p0.y = seg.p0.y + ux; offset.p1.x = seg.p1.x - uy; offset.p1.y = seg.p1.y + ux; } /** * Add an end cap around point p1, terminating a line segment coming from p0 */ public void addLineEndCap(Coordinate p0, Coordinate p1) { LineSegment seg = new LineSegment(p0, p1); LineSegment offsetL = new LineSegment(); computeOffsetSegment(seg, Position.LEFT, distance, offsetL); LineSegment offsetR = new LineSegment(); computeOffsetSegment(seg, Position.RIGHT, distance, offsetR); double dx = p1.x - p0.x; double dy = p1.y - p0.y; double angle = Math.atan2(dy, dx); switch (bufParams.getEndCapStyle()) { case BufferParameters.CAP_ROUND: // add offset seg points with a fillet between them segList.addPt(offsetL.p1); addDirectedFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, Orientation.CLOCKWISE, distance); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_FLAT: // only offset segment points are added segList.addPt(offsetL.p1); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_SQUARE: // add a square defined by extensions of the offset segment endpoints Coordinate squareCapSideOffset = new Coordinate(); squareCapSideOffset.x = Math.abs(distance) * Math.cos(angle); squareCapSideOffset.y = Math.abs(distance) * Math.sin(angle); Coordinate squareCapLOffset = new Coordinate( offsetL.p1.x + squareCapSideOffset.x, offsetL.p1.y + squareCapSideOffset.y); Coordinate squareCapROffset = new Coordinate( offsetR.p1.x + squareCapSideOffset.x, offsetR.p1.y + squareCapSideOffset.y); segList.addPt(squareCapLOffset); segList.addPt(squareCapROffset); break; } } /** * Adds a mitre join connecting the two reflex offset segments. * The mitre will be beveled if it exceeds the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance */ private void addMitreJoin(Coordinate p, LineSegment offset0, LineSegment offset1, double distance) { /** * This computation is unstable if the offset segments are nearly collinear. * However, this situation should have been eliminated earlier by the check * for whether the offset segment endpoints are almost coincident */ Coordinate intPt = Intersection.intersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (intPt != null) { double mitreRatio = distance <= 0.0 ? 1.0 : intPt.distance(p) / Math.abs(distance); if (mitreRatio <= bufParams.getMitreLimit()) { segList.addPt(intPt); return; } } // at this point either intersection failed or mitre limit was exceeded addLimitedMitreJoin(offset0, offset1, distance, bufParams.getMitreLimit()); // addBevelJoin(offset0, offset1); } /** * Adds a limited mitre join connecting the two reflex offset segments. * A limited mitre is a mitre which is beveled at the distance * determined by the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance * @param mitreLimit the mitre limit ratio */ private void addLimitedMitreJoin( LineSegment offset0, LineSegment offset1, double distance, double mitreLimit) { Coordinate basePt = seg0.p1; double ang0 = Angle.angle(basePt, seg0.p0); // oriented angle<SUF> double angDiff = Angle.angleBetweenOriented(seg0.p0, basePt, seg1.p1); // half of the interior angle double angDiffHalf = angDiff / 2; // angle for bisector of the interior angle between the segments double midAng = Angle.normalize(ang0 + angDiffHalf); // rotating this by PI gives the bisector of the reflex angle double mitreMidAng = Angle.normalize(midAng + Math.PI); // the miterLimit determines the distance to the mitre bevel double mitreDist = mitreLimit * distance; // the bevel delta is the difference between the buffer distance // and half of the length of the bevel segment double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf)); double bevelHalfLen = distance - bevelDelta; // compute the midpoint of the bevel segment double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng); double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng); Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY); // compute the mitre midline segment from the corner point to the bevel segment midpoint LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt); // finally the bevel segment endpoints are computed as offsets from // the mitre midline Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen); Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen); if (side == Position.LEFT) { segList.addPt(bevelEndLeft); segList.addPt(bevelEndRight); } else { segList.addPt(bevelEndRight); segList.addPt(bevelEndLeft); } } /** * Adds a bevel join connecting the two offset segments * around a reflex corner. * * @param offset0 the first offset segment * @param offset1 the second offset segment */ private void addBevelJoin( LineSegment offset0, LineSegment offset1) { segList.addPt(offset0.p1); segList.addPt(offset1.p0); } /** * Add points for a circular fillet around a reflex corner. * Adds the start and end points * * @param p base point of curve * @param p0 start point of fillet curve * @param p1 endpoint of fillet curve * @param direction the orientation of the fillet * @param radius the radius of the fillet */ private void addCornerFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) { double dx0 = p0.x - p.x; double dy0 = p0.y - p.y; double startAngle = Math.atan2(dy0, dx0); double dx1 = p1.x - p.x; double dy1 = p1.y - p.y; double endAngle = Math.atan2(dy1, dx1); if (direction == Orientation.CLOCKWISE) { if (startAngle <= endAngle) startAngle += 2.0 * Math.PI; } else { // direction == COUNTERCLOCKWISE if (startAngle >= endAngle) startAngle -= 2.0 * Math.PI; } segList.addPt(p0); addDirectedFillet(p, startAngle, endAngle, direction, radius); segList.addPt(p1); } /** * Adds points for a circular fillet arc * between two specified angles. * The start and end point for the fillet are not added - * the caller must add them if required. * * @param direction is -1 for a CW angle, 1 for a CCW angle * @param radius the radius of the fillet */ private void addDirectedFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) { int directionFactor = direction == Orientation.CLOCKWISE ? -1 : 1; double totalAngle = Math.abs(startAngle - endAngle); int nSegs = (int) (totalAngle / filletAngleQuantum + 0.5); if (nSegs < 1) return; // no segments because angle is less than increment - nothing to do! // choose angle increment so that each segment has equal length double angleInc = totalAngle / nSegs; Coordinate pt = new Coordinate(); for (int i = 0; i < nSegs; i++) { double angle = startAngle + directionFactor * i * angleInc; pt.x = p.x + radius * Math.cos(angle); pt.y = p.y + radius * Math.sin(angle); segList.addPt(pt); } } /** * Creates a CW circle around a point */ public void createCircle(Coordinate p) { // add start point Coordinate pt = new Coordinate(p.x + distance, p.y); segList.addPt(pt); addDirectedFillet(p, 0.0, 2.0 * Math.PI, -1, distance); segList.closeRing(); } /** * Creates a CW square around a point */ public void createSquare(Coordinate p) { segList.addPt(new Coordinate(p.x + distance, p.y + distance)); segList.addPt(new Coordinate(p.x + distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y + distance)); segList.closeRing(); } }
155700_1
class Plante { private int vannBeholder; private int maxGrenseVann; private boolean alive; public Plante(int maxGrenseVann) { this.maxGrenseVann = maxGrenseVann; alive = true; } //Oker vannBeholder med clVann. Om vannBeholder blir storre enn //maxGrenseVann, dor planten. public void vannPlante(int clVann) { vannBeholder += clVann; if(vannBeholder > maxGrenseVann) { System.out.println("\nThe plant is now dead, thanks to you."); System.out.println("It died from drowning.\n"); alive = false; } } //For hver nye dag minker vannBeholder med 20(siden planten drikker vannet). //Om vannBeholder blir mindre enn 0, dor planten. public void nyDag() { vannBeholder -= 20; if(vannBeholder < 0) { System.out.println("\nThe plant is now dead, thanks to you."); System.out.println("It died from dehydration.\n"); alive = false; } } //Om planten er levende skal det returnes 1, om ikke planten er levende skal // det returneres -1. public boolean erLevende() { if(alive) { return true; } return false; } }
alekvage/INOR
1_semester/INF1000/Trix/Plante.java
369
//maxGrenseVann, dor planten.
line_comment
nl
class Plante { private int vannBeholder; private int maxGrenseVann; private boolean alive; public Plante(int maxGrenseVann) { this.maxGrenseVann = maxGrenseVann; alive = true; } //Oker vannBeholder med clVann. Om vannBeholder blir storre enn //maxGrenseVann, dor<SUF> public void vannPlante(int clVann) { vannBeholder += clVann; if(vannBeholder > maxGrenseVann) { System.out.println("\nThe plant is now dead, thanks to you."); System.out.println("It died from drowning.\n"); alive = false; } } //For hver nye dag minker vannBeholder med 20(siden planten drikker vannet). //Om vannBeholder blir mindre enn 0, dor planten. public void nyDag() { vannBeholder -= 20; if(vannBeholder < 0) { System.out.println("\nThe plant is now dead, thanks to you."); System.out.println("It died from dehydration.\n"); alive = false; } } //Om planten er levende skal det returnes 1, om ikke planten er levende skal // det returneres -1. public boolean erLevende() { if(alive) { return true; } return false; } }
47121_31
package klfr.sa2emu.cpuemulator; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Dictionary; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import java.util.Scanner; import klfr.sa2emu.cpuemulator.exceptions.AssemblyError; /** * Assembler-Subprogramm, dass SA2-Assembly in SA2-Maschinensprache übersetzt. * * @author malub */ public class SA2_Assembler { /** fertige Maschinensprache */ private byte[] machineCode; /** * Erzeugt einen neuen Assembler und verarbeitet die angegebenen Assemblybefehle * zu Maschinenbefehlen. * * @param assemblycode SA2-Assembly, die assembled werden soll. * @throws AssemblyError */ public SA2_Assembler(String assemblycode) throws AssemblyError { this(new Scanner(assemblycode)); } /** * Erzeugt einen neuen Assembler und verarbeitet die angegebenen Assemblybefehle * zu Maschinenbefehlen. * * @param assemblycode Scanner, dessen Eingabe assembled werden soll. */ public SA2_Assembler(Scanner assemblyscanner) throws AssemblyError { assemblyscanner.reset(); // First pass Dictionary<String, Integer> labelDict = new Hashtable<String, Integer>(); StringBuilder firstPassBuilder = new StringBuilder(); int linenumber = 0, realline = 0; while (assemblyscanner.hasNextLine()) { // Neue Zeile einlesen und Zeilennummer erhöhen linenumber++; realline++; Scanner linescanner = new Scanner(assemblyscanner.nextLine()); // Basis 16 linescanner.useRadix(10); // Zeile überspringen, falls leer if (!linescanner.hasNext()) { linenumber--; continue; } // Parsen einer Zeile String token = linescanner.next().toLowerCase(Locale.ENGLISH); // Kommentarzeile: alles danach ignorieren if (token.startsWith("/")) { linenumber--; continue; } // Label: speichern aber nicht in den second pass string if (token.startsWith(":")) { // ":" entfernen token = token.split(":")[1]; labelDict.put(token, linenumber); try { token = linescanner.next(); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Missing Element error in line " + realline + ": expected 'command' after label '" + token + "'."); } if (token.startsWith("/")) { linescanner.close(); throw new AssemblyError( "Missing Element error in line " + realline + ": expected 'command' after label '" + token + "'."); } } // Befehl switch (token.toLowerCase(Locale.ENGLISH)) { case "load": /// Laden von Wert in Register firstPassBuilder.append("load "); // hole Operanden try { // für die Operanden sind Leerzeichen egal linescanner.useDelimiter("/+\\z*"); token = linescanner.next().toLowerCase(); linescanner.useDelimiter("\\p{javaWhitespace}+"); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Missing Element error in line " + realline + ": expected load origin after 'load' command."); } token = token.trim(); token = token.replaceAll("\\s", ""); // Zwei Teile des Befehls: Ursprung und Ziel String[] splitted = token.split(",|\\-\\>"); // Java soll mich mal ficken -_- ArrayList<String> ip = new ArrayList<String>(); for (String s : splitted) { if (!s.isEmpty() && s != null) ip.add(s); } String[] instructionParts = new String[ip.size()]; for (int i = 0; i < ip.size(); ++i) { instructionParts[i] = ip.get(i); } // ende vom ficken if (instructionParts.length != 2) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected exactly two identifiers after 'load' command."); } // falls der erste Teil des Befehls (Ursprungsaddresse) die korrekte Form hat // und eventuell ein Operationsliteral enthält das ausgerechnet wird if (instructionParts[0].matches("\\d+([\\+\\-]\\d+)?")) { // Direktes Laden des Werts, der beschrieben wird. try { // Operationsliteral kompilieren int value = compileOperationLiteral(instructionParts[0]); firstPassBuilder.append(stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else if (instructionParts[0].matches("\\$\\d+([\\+\\-]\\d+)?")) { // Laden aus Speicheradresse, die durch Operand beschrieben wird. try { // Operationsliteral ohne $ komplilieren int value = compileOperationLiteral(instructionParts[0].replace("$", "")); firstPassBuilder.append("$ " + stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'OP' or '$OP' after 'load' command."); } // ende von erstem Operand if // Zielregister muss nicht erkannt werden, darum kümmert sich der Second Pass // assembler firstPassBuilder.append(" " + instructionParts[1].replaceAll("\\s", "")); break; // end of load case "store": // Speichern im RAM firstPassBuilder.append("store "); // hole Operanden try { // für die Operanden sind Leerzeichen egal linescanner.useDelimiter("/+\\z*"); token = linescanner.next().toLowerCase(); linescanner.useDelimiter("\\p{javaWhitespace}+"); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected store destination after 'store' command."); } token = token.trim(); token = token.replaceAll("\\s", ""); // Zwei Teile des Befehls: Ursprung und Ziel splitted = token.split("[,(\\-\\>)\\>]"); // Java soll mich mal ficken -_- ip = new ArrayList<String>(); for (String s : splitted) { if (!s.isEmpty() && s != null) ip.add(s); } instructionParts = new String[ip.size()]; for (int i = 0; i < ip.size(); ++i) { instructionParts[i] = ip.get(i); } // ende vom ficken if (instructionParts.length != 2) { linescanner.close(); throw new AssemblyError("Missing Element error in line " + realline + ": expected exactly two identifiers after 'store' command."); } // erster Teil -> Register if (instructionParts[0].matches("[ab]")) { firstPassBuilder.append(instructionParts[0] + " "); } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'A' or 'B' after 'store' command."); } if (instructionParts[1].matches("\\$\\d+([\\+\\-]\\d+)?")) { // Speichern in Speicheradresse, die durch Operand beschrieben wird. try { // Operationsliteral ohne $ komplilieren int value = compileOperationLiteral(instructionParts[1].replace("$", "")); // $ hier nicht nötig, da immer Speichern in Adresse geschieht (Speichern in // Literal macht keinen Sinn) firstPassBuilder.append(stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else { linescanner.close(); throw new AssemblyError("Syntax error in line " + realline + ": expected '$OP' after register identifier in 'store' command."); } // ende von if break; // end of store case "add": case "sub": case "or": case "xor": case "and": // Arithmetisch-logische Operationen firstPassBuilder.append(token + " "); // hole Operanden try { // für die Operanden sind Leerzeichen egal linescanner.useDelimiter("/+\\z*"); token = linescanner.next().toLowerCase(); linescanner.useDelimiter("\\p{javaWhitespace}+"); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError("Missing Element error in line " + realline + ": expected declaration of second operand after 'arithmetic or logic operation' command."); } token = token.trim(); token = token.replaceAll("\\s", ""); if (token.equalsIgnoreCase("b") || token.equalsIgnoreCase("x") || token.equalsIgnoreCase("$b") || token.equalsIgnoreCase("$x")) { // nur x/b/$y/$b firstPassBuilder.append(token); } else if (token.matches("\\$\\d+([\\+\\-]\\d+)?")) { // Operandenliteral mit Berechnung try { // Operationsliteral ohne $ komplilieren int value = compileOperationLiteral(token.replace("$", "")); firstPassBuilder.append("$ " + stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else if (token.matches("\\d+([\\+\\-]\\d+)?")) { // Operandenliteral mit Berechnung try { // Operationsliteral komplilieren int value = compileOperationLiteral(token); firstPassBuilder.append(stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else { linescanner.close(); throw new AssemblyError("Syntax error in line " + realline + ": expected 'B', 'X', '$OP', '$B' or '$X' after 'arithmetic or logic operation' command."); } break; // end of arithmetic/logic case "not": case "bitsr": case "bitsl": case "inc": case "dec": // Unäre Operationen (immer mit A ausgeführt) und Haltebefehl firstPassBuilder.append(token); break; // end of unary/halt case "out": // Ausgabe firstPassBuilder.append(token); // hole Ausgabemodi try { token = linescanner.next().toLowerCase(); } catch (NoSuchElementException e) { // Passiert bei einfachem output firstPassBuilder.append(System.lineSeparator()); continue; } if (token.matches("cmd|addr|dat")) { // gültiger Ausgabebefehl firstPassBuilder.append(" " + token); try { token = linescanner.next().toLowerCase(); // Operationsliteral ohne $ komplilieren if (token.startsWith("$")) { int value = compileOperationLiteral(token.replace("$", "")); firstPassBuilder.append(" $ " + stringify(value)); } else { int value = compileOperationLiteral(token); firstPassBuilder.append(" " + stringify(value)); } } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected '$OP' after 'output type' in 'out' command."); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else if (!token.matches("/.*")) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'output type' after 'out' command."); } break; // end of out case "jmp": case "jmpc": case "jmpnc": case "jmpz": case "jmpnz": case "jmpp": case "jmpnp": case "call": // Sprung (bedingt oder unbedingt) firstPassBuilder.append(token + " "); try { token = linescanner.next().toLowerCase(); token.replaceAll("\\s", ""); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected '$OP' or 'label' in 'jump' or 'call' command."); } if (token.matches("\\$\\d+([\\+\\-]\\d+)?")) { // Sprungadresse try { // Operationsliteral ohne $ komplilieren int value = compileOperationLiteral(token.replace("$", "")); firstPassBuilder.append("$ " + stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else if (token.matches("\\w+")) { // Sprunglabel: wird nach dem Pass behandelt firstPassBuilder.append(token); } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected '$OP' or 'label' in 'jump' or 'call' command."); } break; // end of jump case "move": // Bewegen von Registern in andere Register firstPassBuilder.append(token + " "); // hole Registernamen try { // für die Operanden sind Leerzeichen egal linescanner.useDelimiter("/+\\z*"); token = linescanner.next().toLowerCase(); linescanner.useDelimiter("\\p{javaWhitespace}+"); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Missing Element error in line " + realline + ": expected register names after 'move' command."); } token = token.replaceAll("\\s", ""); // Zwei Teile des Befehls: Ursprung und Ziel splitted = token.split("[,(\\-\\>)\\>]"); // Java soll mich mal ficken -_- ip = new ArrayList<String>(); for (String s : splitted) { if (!s.isEmpty() && s != null) ip.add(s); } instructionParts = new String[ip.size()]; for (int i = 0; i < ip.size(); ++i) { instructionParts[i] = ip.get(i); } // ende vom ficken if (instructionParts.length != 2) { linescanner.close(); throw new AssemblyError("Syntax error in line " + realline + ": expected exactly two register names after 'move' command."); } if (instructionParts[0].matches("a|b|sp")) { firstPassBuilder.append(instructionParts[0] + " "); } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'A', 'B' or 'SP' after 'move' command."); } if (instructionParts[1].matches("[abx(sp)]")) { firstPassBuilder.append(instructionParts[1]); } else { linescanner.close(); throw new AssemblyError("Syntax error in line " + realline + ": expected second 'A', 'X', 'B' or 'SP' after first 'register name' in 'move' command."); } break; // end of move case "push": case "pop": // Stackoperationen (mit einem Parameter) firstPassBuilder.append(token + " "); try { token = linescanner.next().toLowerCase(); token.replaceAll("\\s", ""); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'A' or 'B' in 'push' or 'pop' command."); } if (token.matches("[abx]")) { // Push/Popregister firstPassBuilder.append(token); } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'A' or 'B' in 'push' or 'pop' command."); } break; // end of call/return/push/pop case "noop": break; // end of noop case "halt": case "swap": case "stkrest": case "return": // Operationen ohne Parameter firstPassBuilder.append(token); break; // end of halt/swap/stkrest/return default: linescanner.close(); throw new AssemblyError( "Unknown command exception in line " + realline + ": expected 'command' or 'label' or 'comment'."); } // end of command parse firstPassBuilder.append(System.lineSeparator()); linescanner.close(); } // end of first pass parse // System.out.println(firstPassBuilder); assemblyscanner.close(); // second pass Scanner firstPassScanner = new Scanner(firstPassBuilder.toString()); List<Byte> instructions = new ArrayList<>(); while (firstPassScanner.hasNextLine()) { Scanner lineS = new Scanner(firstPassScanner.nextLine()); if (!lineS.hasNext()) continue; String token = lineS.next(); // Befehl, Operand byte ib = 0x00, ob = 0x00; switch (token) { case "load": ib = 0x10; token = lineS.next(); // Ursprung if (token.equals("$")) { token = lineS.next(); ob = (byte) integer(token); // Memory-loads sind entweder 0x10 oder 0x11 (vorletztes Bit nicht // gesetzt) } else { ob = (byte) integer(token); // Literal-loads sind entweder 0x12 oder 0x13 (vorletztes Bit gesetzt) ib |= 0x02; } // Zielregister token = lineS.next(); if (token.equals("b")) // die Fälle mit gesetztem letzten Bit sind Ladevorgänge in B ib += 1; break; // end of load case "store": ib = 0x20; token = lineS.next(); // Ursprungsregister if (token.equals("b")) { // vergleiche load ib += 1; } token = lineS.next(); // Zieladdresse ob = (byte) integer(token); break; // end of store case "add": case "sub": case "and": case "or": case "xor": // Erster Teil des Befehls abhängig von Operation switch (token) { case "add": ib = 0x30; break; case "sub": ib = 0x40; break; case "or": ib = 0x50; break; case "xor": ib = 0x60; break; case "and": ib = 0x70; break; } // Zweiter Teil (und Operand) abhängig von weiteren Argument(en) token = lineS.next(); switch (token) { case "b": ib |= 0x00; break; case "x": ib |= 0x01; break; case "$": ib |= 0x02; ob = (byte) integer(lineS.next()); break; case "$b": ib |= 0x03; break; case "$x": ib |= 0x04; break; } break; // end of add case "not": ib = (byte) 0x81; break; case "bitsl": ib = (byte) 0x82; break; case "bitsr": ib = (byte) 0x83; break; case "inc": ib = (byte) 0x84; break; case "dec": ib = (byte) 0x85; break; // end of unary arithmetic case "out": ib = (byte) 0x90; try { token = lineS.next(); } catch (NoSuchElementException e) { // erneut den einfach-Ausgabe-Fall abfangen break; } // erweiterte Ein/Ausgabe switch (token) { case "cmd": ib |= 0x01; break; case "addr": ib |= 0x02; break; case "dat": ib |= 0x03; break; } token = lineS.next(); if (token.equals("$")) { // bringt die Werte von 0x91-0x93 auf 0x94-0x96 ib += 3; token = lineS.next(); } ob = (byte) integer(token); break; // end of out's case "jmp": case "jmpc": case "jmpnc": case "jmpz": case "jmpnz": case "jmpp": case "jmpnp": case "call": // Sprung oder Unterprogramm ib = (byte) 0xA0; switch (token) { case "jmpc": ib |= 0x01; break; case "jmpnc": ib |= 0x02; break; case "jmpz": ib |= 0x03; break; case "jmpnz": ib |= 0x04; break; case "jmpp": ib |= 0x05; break; case "jmpnp": ib |= 0x06; break; case "call": ib |= 0x07; break; } token = lineS.next(); if (token.matches("\\w+")) { // Label: Lookup im Dictionary ob = labelDict.get(token).byteValue(); } else { // Speicheradressenzeiger ignorieren if (token.equals("$")) token = lineS.next(); ob = (byte) integer(token); } break; // end of jump's case "return": ib = (byte) 0xA8; break; // end of return case "move": ib = 0x20; token = lineS.next(); switch (token) { case "a": ib |= 0x02; break; case "b": ib |= 0x05; break; case "sp": ib |= 0x08; break; } token = lineS.next(); // Offset durch zweites Argument sorgt für logische Maschinencodes switch (token) { // a sorgt für keinen Offset case "b": ib += 1; break; case "x": ib += 2; break; } break; // end of move case "swap": ib = 0x2B; break; case "push": case "pop": ib = (byte) 0xB0; if (token.equals("pop")) ib += 1; token = lineS.next(); // bei a passiert keine Erhöhung if (token.equals("b")) ib += 2; break; // end of push/pop case "stkrest": ib = (byte) 0xb4; // Somit weiß die CPU, wo der Stack anfängt ob = SA2_CPU.STACK_START; break; case "halt": ib = 0x01; break; } // end of line instructions.add(ib); instructions.add(ob); lineS.close(); } firstPassScanner.close(); // Speichern des Maschinencodes machineCode = new byte[instructions.size()]; for (int i = 0; i < instructions.size(); ++i) { machineCode[i] = instructions.get(i); } } // end of main constructor /** * Erzeugt einen neuen Assembler und verarbeitet die angegebenen Assemblybefehle * zu Maschinenbefehlen. * * @param assemblycode Datei, deren Inhalt assembled werden soll. * @throws AssemblyError */ public SA2_Assembler(File assemblyFile) throws FileNotFoundException, IOException, AssemblyError { this(new Scanner(assemblyFile)); } /** * @return Die Maschinenbefehle, die dieser Assembler verarbeitet hat. */ public byte[] getMachineCode() { return machineCode; } /** * Die Anzahl der Bytes, die die Maschinenbefehle dieses Assemblers einnehmen. */ public int machineCodeLength() { return machineCode.length; } /** * Druckt den Maschinencode schön formatiert, zweizeilig und hexadezimal. * * @param out Der Ausgabestrom, in den gedruckt wird. */ public void printMachineCode(PrintStream out) { byte end = 0; for (byte b : machineCode) { end++; out.print(stringifyHex(b)); if (end > 1) out.println(); else out.print(" "); end %= 2; } } /** * Erzeugt eine Zahl aus einem dezimalen String; Leerzeichen werden ignoriert. */ private static int integer(String s) throws NumberFormatException { s = s.replaceAll("\\s", ""); return Integer.parseInt(s); } /** * Erzeugt einen dezimalen String aus einer Zahl. */ private static String stringify(int i) { return Integer.toString(i); } /** * Erzeugt einen hexadezimalen String aus einem Byte. Vorzeichen sind egal. */ public static String stringifyHex(byte b) { String sb = Integer.toUnsignedString(b, 16); if (sb.length() > 2) sb = sb.substring(sb.length() - 2, sb.length()); return sb; } /** * Kompiliert ein Operationsliteral (Addition oder Subtraktion von zwei * Operanden) und gibt den Integerwert zurück. */ private static int compileOperationLiteral(String operation) throws AssemblyError { operation = operation.trim(); operation = operation.replaceAll("\\s", ""); // Aufteilen in die beiden Operanden der Addition/Subtraktion String[] operands = operation.split("[\\+-]"); // Die Operation, welche ausgeführt werden soll String operationType = operation.indexOf("+") > -1 ? "+" : (operation.indexOf("-") > -1 ? "-" : "+"); if (operands.length == 1) { // einfaches übernehmen des Operanden return integer(operands[0]); } else if (operands.length == 2) { // Addition oder Subtraktion int val = integer(operands[0]); if (operationType.equalsIgnoreCase("+")) { val += integer(operands[1]); } else if (operationType.equalsIgnoreCase("-")) { val -= integer(operands[1]); } else { // sollte nicht passieren (und dann ist der Benutzer schuld) throw new AssemblyError("Unknown error: inline operation not '+' or '-'."); } return val; } else { throw new AssemblyError("Literal Operation error: inline operation with more than two operands."); } } }
kleinesfilmroellchen/ToyCpuEmulator
src/main/java/klfr/sa2emu/cpuemulator/SA2_Assembler.java
7,295
// ende von if
line_comment
nl
package klfr.sa2emu.cpuemulator; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Dictionary; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import java.util.Scanner; import klfr.sa2emu.cpuemulator.exceptions.AssemblyError; /** * Assembler-Subprogramm, dass SA2-Assembly in SA2-Maschinensprache übersetzt. * * @author malub */ public class SA2_Assembler { /** fertige Maschinensprache */ private byte[] machineCode; /** * Erzeugt einen neuen Assembler und verarbeitet die angegebenen Assemblybefehle * zu Maschinenbefehlen. * * @param assemblycode SA2-Assembly, die assembled werden soll. * @throws AssemblyError */ public SA2_Assembler(String assemblycode) throws AssemblyError { this(new Scanner(assemblycode)); } /** * Erzeugt einen neuen Assembler und verarbeitet die angegebenen Assemblybefehle * zu Maschinenbefehlen. * * @param assemblycode Scanner, dessen Eingabe assembled werden soll. */ public SA2_Assembler(Scanner assemblyscanner) throws AssemblyError { assemblyscanner.reset(); // First pass Dictionary<String, Integer> labelDict = new Hashtable<String, Integer>(); StringBuilder firstPassBuilder = new StringBuilder(); int linenumber = 0, realline = 0; while (assemblyscanner.hasNextLine()) { // Neue Zeile einlesen und Zeilennummer erhöhen linenumber++; realline++; Scanner linescanner = new Scanner(assemblyscanner.nextLine()); // Basis 16 linescanner.useRadix(10); // Zeile überspringen, falls leer if (!linescanner.hasNext()) { linenumber--; continue; } // Parsen einer Zeile String token = linescanner.next().toLowerCase(Locale.ENGLISH); // Kommentarzeile: alles danach ignorieren if (token.startsWith("/")) { linenumber--; continue; } // Label: speichern aber nicht in den second pass string if (token.startsWith(":")) { // ":" entfernen token = token.split(":")[1]; labelDict.put(token, linenumber); try { token = linescanner.next(); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Missing Element error in line " + realline + ": expected 'command' after label '" + token + "'."); } if (token.startsWith("/")) { linescanner.close(); throw new AssemblyError( "Missing Element error in line " + realline + ": expected 'command' after label '" + token + "'."); } } // Befehl switch (token.toLowerCase(Locale.ENGLISH)) { case "load": /// Laden von Wert in Register firstPassBuilder.append("load "); // hole Operanden try { // für die Operanden sind Leerzeichen egal linescanner.useDelimiter("/+\\z*"); token = linescanner.next().toLowerCase(); linescanner.useDelimiter("\\p{javaWhitespace}+"); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Missing Element error in line " + realline + ": expected load origin after 'load' command."); } token = token.trim(); token = token.replaceAll("\\s", ""); // Zwei Teile des Befehls: Ursprung und Ziel String[] splitted = token.split(",|\\-\\>"); // Java soll mich mal ficken -_- ArrayList<String> ip = new ArrayList<String>(); for (String s : splitted) { if (!s.isEmpty() && s != null) ip.add(s); } String[] instructionParts = new String[ip.size()]; for (int i = 0; i < ip.size(); ++i) { instructionParts[i] = ip.get(i); } // ende vom ficken if (instructionParts.length != 2) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected exactly two identifiers after 'load' command."); } // falls der erste Teil des Befehls (Ursprungsaddresse) die korrekte Form hat // und eventuell ein Operationsliteral enthält das ausgerechnet wird if (instructionParts[0].matches("\\d+([\\+\\-]\\d+)?")) { // Direktes Laden des Werts, der beschrieben wird. try { // Operationsliteral kompilieren int value = compileOperationLiteral(instructionParts[0]); firstPassBuilder.append(stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else if (instructionParts[0].matches("\\$\\d+([\\+\\-]\\d+)?")) { // Laden aus Speicheradresse, die durch Operand beschrieben wird. try { // Operationsliteral ohne $ komplilieren int value = compileOperationLiteral(instructionParts[0].replace("$", "")); firstPassBuilder.append("$ " + stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'OP' or '$OP' after 'load' command."); } // ende von erstem Operand if // Zielregister muss nicht erkannt werden, darum kümmert sich der Second Pass // assembler firstPassBuilder.append(" " + instructionParts[1].replaceAll("\\s", "")); break; // end of load case "store": // Speichern im RAM firstPassBuilder.append("store "); // hole Operanden try { // für die Operanden sind Leerzeichen egal linescanner.useDelimiter("/+\\z*"); token = linescanner.next().toLowerCase(); linescanner.useDelimiter("\\p{javaWhitespace}+"); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected store destination after 'store' command."); } token = token.trim(); token = token.replaceAll("\\s", ""); // Zwei Teile des Befehls: Ursprung und Ziel splitted = token.split("[,(\\-\\>)\\>]"); // Java soll mich mal ficken -_- ip = new ArrayList<String>(); for (String s : splitted) { if (!s.isEmpty() && s != null) ip.add(s); } instructionParts = new String[ip.size()]; for (int i = 0; i < ip.size(); ++i) { instructionParts[i] = ip.get(i); } // ende vom ficken if (instructionParts.length != 2) { linescanner.close(); throw new AssemblyError("Missing Element error in line " + realline + ": expected exactly two identifiers after 'store' command."); } // erster Teil -> Register if (instructionParts[0].matches("[ab]")) { firstPassBuilder.append(instructionParts[0] + " "); } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'A' or 'B' after 'store' command."); } if (instructionParts[1].matches("\\$\\d+([\\+\\-]\\d+)?")) { // Speichern in Speicheradresse, die durch Operand beschrieben wird. try { // Operationsliteral ohne $ komplilieren int value = compileOperationLiteral(instructionParts[1].replace("$", "")); // $ hier nicht nötig, da immer Speichern in Adresse geschieht (Speichern in // Literal macht keinen Sinn) firstPassBuilder.append(stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else { linescanner.close(); throw new AssemblyError("Syntax error in line " + realline + ": expected '$OP' after register identifier in 'store' command."); } // ende von<SUF> break; // end of store case "add": case "sub": case "or": case "xor": case "and": // Arithmetisch-logische Operationen firstPassBuilder.append(token + " "); // hole Operanden try { // für die Operanden sind Leerzeichen egal linescanner.useDelimiter("/+\\z*"); token = linescanner.next().toLowerCase(); linescanner.useDelimiter("\\p{javaWhitespace}+"); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError("Missing Element error in line " + realline + ": expected declaration of second operand after 'arithmetic or logic operation' command."); } token = token.trim(); token = token.replaceAll("\\s", ""); if (token.equalsIgnoreCase("b") || token.equalsIgnoreCase("x") || token.equalsIgnoreCase("$b") || token.equalsIgnoreCase("$x")) { // nur x/b/$y/$b firstPassBuilder.append(token); } else if (token.matches("\\$\\d+([\\+\\-]\\d+)?")) { // Operandenliteral mit Berechnung try { // Operationsliteral ohne $ komplilieren int value = compileOperationLiteral(token.replace("$", "")); firstPassBuilder.append("$ " + stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else if (token.matches("\\d+([\\+\\-]\\d+)?")) { // Operandenliteral mit Berechnung try { // Operationsliteral komplilieren int value = compileOperationLiteral(token); firstPassBuilder.append(stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else { linescanner.close(); throw new AssemblyError("Syntax error in line " + realline + ": expected 'B', 'X', '$OP', '$B' or '$X' after 'arithmetic or logic operation' command."); } break; // end of arithmetic/logic case "not": case "bitsr": case "bitsl": case "inc": case "dec": // Unäre Operationen (immer mit A ausgeführt) und Haltebefehl firstPassBuilder.append(token); break; // end of unary/halt case "out": // Ausgabe firstPassBuilder.append(token); // hole Ausgabemodi try { token = linescanner.next().toLowerCase(); } catch (NoSuchElementException e) { // Passiert bei einfachem output firstPassBuilder.append(System.lineSeparator()); continue; } if (token.matches("cmd|addr|dat")) { // gültiger Ausgabebefehl firstPassBuilder.append(" " + token); try { token = linescanner.next().toLowerCase(); // Operationsliteral ohne $ komplilieren if (token.startsWith("$")) { int value = compileOperationLiteral(token.replace("$", "")); firstPassBuilder.append(" $ " + stringify(value)); } else { int value = compileOperationLiteral(token); firstPassBuilder.append(" " + stringify(value)); } } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected '$OP' after 'output type' in 'out' command."); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else if (!token.matches("/.*")) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'output type' after 'out' command."); } break; // end of out case "jmp": case "jmpc": case "jmpnc": case "jmpz": case "jmpnz": case "jmpp": case "jmpnp": case "call": // Sprung (bedingt oder unbedingt) firstPassBuilder.append(token + " "); try { token = linescanner.next().toLowerCase(); token.replaceAll("\\s", ""); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected '$OP' or 'label' in 'jump' or 'call' command."); } if (token.matches("\\$\\d+([\\+\\-]\\d+)?")) { // Sprungadresse try { // Operationsliteral ohne $ komplilieren int value = compileOperationLiteral(token.replace("$", "")); firstPassBuilder.append("$ " + stringify(value)); } catch (AssemblyError e) { String[] msg = e.getMessage().split(":"); msg[0] = msg[0].concat(" in line " + realline + ":").concat(msg[1]); linescanner.close(); throw new AssemblyError(msg[0]); } } else if (token.matches("\\w+")) { // Sprunglabel: wird nach dem Pass behandelt firstPassBuilder.append(token); } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected '$OP' or 'label' in 'jump' or 'call' command."); } break; // end of jump case "move": // Bewegen von Registern in andere Register firstPassBuilder.append(token + " "); // hole Registernamen try { // für die Operanden sind Leerzeichen egal linescanner.useDelimiter("/+\\z*"); token = linescanner.next().toLowerCase(); linescanner.useDelimiter("\\p{javaWhitespace}+"); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Missing Element error in line " + realline + ": expected register names after 'move' command."); } token = token.replaceAll("\\s", ""); // Zwei Teile des Befehls: Ursprung und Ziel splitted = token.split("[,(\\-\\>)\\>]"); // Java soll mich mal ficken -_- ip = new ArrayList<String>(); for (String s : splitted) { if (!s.isEmpty() && s != null) ip.add(s); } instructionParts = new String[ip.size()]; for (int i = 0; i < ip.size(); ++i) { instructionParts[i] = ip.get(i); } // ende vom ficken if (instructionParts.length != 2) { linescanner.close(); throw new AssemblyError("Syntax error in line " + realline + ": expected exactly two register names after 'move' command."); } if (instructionParts[0].matches("a|b|sp")) { firstPassBuilder.append(instructionParts[0] + " "); } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'A', 'B' or 'SP' after 'move' command."); } if (instructionParts[1].matches("[abx(sp)]")) { firstPassBuilder.append(instructionParts[1]); } else { linescanner.close(); throw new AssemblyError("Syntax error in line " + realline + ": expected second 'A', 'X', 'B' or 'SP' after first 'register name' in 'move' command."); } break; // end of move case "push": case "pop": // Stackoperationen (mit einem Parameter) firstPassBuilder.append(token + " "); try { token = linescanner.next().toLowerCase(); token.replaceAll("\\s", ""); } catch (NoSuchElementException e) { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'A' or 'B' in 'push' or 'pop' command."); } if (token.matches("[abx]")) { // Push/Popregister firstPassBuilder.append(token); } else { linescanner.close(); throw new AssemblyError( "Syntax error in line " + realline + ": expected 'A' or 'B' in 'push' or 'pop' command."); } break; // end of call/return/push/pop case "noop": break; // end of noop case "halt": case "swap": case "stkrest": case "return": // Operationen ohne Parameter firstPassBuilder.append(token); break; // end of halt/swap/stkrest/return default: linescanner.close(); throw new AssemblyError( "Unknown command exception in line " + realline + ": expected 'command' or 'label' or 'comment'."); } // end of command parse firstPassBuilder.append(System.lineSeparator()); linescanner.close(); } // end of first pass parse // System.out.println(firstPassBuilder); assemblyscanner.close(); // second pass Scanner firstPassScanner = new Scanner(firstPassBuilder.toString()); List<Byte> instructions = new ArrayList<>(); while (firstPassScanner.hasNextLine()) { Scanner lineS = new Scanner(firstPassScanner.nextLine()); if (!lineS.hasNext()) continue; String token = lineS.next(); // Befehl, Operand byte ib = 0x00, ob = 0x00; switch (token) { case "load": ib = 0x10; token = lineS.next(); // Ursprung if (token.equals("$")) { token = lineS.next(); ob = (byte) integer(token); // Memory-loads sind entweder 0x10 oder 0x11 (vorletztes Bit nicht // gesetzt) } else { ob = (byte) integer(token); // Literal-loads sind entweder 0x12 oder 0x13 (vorletztes Bit gesetzt) ib |= 0x02; } // Zielregister token = lineS.next(); if (token.equals("b")) // die Fälle mit gesetztem letzten Bit sind Ladevorgänge in B ib += 1; break; // end of load case "store": ib = 0x20; token = lineS.next(); // Ursprungsregister if (token.equals("b")) { // vergleiche load ib += 1; } token = lineS.next(); // Zieladdresse ob = (byte) integer(token); break; // end of store case "add": case "sub": case "and": case "or": case "xor": // Erster Teil des Befehls abhängig von Operation switch (token) { case "add": ib = 0x30; break; case "sub": ib = 0x40; break; case "or": ib = 0x50; break; case "xor": ib = 0x60; break; case "and": ib = 0x70; break; } // Zweiter Teil (und Operand) abhängig von weiteren Argument(en) token = lineS.next(); switch (token) { case "b": ib |= 0x00; break; case "x": ib |= 0x01; break; case "$": ib |= 0x02; ob = (byte) integer(lineS.next()); break; case "$b": ib |= 0x03; break; case "$x": ib |= 0x04; break; } break; // end of add case "not": ib = (byte) 0x81; break; case "bitsl": ib = (byte) 0x82; break; case "bitsr": ib = (byte) 0x83; break; case "inc": ib = (byte) 0x84; break; case "dec": ib = (byte) 0x85; break; // end of unary arithmetic case "out": ib = (byte) 0x90; try { token = lineS.next(); } catch (NoSuchElementException e) { // erneut den einfach-Ausgabe-Fall abfangen break; } // erweiterte Ein/Ausgabe switch (token) { case "cmd": ib |= 0x01; break; case "addr": ib |= 0x02; break; case "dat": ib |= 0x03; break; } token = lineS.next(); if (token.equals("$")) { // bringt die Werte von 0x91-0x93 auf 0x94-0x96 ib += 3; token = lineS.next(); } ob = (byte) integer(token); break; // end of out's case "jmp": case "jmpc": case "jmpnc": case "jmpz": case "jmpnz": case "jmpp": case "jmpnp": case "call": // Sprung oder Unterprogramm ib = (byte) 0xA0; switch (token) { case "jmpc": ib |= 0x01; break; case "jmpnc": ib |= 0x02; break; case "jmpz": ib |= 0x03; break; case "jmpnz": ib |= 0x04; break; case "jmpp": ib |= 0x05; break; case "jmpnp": ib |= 0x06; break; case "call": ib |= 0x07; break; } token = lineS.next(); if (token.matches("\\w+")) { // Label: Lookup im Dictionary ob = labelDict.get(token).byteValue(); } else { // Speicheradressenzeiger ignorieren if (token.equals("$")) token = lineS.next(); ob = (byte) integer(token); } break; // end of jump's case "return": ib = (byte) 0xA8; break; // end of return case "move": ib = 0x20; token = lineS.next(); switch (token) { case "a": ib |= 0x02; break; case "b": ib |= 0x05; break; case "sp": ib |= 0x08; break; } token = lineS.next(); // Offset durch zweites Argument sorgt für logische Maschinencodes switch (token) { // a sorgt für keinen Offset case "b": ib += 1; break; case "x": ib += 2; break; } break; // end of move case "swap": ib = 0x2B; break; case "push": case "pop": ib = (byte) 0xB0; if (token.equals("pop")) ib += 1; token = lineS.next(); // bei a passiert keine Erhöhung if (token.equals("b")) ib += 2; break; // end of push/pop case "stkrest": ib = (byte) 0xb4; // Somit weiß die CPU, wo der Stack anfängt ob = SA2_CPU.STACK_START; break; case "halt": ib = 0x01; break; } // end of line instructions.add(ib); instructions.add(ob); lineS.close(); } firstPassScanner.close(); // Speichern des Maschinencodes machineCode = new byte[instructions.size()]; for (int i = 0; i < instructions.size(); ++i) { machineCode[i] = instructions.get(i); } } // end of main constructor /** * Erzeugt einen neuen Assembler und verarbeitet die angegebenen Assemblybefehle * zu Maschinenbefehlen. * * @param assemblycode Datei, deren Inhalt assembled werden soll. * @throws AssemblyError */ public SA2_Assembler(File assemblyFile) throws FileNotFoundException, IOException, AssemblyError { this(new Scanner(assemblyFile)); } /** * @return Die Maschinenbefehle, die dieser Assembler verarbeitet hat. */ public byte[] getMachineCode() { return machineCode; } /** * Die Anzahl der Bytes, die die Maschinenbefehle dieses Assemblers einnehmen. */ public int machineCodeLength() { return machineCode.length; } /** * Druckt den Maschinencode schön formatiert, zweizeilig und hexadezimal. * * @param out Der Ausgabestrom, in den gedruckt wird. */ public void printMachineCode(PrintStream out) { byte end = 0; for (byte b : machineCode) { end++; out.print(stringifyHex(b)); if (end > 1) out.println(); else out.print(" "); end %= 2; } } /** * Erzeugt eine Zahl aus einem dezimalen String; Leerzeichen werden ignoriert. */ private static int integer(String s) throws NumberFormatException { s = s.replaceAll("\\s", ""); return Integer.parseInt(s); } /** * Erzeugt einen dezimalen String aus einer Zahl. */ private static String stringify(int i) { return Integer.toString(i); } /** * Erzeugt einen hexadezimalen String aus einem Byte. Vorzeichen sind egal. */ public static String stringifyHex(byte b) { String sb = Integer.toUnsignedString(b, 16); if (sb.length() > 2) sb = sb.substring(sb.length() - 2, sb.length()); return sb; } /** * Kompiliert ein Operationsliteral (Addition oder Subtraktion von zwei * Operanden) und gibt den Integerwert zurück. */ private static int compileOperationLiteral(String operation) throws AssemblyError { operation = operation.trim(); operation = operation.replaceAll("\\s", ""); // Aufteilen in die beiden Operanden der Addition/Subtraktion String[] operands = operation.split("[\\+-]"); // Die Operation, welche ausgeführt werden soll String operationType = operation.indexOf("+") > -1 ? "+" : (operation.indexOf("-") > -1 ? "-" : "+"); if (operands.length == 1) { // einfaches übernehmen des Operanden return integer(operands[0]); } else if (operands.length == 2) { // Addition oder Subtraktion int val = integer(operands[0]); if (operationType.equalsIgnoreCase("+")) { val += integer(operands[1]); } else if (operationType.equalsIgnoreCase("-")) { val -= integer(operands[1]); } else { // sollte nicht passieren (und dann ist der Benutzer schuld) throw new AssemblyError("Unknown error: inline operation not '+' or '-'."); } return val; } else { throw new AssemblyError("Literal Operation error: inline operation with more than two operands."); } } }
195993_4
package nl.opengeogroep.safetymaps.viewer; import java.sql.Connection; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static nl.opengeogroep.safetymaps.server.db.JSONUtils.rowToJson; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.ColumnListHandler; import org.apache.commons.dbutils.handlers.KeyedHandler; import org.apache.commons.dbutils.handlers.MapListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Class to export object data for safetymaps-viewer, meant for both online use * within safetymaps-server and for exporting to filesystem for offline viewers. * * @author Matthijs Laan */ public class ViewerDataExporter { // TODO LogFactory use, so errors get logged both online and when exporting private Connection c; public ViewerDataExporter(Connection c) { this.c = c; } /** * Get a tag with the latest date an object was modified and total object * count, to use as caching ETag. */ public String getObjectsETag() throws Exception { String key = new QueryRunner().query(c, "select max(datum_actualisatie) || '_' || count(*) from viewer.viewer_object", new ScalarHandler<String>()); key += "_v" + new QueryRunner().query(c, "select max(value) from viewer.schema_version", new ScalarHandler<>()); if(key == null) { return "empty_db"; } else { return key; } } /** * @return All the objects that should be visible in the viewer with all object * properties needed by the viewer as a JSON array, without properties that are * null or empty strings. */ public JSONArray getViewerObjectMapOverview() throws Exception { List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_map", new MapListHandler()); // Not efficient in PostgreSQL: selectieadressen and verdiepingen Set<Integer> verdiepingenIds = new HashSet(new QueryRunner().query(c, "select hoofdobject_id from viewer.viewer_object where hoofdobject_id is not null", new ColumnListHandler<>())); Map selectieadressen = new QueryRunner().query(c, "select * from viewer.viewer_object_selectieadressen", new KeyedHandler<>("id")); JSONArray a = new JSONArray(); for(Map<String, Object> row: rows) { Integer id = (Integer)row.get("id"); String name = (String)row.get("formele_naam"); try { JSONObject o = rowToJson(row, true, true); if(verdiepingenIds.contains(id)) { o.put("heeft_verdiepingen", true); } Map sa = (Map)selectieadressen.get(id); if(sa != null) { o.put("selectieadressen", new JSONArray(sa.get("selectieadressen").toString())); } a.put(o); } catch(Exception e) { throw new Exception(String.format("Error processing object id=%d, name \"%s\"", id, name), e); } } return a; } /** * @return All details for the viewer of an objector null * if the object is not found or visible in the viewer */ public JSONObject getViewerObjectDetails(long id) throws Exception { List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_details where id = ?", new MapListHandler(), id); if(rows.isEmpty()) { return null; } try { return rowToJson(rows.get(0), true, true); } catch(Exception e) { throw new Exception(String.format("Error getting object details for id " + id), e); } } /** * Get all ids of objects that should be visible in the viewer. */ public List<Integer> getViewerObjectIds() throws Exception { return new QueryRunner().query(c, "select id from viewer.viewer_object_map", new ColumnListHandler<Integer>()); } /** * @return All details for viewer objects using a single query */ public List<JSONObject> getAllViewerObjectDetails() throws Exception { List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_details", new MapListHandler()); List<JSONObject> result = new ArrayList(); for(Map<String,Object> row: rows) { Object id = row.get("id"); Object name = row.get("name"); try { result.add(rowToJson(row, true, true)); } catch(Exception e) { throw new Exception(String.format("Error converting object details to JSON for id " + id + ", name " + name), e); } } return result; } /** * Get styling information */ public JSONObject getStyles() throws Exception { JSONObject o = new JSONObject(); JSONObject compartments = new JSONObject(); o.put("compartments", compartments); List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from wfs.type_compartment", new MapListHandler()); for(Map<String,Object> row: rows) { String code = (String)row.get("code"); JSONObject compartment = rowToJson(row, false, false); compartments.put(code, compartment); } JSONObject lines = new JSONObject(); o.put("custom_lines", lines); rows = new QueryRunner().query(c, "select * from wfs.type_custom_line", new MapListHandler()); for(Map<String,Object> row: rows) { String code = (String)row.get("code"); JSONObject line = rowToJson(row, false, false); lines.put(code, line); } JSONObject polygons = new JSONObject(); o.put("custom_polygons", polygons); rows = new QueryRunner().query(c, "select * from wfs.type_custom_polygon", new MapListHandler()); for(Map<String,Object> row: rows) { String code = (String)row.get("code"); JSONObject polygon = rowToJson(row, false, false); polygons.put(code, polygon); } return o; } }
opengeogroep/safetymaps-server
src/main/java/nl/opengeogroep/safetymaps/viewer/ViewerDataExporter.java
1,662
// Not efficient in PostgreSQL: selectieadressen and verdiepingen
line_comment
nl
package nl.opengeogroep.safetymaps.viewer; import java.sql.Connection; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static nl.opengeogroep.safetymaps.server.db.JSONUtils.rowToJson; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.ColumnListHandler; import org.apache.commons.dbutils.handlers.KeyedHandler; import org.apache.commons.dbutils.handlers.MapListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Class to export object data for safetymaps-viewer, meant for both online use * within safetymaps-server and for exporting to filesystem for offline viewers. * * @author Matthijs Laan */ public class ViewerDataExporter { // TODO LogFactory use, so errors get logged both online and when exporting private Connection c; public ViewerDataExporter(Connection c) { this.c = c; } /** * Get a tag with the latest date an object was modified and total object * count, to use as caching ETag. */ public String getObjectsETag() throws Exception { String key = new QueryRunner().query(c, "select max(datum_actualisatie) || '_' || count(*) from viewer.viewer_object", new ScalarHandler<String>()); key += "_v" + new QueryRunner().query(c, "select max(value) from viewer.schema_version", new ScalarHandler<>()); if(key == null) { return "empty_db"; } else { return key; } } /** * @return All the objects that should be visible in the viewer with all object * properties needed by the viewer as a JSON array, without properties that are * null or empty strings. */ public JSONArray getViewerObjectMapOverview() throws Exception { List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_map", new MapListHandler()); // Not efficient<SUF> Set<Integer> verdiepingenIds = new HashSet(new QueryRunner().query(c, "select hoofdobject_id from viewer.viewer_object where hoofdobject_id is not null", new ColumnListHandler<>())); Map selectieadressen = new QueryRunner().query(c, "select * from viewer.viewer_object_selectieadressen", new KeyedHandler<>("id")); JSONArray a = new JSONArray(); for(Map<String, Object> row: rows) { Integer id = (Integer)row.get("id"); String name = (String)row.get("formele_naam"); try { JSONObject o = rowToJson(row, true, true); if(verdiepingenIds.contains(id)) { o.put("heeft_verdiepingen", true); } Map sa = (Map)selectieadressen.get(id); if(sa != null) { o.put("selectieadressen", new JSONArray(sa.get("selectieadressen").toString())); } a.put(o); } catch(Exception e) { throw new Exception(String.format("Error processing object id=%d, name \"%s\"", id, name), e); } } return a; } /** * @return All details for the viewer of an objector null * if the object is not found or visible in the viewer */ public JSONObject getViewerObjectDetails(long id) throws Exception { List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_details where id = ?", new MapListHandler(), id); if(rows.isEmpty()) { return null; } try { return rowToJson(rows.get(0), true, true); } catch(Exception e) { throw new Exception(String.format("Error getting object details for id " + id), e); } } /** * Get all ids of objects that should be visible in the viewer. */ public List<Integer> getViewerObjectIds() throws Exception { return new QueryRunner().query(c, "select id from viewer.viewer_object_map", new ColumnListHandler<Integer>()); } /** * @return All details for viewer objects using a single query */ public List<JSONObject> getAllViewerObjectDetails() throws Exception { List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from viewer.viewer_object_details", new MapListHandler()); List<JSONObject> result = new ArrayList(); for(Map<String,Object> row: rows) { Object id = row.get("id"); Object name = row.get("name"); try { result.add(rowToJson(row, true, true)); } catch(Exception e) { throw new Exception(String.format("Error converting object details to JSON for id " + id + ", name " + name), e); } } return result; } /** * Get styling information */ public JSONObject getStyles() throws Exception { JSONObject o = new JSONObject(); JSONObject compartments = new JSONObject(); o.put("compartments", compartments); List<Map<String,Object>> rows = new QueryRunner().query(c, "select * from wfs.type_compartment", new MapListHandler()); for(Map<String,Object> row: rows) { String code = (String)row.get("code"); JSONObject compartment = rowToJson(row, false, false); compartments.put(code, compartment); } JSONObject lines = new JSONObject(); o.put("custom_lines", lines); rows = new QueryRunner().query(c, "select * from wfs.type_custom_line", new MapListHandler()); for(Map<String,Object> row: rows) { String code = (String)row.get("code"); JSONObject line = rowToJson(row, false, false); lines.put(code, line); } JSONObject polygons = new JSONObject(); o.put("custom_polygons", polygons); rows = new QueryRunner().query(c, "select * from wfs.type_custom_polygon", new MapListHandler()); for(Map<String,Object> row: rows) { String code = (String)row.get("code"); JSONObject polygon = rowToJson(row, false, false); polygons.put(code, polygon); } return o; } }
15071_3
package org.redcross.openmapkit.deployments; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ExpandableListView; import android.widget.ProgressBar; import android.widget.TextView; import org.json.JSONObject; import org.redcross.openmapkit.ExternalStorage; import org.redcross.openmapkit.MapActivity; import org.redcross.openmapkit.R; public class DeploymentDetailsActivity extends AppCompatActivity implements View.OnClickListener, DeploymentDownloaderListener { private Deployment deployment; private FloatingActionButton fab; private FloatingActionButton checkoutFab; private TextView progressTextView; private ProgressBar progressBar; private enum DownloadState { FRESH, DOWNLOADING, CANCELED, ERROR, COMPLETE, DELETED } private DownloadState downloadState = DownloadState.FRESH; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_deployment_details); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(true); } if(android.os.Build.VERSION.SDK_INT >= 21) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(getResources().getColor(R.color.osm_light_green)); } Intent intent = getIntent(); int position = intent.getIntExtra("POSITION", 0); deployment = Deployments.singleton().get(position); deployment.setDownloaderListener(this); String title = deployment.title(); TextView nameTextView = (TextView)findViewById(R.id.nameTextView); nameTextView.setText(title); JSONObject manifest = deployment.json().optJSONObject("manifest"); if (manifest != null) { String description = manifest.optString("description"); TextView descriptionTextView = (TextView)findViewById(R.id.descriptionTextView); descriptionTextView.setText(description); } progressTextView = (TextView)findViewById(R.id.progressTextView); progressBar = (ProgressBar)findViewById(R.id.progressBar); progressBar.setMax((int)deployment.totalSize()); /** * SETUP FOR EXPANDABLE LIST VIEW FOR MBTILES AND OSM FILES */ ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id.expandableListView); FileExpandableListAdapter fileExpandableListAdapter = new FileExpandableListAdapter(this, deployment); expandableListView.setAdapter(fileExpandableListAdapter); /** * FAB to initiate downloads. */ fab = (FloatingActionButton)findViewById(R.id.fab); fab.setOnClickListener(this); checkoutFab = (FloatingActionButton)findViewById(R.id.fab_checkout_deployment); setFreshUIState(); } private void setCancelFab() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_clear_white_36dp, getApplicationContext().getTheme())); } else { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_clear_white_36dp)); } } private void setDeleteFab() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_delete_white_36dp, getApplicationContext().getTheme())); } else { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_delete_white_36dp)); } } private void setDownloadFab() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_file_download_white_36dp, getApplicationContext().getTheme())); } else { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_file_download_white_36dp)); } } private void setFreshUIState() { if (deployment.downloadComplete()) { onDeploymentDownloadComplete(); } else { progressTextView.setText(deployment.fileCount() + " files. Total Size: " + deployment.totalSizeMB()); progressTextView.setTextColor(getResources().getColor(R.color.black)); progressTextView.setTypeface(null, Typeface.NORMAL); progressBar.setProgress(0); setDownloadFab(); checkoutFab.setVisibility(View.GONE); } } /** * FAB OnClickListener method * @param v */ @Override public void onClick(View v) { if (downloadState == DownloadState.FRESH) { startDownload(); return; } if (downloadState == DownloadState.DOWNLOADING) { deployment.cancelDownload(); return; } if (downloadState == DownloadState.COMPLETE) { deleteDownload(); return; } if (downloadState == DownloadState.CANCELED) { startDownload(); return; } if (downloadState == DownloadState.ERROR) { startDownload(); return; } if (downloadState == DownloadState.DELETED) { startDownload(); } } private void startDownload() { if (deployment.fileCount() > 0) { deployment.startDownload(this); setCancelFab(); } else { Snackbar.make(findViewById(R.id.deploymentDetailsActivity), "Does not contain any files. Please check that your server deployment is complete.", Snackbar.LENGTH_LONG) .setAction("Retry", new View.OnClickListener() { // undo action @Override public void onClick(View v) { startDownload(); } }) .setActionTextColor(Color.rgb(126, 188, 111)) .show(); } } private void deleteDownload() { Snackbar.make(findViewById(R.id.deploymentDetailsActivity), "Are you sure you want to delete this deployment?", Snackbar.LENGTH_LONG) .setAction("Delete", new View.OnClickListener() { // undo action @Override public void onClick(View v) { ExternalStorage.deleteDeployment(deployment.name()); downloadState = DownloadState.DELETED; setFreshUIState(); } }) .setActionTextColor(Color.RED) .show(); } /** * DeploymentDownloader Listener Methods */ @Override public void onDeploymentDownloadProgressUpdate(String msg, long bytesDownloaded) { downloadState = DownloadState.DOWNLOADING; progressTextView.setText(msg); progressTextView.setTextColor(getResources().getColor(R.color.black)); progressTextView.setTypeface(null, Typeface.NORMAL); progressBar.setProgress((int) bytesDownloaded); setCancelFab(); } @Override public void onDeploymentDownloadCancel() { downloadState = DownloadState.CANCELED; setDownloadFab(); progressTextView.setText(R.string.deploymentDownloadCanceled); progressTextView.setTextColor(getResources().getColor(R.color.holo_red_light)); progressTextView.setTypeface(null, Typeface.BOLD); checkoutFab.setVisibility(View.GONE); } @Override public void onDeploymentDownloadError(String msg) { downloadState = DownloadState.ERROR; setDownloadFab(); progressTextView.setText(msg); progressTextView.setTextColor(getResources().getColor(R.color.holo_red_light)); progressTextView.setTypeface(null, Typeface.BOLD); checkoutFab.setVisibility(View.GONE); } @Override public void onDeploymentDownloadComplete() { downloadState = DownloadState.COMPLETE; setDeleteFab(); progressTextView.setText(R.string.deploymentDownloadComplete); progressTextView.setTextColor(getResources().getColor(R.color.osm_dark_green)); progressTextView.setTypeface(null, Typeface.BOLD); checkoutFab.setVisibility(View.VISIBLE); } public void fabCheckoutDeploymentClick(View v) { deployment.addToMap(); Intent mapActivity = new Intent(getApplicationContext(), MapActivity.class); startActivity(mapActivity); } }
posm/OpenMapKitAndroid
app/src/main/java/org/redcross/openmapkit/deployments/DeploymentDetailsActivity.java
2,169
/** * DeploymentDownloader Listener Methods */
block_comment
nl
package org.redcross.openmapkit.deployments; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ExpandableListView; import android.widget.ProgressBar; import android.widget.TextView; import org.json.JSONObject; import org.redcross.openmapkit.ExternalStorage; import org.redcross.openmapkit.MapActivity; import org.redcross.openmapkit.R; public class DeploymentDetailsActivity extends AppCompatActivity implements View.OnClickListener, DeploymentDownloaderListener { private Deployment deployment; private FloatingActionButton fab; private FloatingActionButton checkoutFab; private TextView progressTextView; private ProgressBar progressBar; private enum DownloadState { FRESH, DOWNLOADING, CANCELED, ERROR, COMPLETE, DELETED } private DownloadState downloadState = DownloadState.FRESH; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_deployment_details); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(true); } if(android.os.Build.VERSION.SDK_INT >= 21) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(getResources().getColor(R.color.osm_light_green)); } Intent intent = getIntent(); int position = intent.getIntExtra("POSITION", 0); deployment = Deployments.singleton().get(position); deployment.setDownloaderListener(this); String title = deployment.title(); TextView nameTextView = (TextView)findViewById(R.id.nameTextView); nameTextView.setText(title); JSONObject manifest = deployment.json().optJSONObject("manifest"); if (manifest != null) { String description = manifest.optString("description"); TextView descriptionTextView = (TextView)findViewById(R.id.descriptionTextView); descriptionTextView.setText(description); } progressTextView = (TextView)findViewById(R.id.progressTextView); progressBar = (ProgressBar)findViewById(R.id.progressBar); progressBar.setMax((int)deployment.totalSize()); /** * SETUP FOR EXPANDABLE LIST VIEW FOR MBTILES AND OSM FILES */ ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id.expandableListView); FileExpandableListAdapter fileExpandableListAdapter = new FileExpandableListAdapter(this, deployment); expandableListView.setAdapter(fileExpandableListAdapter); /** * FAB to initiate downloads. */ fab = (FloatingActionButton)findViewById(R.id.fab); fab.setOnClickListener(this); checkoutFab = (FloatingActionButton)findViewById(R.id.fab_checkout_deployment); setFreshUIState(); } private void setCancelFab() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_clear_white_36dp, getApplicationContext().getTheme())); } else { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_clear_white_36dp)); } } private void setDeleteFab() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_delete_white_36dp, getApplicationContext().getTheme())); } else { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_delete_white_36dp)); } } private void setDownloadFab() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_file_download_white_36dp, getApplicationContext().getTheme())); } else { fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_file_download_white_36dp)); } } private void setFreshUIState() { if (deployment.downloadComplete()) { onDeploymentDownloadComplete(); } else { progressTextView.setText(deployment.fileCount() + " files. Total Size: " + deployment.totalSizeMB()); progressTextView.setTextColor(getResources().getColor(R.color.black)); progressTextView.setTypeface(null, Typeface.NORMAL); progressBar.setProgress(0); setDownloadFab(); checkoutFab.setVisibility(View.GONE); } } /** * FAB OnClickListener method * @param v */ @Override public void onClick(View v) { if (downloadState == DownloadState.FRESH) { startDownload(); return; } if (downloadState == DownloadState.DOWNLOADING) { deployment.cancelDownload(); return; } if (downloadState == DownloadState.COMPLETE) { deleteDownload(); return; } if (downloadState == DownloadState.CANCELED) { startDownload(); return; } if (downloadState == DownloadState.ERROR) { startDownload(); return; } if (downloadState == DownloadState.DELETED) { startDownload(); } } private void startDownload() { if (deployment.fileCount() > 0) { deployment.startDownload(this); setCancelFab(); } else { Snackbar.make(findViewById(R.id.deploymentDetailsActivity), "Does not contain any files. Please check that your server deployment is complete.", Snackbar.LENGTH_LONG) .setAction("Retry", new View.OnClickListener() { // undo action @Override public void onClick(View v) { startDownload(); } }) .setActionTextColor(Color.rgb(126, 188, 111)) .show(); } } private void deleteDownload() { Snackbar.make(findViewById(R.id.deploymentDetailsActivity), "Are you sure you want to delete this deployment?", Snackbar.LENGTH_LONG) .setAction("Delete", new View.OnClickListener() { // undo action @Override public void onClick(View v) { ExternalStorage.deleteDeployment(deployment.name()); downloadState = DownloadState.DELETED; setFreshUIState(); } }) .setActionTextColor(Color.RED) .show(); } /** * DeploymentDownloader Listener Methods<SUF>*/ @Override public void onDeploymentDownloadProgressUpdate(String msg, long bytesDownloaded) { downloadState = DownloadState.DOWNLOADING; progressTextView.setText(msg); progressTextView.setTextColor(getResources().getColor(R.color.black)); progressTextView.setTypeface(null, Typeface.NORMAL); progressBar.setProgress((int) bytesDownloaded); setCancelFab(); } @Override public void onDeploymentDownloadCancel() { downloadState = DownloadState.CANCELED; setDownloadFab(); progressTextView.setText(R.string.deploymentDownloadCanceled); progressTextView.setTextColor(getResources().getColor(R.color.holo_red_light)); progressTextView.setTypeface(null, Typeface.BOLD); checkoutFab.setVisibility(View.GONE); } @Override public void onDeploymentDownloadError(String msg) { downloadState = DownloadState.ERROR; setDownloadFab(); progressTextView.setText(msg); progressTextView.setTextColor(getResources().getColor(R.color.holo_red_light)); progressTextView.setTypeface(null, Typeface.BOLD); checkoutFab.setVisibility(View.GONE); } @Override public void onDeploymentDownloadComplete() { downloadState = DownloadState.COMPLETE; setDeleteFab(); progressTextView.setText(R.string.deploymentDownloadComplete); progressTextView.setTextColor(getResources().getColor(R.color.osm_dark_green)); progressTextView.setTypeface(null, Typeface.BOLD); checkoutFab.setVisibility(View.VISIBLE); } public void fabCheckoutDeploymentClick(View v) { deployment.addToMap(); Intent mapActivity = new Intent(getApplicationContext(), MapActivity.class); startActivity(mapActivity); } }
21646_1
package nl.kennisnet.arena.services; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import nl.kennisnet.arena.client.domain.QuestDTO; import nl.kennisnet.arena.model.Participant; import nl.kennisnet.arena.model.Participation; import nl.kennisnet.arena.model.Quest; import nl.kennisnet.arena.repository.LocationRepository; import nl.kennisnet.arena.repository.ParticipantRepository; import nl.kennisnet.arena.repository.ParticipationRepository; import nl.kennisnet.arena.repository.PositionableRepository; import nl.kennisnet.arena.repository.QuestRepository; import nl.kennisnet.arena.services.factories.DTOFactory; import nl.kennisnet.arena.services.factories.DomainObjectFactory; import nl.kennisnet.arena.utils.UtilityHelper; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.InputStreamSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class QuestService { private static final int INITIAL_SCORE = 0; private static final String newLine = System.getProperty("line.separator"); @Autowired private LocationRepository locationRepository; @Autowired PositionableRepository positionableRepository; @Autowired private ParticipationRepository participationRepository; @Autowired private QuestRepository questRepository; @Autowired private ParticipantRepository participantRepository; @Autowired private JavaMailSender mailSender; @Autowired private CompositeConfiguration configuration; @Autowired private ParticipantService participantService; private Logger log = Logger.getLogger(QuestService.class); public Quest getQuest(final Long questId) { return questRepository.get(questId); } public void getQuest(final Long questId, final TransactionalCallback<Quest> callback) { callback.onResult(getQuest(questId)); } public QuestDTO getQuestDTO(Long id) { Quest quest = getQuest(id); if (quest != null) { return DTOFactory.create(quest); } return null; } public void buildQrCodesPdf(String url, long questId, OutputStream outputStream) { QrCodesPdfBuilder builder = new QrCodesPdfBuilder(url, participantService.getAllParticipants()); builder.setQuestId(questId); builder.build(outputStream); } public long participateInQuest(long participantId, Quest quest) { Participant participant = participantRepository.get(participantId); Participation participation = participationRepository .findParticipation(participant, quest, quest.getActiveRound()); if (participation != null) { return participation.getId(); } else { Participation part = new Participation(participant, quest, INITIAL_SCORE); return participationRepository.merge(part).getId(); } } public QuestDTO save(QuestDTO questDTO, boolean sendNotification) { boolean update = false; Quest originalQuest = null; if (questDTO.getId() != null) { originalQuest = questRepository.get(questDTO.getId()); } Quest quest = null; if (originalQuest == null || !savedByOwner(questDTO, originalQuest)) { quest = DomainObjectFactory.create(questDTO); } else { quest = DomainObjectFactory.update(questDTO, originalQuest); update = true; } quest = questRepository.merge(quest); if (sendNotification && !update) { // sendNotification(quest); } return DTOFactory.create(quest); } private boolean savedByOwner(QuestDTO questDTO, Quest originalQuest) { return originalQuest != null && originalQuest.getEmailOwner().equals(questDTO.getEmailOwner()); } private void sendNotification(Quest quest) { try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(quest.getEmailOwner()); helper.setText(createMailText(quest)); helper.setSubject("Bewaard: ARena " + quest.getName()); helper.setFrom(configuration.getString("mail.from.adres")); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); System.out.println(createGamarayUrl(quest)); buildQrCodesPdf(createGamarayUrl(quest), quest.getId(), outputStream); byte[] byteArray = outputStream.toByteArray(); InputStreamSource source = new ByteArrayResource(byteArray); helper.addAttachment(String.format("ToegangsTickets_%s_%s.pdf", quest.getName(), currentShortDate(new Locale("nl"))), source); mailSender.send(message); } catch (MessagingException ex) { log.error("Failed to send saved quest mail", ex); } } private String createGamarayUrl(Quest quest) { String baseUrl = UtilityHelper.getBaseUrl(configuration); String url = String.format("%smixare/%d.mix", baseUrl, quest.getId()); return url; } private String createMailText(Quest quest) { StringBuffer result = new StringBuffer(); String baseUrl = UtilityHelper.getBaseUrl(configuration); String designerUrl = String.format("%smain.do?arenaId=%s", baseUrl, quest.getId()); // String monitorUrl = String.format("%s/ARenaMonitor.html?arenaId=%s", // baseUrl, quest.getId()); result.append("Beste " + quest.getEmailOwner() + newLine + newLine); result.append("U heeft op " + currentDate(new Locale("nl")) + " om " + currentTime(new Locale("nl")) + " uw ontwerp opgeslagen:" + newLine); result.append("Arena : " + quest.getName() + " " + newLine); result.append("Opgeslagen op: " + designerUrl + "" + newLine); result.append("" + newLine); result.append("U kunt uw ontwerp op ieder moment aanpassen via de bovenstaande link. " + newLine); result.append("" + newLine); result.append("Gebruik maken van de Arena" + newLine); result.append("ARena " + quest.getName() + " is nu actief en deelnemers kunnen hem 24 uur/dag ervaren. " + newLine); result.append("Om de deelnemers de Arena te laten ervaren dienen zij in het bezit te zijn van een toegangsticket. " + "Door de toegangstickets (PDF) uit te printen en aan de deelnemers verstrekken hebben zij toegang tot de Arena." + newLine); result.append("" + newLine); result.append("Resultaten van de deelnemers" + newLine); result.append("Via onderstaande link vindt u direct de resultaten van de deelnemende teams." + " Het overzicht wordt Live ververst, bij iedere activiteit in uw ARena." + newLine); result.append(newLine); result.append("Het PDF bestand kan niet worden geopend" + newLine); result.append("Het PDF bestand bevat de elektronische toegangstickets. Om dit bestand te openen heeft u de software “Adobe Reader” nodig. " + "Installeer de gratis software Adobe Reader (http://get.adobe.com/reader/) en open het bestand nogmaals " + newLine); result.append("" + newLine); result.append("" + newLine); result.append("Veel leerplezier," + newLine); result.append("" + newLine); result.append("het ARena Team" + newLine); result.append("E: [email protected]" + newLine); result.append("" + newLine); result.append("Stichting Kennisnet" + newLine); result.append("Surfnet/Kennisnet Innovatieprogramma" + newLine); result.append("" + newLine); result.append("ARena is een experimenteel project. Wij ontvangen graag uw verbetersuggesties, ervaringen en vragen." + newLine); return result.toString(); } private String currentDate(Locale locale) { SimpleDateFormat format = new SimpleDateFormat("EEEE dd MMMM yyyy", locale); return format.format(new Date()); } private String currentShortDate(Locale locale) { SimpleDateFormat format = new SimpleDateFormat("ddMMyy", locale); return format.format(new Date()); } private String currentTime(Locale locale) { SimpleDateFormat format = new SimpleDateFormat("k:mm", locale); return format.format(new Date()); } }
finalist/Project-Arena-Server
src/main/java/nl/kennisnet/arena/services/QuestService.java
2,213
//get.adobe.com/reader/) en open het bestand nogmaals "
line_comment
nl
package nl.kennisnet.arena.services; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import nl.kennisnet.arena.client.domain.QuestDTO; import nl.kennisnet.arena.model.Participant; import nl.kennisnet.arena.model.Participation; import nl.kennisnet.arena.model.Quest; import nl.kennisnet.arena.repository.LocationRepository; import nl.kennisnet.arena.repository.ParticipantRepository; import nl.kennisnet.arena.repository.ParticipationRepository; import nl.kennisnet.arena.repository.PositionableRepository; import nl.kennisnet.arena.repository.QuestRepository; import nl.kennisnet.arena.services.factories.DTOFactory; import nl.kennisnet.arena.services.factories.DomainObjectFactory; import nl.kennisnet.arena.utils.UtilityHelper; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.InputStreamSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class QuestService { private static final int INITIAL_SCORE = 0; private static final String newLine = System.getProperty("line.separator"); @Autowired private LocationRepository locationRepository; @Autowired PositionableRepository positionableRepository; @Autowired private ParticipationRepository participationRepository; @Autowired private QuestRepository questRepository; @Autowired private ParticipantRepository participantRepository; @Autowired private JavaMailSender mailSender; @Autowired private CompositeConfiguration configuration; @Autowired private ParticipantService participantService; private Logger log = Logger.getLogger(QuestService.class); public Quest getQuest(final Long questId) { return questRepository.get(questId); } public void getQuest(final Long questId, final TransactionalCallback<Quest> callback) { callback.onResult(getQuest(questId)); } public QuestDTO getQuestDTO(Long id) { Quest quest = getQuest(id); if (quest != null) { return DTOFactory.create(quest); } return null; } public void buildQrCodesPdf(String url, long questId, OutputStream outputStream) { QrCodesPdfBuilder builder = new QrCodesPdfBuilder(url, participantService.getAllParticipants()); builder.setQuestId(questId); builder.build(outputStream); } public long participateInQuest(long participantId, Quest quest) { Participant participant = participantRepository.get(participantId); Participation participation = participationRepository .findParticipation(participant, quest, quest.getActiveRound()); if (participation != null) { return participation.getId(); } else { Participation part = new Participation(participant, quest, INITIAL_SCORE); return participationRepository.merge(part).getId(); } } public QuestDTO save(QuestDTO questDTO, boolean sendNotification) { boolean update = false; Quest originalQuest = null; if (questDTO.getId() != null) { originalQuest = questRepository.get(questDTO.getId()); } Quest quest = null; if (originalQuest == null || !savedByOwner(questDTO, originalQuest)) { quest = DomainObjectFactory.create(questDTO); } else { quest = DomainObjectFactory.update(questDTO, originalQuest); update = true; } quest = questRepository.merge(quest); if (sendNotification && !update) { // sendNotification(quest); } return DTOFactory.create(quest); } private boolean savedByOwner(QuestDTO questDTO, Quest originalQuest) { return originalQuest != null && originalQuest.getEmailOwner().equals(questDTO.getEmailOwner()); } private void sendNotification(Quest quest) { try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(quest.getEmailOwner()); helper.setText(createMailText(quest)); helper.setSubject("Bewaard: ARena " + quest.getName()); helper.setFrom(configuration.getString("mail.from.adres")); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); System.out.println(createGamarayUrl(quest)); buildQrCodesPdf(createGamarayUrl(quest), quest.getId(), outputStream); byte[] byteArray = outputStream.toByteArray(); InputStreamSource source = new ByteArrayResource(byteArray); helper.addAttachment(String.format("ToegangsTickets_%s_%s.pdf", quest.getName(), currentShortDate(new Locale("nl"))), source); mailSender.send(message); } catch (MessagingException ex) { log.error("Failed to send saved quest mail", ex); } } private String createGamarayUrl(Quest quest) { String baseUrl = UtilityHelper.getBaseUrl(configuration); String url = String.format("%smixare/%d.mix", baseUrl, quest.getId()); return url; } private String createMailText(Quest quest) { StringBuffer result = new StringBuffer(); String baseUrl = UtilityHelper.getBaseUrl(configuration); String designerUrl = String.format("%smain.do?arenaId=%s", baseUrl, quest.getId()); // String monitorUrl = String.format("%s/ARenaMonitor.html?arenaId=%s", // baseUrl, quest.getId()); result.append("Beste " + quest.getEmailOwner() + newLine + newLine); result.append("U heeft op " + currentDate(new Locale("nl")) + " om " + currentTime(new Locale("nl")) + " uw ontwerp opgeslagen:" + newLine); result.append("Arena : " + quest.getName() + " " + newLine); result.append("Opgeslagen op: " + designerUrl + "" + newLine); result.append("" + newLine); result.append("U kunt uw ontwerp op ieder moment aanpassen via de bovenstaande link. " + newLine); result.append("" + newLine); result.append("Gebruik maken van de Arena" + newLine); result.append("ARena " + quest.getName() + " is nu actief en deelnemers kunnen hem 24 uur/dag ervaren. " + newLine); result.append("Om de deelnemers de Arena te laten ervaren dienen zij in het bezit te zijn van een toegangsticket. " + "Door de toegangstickets (PDF) uit te printen en aan de deelnemers verstrekken hebben zij toegang tot de Arena." + newLine); result.append("" + newLine); result.append("Resultaten van de deelnemers" + newLine); result.append("Via onderstaande link vindt u direct de resultaten van de deelnemende teams." + " Het overzicht wordt Live ververst, bij iedere activiteit in uw ARena." + newLine); result.append(newLine); result.append("Het PDF bestand kan niet worden geopend" + newLine); result.append("Het PDF bestand bevat de elektronische toegangstickets. Om dit bestand te openen heeft u de software “Adobe Reader” nodig. " + "Installeer de gratis software Adobe Reader (http://get.adobe.com/reader/) <SUF> + newLine); result.append("" + newLine); result.append("" + newLine); result.append("Veel leerplezier," + newLine); result.append("" + newLine); result.append("het ARena Team" + newLine); result.append("E: [email protected]" + newLine); result.append("" + newLine); result.append("Stichting Kennisnet" + newLine); result.append("Surfnet/Kennisnet Innovatieprogramma" + newLine); result.append("" + newLine); result.append("ARena is een experimenteel project. Wij ontvangen graag uw verbetersuggesties, ervaringen en vragen." + newLine); return result.toString(); } private String currentDate(Locale locale) { SimpleDateFormat format = new SimpleDateFormat("EEEE dd MMMM yyyy", locale); return format.format(new Date()); } private String currentShortDate(Locale locale) { SimpleDateFormat format = new SimpleDateFormat("ddMMyy", locale); return format.format(new Date()); } private String currentTime(Locale locale) { SimpleDateFormat format = new SimpleDateFormat("k:mm", locale); return format.format(new Date()); } }
57133_24
/* * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xrengine.xr.rendering; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.opengl.Matrix; import com.google.ar.core.Camera; import com.google.ar.core.Plane; import com.google.ar.core.Pose; import com.google.ar.core.Trackable.*; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Renders the detected AR planes. */ public class PlaneRenderer { private static final String TAG = PlaneRenderer.class.getSimpleName(); private static final int BYTES_PER_FLOAT = Float.SIZE / 8; private static final int BYTES_PER_SHORT = Short.SIZE / 8; private static final int COORDS_PER_VERTEX = 3; // x, z, alpha private static final int VERTS_PER_BOUNDARY_VERT = 2; private static final int INDICES_PER_BOUNDARY_VERT = 3; private static final int INITIAL_BUFFER_BOUNDARY_VERTS = 64; private static final int INITIAL_VERTEX_BUFFER_SIZE_BYTES = BYTES_PER_FLOAT * COORDS_PER_VERTEX * VERTS_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS; private static final int INITIAL_INDEX_BUFFER_SIZE_BYTES = BYTES_PER_SHORT * INDICES_PER_BOUNDARY_VERT * INDICES_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS; private static final float FADE_RADIUS_M = 0.25f; private static final float DOTS_PER_METER = 10.0f; private static final float EQUILATERAL_TRIANGLE_SCALE = (float) (1 / Math.sqrt(3)); // Using the "signed distance field" approach to render sharp lines and circles. // {dotThreshold, lineThreshold, lineFadeSpeed, occlusionScale} // dotThreshold/lineThreshold: red/green intensity above which dots/lines are present // lineFadeShrink: lines will fade in between alpha = 1-(1/lineFadeShrink) and 1.0 // occlusionShrink: occluded planes will fade out between alpha = 0 and 1/occlusionShrink private static final float[] GRID_CONTROL = {0.2f, 0.4f, 2.0f, 1.5f}; private int mPlaneProgram; private int[] mTextures = new int[1]; private int mPlaneXZPositionAlphaAttribute; private int mPlaneModelUniform; private int mPlaneModelViewProjectionUniform; private int mTextureUniform; private int mLineColorUniform; private int mDotColorUniform; private int mGridControlUniform; private int mPlaneUvMatrixUniform; private FloatBuffer mVertexBuffer = ByteBuffer.allocateDirect(INITIAL_VERTEX_BUFFER_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asFloatBuffer(); private ShortBuffer mIndexBuffer = ByteBuffer.allocateDirect(INITIAL_INDEX_BUFFER_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asShortBuffer(); // Temporary lists/matrices allocated here to reduce number of allocations for each frame. private float[] mModelMatrix = new float[16]; private float[] mModelViewMatrix = new float[16]; private float[] mModelViewProjectionMatrix = new float[16]; private float[] mPlaneColor = new float[4]; private float[] mPlaneAngleUvMatrix = new float[4]; // 2x2 rotation matrix applied to uv coords. private Map<Plane, Integer> mPlaneIndexMap = new HashMap<Plane, Integer>(); public PlaneRenderer() { } /** * Allocates and initializes OpenGL resources needed by the plane renderer. Must be * called on the OpenGL thread, typically in * {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}. * * @param context Needed to access shader source and texture PNG. * @param gridDistanceTextureName Name of the PNG file containing the grid texture. */ public void createOnGlThread(Context context, String gridDistanceTextureName) throws IOException { // TODO: UNCOMMENT instead of = 0 int vertexShader = 0; // ShaderUtil.loadGLShader(TAG, context, // GLES20.GL_VERTEX_SHADER, R.raw.plane_vertex); int passthroughShader = 0; // ShaderUtil.loadGLShader(TAG, context, // GLES20.GL_FRAGMENT_SHADER, R.raw.plane_fragment); mPlaneProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(mPlaneProgram, vertexShader); GLES20.glAttachShader(mPlaneProgram, passthroughShader); GLES20.glLinkProgram(mPlaneProgram); GLES20.glUseProgram(mPlaneProgram); ShaderUtil.checkGLError(TAG, "Program creation"); // Read the texture. Bitmap textureBitmap = BitmapFactory.decodeStream( context.getAssets().open(gridDistanceTextureName)); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glGenTextures(mTextures.length, mTextures, 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextures[0]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, textureBitmap, 0); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); ShaderUtil.checkGLError(TAG, "Texture loading"); mPlaneXZPositionAlphaAttribute = GLES20.glGetAttribLocation(mPlaneProgram, "a_XZPositionAlpha"); mPlaneModelUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_Model"); mPlaneModelViewProjectionUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_ModelViewProjection"); mTextureUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_Texture"); mLineColorUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_lineColor"); mDotColorUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_dotColor"); mGridControlUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_gridControl"); mPlaneUvMatrixUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_PlaneUvMatrix"); ShaderUtil.checkGLError(TAG, "Program parameters"); } /** * Updates the plane model transform matrix and extents. */ private void updatePlaneParameters(float[] planeMatrix, float extentX, float extentZ, FloatBuffer boundary) { System.arraycopy(planeMatrix, 0, mModelMatrix, 0, 16); if (boundary == null) { mVertexBuffer.limit(0); mIndexBuffer.limit(0); return; } // Generate a new set of vertices and a corresponding triangle strip index set so that // the plane boundary polygon has a fading edge. This is done by making a copy of the // boundary polygon vertices and scaling it down around center to push it inwards. Then // the index buffer is setup accordingly. boundary.rewind(); int boundaryVertices = boundary.limit() / 2; int numVertices; int numIndices; numVertices = boundaryVertices * VERTS_PER_BOUNDARY_VERT; // drawn as GL_TRIANGLE_STRIP with 3n-2 triangles (n-2 for fill, 2n for perimeter). numIndices = boundaryVertices * INDICES_PER_BOUNDARY_VERT; if (mVertexBuffer.capacity() < numVertices * COORDS_PER_VERTEX) { int size = mVertexBuffer.capacity(); while (size < numVertices * COORDS_PER_VERTEX) { size *= 2; } mVertexBuffer = ByteBuffer.allocateDirect(BYTES_PER_FLOAT * size) .order(ByteOrder.nativeOrder()).asFloatBuffer(); } mVertexBuffer.rewind(); mVertexBuffer.limit(numVertices * COORDS_PER_VERTEX); if (mIndexBuffer.capacity() < numIndices) { int size = mIndexBuffer.capacity(); while (size < numIndices) { size *= 2; } mIndexBuffer = ByteBuffer.allocateDirect(BYTES_PER_SHORT * size) .order(ByteOrder.nativeOrder()).asShortBuffer(); } mIndexBuffer.rewind(); mIndexBuffer.limit(numIndices); // Note: when either dimension of the bounding box is smaller than 2*FADE_RADIUS_M we // generate a bunch of 0-area triangles. These don't get rendered though so it works // out ok. float xScale = Math.max((extentX - 2 * FADE_RADIUS_M) / extentX, 0.0f); float zScale = Math.max((extentZ - 2 * FADE_RADIUS_M) / extentZ, 0.0f); while (boundary.hasRemaining()) { float x = boundary.get(); float z = boundary.get(); mVertexBuffer.put(x); mVertexBuffer.put(z); mVertexBuffer.put(0.0f); mVertexBuffer.put(x * xScale); mVertexBuffer.put(z * zScale); mVertexBuffer.put(1.0f); } // step 1, perimeter mIndexBuffer.put((short) ((boundaryVertices - 1) * 2)); for (int i = 0; i < boundaryVertices; ++i) { mIndexBuffer.put((short) (i * 2)); mIndexBuffer.put((short) (i * 2 + 1)); } mIndexBuffer.put((short) 1); // This leaves us on the interior edge of the perimeter between the inset vertices // for boundary verts n-1 and 0. // step 2, interior: for (int i = 1; i < boundaryVertices / 2; ++i) { mIndexBuffer.put((short) ((boundaryVertices - 1 - i) * 2 + 1)); mIndexBuffer.put((short) (i * 2 + 1)); } if (boundaryVertices % 2 != 0) { mIndexBuffer.put((short) ((boundaryVertices / 2) * 2 + 1)); } } private void draw(float[] cameraView, float[] cameraPerspective) { // Build the ModelView and ModelViewProjection matrices // for calculating cube position and light. Matrix.multiplyMM(mModelViewMatrix, 0, cameraView, 0, mModelMatrix, 0); Matrix.multiplyMM(mModelViewProjectionMatrix, 0, cameraPerspective, 0, mModelViewMatrix, 0); // Set the position of the plane mVertexBuffer.rewind(); GLES20.glVertexAttribPointer( mPlaneXZPositionAlphaAttribute, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, BYTES_PER_FLOAT * COORDS_PER_VERTEX, mVertexBuffer); // Set the Model and ModelViewProjection matrices in the shader. GLES20.glUniformMatrix4fv(mPlaneModelUniform, 1, false, mModelMatrix, 0); GLES20.glUniformMatrix4fv( mPlaneModelViewProjectionUniform, 1, false, mModelViewProjectionMatrix, 0); mIndexBuffer.rewind(); GLES20.glDrawElements(GLES20.GL_TRIANGLE_STRIP, mIndexBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, mIndexBuffer); ShaderUtil.checkGLError(TAG, "Drawing plane"); } static class SortablePlane { final float mDistance; final Plane mPlane; SortablePlane(float distance, Plane plane) { this.mDistance = distance; this.mPlane = plane; } } /** * Draws the collection of tracked planes, with closer planes hiding more distant ones. * * @param allPlanes The collection of planes to draw. * @param cameraPose The pose of the camera, as returned by {@link Camera#getPose()} * @param cameraPerspective The projection matrix, as returned by * {@link Camera#getProjectionMatrix(float[], int, float, float)} */ public void drawPlanes(Collection<Plane> allPlanes, Pose cameraPose, float[] cameraPerspective) { // Planes must be sorted by distance from camera so that we draw closer planes first, and // they occlude the farther planes. List<SortablePlane> sortedPlanes = new ArrayList<SortablePlane>(); float[] normal = new float[3]; float cameraX = cameraPose.tx(); float cameraY = cameraPose.ty(); float cameraZ = cameraPose.tz(); for (Plane plane : allPlanes) { // if (plane.getTrackingState() != TrackingState.TRACKING // || plane.getSubsumedBy() != null) { // continue; // } Pose center = plane.getCenterPose(); // Get transformed Y axis of plane's coordinate system. center.getTransformedAxis(1, 1.0f, normal, 0); // Compute dot product of plane's normal with vector from camera to plane center. float distance = (cameraX - center.tx()) * normal[0] + (cameraY - center.ty()) * normal[1] + (cameraZ - center.tz()) * normal[2]; if (distance < 0) { // Plane is back-facing. continue; } sortedPlanes.add(new SortablePlane(distance, plane)); } Collections.sort(sortedPlanes, new Comparator<SortablePlane>() { @Override public int compare(SortablePlane a, SortablePlane b) { return Float.compare(a.mDistance, b.mDistance); } }); float[] cameraView = new float[16]; cameraPose.inverse().toMatrix(cameraView, 0); // Planes are drawn with additive blending, masked by the alpha channel for occlusion. // Start by clearing the alpha channel of the color buffer to 1.0. GLES20.glClearColor(1, 1, 1, 1); GLES20.glColorMask(false, false, false, true); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); GLES20.glColorMask(true, true, true, true); // Disable depth write. GLES20.glDepthMask(false); // Additive blending, masked by alpha channel, clearing alpha channel. GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFuncSeparate( GLES20.GL_DST_ALPHA, GLES20.GL_ONE, // RGB (src, dest) GLES20.GL_ZERO, GLES20.GL_ONE_MINUS_SRC_ALPHA); // ALPHA (src, dest) // Set up the shader. GLES20.glUseProgram(mPlaneProgram); // Attach the texture. GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextures[0]); GLES20.glUniform1i(mTextureUniform, 0); // Shared fragment uniforms. GLES20.glUniform4fv(mGridControlUniform, 1, GRID_CONTROL, 0); // Enable vertex arrays GLES20.glEnableVertexAttribArray(mPlaneXZPositionAlphaAttribute); ShaderUtil.checkGLError(TAG, "Setting up to draw planes"); for (SortablePlane sortedPlane : sortedPlanes) { Plane plane = sortedPlane.mPlane; float[] planeMatrix = new float[16]; plane.getCenterPose().toMatrix(planeMatrix, 0); updatePlaneParameters( planeMatrix, plane.getExtentX(), plane.getExtentZ(), plane.getPolygon()); // Get plane index. Keep a map to assign same indices to same planes. Integer planeIndex = mPlaneIndexMap.get(plane); if (planeIndex == null) { planeIndex = mPlaneIndexMap.size(); mPlaneIndexMap.put(plane, planeIndex); } // Set plane color. Computed deterministically from the Plane index. int colorIndex = planeIndex % PLANE_COLORS_RGBA.length; colorRgbaToFloat(mPlaneColor, PLANE_COLORS_RGBA[colorIndex]); GLES20.glUniform4fv(mLineColorUniform, 1, mPlaneColor, 0); GLES20.glUniform4fv(mDotColorUniform, 1, mPlaneColor, 0); // Each plane will have its own angle offset from others, to make them easier to // distinguish. Compute a 2x2 rotation matrix from the angle. float angleRadians = planeIndex * 0.144f; float uScale = DOTS_PER_METER; float vScale = DOTS_PER_METER * EQUILATERAL_TRIANGLE_SCALE; mPlaneAngleUvMatrix[0] = +(float) Math.cos(angleRadians) * uScale; mPlaneAngleUvMatrix[1] = -(float) Math.sin(angleRadians) * vScale; mPlaneAngleUvMatrix[2] = +(float) Math.sin(angleRadians) * uScale; mPlaneAngleUvMatrix[3] = +(float) Math.cos(angleRadians) * vScale; GLES20.glUniformMatrix2fv(mPlaneUvMatrixUniform, 1, false, mPlaneAngleUvMatrix, 0); draw(cameraView, cameraPerspective); } // Clean up the state we set GLES20.glDisableVertexAttribArray(mPlaneXZPositionAlphaAttribute); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDepthMask(true); ShaderUtil.checkGLError(TAG, "Cleaning up after drawing planes"); } private static void colorRgbaToFloat(float[] planeColor, int colorRgba) { planeColor[0] = ((float) ((colorRgba >> 24) & 0xff)) / 255.0f; planeColor[1] = ((float) ((colorRgba >> 16) & 0xff)) / 255.0f; planeColor[2] = ((float) ((colorRgba >> 8) & 0xff)) / 255.0f; planeColor[3] = ((float) ((colorRgba >> 0) & 0xff)) / 255.0f; } private static final int[] PLANE_COLORS_RGBA = { 0xFFFFFFFF, 0xF44336FF, 0xE91E63FF, 0x9C27B0FF, 0x673AB7FF, 0x3F51B5FF, 0x2196F3FF, 0x03A9F4FF, 0x00BCD4FF, 0x009688FF, 0x4CAF50FF, 0x8BC34AFF, 0xCDDC39FF, 0xFFEB3BFF, 0xFFC107FF, 0xFF9800FF, }; }
EtherealEngine/Native-XR-for-Web
android/src/main/java/com/xrengine/xr/rendering/PlaneRenderer.java
5,176
// step 2, interior:
line_comment
nl
/* * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xrengine.xr.rendering; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.opengl.Matrix; import com.google.ar.core.Camera; import com.google.ar.core.Plane; import com.google.ar.core.Pose; import com.google.ar.core.Trackable.*; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Renders the detected AR planes. */ public class PlaneRenderer { private static final String TAG = PlaneRenderer.class.getSimpleName(); private static final int BYTES_PER_FLOAT = Float.SIZE / 8; private static final int BYTES_PER_SHORT = Short.SIZE / 8; private static final int COORDS_PER_VERTEX = 3; // x, z, alpha private static final int VERTS_PER_BOUNDARY_VERT = 2; private static final int INDICES_PER_BOUNDARY_VERT = 3; private static final int INITIAL_BUFFER_BOUNDARY_VERTS = 64; private static final int INITIAL_VERTEX_BUFFER_SIZE_BYTES = BYTES_PER_FLOAT * COORDS_PER_VERTEX * VERTS_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS; private static final int INITIAL_INDEX_BUFFER_SIZE_BYTES = BYTES_PER_SHORT * INDICES_PER_BOUNDARY_VERT * INDICES_PER_BOUNDARY_VERT * INITIAL_BUFFER_BOUNDARY_VERTS; private static final float FADE_RADIUS_M = 0.25f; private static final float DOTS_PER_METER = 10.0f; private static final float EQUILATERAL_TRIANGLE_SCALE = (float) (1 / Math.sqrt(3)); // Using the "signed distance field" approach to render sharp lines and circles. // {dotThreshold, lineThreshold, lineFadeSpeed, occlusionScale} // dotThreshold/lineThreshold: red/green intensity above which dots/lines are present // lineFadeShrink: lines will fade in between alpha = 1-(1/lineFadeShrink) and 1.0 // occlusionShrink: occluded planes will fade out between alpha = 0 and 1/occlusionShrink private static final float[] GRID_CONTROL = {0.2f, 0.4f, 2.0f, 1.5f}; private int mPlaneProgram; private int[] mTextures = new int[1]; private int mPlaneXZPositionAlphaAttribute; private int mPlaneModelUniform; private int mPlaneModelViewProjectionUniform; private int mTextureUniform; private int mLineColorUniform; private int mDotColorUniform; private int mGridControlUniform; private int mPlaneUvMatrixUniform; private FloatBuffer mVertexBuffer = ByteBuffer.allocateDirect(INITIAL_VERTEX_BUFFER_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asFloatBuffer(); private ShortBuffer mIndexBuffer = ByteBuffer.allocateDirect(INITIAL_INDEX_BUFFER_SIZE_BYTES) .order(ByteOrder.nativeOrder()).asShortBuffer(); // Temporary lists/matrices allocated here to reduce number of allocations for each frame. private float[] mModelMatrix = new float[16]; private float[] mModelViewMatrix = new float[16]; private float[] mModelViewProjectionMatrix = new float[16]; private float[] mPlaneColor = new float[4]; private float[] mPlaneAngleUvMatrix = new float[4]; // 2x2 rotation matrix applied to uv coords. private Map<Plane, Integer> mPlaneIndexMap = new HashMap<Plane, Integer>(); public PlaneRenderer() { } /** * Allocates and initializes OpenGL resources needed by the plane renderer. Must be * called on the OpenGL thread, typically in * {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}. * * @param context Needed to access shader source and texture PNG. * @param gridDistanceTextureName Name of the PNG file containing the grid texture. */ public void createOnGlThread(Context context, String gridDistanceTextureName) throws IOException { // TODO: UNCOMMENT instead of = 0 int vertexShader = 0; // ShaderUtil.loadGLShader(TAG, context, // GLES20.GL_VERTEX_SHADER, R.raw.plane_vertex); int passthroughShader = 0; // ShaderUtil.loadGLShader(TAG, context, // GLES20.GL_FRAGMENT_SHADER, R.raw.plane_fragment); mPlaneProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(mPlaneProgram, vertexShader); GLES20.glAttachShader(mPlaneProgram, passthroughShader); GLES20.glLinkProgram(mPlaneProgram); GLES20.glUseProgram(mPlaneProgram); ShaderUtil.checkGLError(TAG, "Program creation"); // Read the texture. Bitmap textureBitmap = BitmapFactory.decodeStream( context.getAssets().open(gridDistanceTextureName)); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glGenTextures(mTextures.length, mTextures, 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextures[0]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, textureBitmap, 0); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); ShaderUtil.checkGLError(TAG, "Texture loading"); mPlaneXZPositionAlphaAttribute = GLES20.glGetAttribLocation(mPlaneProgram, "a_XZPositionAlpha"); mPlaneModelUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_Model"); mPlaneModelViewProjectionUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_ModelViewProjection"); mTextureUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_Texture"); mLineColorUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_lineColor"); mDotColorUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_dotColor"); mGridControlUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_gridControl"); mPlaneUvMatrixUniform = GLES20.glGetUniformLocation(mPlaneProgram, "u_PlaneUvMatrix"); ShaderUtil.checkGLError(TAG, "Program parameters"); } /** * Updates the plane model transform matrix and extents. */ private void updatePlaneParameters(float[] planeMatrix, float extentX, float extentZ, FloatBuffer boundary) { System.arraycopy(planeMatrix, 0, mModelMatrix, 0, 16); if (boundary == null) { mVertexBuffer.limit(0); mIndexBuffer.limit(0); return; } // Generate a new set of vertices and a corresponding triangle strip index set so that // the plane boundary polygon has a fading edge. This is done by making a copy of the // boundary polygon vertices and scaling it down around center to push it inwards. Then // the index buffer is setup accordingly. boundary.rewind(); int boundaryVertices = boundary.limit() / 2; int numVertices; int numIndices; numVertices = boundaryVertices * VERTS_PER_BOUNDARY_VERT; // drawn as GL_TRIANGLE_STRIP with 3n-2 triangles (n-2 for fill, 2n for perimeter). numIndices = boundaryVertices * INDICES_PER_BOUNDARY_VERT; if (mVertexBuffer.capacity() < numVertices * COORDS_PER_VERTEX) { int size = mVertexBuffer.capacity(); while (size < numVertices * COORDS_PER_VERTEX) { size *= 2; } mVertexBuffer = ByteBuffer.allocateDirect(BYTES_PER_FLOAT * size) .order(ByteOrder.nativeOrder()).asFloatBuffer(); } mVertexBuffer.rewind(); mVertexBuffer.limit(numVertices * COORDS_PER_VERTEX); if (mIndexBuffer.capacity() < numIndices) { int size = mIndexBuffer.capacity(); while (size < numIndices) { size *= 2; } mIndexBuffer = ByteBuffer.allocateDirect(BYTES_PER_SHORT * size) .order(ByteOrder.nativeOrder()).asShortBuffer(); } mIndexBuffer.rewind(); mIndexBuffer.limit(numIndices); // Note: when either dimension of the bounding box is smaller than 2*FADE_RADIUS_M we // generate a bunch of 0-area triangles. These don't get rendered though so it works // out ok. float xScale = Math.max((extentX - 2 * FADE_RADIUS_M) / extentX, 0.0f); float zScale = Math.max((extentZ - 2 * FADE_RADIUS_M) / extentZ, 0.0f); while (boundary.hasRemaining()) { float x = boundary.get(); float z = boundary.get(); mVertexBuffer.put(x); mVertexBuffer.put(z); mVertexBuffer.put(0.0f); mVertexBuffer.put(x * xScale); mVertexBuffer.put(z * zScale); mVertexBuffer.put(1.0f); } // step 1, perimeter mIndexBuffer.put((short) ((boundaryVertices - 1) * 2)); for (int i = 0; i < boundaryVertices; ++i) { mIndexBuffer.put((short) (i * 2)); mIndexBuffer.put((short) (i * 2 + 1)); } mIndexBuffer.put((short) 1); // This leaves us on the interior edge of the perimeter between the inset vertices // for boundary verts n-1 and 0. // step 2,<SUF> for (int i = 1; i < boundaryVertices / 2; ++i) { mIndexBuffer.put((short) ((boundaryVertices - 1 - i) * 2 + 1)); mIndexBuffer.put((short) (i * 2 + 1)); } if (boundaryVertices % 2 != 0) { mIndexBuffer.put((short) ((boundaryVertices / 2) * 2 + 1)); } } private void draw(float[] cameraView, float[] cameraPerspective) { // Build the ModelView and ModelViewProjection matrices // for calculating cube position and light. Matrix.multiplyMM(mModelViewMatrix, 0, cameraView, 0, mModelMatrix, 0); Matrix.multiplyMM(mModelViewProjectionMatrix, 0, cameraPerspective, 0, mModelViewMatrix, 0); // Set the position of the plane mVertexBuffer.rewind(); GLES20.glVertexAttribPointer( mPlaneXZPositionAlphaAttribute, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, BYTES_PER_FLOAT * COORDS_PER_VERTEX, mVertexBuffer); // Set the Model and ModelViewProjection matrices in the shader. GLES20.glUniformMatrix4fv(mPlaneModelUniform, 1, false, mModelMatrix, 0); GLES20.glUniformMatrix4fv( mPlaneModelViewProjectionUniform, 1, false, mModelViewProjectionMatrix, 0); mIndexBuffer.rewind(); GLES20.glDrawElements(GLES20.GL_TRIANGLE_STRIP, mIndexBuffer.limit(), GLES20.GL_UNSIGNED_SHORT, mIndexBuffer); ShaderUtil.checkGLError(TAG, "Drawing plane"); } static class SortablePlane { final float mDistance; final Plane mPlane; SortablePlane(float distance, Plane plane) { this.mDistance = distance; this.mPlane = plane; } } /** * Draws the collection of tracked planes, with closer planes hiding more distant ones. * * @param allPlanes The collection of planes to draw. * @param cameraPose The pose of the camera, as returned by {@link Camera#getPose()} * @param cameraPerspective The projection matrix, as returned by * {@link Camera#getProjectionMatrix(float[], int, float, float)} */ public void drawPlanes(Collection<Plane> allPlanes, Pose cameraPose, float[] cameraPerspective) { // Planes must be sorted by distance from camera so that we draw closer planes first, and // they occlude the farther planes. List<SortablePlane> sortedPlanes = new ArrayList<SortablePlane>(); float[] normal = new float[3]; float cameraX = cameraPose.tx(); float cameraY = cameraPose.ty(); float cameraZ = cameraPose.tz(); for (Plane plane : allPlanes) { // if (plane.getTrackingState() != TrackingState.TRACKING // || plane.getSubsumedBy() != null) { // continue; // } Pose center = plane.getCenterPose(); // Get transformed Y axis of plane's coordinate system. center.getTransformedAxis(1, 1.0f, normal, 0); // Compute dot product of plane's normal with vector from camera to plane center. float distance = (cameraX - center.tx()) * normal[0] + (cameraY - center.ty()) * normal[1] + (cameraZ - center.tz()) * normal[2]; if (distance < 0) { // Plane is back-facing. continue; } sortedPlanes.add(new SortablePlane(distance, plane)); } Collections.sort(sortedPlanes, new Comparator<SortablePlane>() { @Override public int compare(SortablePlane a, SortablePlane b) { return Float.compare(a.mDistance, b.mDistance); } }); float[] cameraView = new float[16]; cameraPose.inverse().toMatrix(cameraView, 0); // Planes are drawn with additive blending, masked by the alpha channel for occlusion. // Start by clearing the alpha channel of the color buffer to 1.0. GLES20.glClearColor(1, 1, 1, 1); GLES20.glColorMask(false, false, false, true); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); GLES20.glColorMask(true, true, true, true); // Disable depth write. GLES20.glDepthMask(false); // Additive blending, masked by alpha channel, clearing alpha channel. GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFuncSeparate( GLES20.GL_DST_ALPHA, GLES20.GL_ONE, // RGB (src, dest) GLES20.GL_ZERO, GLES20.GL_ONE_MINUS_SRC_ALPHA); // ALPHA (src, dest) // Set up the shader. GLES20.glUseProgram(mPlaneProgram); // Attach the texture. GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextures[0]); GLES20.glUniform1i(mTextureUniform, 0); // Shared fragment uniforms. GLES20.glUniform4fv(mGridControlUniform, 1, GRID_CONTROL, 0); // Enable vertex arrays GLES20.glEnableVertexAttribArray(mPlaneXZPositionAlphaAttribute); ShaderUtil.checkGLError(TAG, "Setting up to draw planes"); for (SortablePlane sortedPlane : sortedPlanes) { Plane plane = sortedPlane.mPlane; float[] planeMatrix = new float[16]; plane.getCenterPose().toMatrix(planeMatrix, 0); updatePlaneParameters( planeMatrix, plane.getExtentX(), plane.getExtentZ(), plane.getPolygon()); // Get plane index. Keep a map to assign same indices to same planes. Integer planeIndex = mPlaneIndexMap.get(plane); if (planeIndex == null) { planeIndex = mPlaneIndexMap.size(); mPlaneIndexMap.put(plane, planeIndex); } // Set plane color. Computed deterministically from the Plane index. int colorIndex = planeIndex % PLANE_COLORS_RGBA.length; colorRgbaToFloat(mPlaneColor, PLANE_COLORS_RGBA[colorIndex]); GLES20.glUniform4fv(mLineColorUniform, 1, mPlaneColor, 0); GLES20.glUniform4fv(mDotColorUniform, 1, mPlaneColor, 0); // Each plane will have its own angle offset from others, to make them easier to // distinguish. Compute a 2x2 rotation matrix from the angle. float angleRadians = planeIndex * 0.144f; float uScale = DOTS_PER_METER; float vScale = DOTS_PER_METER * EQUILATERAL_TRIANGLE_SCALE; mPlaneAngleUvMatrix[0] = +(float) Math.cos(angleRadians) * uScale; mPlaneAngleUvMatrix[1] = -(float) Math.sin(angleRadians) * vScale; mPlaneAngleUvMatrix[2] = +(float) Math.sin(angleRadians) * uScale; mPlaneAngleUvMatrix[3] = +(float) Math.cos(angleRadians) * vScale; GLES20.glUniformMatrix2fv(mPlaneUvMatrixUniform, 1, false, mPlaneAngleUvMatrix, 0); draw(cameraView, cameraPerspective); } // Clean up the state we set GLES20.glDisableVertexAttribArray(mPlaneXZPositionAlphaAttribute); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDepthMask(true); ShaderUtil.checkGLError(TAG, "Cleaning up after drawing planes"); } private static void colorRgbaToFloat(float[] planeColor, int colorRgba) { planeColor[0] = ((float) ((colorRgba >> 24) & 0xff)) / 255.0f; planeColor[1] = ((float) ((colorRgba >> 16) & 0xff)) / 255.0f; planeColor[2] = ((float) ((colorRgba >> 8) & 0xff)) / 255.0f; planeColor[3] = ((float) ((colorRgba >> 0) & 0xff)) / 255.0f; } private static final int[] PLANE_COLORS_RGBA = { 0xFFFFFFFF, 0xF44336FF, 0xE91E63FF, 0x9C27B0FF, 0x673AB7FF, 0x3F51B5FF, 0x2196F3FF, 0x03A9F4FF, 0x00BCD4FF, 0x009688FF, 0x4CAF50FF, 0x8BC34AFF, 0xCDDC39FF, 0xFFEB3BFF, 0xFFC107FF, 0xFF9800FF, }; }
75554_1
package webservices; import model.Afspraak; import model.Bedrijf; import model.Klant; import model.Medewerker; import javax.annotation.PostConstruct; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.StringReader; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; @Path("/afspraken") public class AfspraakResources { @Context private ServletContext servletContext; private Bedrijf bedrijf; @PostConstruct private void init() { bedrijf = (Bedrijf) servletContext.getAttribute("bedrijf"); } @GET @Path("/{email}") @Produces(MediaType.APPLICATION_JSON) public ArrayList<Afspraak> getAfspraken(@PathParam("email") String email) { Klant klant = (Klant) servletContext.getAttribute(email); return klant.getAfspraken(); } @POST @Path("/{email}") @Produces(MediaType.APPLICATION_JSON) public Response addAfspraak(@PathParam("email") String email, String jsonBody) { JsonObjectBuilder responseObject = Json.createObjectBuilder(); try { StringReader stringReader = new StringReader(jsonBody); JsonReader jsonReader = Json.createReader(stringReader); JsonObject jsonObject = jsonReader.readObject(); LocalDate datum = LocalDate.parse(jsonObject.getString("datum")); LocalTime beginTijd = LocalTime.parse(jsonObject.getString("beginTijd")); LocalTime eindTijd = LocalTime.parse(jsonObject.getString("eindTijd")); String woonplaats = jsonObject.getString("woonplaats"); String straatnaam = jsonObject.getString("straatnaam"); int huisNummer = Integer.parseInt(jsonObject.getString("huisNummer")); String onderwerp = jsonObject.getString("onderwerp"); ArrayList<Medewerker> medewerkers = bedrijf.getMedewerkers(); Afspraak afspraak = new Afspraak(datum, beginTijd, eindTijd, woonplaats, straatnaam, huisNummer, onderwerp); afspraak.setMedewerker(medewerkers.get(0)); // for(Medewerker medewerker : medewerkers) { // if (!medewerker.isBezet(afspraak)) { // afspraak.setMedewerker(medewerker); // break; // } // } Klant klant = Bedrijf.getKlant(bedrijf.getKlanten(), email); assert klant != null; klant.addAfspraak(afspraak); responseObject.add("message", "Afspraak gemaakt"); } catch (Exception e) { responseObject.add("message", "Error " + e.getMessage()); } return Response.ok(responseObject.build()).build(); } }
OnnoKoreneef/IPASS
src/main/java/webservices/AfspraakResources.java
729
// if (!medewerker.isBezet(afspraak)) {
line_comment
nl
package webservices; import model.Afspraak; import model.Bedrijf; import model.Klant; import model.Medewerker; import javax.annotation.PostConstruct; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.StringReader; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; @Path("/afspraken") public class AfspraakResources { @Context private ServletContext servletContext; private Bedrijf bedrijf; @PostConstruct private void init() { bedrijf = (Bedrijf) servletContext.getAttribute("bedrijf"); } @GET @Path("/{email}") @Produces(MediaType.APPLICATION_JSON) public ArrayList<Afspraak> getAfspraken(@PathParam("email") String email) { Klant klant = (Klant) servletContext.getAttribute(email); return klant.getAfspraken(); } @POST @Path("/{email}") @Produces(MediaType.APPLICATION_JSON) public Response addAfspraak(@PathParam("email") String email, String jsonBody) { JsonObjectBuilder responseObject = Json.createObjectBuilder(); try { StringReader stringReader = new StringReader(jsonBody); JsonReader jsonReader = Json.createReader(stringReader); JsonObject jsonObject = jsonReader.readObject(); LocalDate datum = LocalDate.parse(jsonObject.getString("datum")); LocalTime beginTijd = LocalTime.parse(jsonObject.getString("beginTijd")); LocalTime eindTijd = LocalTime.parse(jsonObject.getString("eindTijd")); String woonplaats = jsonObject.getString("woonplaats"); String straatnaam = jsonObject.getString("straatnaam"); int huisNummer = Integer.parseInt(jsonObject.getString("huisNummer")); String onderwerp = jsonObject.getString("onderwerp"); ArrayList<Medewerker> medewerkers = bedrijf.getMedewerkers(); Afspraak afspraak = new Afspraak(datum, beginTijd, eindTijd, woonplaats, straatnaam, huisNummer, onderwerp); afspraak.setMedewerker(medewerkers.get(0)); // for(Medewerker medewerker : medewerkers) { // if (!medewerker.isBezet(afspraak))<SUF> // afspraak.setMedewerker(medewerker); // break; // } // } Klant klant = Bedrijf.getKlant(bedrijf.getKlanten(), email); assert klant != null; klant.addAfspraak(afspraak); responseObject.add("message", "Afspraak gemaakt"); } catch (Exception e) { responseObject.add("message", "Error " + e.getMessage()); } return Response.ok(responseObject.build()).build(); } }
179786_13
package com.mygdx.game.entities.gameEntities; import com.badlogic.gdx.Gdx; import com.mygdx.game.entities.entityInterfaces.CollectibleEffect; import com.mygdx.game.collision.Collidable; import com.mygdx.game.entities.dynamicEntities.CollidableDynamicEntity; import static com.mygdx.game.scenes.GameLevelScene.floorHeight; import static com.mygdx.game.scenes.GameLevelScene.playAreaHeight; public class PlayerEntity extends CollidableDynamicEntity { private float yVelocity = 0; private final float normalGravity = -9.8f; // Normal gravity private final float strongGravity = -130f; // Stronger gravity for faster descent private final float maxFallSpeed = -160f; // Maximum falling speed private final float jetpackForce = 160f; private final float strongJetpackForce = 150f; // Stronger jetpack thrust for quick ascent private float currentJetpackForce = jetpackForce; private float effectDuration; private boolean isJetpackActive = false; private boolean justDeactivatedJetpack = false; // Flag to check if jetpack was just turned off private boolean usingStrongJetpack = false; // Indicates if strong jetpack force is being used public PlayerEntity(String texturePath, float width, float height, float x, float y, float speed) { super(texturePath, width, height, x, y, speed); } public void activateJetpack() { isJetpackActive = true; justDeactivatedJetpack = false; usingStrongJetpack = true; // Activate strong jetpack force initially or under certain conditions } public void deactivateJetpack() { isJetpackActive = false; justDeactivatedJetpack = true; usingStrongJetpack = false; // Reset when jetpack is deactivated } @Override public void update() { float deltaTime = Gdx.graphics.getDeltaTime(); // Determine which gravity to apply float appliedGravity = isJetpackActive ? normalGravity : (justDeactivatedJetpack ? strongGravity : normalGravity); // Apply gravity yVelocity += appliedGravity * deltaTime; // Apply jetpack force if active if (isJetpackActive) { float appliedJetpackForce = usingStrongJetpack ? strongJetpackForce : jetpackForce; yVelocity = Math.min(yVelocity + currentJetpackForce * deltaTime, currentJetpackForce); } // Ensure max falling speed is not exceeded if (!isJetpackActive) { yVelocity = Math.max(yVelocity, maxFallSpeed); } // Update player position float newY = getY() + yVelocity * deltaTime; // Check vertical screen boundaries (example assumes 0 is the bottom and screenHeight is the top) if (newY < floorHeight) { newY = floorHeight; // Ensure entity is on or above the elevated floor yVelocity = 0; // Stop downward movement } else if (newY > playAreaHeight - this.getHeight()) { newY = playAreaHeight - this.getHeight(); // Ensure entity doesn't go above the play area yVelocity = 0; // Stop upward movement } // Apply the new position setY(newY); // Reset the justDeactivatedJetpack flag if necessary if (justDeactivatedJetpack && yVelocity <= maxFallSpeed) { justDeactivatedJetpack = false; } // Update the effect timer if (effectDuration > 0) { effectDuration -= deltaTime; if (effectDuration <= 0) { // Time's up, revert to normal jetpack force currentJetpackForce = jetpackForce; } } } public void applyEffect(CollectibleEffect effect) { effect.applyEffect(this); } public void activateTemporaryJetpackForce(float newForce, float duration) { currentJetpackForce = newForce; effectDuration = duration; } @Override public void onCollision(Collidable other) { // Handle collision logic here if (other instanceof CollectibleEffect) { ((CollectibleEffect) other).applyEffect(this); } // Other collision handling... } }
sitsbstfrnndz/Healthy-Copter
OOP_P1T1_Part_2 _Project/desktop/src/com/mygdx/game/entities/gameEntities/PlayerEntity.java
1,029
// Stop downward movement
line_comment
nl
package com.mygdx.game.entities.gameEntities; import com.badlogic.gdx.Gdx; import com.mygdx.game.entities.entityInterfaces.CollectibleEffect; import com.mygdx.game.collision.Collidable; import com.mygdx.game.entities.dynamicEntities.CollidableDynamicEntity; import static com.mygdx.game.scenes.GameLevelScene.floorHeight; import static com.mygdx.game.scenes.GameLevelScene.playAreaHeight; public class PlayerEntity extends CollidableDynamicEntity { private float yVelocity = 0; private final float normalGravity = -9.8f; // Normal gravity private final float strongGravity = -130f; // Stronger gravity for faster descent private final float maxFallSpeed = -160f; // Maximum falling speed private final float jetpackForce = 160f; private final float strongJetpackForce = 150f; // Stronger jetpack thrust for quick ascent private float currentJetpackForce = jetpackForce; private float effectDuration; private boolean isJetpackActive = false; private boolean justDeactivatedJetpack = false; // Flag to check if jetpack was just turned off private boolean usingStrongJetpack = false; // Indicates if strong jetpack force is being used public PlayerEntity(String texturePath, float width, float height, float x, float y, float speed) { super(texturePath, width, height, x, y, speed); } public void activateJetpack() { isJetpackActive = true; justDeactivatedJetpack = false; usingStrongJetpack = true; // Activate strong jetpack force initially or under certain conditions } public void deactivateJetpack() { isJetpackActive = false; justDeactivatedJetpack = true; usingStrongJetpack = false; // Reset when jetpack is deactivated } @Override public void update() { float deltaTime = Gdx.graphics.getDeltaTime(); // Determine which gravity to apply float appliedGravity = isJetpackActive ? normalGravity : (justDeactivatedJetpack ? strongGravity : normalGravity); // Apply gravity yVelocity += appliedGravity * deltaTime; // Apply jetpack force if active if (isJetpackActive) { float appliedJetpackForce = usingStrongJetpack ? strongJetpackForce : jetpackForce; yVelocity = Math.min(yVelocity + currentJetpackForce * deltaTime, currentJetpackForce); } // Ensure max falling speed is not exceeded if (!isJetpackActive) { yVelocity = Math.max(yVelocity, maxFallSpeed); } // Update player position float newY = getY() + yVelocity * deltaTime; // Check vertical screen boundaries (example assumes 0 is the bottom and screenHeight is the top) if (newY < floorHeight) { newY = floorHeight; // Ensure entity is on or above the elevated floor yVelocity = 0; // Stop downward<SUF> } else if (newY > playAreaHeight - this.getHeight()) { newY = playAreaHeight - this.getHeight(); // Ensure entity doesn't go above the play area yVelocity = 0; // Stop upward movement } // Apply the new position setY(newY); // Reset the justDeactivatedJetpack flag if necessary if (justDeactivatedJetpack && yVelocity <= maxFallSpeed) { justDeactivatedJetpack = false; } // Update the effect timer if (effectDuration > 0) { effectDuration -= deltaTime; if (effectDuration <= 0) { // Time's up, revert to normal jetpack force currentJetpackForce = jetpackForce; } } } public void applyEffect(CollectibleEffect effect) { effect.applyEffect(this); } public void activateTemporaryJetpackForce(float newForce, float duration) { currentJetpackForce = newForce; effectDuration = duration; } @Override public void onCollision(Collidable other) { // Handle collision logic here if (other instanceof CollectibleEffect) { ((CollectibleEffect) other).applyEffect(this); } // Other collision handling... } }
116238_1
package koopa.core.trees; import java.util.LinkedList; import java.util.List; import java.util.Stack; import koopa.core.data.Token; import koopa.core.data.markers.End; import koopa.core.data.markers.InWater; import koopa.core.data.markers.Start; import koopa.core.grammars.Grammar; public class KoopaTreeBuilder extends TreeBuildingTarget { /** * Any leaves preceding the first tree get tracked here. They will be added * to the first tree once we get it. */ private LinkedList<Tree> leading = new LinkedList<>(); /** * Tree being built. */ private Stack<Tree> treeparts = new Stack<>(); /** * Trees which have been built. */ private List<Tree> trees = new LinkedList<>(); public KoopaTreeBuilder(Grammar grammar) { this(grammar, false); } public KoopaTreeBuilder(Grammar grammar, boolean hideWater) { super(hideWater); } public List<Tree> getTrees() { return this.trees; } public Tree getTree() { if (trees.isEmpty()) return null; else return trees.get(0); } /** {@inheritDoc} */ @Override public void down(Start start) { Tree tree = new Tree(start); if (!this.treeparts.isEmpty()) this.treeparts.peek().addChild(tree); else while (!leading.isEmpty()) tree.addChild(leading.removeFirst()); this.treeparts.push(tree); } /** {@inheritDoc} */ @Override public void leaf(Token token) { Tree tree = new Tree(token); if (!this.treeparts.isEmpty()) this.treeparts.peek().addChild(tree); else leading.add(tree); } /** {@inheritDoc} */ @Override public void up(End end) { assert (!this.treeparts.isEmpty()); final Tree tree = this.treeparts.pop(); if (this.treeparts.isEmpty()) this.trees.add(tree); } /** {@inheritDoc} */ @Override public void water(InWater water) { Tree tree = new Tree(water); if (!this.treeparts.isEmpty()) this.treeparts.peek().addChild(tree); this.treeparts.push(tree); } /** {@inheritDoc} */ @Override public void land() { assert (!this.treeparts.isEmpty()); final Tree tree = this.treeparts.pop(); if (this.treeparts.isEmpty()) this.trees.add(tree); } }
krisds/koopa
src/core/koopa/core/trees/KoopaTreeBuilder.java
697
/** * Tree being built. */
block_comment
nl
package koopa.core.trees; import java.util.LinkedList; import java.util.List; import java.util.Stack; import koopa.core.data.Token; import koopa.core.data.markers.End; import koopa.core.data.markers.InWater; import koopa.core.data.markers.Start; import koopa.core.grammars.Grammar; public class KoopaTreeBuilder extends TreeBuildingTarget { /** * Any leaves preceding the first tree get tracked here. They will be added * to the first tree once we get it. */ private LinkedList<Tree> leading = new LinkedList<>(); /** * Tree being built.<SUF>*/ private Stack<Tree> treeparts = new Stack<>(); /** * Trees which have been built. */ private List<Tree> trees = new LinkedList<>(); public KoopaTreeBuilder(Grammar grammar) { this(grammar, false); } public KoopaTreeBuilder(Grammar grammar, boolean hideWater) { super(hideWater); } public List<Tree> getTrees() { return this.trees; } public Tree getTree() { if (trees.isEmpty()) return null; else return trees.get(0); } /** {@inheritDoc} */ @Override public void down(Start start) { Tree tree = new Tree(start); if (!this.treeparts.isEmpty()) this.treeparts.peek().addChild(tree); else while (!leading.isEmpty()) tree.addChild(leading.removeFirst()); this.treeparts.push(tree); } /** {@inheritDoc} */ @Override public void leaf(Token token) { Tree tree = new Tree(token); if (!this.treeparts.isEmpty()) this.treeparts.peek().addChild(tree); else leading.add(tree); } /** {@inheritDoc} */ @Override public void up(End end) { assert (!this.treeparts.isEmpty()); final Tree tree = this.treeparts.pop(); if (this.treeparts.isEmpty()) this.trees.add(tree); } /** {@inheritDoc} */ @Override public void water(InWater water) { Tree tree = new Tree(water); if (!this.treeparts.isEmpty()) this.treeparts.peek().addChild(tree); this.treeparts.push(tree); } /** {@inheritDoc} */ @Override public void land() { assert (!this.treeparts.isEmpty()); final Tree tree = this.treeparts.pop(); if (this.treeparts.isEmpty()) this.trees.add(tree); } }
125771_2
package cz.agents.agentdrive.simulator.lite.environment; import cz.agents.agentdrive.highway.environment.HighwayEnvironment; import cz.agents.agentdrive.highway.environment.SimulatorHandlers.PlanCallback; import cz.agents.agentdrive.highway.environment.roadnet.RoadNetworkRouter; import cz.agents.agentdrive.highway.environment.roadnet.XMLReader; import cz.agents.agentdrive.highway.environment.roadnet.network.RoadNetwork; import cz.agents.agentdrive.highway.storage.HighwayStorage; import cz.agents.agentdrive.highway.storage.RadarData; import cz.agents.agentdrive.highway.storage.RoadObject; import cz.agents.agentdrive.highway.storage.plan.Action; import cz.agents.agentdrive.highway.storage.plan.PlansOut; import cz.agents.agentdrive.highway.storage.plan.WPAction; import cz.agents.agentdrive.simulator.lite.storage.SimulatorEvent; import cz.agents.agentdrive.simulator.lite.storage.VehicleStorage; import cz.agents.agentdrive.simulator.lite.storage.vehicle.Car; import cz.agents.agentdrive.simulator.lite.storage.vehicle.Vehicle; import cz.agents.alite.common.event.Event; import cz.agents.alite.common.event.EventHandler; import cz.agents.alite.common.event.EventProcessor; import cz.agents.alite.common.event.EventProcessorEventType; import cz.agents.alite.configurator.Configurator; import cz.agents.alite.environment.eventbased.EventBasedEnvironment; import cz.agents.alite.simulation.SimulationEventType; import org.apache.log4j.Logger; import javax.vecmath.Point3f; import javax.vecmath.Vector3f; import java.util.*; /** * Class representing the environment of the simulation * <p/> * Created by wmatex on 3.7.14. */ public class SimulatorEnvironment extends EventBasedEnvironment { private static final Logger logger = Logger.getLogger(SimulatorEnvironment.class); /// All simulated vehicles private VehicleStorage vehicleStorage; private HighwayEnvironment highwayEnvironment; private RoadNetwork roadNetwork; private RadarData currentState = new RadarData(); private PlansOut plansOut = new PlansOut(); private PlanCallback planCallback = new PlanCallbackImp(); protected long timestep = Configurator.getParamInt("simulator.lite.timestep", 100); private int counter = 0; /// Time between updates static public final long UPDATE_STEP = 20; /// Time between communication updates static public final long COMM_STEP = 20; private static boolean perfectExecution = Configurator.getParamBool("simulator.lite.perfectExecution", true); /** * Create the environment, the storage and register event handlers */ public SimulatorEnvironment(final EventProcessor eventProcessor) { super(eventProcessor); vehicleStorage = new VehicleStorage(this); XMLReader xmlReader = new XMLReader(); roadNetwork = xmlReader.parseNetwork(Configurator.getParamString("simulator.net.folder", "nets/junction-big/")); RoadNetworkRouter.setRoadNet(roadNetwork); highwayEnvironment = new HighwayEnvironment(this.getEventProcessor(), roadNetwork); getEventProcessor().addEventHandler(new EventHandler() { @Override public EventProcessor getEventProcessor() { return eventProcessor; } @Override public void handleEvent(Event event) { // Start updating vehicles when the simulation starts if (event.isType(SimulationEventType.SIMULATION_STARTED)) { logger.info("SIMULATION STARTED"); if (Configurator.getParamBool("highway.dashboard.systemTime", false)) { highwayEnvironment.getStorage().setSTARTTIME(System.currentTimeMillis()); } else { highwayEnvironment.getStorage().setSTARTTIME(getEventProcessor().getCurrentTime()); } highwayEnvironment.getStorage().updateCars(new RadarData()); logger.debug("HighwayStorage: handled simulation START"); getEventProcessor().addEvent(SimulatorEvent.TIMESTEP, null, null, null); getEventProcessor().addEvent(SimulatorEvent.UPDATE, null, null, null); getEventProcessor().addEvent(SimulatorEvent.COMMUNICATION_UPDATE, null, null, null); } else if (event.isType(SimulatorEvent.COMMUNICATION_UPDATE)) { if (highwayEnvironment.getStorage().getCounter() > 0 && !perfectExecution) highwayEnvironment.getStorage().updateCars(vehicleStorage.generateRadarData()); if (highwayEnvironment.getStorage().getCounter() > 0 && perfectExecution) highwayEnvironment.getStorage().updateCars(highwayEnvironment.getStorage().getCurrentRadarData()); getEventProcessor().addEvent(SimulatorEvent.COMMUNICATION_UPDATE, null, null, null, Math.max(1, (long) (timestep * COMM_STEP))); } else if (event.isType(SimulatorEvent.TIMESTEP)) { if (!highwayEnvironment.getStorage().vehiclesForInsert.isEmpty() && highwayEnvironment.getStorage().getPosCurr().isEmpty()) highwayEnvironment.getStorage().updateCars(new RadarData()); if (HighwayStorage.isFinished) getEventProcessor().addEvent(EventProcessorEventType.STOP, null, null, null, timestep); else getEventProcessor().addEvent(SimulatorEvent.TIMESTEP, null, null, null, timestep); } } }); } private void acceptPlans(PlansOut plans) { logger.debug("Received plans: " + plans.getCarIds()); for (int carID : plans.getCarIds()) { logger.debug("Plan for car " + carID + ": " + plans.getPlan(carID)); // This is the init plan if (((WPAction) plans.getPlan(carID).iterator().next()).getSpeed() == -1) { vehicleStorage.removeVehicle(carID); } else { Vehicle vehicle = vehicleStorage.getVehicle(carID); if (vehicle == null) { // Get the first action containing car info WPAction action = (WPAction) plans.getPlan(carID).iterator().next(); if (plans.getPlan(carID).size() > 1) { Iterator<Action> iter = plans.getPlan(carID).iterator(); Point3f first = ((WPAction) iter.next()).getPosition(); Point3f second = ((WPAction) iter.next()).getPosition(); Vector3f heading = new Vector3f(second.x - first.x, second.y - first.y, second.z - first.z); heading.normalize(); vehicleStorage.addVehicle(new Car(carID, 0, action.getPosition(), heading, (float) action.getSpeed() /*30.0f*/)); } else { vehicleStorage.addVehicle(new Car(carID, 0, action.getPosition(), plans.getCurrStates().get(carID).getVelocity(), (float) action.getSpeed())); } } else { vehicle.getVelocityController().updatePlan(plans.getPlan(carID)); vehicle.setWayPoints(plans.getPlan(carID)); } } } } /** * Initialize the environment and add some vehicles */ public void init() { getEventProcessor().addEventHandler(vehicleStorage); } public VehicleStorage getStorage() { return vehicleStorage; } public RoadNetwork getRoadNetwork() { return roadNetwork; } public HighwayEnvironment getHighwayEnvironment() { return highwayEnvironment; } public PlanCallback getPlanCallback() { return planCallback; } class PlanCallbackImp extends PlanCallback { @Override public RadarData execute(PlansOut plans) { Map<Integer, RoadObject> currStates = plans.getCurrStates(); RadarData radarData = new RadarData(); if (Configurator.getParamBool("simulator.lite.perfectExecution", true)) { float duration = 0; float lastDuration = 0; double timest = Configurator.getParamDouble("highway.SimulatorLocal.timestep", 1.0); float timestep = (float) timest; boolean removeCar = false; for (Integer carID : plans.getCarIds()) { Collection<Action> plan = plans.getPlan(carID); RoadObject state = currStates.get(carID); Point3f lastPosition = state.getPosition(); Point3f myPosition = state.getPosition(); for (Action action : plan) { if (action.getClass().equals(WPAction.class)) { WPAction wpAction = (WPAction) action; if (wpAction.getSpeed() == -1) { myPosition = wpAction.getPosition(); removeCar = true; } if (wpAction.getSpeed() < 0.001) { duration += 0.10f; } else { myPosition = wpAction.getPosition(); lastDuration = (float) (wpAction.getPosition().distance(lastPosition) / (wpAction.getSpeed())); duration += wpAction.getPosition().distance(lastPosition) / (wpAction.getSpeed()); } // creating point between the waypoints if my duration is greater than the defined timestep if (duration >= timestep) { float remainingDuration = timestep - (duration - lastDuration); float ration = remainingDuration / lastDuration; float x = myPosition.x - lastPosition.x; float y = myPosition.y - lastPosition.y; float z = myPosition.z - lastPosition.z; Vector3f vec = new Vector3f(x, y, z); vec.scale(ration); myPosition = new Point3f(vec.x + 0 + lastPosition.x, vec.y + lastPosition.y, vec.z + lastPosition.z); break; } lastPosition = wpAction.getPosition(); } } if (removeCar) { if (Configurator.getParamBool("highway.dashboard.sumoSimulation", true)) { this.addToPlannedVehiclesToRemove(carID); } removeCar = false; } else { Vector3f vel = new Vector3f(state.getPosition()); vel.negate(); vel.add(myPosition); if (vel.length() < 0.0001) { vel = state.getVelocity(); vel.normalize(); vel.scale(0.0010f); } int lane = highwayEnvironment.getRoadNetwork().getClosestLane(myPosition).getIndex(); state = new RoadObject(carID, highwayEnvironment.getCurrentTime(), lane, myPosition, vel); radarData.add(state); duration = 0; } } currentState = radarData; } else { acceptPlans(plans); // let VehicleStorage apply plans from HighwayStorage } counter++; return radarData; } } }
schaemar/AgentDrive
src/main/java/cz/agents/agentdrive/simulator/lite/environment/SimulatorEnvironment.java
2,643
/// Time between updates
line_comment
nl
package cz.agents.agentdrive.simulator.lite.environment; import cz.agents.agentdrive.highway.environment.HighwayEnvironment; import cz.agents.agentdrive.highway.environment.SimulatorHandlers.PlanCallback; import cz.agents.agentdrive.highway.environment.roadnet.RoadNetworkRouter; import cz.agents.agentdrive.highway.environment.roadnet.XMLReader; import cz.agents.agentdrive.highway.environment.roadnet.network.RoadNetwork; import cz.agents.agentdrive.highway.storage.HighwayStorage; import cz.agents.agentdrive.highway.storage.RadarData; import cz.agents.agentdrive.highway.storage.RoadObject; import cz.agents.agentdrive.highway.storage.plan.Action; import cz.agents.agentdrive.highway.storage.plan.PlansOut; import cz.agents.agentdrive.highway.storage.plan.WPAction; import cz.agents.agentdrive.simulator.lite.storage.SimulatorEvent; import cz.agents.agentdrive.simulator.lite.storage.VehicleStorage; import cz.agents.agentdrive.simulator.lite.storage.vehicle.Car; import cz.agents.agentdrive.simulator.lite.storage.vehicle.Vehicle; import cz.agents.alite.common.event.Event; import cz.agents.alite.common.event.EventHandler; import cz.agents.alite.common.event.EventProcessor; import cz.agents.alite.common.event.EventProcessorEventType; import cz.agents.alite.configurator.Configurator; import cz.agents.alite.environment.eventbased.EventBasedEnvironment; import cz.agents.alite.simulation.SimulationEventType; import org.apache.log4j.Logger; import javax.vecmath.Point3f; import javax.vecmath.Vector3f; import java.util.*; /** * Class representing the environment of the simulation * <p/> * Created by wmatex on 3.7.14. */ public class SimulatorEnvironment extends EventBasedEnvironment { private static final Logger logger = Logger.getLogger(SimulatorEnvironment.class); /// All simulated vehicles private VehicleStorage vehicleStorage; private HighwayEnvironment highwayEnvironment; private RoadNetwork roadNetwork; private RadarData currentState = new RadarData(); private PlansOut plansOut = new PlansOut(); private PlanCallback planCallback = new PlanCallbackImp(); protected long timestep = Configurator.getParamInt("simulator.lite.timestep", 100); private int counter = 0; /// Time between<SUF> static public final long UPDATE_STEP = 20; /// Time between communication updates static public final long COMM_STEP = 20; private static boolean perfectExecution = Configurator.getParamBool("simulator.lite.perfectExecution", true); /** * Create the environment, the storage and register event handlers */ public SimulatorEnvironment(final EventProcessor eventProcessor) { super(eventProcessor); vehicleStorage = new VehicleStorage(this); XMLReader xmlReader = new XMLReader(); roadNetwork = xmlReader.parseNetwork(Configurator.getParamString("simulator.net.folder", "nets/junction-big/")); RoadNetworkRouter.setRoadNet(roadNetwork); highwayEnvironment = new HighwayEnvironment(this.getEventProcessor(), roadNetwork); getEventProcessor().addEventHandler(new EventHandler() { @Override public EventProcessor getEventProcessor() { return eventProcessor; } @Override public void handleEvent(Event event) { // Start updating vehicles when the simulation starts if (event.isType(SimulationEventType.SIMULATION_STARTED)) { logger.info("SIMULATION STARTED"); if (Configurator.getParamBool("highway.dashboard.systemTime", false)) { highwayEnvironment.getStorage().setSTARTTIME(System.currentTimeMillis()); } else { highwayEnvironment.getStorage().setSTARTTIME(getEventProcessor().getCurrentTime()); } highwayEnvironment.getStorage().updateCars(new RadarData()); logger.debug("HighwayStorage: handled simulation START"); getEventProcessor().addEvent(SimulatorEvent.TIMESTEP, null, null, null); getEventProcessor().addEvent(SimulatorEvent.UPDATE, null, null, null); getEventProcessor().addEvent(SimulatorEvent.COMMUNICATION_UPDATE, null, null, null); } else if (event.isType(SimulatorEvent.COMMUNICATION_UPDATE)) { if (highwayEnvironment.getStorage().getCounter() > 0 && !perfectExecution) highwayEnvironment.getStorage().updateCars(vehicleStorage.generateRadarData()); if (highwayEnvironment.getStorage().getCounter() > 0 && perfectExecution) highwayEnvironment.getStorage().updateCars(highwayEnvironment.getStorage().getCurrentRadarData()); getEventProcessor().addEvent(SimulatorEvent.COMMUNICATION_UPDATE, null, null, null, Math.max(1, (long) (timestep * COMM_STEP))); } else if (event.isType(SimulatorEvent.TIMESTEP)) { if (!highwayEnvironment.getStorage().vehiclesForInsert.isEmpty() && highwayEnvironment.getStorage().getPosCurr().isEmpty()) highwayEnvironment.getStorage().updateCars(new RadarData()); if (HighwayStorage.isFinished) getEventProcessor().addEvent(EventProcessorEventType.STOP, null, null, null, timestep); else getEventProcessor().addEvent(SimulatorEvent.TIMESTEP, null, null, null, timestep); } } }); } private void acceptPlans(PlansOut plans) { logger.debug("Received plans: " + plans.getCarIds()); for (int carID : plans.getCarIds()) { logger.debug("Plan for car " + carID + ": " + plans.getPlan(carID)); // This is the init plan if (((WPAction) plans.getPlan(carID).iterator().next()).getSpeed() == -1) { vehicleStorage.removeVehicle(carID); } else { Vehicle vehicle = vehicleStorage.getVehicle(carID); if (vehicle == null) { // Get the first action containing car info WPAction action = (WPAction) plans.getPlan(carID).iterator().next(); if (plans.getPlan(carID).size() > 1) { Iterator<Action> iter = plans.getPlan(carID).iterator(); Point3f first = ((WPAction) iter.next()).getPosition(); Point3f second = ((WPAction) iter.next()).getPosition(); Vector3f heading = new Vector3f(second.x - first.x, second.y - first.y, second.z - first.z); heading.normalize(); vehicleStorage.addVehicle(new Car(carID, 0, action.getPosition(), heading, (float) action.getSpeed() /*30.0f*/)); } else { vehicleStorage.addVehicle(new Car(carID, 0, action.getPosition(), plans.getCurrStates().get(carID).getVelocity(), (float) action.getSpeed())); } } else { vehicle.getVelocityController().updatePlan(plans.getPlan(carID)); vehicle.setWayPoints(plans.getPlan(carID)); } } } } /** * Initialize the environment and add some vehicles */ public void init() { getEventProcessor().addEventHandler(vehicleStorage); } public VehicleStorage getStorage() { return vehicleStorage; } public RoadNetwork getRoadNetwork() { return roadNetwork; } public HighwayEnvironment getHighwayEnvironment() { return highwayEnvironment; } public PlanCallback getPlanCallback() { return planCallback; } class PlanCallbackImp extends PlanCallback { @Override public RadarData execute(PlansOut plans) { Map<Integer, RoadObject> currStates = plans.getCurrStates(); RadarData radarData = new RadarData(); if (Configurator.getParamBool("simulator.lite.perfectExecution", true)) { float duration = 0; float lastDuration = 0; double timest = Configurator.getParamDouble("highway.SimulatorLocal.timestep", 1.0); float timestep = (float) timest; boolean removeCar = false; for (Integer carID : plans.getCarIds()) { Collection<Action> plan = plans.getPlan(carID); RoadObject state = currStates.get(carID); Point3f lastPosition = state.getPosition(); Point3f myPosition = state.getPosition(); for (Action action : plan) { if (action.getClass().equals(WPAction.class)) { WPAction wpAction = (WPAction) action; if (wpAction.getSpeed() == -1) { myPosition = wpAction.getPosition(); removeCar = true; } if (wpAction.getSpeed() < 0.001) { duration += 0.10f; } else { myPosition = wpAction.getPosition(); lastDuration = (float) (wpAction.getPosition().distance(lastPosition) / (wpAction.getSpeed())); duration += wpAction.getPosition().distance(lastPosition) / (wpAction.getSpeed()); } // creating point between the waypoints if my duration is greater than the defined timestep if (duration >= timestep) { float remainingDuration = timestep - (duration - lastDuration); float ration = remainingDuration / lastDuration; float x = myPosition.x - lastPosition.x; float y = myPosition.y - lastPosition.y; float z = myPosition.z - lastPosition.z; Vector3f vec = new Vector3f(x, y, z); vec.scale(ration); myPosition = new Point3f(vec.x + 0 + lastPosition.x, vec.y + lastPosition.y, vec.z + lastPosition.z); break; } lastPosition = wpAction.getPosition(); } } if (removeCar) { if (Configurator.getParamBool("highway.dashboard.sumoSimulation", true)) { this.addToPlannedVehiclesToRemove(carID); } removeCar = false; } else { Vector3f vel = new Vector3f(state.getPosition()); vel.negate(); vel.add(myPosition); if (vel.length() < 0.0001) { vel = state.getVelocity(); vel.normalize(); vel.scale(0.0010f); } int lane = highwayEnvironment.getRoadNetwork().getClosestLane(myPosition).getIndex(); state = new RoadObject(carID, highwayEnvironment.getCurrentTime(), lane, myPosition, vel); radarData.add(state); duration = 0; } } currentState = radarData; } else { acceptPlans(plans); // let VehicleStorage apply plans from HighwayStorage } counter++; return radarData; } } }
140631_32
/* * Copyright 2013-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.s3.internal.crypto.v2; import static com.amazonaws.services.s3.model.CryptoMode.AuthenticatedEncryption; import static com.amazonaws.services.s3.model.CryptoMode.StrictAuthenticatedEncryption; import static com.amazonaws.services.s3.model.ExtraMaterialsDescription.NONE; import static com.amazonaws.util.IOUtils.closeQuietly; import com.amazonaws.services.s3.model.CryptoRangeGetMode; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collections; import java.util.Map; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.internal.SdkFilterInputStream; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.s3.internal.S3Direct; import com.amazonaws.services.s3.internal.crypto.AdjustedRangeInputStream; import com.amazonaws.services.s3.internal.crypto.CipherLite; import com.amazonaws.services.s3.internal.crypto.CipherLiteInputStream; import com.amazonaws.services.s3.internal.crypto.ContentCryptoScheme; import com.amazonaws.services.s3.internal.crypto.CryptoRuntime; import com.amazonaws.services.s3.model.CryptoConfigurationV2; import com.amazonaws.services.s3.model.CryptoMode; import com.amazonaws.services.s3.model.EncryptedGetObjectRequest; import com.amazonaws.services.s3.model.EncryptionMaterialsProvider; import com.amazonaws.services.s3.model.ExtraMaterialsDescription; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectId; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.util.json.Jackson; /** * Authenticated encryption (AE) cryptographic module for the S3 encryption client. */ public class S3CryptoModuleAE extends S3CryptoModuleBase<MultipartUploadCryptoContext> { static { // Enable bouncy castle if available CryptoRuntime.enableBouncyCastle(); } /** * @param cryptoConfig a read-only copy of the crypto configuration. */ public S3CryptoModuleAE(AWSKMS kms, S3Direct s3, AWSCredentialsProvider credentialsProvider, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { super(kms, s3, encryptionMaterialsProvider, cryptoConfig); CryptoMode mode = cryptoConfig.getCryptoMode(); if (mode != StrictAuthenticatedEncryption && mode != AuthenticatedEncryption) { throw new IllegalArgumentException(); } } /** * Used for testing purposes only. */ S3CryptoModuleAE(S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { this(null, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); } /** * Used for testing purposes only. */ S3CryptoModuleAE(AWSKMS kms, S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { this(kms, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); } /** * Returns true if a strict encryption mode is in use in the current crypto * module; false otherwise. */ protected boolean isStrict() { return false; } @Override public S3Object getObjectSecurely(GetObjectRequest req) { // Adjust the crypto range to retrieve all of the cipher blocks needed to contain the user's desired // range of bytes. long[] desiredRange = req.getRange(); boolean isPartialObject = desiredRange != null || req.getPartNumber() != null; if (isPartialObject) { assertCanGetPartialObject(); } long[] adjustedCryptoRange = getAdjustedCryptoRange(desiredRange); if (adjustedCryptoRange != null) req.setRange(adjustedCryptoRange[0], adjustedCryptoRange[1]); // Get the object from S3 S3Object retrieved = s3.getObject(req); // If the caller has specified constraints, it's possible that super.getObject(...) // would return null, so we simply return null as well. if (retrieved == null) return null; String suffix = null; if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; suffix = ereq.getInstructionFileSuffix(); } try { return suffix == null || suffix.trim().isEmpty() ? decipher(req, desiredRange, adjustedCryptoRange, retrieved) : decipherWithInstFileSuffix(req, desiredRange, adjustedCryptoRange, retrieved, suffix) ; } catch (RuntimeException ex) { // If we're unable to set up the decryption, make sure we close the // HTTP connection closeQuietly(retrieved, log); throw ex; } catch (Error error) { closeQuietly(retrieved, log); throw error; } } private S3Object decipher(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved) { S3ObjectWrapper wrapped = new S3ObjectWrapper(retrieved, req.getS3ObjectId()); // Check if encryption info is in object metadata if (wrapped.hasEncryptionInfo()) return decipherWithMetadata(req, desiredRange, cryptoRange, wrapped); // Check if encrypted info is in an instruction file S3ObjectWrapper ifile = fetchInstructionFile(req.getS3ObjectId(), null); if (ifile != null) { try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, wrapped, ifile); } finally { closeQuietly(ifile, log); } } if (isStrict()) { closeQuietly(wrapped, log); throw new SecurityException("Unencrypted object found, cannot be decrypted in mode " + StrictAuthenticatedEncryption + "; bucket name: " + retrieved.getBucketName() + ", key: " + retrieved.getKey()); } if (cryptoConfig.isUnsafeUndecryptableObjectPassthrough()) { log.warn(String.format( "Unable to detect encryption information for object '%s' in bucket '%s'. " + "Returning object without decryption.", retrieved.getKey(), retrieved.getBucketName())); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange(wrapped, desiredRange, null); return adjusted.getS3Object(); } else { closeQuietly(wrapped, log); throw new SecurityException("Instruction file not found for S3 object with bucket name: " + retrieved.getBucketName() + ", key: " + retrieved.getKey()); } } /** * Same as {@link #decipher(GetObjectRequest, long[], long[], S3Object)} * but makes use of an instruction file with the specified suffix. * @param instFileSuffix never null or empty (which is assumed to have been * sanitized upstream.) */ private S3Object decipherWithInstFileSuffix(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved, String instFileSuffix) { final S3ObjectId id = req.getS3ObjectId(); // Check if encrypted info is in an instruction file final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix); if (ifile == null) { throw new SdkClientException("Instruction file with suffix " + instFileSuffix + " is not found for " + retrieved); } try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, new S3ObjectWrapper(retrieved, id), ifile); } finally { closeQuietly(ifile, log); } } private S3Object decipherWithInstructionFile(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved, S3ObjectWrapper instructionFile) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } String json = instructionFile.toJsonString(); Map<String, String> matdesc = Collections.unmodifiableMap(Jackson.stringMapFromJsonString(json)); ContentCryptoMaterial cekMaterial = ContentCryptoMaterial.fromInstructionFile( matdesc, kekMaterialsProvider, cryptoConfig, cryptoRange, // range is sometimes necessary to compute the adjusted IV extraMatDesc, keyWrapExpected, kms ); boolean isRangeGet = desiredRange != null; securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, matdesc); return adjusted.getS3Object(); } private S3Object decipherWithMetadata(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } ContentCryptoMaterial cekMaterial = ContentCryptoMaterial .fromObjectMetadata(retrieved.getObjectMetadata().getUserMetadata(), kekMaterialsProvider, cryptoConfig, // range is sometimes necessary to compute the adjusted IV cryptoRange, extraMatDesc, keyWrapExpected, kms ); boolean isRangeGet = desiredRange != null; securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, null); return adjusted.getS3Object(); } /** * Adjusts the retrieved S3Object so that the object contents contain only the range of bytes * desired by the user. Since encrypted contents can only be retrieved in CIPHER_BLOCK_SIZE * (16 bytes) chunks, the S3Object potentially contains more bytes than desired, so this method * adjusts the contents range. * * @param s3object * The S3Object retrieved from S3 that could possibly contain more bytes than desired * by the user. * @param range * A two-element array of longs corresponding to the start and finish (inclusive) of a desired * range of bytes. * @param instruction * Instruction file in JSON or null if no instruction file is involved * @return * The S3Object with adjusted object contents containing only the range desired by the user. * If the range specified is invalid, then the S3Object is returned without any modifications. */ protected final S3ObjectWrapper adjustToDesiredRange(S3ObjectWrapper s3object, long[] range, Map<String,String> instruction) { if (range == null) return s3object; // Figure out the original encryption scheme used, which can be // different from the crypto scheme used for decryption. ContentCryptoScheme encryptionScheme = s3object.encryptionSchemeOf(instruction); // range get on data encrypted using AES_GCM final long instanceLen = s3object.getObjectMetadata().getInstanceLength(); final long maxOffset = instanceLen - encryptionScheme.getTagLengthInBits() / 8 - 1; if (range[1] > maxOffset) { range[1] = maxOffset; if (range[0] > range[1]) { // Return empty content // First let's close the existing input stream to avoid resource // leakage closeQuietly(s3object.getObjectContent(), log); s3object.setObjectContent(new ByteArrayInputStream(new byte[0])); return s3object; } } if (range[0] > range[1]) { // Make no modifications if range is invalid. return s3object; } try { S3ObjectInputStream objectContent = s3object.getObjectContent(); InputStream adjustedRangeContents = new AdjustedRangeInputStream(objectContent, range[0], range[1]); s3object.setObjectContent(new S3ObjectInputStream(adjustedRangeContents, objectContent.getHttpRequest())); return s3object; } catch (IOException e) { throw new SdkClientException("Error adjusting output to desired byte range: " + e.getMessage()); } } @Override public ObjectMetadata getObjectSecurely(GetObjectRequest getObjectRequest, File destinationFile) { assertParameterNotNull(destinationFile, "The destination file parameter must be specified when downloading an object directly to a file"); S3Object s3Object = getObjectSecurely(getObjectRequest); // getObject can return null if constraints were specified but not met if (s3Object == null) return null; OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); byte[] buffer = new byte[1024*10]; int bytesRead; while ((bytesRead = s3Object.getObjectContent().read(buffer)) > -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new SdkClientException( "Unable to store object contents to disk: " + e.getMessage(), e); } finally { closeQuietly(outputStream, log); closeQuietly(s3Object.getObjectContent(), log); } /* * Unlike the standard Amazon S3 Client, the Amazon S3 Encryption Client does not do an MD5 check * here because the contents stored in S3 and the contents we just retrieved are different. In * S3, the stored contents are encrypted, and locally, the retrieved contents are decrypted. */ return s3Object.getObjectMetadata(); } @Override final MultipartUploadCryptoContext newUploadContext( InitiateMultipartUploadRequest req, ContentCryptoMaterial cekMaterial) { return new MultipartUploadCryptoContext( req.getBucketName(), req.getKey(), cekMaterial); } //// specific overrides for uploading parts. @Override final CipherLite cipherLiteForNextPart( MultipartUploadCryptoContext uploadContext) { return uploadContext.getCipherLite(); } @Override final SdkFilterInputStream wrapForMultipart( CipherLiteInputStream is, long partSize) { return is; } @Override final long computeLastPartSize(UploadPartRequest req) { return req.getPartSize() + (contentCryptoScheme.getTagLengthInBits() / 8); } @Override final void updateUploadContext(MultipartUploadCryptoContext uploadContext, SdkFilterInputStream is) { } /* * Private helper methods */ /** * Returns an updated object where the object content input stream contains the decrypted contents. * * @param wrapper * The object whose contents are to be decrypted. * @param cekMaterial * The instruction that will be used to decrypt the object data. * @return * The updated object where the object content input stream contains the decrypted contents. */ private S3ObjectWrapper decrypt(S3ObjectWrapper wrapper, ContentCryptoMaterial cekMaterial, long[] range) { S3ObjectInputStream objectContent = wrapper.getObjectContent(); wrapper.setObjectContent(new S3ObjectInputStream( new CipherLiteInputStream(objectContent, cekMaterial.getCipherLite(), DEFAULT_BUFFER_SIZE), objectContent.getHttpRequest())); return wrapper; } /** * Asserts that the specified parameter value is not null and if it is, * throws an IllegalArgumentException with the specified error message. * * @param parameterValue * The parameter value being checked. * @param errorMessage * The error message to include in the IllegalArgumentException * if the specified parameter is null. */ private void assertParameterNotNull(Object parameterValue, String errorMessage) { if (parameterValue == null) throw new IllegalArgumentException(errorMessage); } @Override protected final long ciphertextLength(long originalContentLength) { // Add 16 bytes for the 128-bit tag length using AES/GCM return originalContentLength + contentCryptoScheme.getTagLengthInBits()/8; } private void assertCanGetPartialObject() { if (!isRangeGetEnabled()) { String msg = "Unable to perform range get request: Range get support has been disabled. " + "See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html"; throw new SecurityException(msg); } } protected boolean isRangeGetEnabled() { CryptoRangeGetMode rangeGetMode = cryptoConfig.getRangeGetMode(); switch (rangeGetMode) { case ALL: return true; case DISABLED: default: return false; } } }
Exnadella/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/v2/S3CryptoModuleAE.java
4,602
/* * Private helper methods */
block_comment
nl
/* * Copyright 2013-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.s3.internal.crypto.v2; import static com.amazonaws.services.s3.model.CryptoMode.AuthenticatedEncryption; import static com.amazonaws.services.s3.model.CryptoMode.StrictAuthenticatedEncryption; import static com.amazonaws.services.s3.model.ExtraMaterialsDescription.NONE; import static com.amazonaws.util.IOUtils.closeQuietly; import com.amazonaws.services.s3.model.CryptoRangeGetMode; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collections; import java.util.Map; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.internal.SdkFilterInputStream; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.s3.internal.S3Direct; import com.amazonaws.services.s3.internal.crypto.AdjustedRangeInputStream; import com.amazonaws.services.s3.internal.crypto.CipherLite; import com.amazonaws.services.s3.internal.crypto.CipherLiteInputStream; import com.amazonaws.services.s3.internal.crypto.ContentCryptoScheme; import com.amazonaws.services.s3.internal.crypto.CryptoRuntime; import com.amazonaws.services.s3.model.CryptoConfigurationV2; import com.amazonaws.services.s3.model.CryptoMode; import com.amazonaws.services.s3.model.EncryptedGetObjectRequest; import com.amazonaws.services.s3.model.EncryptionMaterialsProvider; import com.amazonaws.services.s3.model.ExtraMaterialsDescription; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectId; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.util.json.Jackson; /** * Authenticated encryption (AE) cryptographic module for the S3 encryption client. */ public class S3CryptoModuleAE extends S3CryptoModuleBase<MultipartUploadCryptoContext> { static { // Enable bouncy castle if available CryptoRuntime.enableBouncyCastle(); } /** * @param cryptoConfig a read-only copy of the crypto configuration. */ public S3CryptoModuleAE(AWSKMS kms, S3Direct s3, AWSCredentialsProvider credentialsProvider, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { super(kms, s3, encryptionMaterialsProvider, cryptoConfig); CryptoMode mode = cryptoConfig.getCryptoMode(); if (mode != StrictAuthenticatedEncryption && mode != AuthenticatedEncryption) { throw new IllegalArgumentException(); } } /** * Used for testing purposes only. */ S3CryptoModuleAE(S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { this(null, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); } /** * Used for testing purposes only. */ S3CryptoModuleAE(AWSKMS kms, S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfigurationV2 cryptoConfig) { this(kms, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); } /** * Returns true if a strict encryption mode is in use in the current crypto * module; false otherwise. */ protected boolean isStrict() { return false; } @Override public S3Object getObjectSecurely(GetObjectRequest req) { // Adjust the crypto range to retrieve all of the cipher blocks needed to contain the user's desired // range of bytes. long[] desiredRange = req.getRange(); boolean isPartialObject = desiredRange != null || req.getPartNumber() != null; if (isPartialObject) { assertCanGetPartialObject(); } long[] adjustedCryptoRange = getAdjustedCryptoRange(desiredRange); if (adjustedCryptoRange != null) req.setRange(adjustedCryptoRange[0], adjustedCryptoRange[1]); // Get the object from S3 S3Object retrieved = s3.getObject(req); // If the caller has specified constraints, it's possible that super.getObject(...) // would return null, so we simply return null as well. if (retrieved == null) return null; String suffix = null; if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; suffix = ereq.getInstructionFileSuffix(); } try { return suffix == null || suffix.trim().isEmpty() ? decipher(req, desiredRange, adjustedCryptoRange, retrieved) : decipherWithInstFileSuffix(req, desiredRange, adjustedCryptoRange, retrieved, suffix) ; } catch (RuntimeException ex) { // If we're unable to set up the decryption, make sure we close the // HTTP connection closeQuietly(retrieved, log); throw ex; } catch (Error error) { closeQuietly(retrieved, log); throw error; } } private S3Object decipher(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved) { S3ObjectWrapper wrapped = new S3ObjectWrapper(retrieved, req.getS3ObjectId()); // Check if encryption info is in object metadata if (wrapped.hasEncryptionInfo()) return decipherWithMetadata(req, desiredRange, cryptoRange, wrapped); // Check if encrypted info is in an instruction file S3ObjectWrapper ifile = fetchInstructionFile(req.getS3ObjectId(), null); if (ifile != null) { try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, wrapped, ifile); } finally { closeQuietly(ifile, log); } } if (isStrict()) { closeQuietly(wrapped, log); throw new SecurityException("Unencrypted object found, cannot be decrypted in mode " + StrictAuthenticatedEncryption + "; bucket name: " + retrieved.getBucketName() + ", key: " + retrieved.getKey()); } if (cryptoConfig.isUnsafeUndecryptableObjectPassthrough()) { log.warn(String.format( "Unable to detect encryption information for object '%s' in bucket '%s'. " + "Returning object without decryption.", retrieved.getKey(), retrieved.getBucketName())); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange(wrapped, desiredRange, null); return adjusted.getS3Object(); } else { closeQuietly(wrapped, log); throw new SecurityException("Instruction file not found for S3 object with bucket name: " + retrieved.getBucketName() + ", key: " + retrieved.getKey()); } } /** * Same as {@link #decipher(GetObjectRequest, long[], long[], S3Object)} * but makes use of an instruction file with the specified suffix. * @param instFileSuffix never null or empty (which is assumed to have been * sanitized upstream.) */ private S3Object decipherWithInstFileSuffix(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3Object retrieved, String instFileSuffix) { final S3ObjectId id = req.getS3ObjectId(); // Check if encrypted info is in an instruction file final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix); if (ifile == null) { throw new SdkClientException("Instruction file with suffix " + instFileSuffix + " is not found for " + retrieved); } try { return decipherWithInstructionFile(req, desiredRange, cryptoRange, new S3ObjectWrapper(retrieved, id), ifile); } finally { closeQuietly(ifile, log); } } private S3Object decipherWithInstructionFile(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved, S3ObjectWrapper instructionFile) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } String json = instructionFile.toJsonString(); Map<String, String> matdesc = Collections.unmodifiableMap(Jackson.stringMapFromJsonString(json)); ContentCryptoMaterial cekMaterial = ContentCryptoMaterial.fromInstructionFile( matdesc, kekMaterialsProvider, cryptoConfig, cryptoRange, // range is sometimes necessary to compute the adjusted IV extraMatDesc, keyWrapExpected, kms ); boolean isRangeGet = desiredRange != null; securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, matdesc); return adjusted.getS3Object(); } private S3Object decipherWithMetadata(GetObjectRequest req, long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved) { ExtraMaterialsDescription extraMatDesc = NONE; boolean keyWrapExpected = isStrict(); if (req instanceof EncryptedGetObjectRequest) { EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req; extraMatDesc = ereq.getExtraMaterialDescription(); if (!keyWrapExpected) keyWrapExpected = ereq.isKeyWrapExpected(); } ContentCryptoMaterial cekMaterial = ContentCryptoMaterial .fromObjectMetadata(retrieved.getObjectMetadata().getUserMetadata(), kekMaterialsProvider, cryptoConfig, // range is sometimes necessary to compute the adjusted IV cryptoRange, extraMatDesc, keyWrapExpected, kms ); boolean isRangeGet = desiredRange != null; securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet); S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange); // Adjust the output to the desired range of bytes. S3ObjectWrapper adjusted = adjustToDesiredRange( decrypted, desiredRange, null); return adjusted.getS3Object(); } /** * Adjusts the retrieved S3Object so that the object contents contain only the range of bytes * desired by the user. Since encrypted contents can only be retrieved in CIPHER_BLOCK_SIZE * (16 bytes) chunks, the S3Object potentially contains more bytes than desired, so this method * adjusts the contents range. * * @param s3object * The S3Object retrieved from S3 that could possibly contain more bytes than desired * by the user. * @param range * A two-element array of longs corresponding to the start and finish (inclusive) of a desired * range of bytes. * @param instruction * Instruction file in JSON or null if no instruction file is involved * @return * The S3Object with adjusted object contents containing only the range desired by the user. * If the range specified is invalid, then the S3Object is returned without any modifications. */ protected final S3ObjectWrapper adjustToDesiredRange(S3ObjectWrapper s3object, long[] range, Map<String,String> instruction) { if (range == null) return s3object; // Figure out the original encryption scheme used, which can be // different from the crypto scheme used for decryption. ContentCryptoScheme encryptionScheme = s3object.encryptionSchemeOf(instruction); // range get on data encrypted using AES_GCM final long instanceLen = s3object.getObjectMetadata().getInstanceLength(); final long maxOffset = instanceLen - encryptionScheme.getTagLengthInBits() / 8 - 1; if (range[1] > maxOffset) { range[1] = maxOffset; if (range[0] > range[1]) { // Return empty content // First let's close the existing input stream to avoid resource // leakage closeQuietly(s3object.getObjectContent(), log); s3object.setObjectContent(new ByteArrayInputStream(new byte[0])); return s3object; } } if (range[0] > range[1]) { // Make no modifications if range is invalid. return s3object; } try { S3ObjectInputStream objectContent = s3object.getObjectContent(); InputStream adjustedRangeContents = new AdjustedRangeInputStream(objectContent, range[0], range[1]); s3object.setObjectContent(new S3ObjectInputStream(adjustedRangeContents, objectContent.getHttpRequest())); return s3object; } catch (IOException e) { throw new SdkClientException("Error adjusting output to desired byte range: " + e.getMessage()); } } @Override public ObjectMetadata getObjectSecurely(GetObjectRequest getObjectRequest, File destinationFile) { assertParameterNotNull(destinationFile, "The destination file parameter must be specified when downloading an object directly to a file"); S3Object s3Object = getObjectSecurely(getObjectRequest); // getObject can return null if constraints were specified but not met if (s3Object == null) return null; OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); byte[] buffer = new byte[1024*10]; int bytesRead; while ((bytesRead = s3Object.getObjectContent().read(buffer)) > -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new SdkClientException( "Unable to store object contents to disk: " + e.getMessage(), e); } finally { closeQuietly(outputStream, log); closeQuietly(s3Object.getObjectContent(), log); } /* * Unlike the standard Amazon S3 Client, the Amazon S3 Encryption Client does not do an MD5 check * here because the contents stored in S3 and the contents we just retrieved are different. In * S3, the stored contents are encrypted, and locally, the retrieved contents are decrypted. */ return s3Object.getObjectMetadata(); } @Override final MultipartUploadCryptoContext newUploadContext( InitiateMultipartUploadRequest req, ContentCryptoMaterial cekMaterial) { return new MultipartUploadCryptoContext( req.getBucketName(), req.getKey(), cekMaterial); } //// specific overrides for uploading parts. @Override final CipherLite cipherLiteForNextPart( MultipartUploadCryptoContext uploadContext) { return uploadContext.getCipherLite(); } @Override final SdkFilterInputStream wrapForMultipart( CipherLiteInputStream is, long partSize) { return is; } @Override final long computeLastPartSize(UploadPartRequest req) { return req.getPartSize() + (contentCryptoScheme.getTagLengthInBits() / 8); } @Override final void updateUploadContext(MultipartUploadCryptoContext uploadContext, SdkFilterInputStream is) { } /* * Private helper methods<SUF>*/ /** * Returns an updated object where the object content input stream contains the decrypted contents. * * @param wrapper * The object whose contents are to be decrypted. * @param cekMaterial * The instruction that will be used to decrypt the object data. * @return * The updated object where the object content input stream contains the decrypted contents. */ private S3ObjectWrapper decrypt(S3ObjectWrapper wrapper, ContentCryptoMaterial cekMaterial, long[] range) { S3ObjectInputStream objectContent = wrapper.getObjectContent(); wrapper.setObjectContent(new S3ObjectInputStream( new CipherLiteInputStream(objectContent, cekMaterial.getCipherLite(), DEFAULT_BUFFER_SIZE), objectContent.getHttpRequest())); return wrapper; } /** * Asserts that the specified parameter value is not null and if it is, * throws an IllegalArgumentException with the specified error message. * * @param parameterValue * The parameter value being checked. * @param errorMessage * The error message to include in the IllegalArgumentException * if the specified parameter is null. */ private void assertParameterNotNull(Object parameterValue, String errorMessage) { if (parameterValue == null) throw new IllegalArgumentException(errorMessage); } @Override protected final long ciphertextLength(long originalContentLength) { // Add 16 bytes for the 128-bit tag length using AES/GCM return originalContentLength + contentCryptoScheme.getTagLengthInBits()/8; } private void assertCanGetPartialObject() { if (!isRangeGetEnabled()) { String msg = "Unable to perform range get request: Range get support has been disabled. " + "See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html"; throw new SecurityException(msg); } } protected boolean isRangeGetEnabled() { CryptoRangeGetMode rangeGetMode = cryptoConfig.getRangeGetMode(); switch (rangeGetMode) { case ALL: return true; case DISABLED: default: return false; } } }
129533_4
import Entities.*; import Screen.PakbonScreenPopup; import Screen.StockScreenEditPopup; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.io.IOException; import java.util.List; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; public class MainScreen extends JFrame implements ActionListener { private JMenuBar menuBar; private JMenuItem menuButtonVoorraad; private JMenuItem menuButtonOrders; private JMenuItem menuButtonWeergave; private JMenuItem menuButton1; private JMenuItem menuButton2; private JMenuItem menuButtonHelp; CardLayout cardLayout; JPanel root; JList voorraadList; JList orders; OrderList orderList; ProductList productList; int index; Order selectedOrder; Order gezochteOrder; JList orderLines; JPanel OrderInfo; JTextField zoekenOrder; ArrayList<Order> orderResult; ArrayList<Product> stockResult; OrderLine selectedOrderLine; JButton aanpassenOrderLine; JButton PakbonPrinten; public MainScreen(){ // Screen setup this.setExtendedState(JFrame.MAXIMIZED_BOTH); this.setMinimumSize(new Dimension(1200, 500)); this.setTitle("HMI-application"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cardLayout = new CardLayout(); root = new JPanel(); root.setLayout(cardLayout); this.add(root); // Menubar Setup menuBar = new JMenuBar(); this.setJMenuBar(menuBar); menuButtonVoorraad = new JMenuItem("Voorraad"); menuButtonVoorraad.setActionCommand("Voorraad"); menuButtonVoorraad.addActionListener(this); menuButtonOrders = new JMenuItem("Orders"); menuButtonOrders.setActionCommand("Orders"); menuButtonOrders.addActionListener(this); menuButtonWeergave = new JMenuItem("Weergave"); menuButtonWeergave.setActionCommand("Weergave"); menuButtonWeergave.addActionListener(this); menuButton1 = new JMenuItem("-"); menuButton1.setActionCommand("button1"); menuButton1.addActionListener(this); menuButton2 = new JMenuItem("-"); menuButton2.setActionCommand("button2"); menuButton2.addActionListener(this); menuButtonHelp = new JMenuItem("Help"); menuButtonHelp.setActionCommand("Help"); menuButtonHelp.addActionListener(this); // Add buttons to menu bar menuBar.add(menuButtonVoorraad); menuBar.add(menuButtonOrders); menuBar.add(menuButtonWeergave); menuBar.add(menuButton1); menuBar.add(menuButton2); menuBar.add(menuButtonHelp); // Setup StockScreen productList = new ProductList(); productList.getProductsFromDatabase(); JPanel StockPanel = new JPanel(); StockPanel.setLayout(new BorderLayout()); voorraadList = new JList(productList.getProducts().toArray()); JScrollPane scrollPaneStockScreen = new JScrollPane(voorraadList); scrollPaneStockScreen.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneStockScreen.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPaneStockScreen.getVerticalScrollBar().setUnitIncrement(16); JPanel selectedStockScreen = new JPanel(new FlowLayout(FlowLayout.LEFT)); StockPanel.add(scrollPaneStockScreen, BorderLayout.CENTER); // Buttom bar (Selected bar) JButton buttonAanpassenStock = new JButton("Aanpassen"); buttonAanpassenStock.setActionCommand("AanpassenStock"); buttonAanpassenStock.addActionListener(this); JButton buttonZoekenStock = new JButton("Zoeken"); buttonZoekenStock.setActionCommand("Zoeken"); buttonZoekenStock.addActionListener(this); JTextField zoekenStock = new JTextField(10); zoekenStock.setText("Zoeken..."); zoekenStock.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { if (zoekenStock.getText().equals("Zoeken...")) { zoekenStock.setText(""); } } public void focusLost(java.awt.event.FocusEvent evt) { if (zoekenStock.getText().isEmpty()) { zoekenStock.setText("Zoeken..."); } } }); zoekenStock.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { filterStock(voorraadList, productList.getProducts()); } @Override public void removeUpdate(DocumentEvent e) { filterStock(voorraadList, productList.getProducts()); } @Override public void changedUpdate(DocumentEvent e) { filterStock(voorraadList, productList.getProducts()); } public void filterStock(JList<Product> product, List<Product> productList) { ArrayList<Product> foundStocks = new ArrayList<>(); try { int orderID = Integer.parseInt(zoekenStock.getText()); for (Product foundStock : productList) { if (String.valueOf(foundStock.getId()).equals(String.valueOf(orderID))) { foundStocks.add(foundStock); } } // if (foundStocks.size() >0){ product.setListData(foundStocks.toArray(new Product[0])); // // } } catch (NumberFormatException e) { String orderNaam = zoekenStock.getText(); if (orderNaam.equals("Zoeken...")) { foundStocks.addAll(productList); } else { for (Product foundStock : productList) { if (String.valueOf(foundStock.getName()).contains(String.valueOf(orderNaam))) { foundStocks.add(foundStock); } } product.setListData(foundStocks.toArray(new Product[0])); } } product.setListData(foundStocks.toArray(new Product[0])); if(foundStocks.size() == 0) { zoekenStock.setBackground(Color.RED); } else { zoekenStock.setBackground(Color.white); } } }); JLabel selectedProductLabel = new JLabel(" "); voorraadList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if(voorraadList.getSelectedIndex() != 0) { selectedProductLabel.setText(productList.getProducts().get(voorraadList.getSelectedIndex()).toString()); } else { selectedProductLabel.setText(String.valueOf(voorraadList.getModel().getElementAt(0))); } index = voorraadList.getSelectedIndex(); } }); selectedStockScreen.add(buttonAanpassenStock); selectedStockScreen.add(buttonZoekenStock); selectedStockScreen.add(zoekenStock); selectedStockScreen.add(selectedProductLabel); StockPanel.add(selectedStockScreen, BorderLayout.SOUTH); root.add("Voorraad", StockPanel); // Setup OrderScreen orderList = new OrderList(); orderList.getOrdersFromDatabase(); JPanel OrderPanel = new JPanel(); OrderPanel.setLayout(new BorderLayout()); orderResult =orderList.getOrders(); orders = new JList(orderResult.toArray()); JScrollPane scrollPaneOrderScreen = new JScrollPane(orders); scrollPaneOrderScreen.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneOrderScreen.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPaneOrderScreen.getVerticalScrollBar().setUnitIncrement(16); scrollPaneOrderScreen.setSize(new Dimension(this.getHeight(), 1500)); OrderPanel.add(scrollPaneOrderScreen, BorderLayout.WEST); root.add("Order", OrderPanel); //setup orderinfo scherm JPanel ProductView = new JPanel(); ProductView.setLayout(new BoxLayout(ProductView, BoxLayout.Y_AXIS)); OrderPanel.add(ProductView, BorderLayout.CENTER); selectedOrder = orderResult.get(0); JLabel OrderNummer = new JLabel(); ProductView.add(OrderNummer); orderLines = new JList(selectedOrder.getOrderLines().toArray()); JScrollPane scrollpaneOrderLines = new JScrollPane(orderLines); ProductView.add(scrollpaneOrderLines); ProductView.setVisible(false); JPanel adressLines = new JPanel(); adressLines.setLayout(new GridLayout(15, 1)); adressLines.setPreferredSize(new Dimension(this.getWidth()/4, this.getHeight())); JPanel adressLinesPanel = new JPanel(); adressLinesPanel.setLayout(new BorderLayout()); adressLinesPanel.add(adressLines, BorderLayout.CENTER); OrderPanel.add(adressLinesPanel, BorderLayout.EAST); JLabel naam = new JLabel(); adressLines.add(naam); JLabel adres = new JLabel(); adressLines.add(adres); JLabel postcode = new JLabel(); adressLines.add(postcode); JLabel woonplaats = new JLabel(); adressLines.add(woonplaats); JLabel telnr = new JLabel(); adressLines.add(telnr); JPanel adressLinesKnoppen = new JPanel(); adressLinesKnoppen.setLayout(new GridLayout(1, 2)); adressLinesKnoppen.setPreferredSize(new Dimension(adressLinesPanel.getWidth(), 25)); adressLinesPanel.add(adressLinesKnoppen, BorderLayout.SOUTH); JButton pickOrder = new JButton("Order Picken"); adressLinesKnoppen.add(pickOrder); aanpassenOrderLine = new JButton("Product aanpassen"); aanpassenOrderLine.setActionCommand("AanpassenOrder"); aanpassenOrderLine.addActionListener(this); adressLinesKnoppen.add(aanpassenOrderLine); PakbonPrinten = new JButton("Pakbon"); PakbonPrinten.setActionCommand("PakbonPrinten"); PakbonPrinten.addActionListener(this); adressLinesKnoppen.add(PakbonPrinten); adressLinesPanel.setVisible(false); orders.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { int selectedIndex = orders.getSelectedIndex(); if(selectedIndex != 0) { selectedOrder = orderList.getOrders().get(selectedIndex); } else { selectedOrder = (Order) orders.getModel().getElementAt(0); } // selectedOrder = orderList.getOrders().get() ; orderLines.clearSelection(); orderLines.setListData(selectedOrder.getOrderLines().toArray()); OrderNummer.setText("Ordernummer: " + selectedOrder.getId()); naam.setText("Naam: " + selectedOrder.getCustomer().getName()); adres.setText("Adres: " + selectedOrder.getCustomer().getAddressLine2()); postcode.setText("Postcode: " + selectedOrder.getCustomer().getPostalCode()); woonplaats.setText("Woonplaats: " + selectedOrder.getCustomer().getCity()); telnr.setText("Telefoonnummer: " + selectedOrder.getCustomer().getName()); ProductView.setVisible(true); adressLinesPanel.setVisible(true); OrderPanel.revalidate(); OrderPanel.repaint(); } }); orderLines.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { selectedOrderLine = selectedOrder.getOrderLines().get(orderLines.getSelectedIndex()); } }); //setup zoekbalk JButton buttonAanpassenPickDatum = new JButton("Pickdatum aanpassen"); buttonAanpassenPickDatum.setActionCommand("AanpassenPickDatum"); buttonAanpassenPickDatum.addActionListener(this); JButton buttonzoekenOrder = new JButton("Zoeken"); buttonzoekenOrder.setActionCommand("Zoeken"); buttonzoekenOrder.addActionListener(this); zoekenOrder = new JTextField(10); zoekenOrder.setText("Zoeken..."); zoekenOrder.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { if (zoekenOrder.getText().equals("Zoeken...")) { zoekenOrder.setText(""); } } public void focusLost(java.awt.event.FocusEvent evt) { if (zoekenOrder.getText().isEmpty()) { zoekenOrder.setText("Zoeken..."); } } }); zoekenOrder.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { filterOrder(orders, orderResult); } @Override public void removeUpdate(DocumentEvent e) { filterOrder(orders, orderResult); } @Override public void changedUpdate(DocumentEvent e) { filterOrder(orders, orderResult); } public void filterOrder(JList<Order> order, List<Order> orderList) { ArrayList<Order> foundOrders = new ArrayList<>(); try { int orderID = Integer.parseInt(zoekenOrder.getText()); for (Order foundOrder : orderList) { if (String.valueOf(foundOrder.getId()).equals(String.valueOf(orderID))) { foundOrders.add(foundOrder); } } order.setListData(foundOrders.toArray(new Order[0])); } catch (NumberFormatException e) { String orderNaam = zoekenOrder.getText(); if (orderNaam.equals("Zoeken...")) { foundOrders.addAll(orderList); }else if (orderNaam.equals("")){ foundOrders.addAll(orderList); } else{ order.setListData(foundOrders.toArray(new Order[0])); } } order.setListData(foundOrders.toArray(new Order[0])); if(foundOrders.size() == 0) { zoekenOrder.setBackground(Color.RED); } else { zoekenOrder.setBackground(Color.white); } } }); JPanel selectedOrderScreen = new JPanel(new FlowLayout(FlowLayout.LEFT)); selectedOrderScreen.add(buttonAanpassenPickDatum); selectedOrderScreen.add(buttonzoekenOrder); selectedOrderScreen.add(zoekenOrder); OrderPanel.add(selectedOrderScreen, BorderLayout.SOUTH); root.add("Orders", OrderPanel); // Setup WeergaveScreen JPanel WeergavePanel = new JPanel(); JScrollPane scrollPaneWeergaveScreen = new JScrollPane(WeergavePanel); WeergavePanel.setLayout(new BoxLayout(WeergavePanel, BoxLayout.Y_AXIS)); WeergavePanel.add(Box.createVerticalGlue()); scrollPaneWeergaveScreen.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneWeergaveScreen.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); JLabel WeergaveLabel = new JLabel("Weergave"); WeergavePanel.add(WeergaveLabel); root.add("Weergave", scrollPaneWeergaveScreen); // Setup HelpScreen JPanel HelpPanel = new JPanel(); JScrollPane scrollPaneHelpScreen = new JScrollPane(HelpPanel); HelpPanel.setLayout(new BoxLayout(HelpPanel, BoxLayout.Y_AXIS)); HelpPanel.add(Box.createVerticalGlue()); scrollPaneHelpScreen.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneHelpScreen.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); JLabel HelpLabel = new JLabel("Help"); HelpPanel.add(HelpLabel); root.add("Help", scrollPaneHelpScreen); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Voorraad")){ cardLayout.show(root, "Voorraad"); } else if (e.getActionCommand().equals("Orders")){ cardLayout.show(root, "Orders"); } else if (e.getActionCommand().equals("Weergave")){ cardLayout.show(root, "Weergave"); } else if (e.getActionCommand().equals("Help")){ cardLayout.show(root, "Help"); } else if (e.getActionCommand().equals("AanpassenStock")){ StockScreenEditPopup popup = new StockScreenEditPopup(productList.getProducts().get(index), "Change stock of '" + productList.getProducts().get(index).getName() + "'", productList.getProducts().get(index).getStock()); // productList.getProducts().get(index).setStockFromDatabase(); // this.voorraadList.revalidate(); } else if (e.getActionCommand().equals("AanpassenOrder")){ try { aanpassenOrderLine.setBackground(null); int voorraad = selectedOrderLine.getProduct().getStock(); OrderScreenEditPopup popup = new OrderScreenEditPopup(selectedOrderLine, "Change order " + selectedOrder.getId() + ", orderline " + selectedOrderLine.getId(), voorraad); } catch (NullPointerException npe) { aanpassenOrderLine.setBackground(new Color(255, 0, 0)); } } else if (e.getActionCommand().equals("AanpassenPickDatum")) { SetPickingPopup popup = new SetPickingPopup(selectedOrder.setPickingCompletedWhen(), selectedOrder.getId()); } else if (e.getActionCommand().equals("PakbonPrinten")) { try { PakbonScreenPopup popup = new PakbonScreenPopup(selectedOrder, "Pakbon van ' " + selectedOrder.getId() + " ' "); } catch (IOException ex) { throw new RuntimeException(ex); } // productList.getProducts().get(index).setStockFromDatabase(); // this.voorraadList.revalidate(); } this.voorraadList.revalidate(); this.orders.revalidate(); this.revalidate(); } public String ShortenString(String string, int length){ if (string.length() < length){ return string; } else { return string.substring(0, length) + "..."; } } }
Steven-Zwaan/KBS2-Retrieval-System
Bernard-Mulder/Bernard-Mulder/src/main/java/MainScreen.java
4,394
// selectedOrder = orderList.getOrders().get() ;
line_comment
nl
import Entities.*; import Screen.PakbonScreenPopup; import Screen.StockScreenEditPopup; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.io.IOException; import java.util.List; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; public class MainScreen extends JFrame implements ActionListener { private JMenuBar menuBar; private JMenuItem menuButtonVoorraad; private JMenuItem menuButtonOrders; private JMenuItem menuButtonWeergave; private JMenuItem menuButton1; private JMenuItem menuButton2; private JMenuItem menuButtonHelp; CardLayout cardLayout; JPanel root; JList voorraadList; JList orders; OrderList orderList; ProductList productList; int index; Order selectedOrder; Order gezochteOrder; JList orderLines; JPanel OrderInfo; JTextField zoekenOrder; ArrayList<Order> orderResult; ArrayList<Product> stockResult; OrderLine selectedOrderLine; JButton aanpassenOrderLine; JButton PakbonPrinten; public MainScreen(){ // Screen setup this.setExtendedState(JFrame.MAXIMIZED_BOTH); this.setMinimumSize(new Dimension(1200, 500)); this.setTitle("HMI-application"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cardLayout = new CardLayout(); root = new JPanel(); root.setLayout(cardLayout); this.add(root); // Menubar Setup menuBar = new JMenuBar(); this.setJMenuBar(menuBar); menuButtonVoorraad = new JMenuItem("Voorraad"); menuButtonVoorraad.setActionCommand("Voorraad"); menuButtonVoorraad.addActionListener(this); menuButtonOrders = new JMenuItem("Orders"); menuButtonOrders.setActionCommand("Orders"); menuButtonOrders.addActionListener(this); menuButtonWeergave = new JMenuItem("Weergave"); menuButtonWeergave.setActionCommand("Weergave"); menuButtonWeergave.addActionListener(this); menuButton1 = new JMenuItem("-"); menuButton1.setActionCommand("button1"); menuButton1.addActionListener(this); menuButton2 = new JMenuItem("-"); menuButton2.setActionCommand("button2"); menuButton2.addActionListener(this); menuButtonHelp = new JMenuItem("Help"); menuButtonHelp.setActionCommand("Help"); menuButtonHelp.addActionListener(this); // Add buttons to menu bar menuBar.add(menuButtonVoorraad); menuBar.add(menuButtonOrders); menuBar.add(menuButtonWeergave); menuBar.add(menuButton1); menuBar.add(menuButton2); menuBar.add(menuButtonHelp); // Setup StockScreen productList = new ProductList(); productList.getProductsFromDatabase(); JPanel StockPanel = new JPanel(); StockPanel.setLayout(new BorderLayout()); voorraadList = new JList(productList.getProducts().toArray()); JScrollPane scrollPaneStockScreen = new JScrollPane(voorraadList); scrollPaneStockScreen.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneStockScreen.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPaneStockScreen.getVerticalScrollBar().setUnitIncrement(16); JPanel selectedStockScreen = new JPanel(new FlowLayout(FlowLayout.LEFT)); StockPanel.add(scrollPaneStockScreen, BorderLayout.CENTER); // Buttom bar (Selected bar) JButton buttonAanpassenStock = new JButton("Aanpassen"); buttonAanpassenStock.setActionCommand("AanpassenStock"); buttonAanpassenStock.addActionListener(this); JButton buttonZoekenStock = new JButton("Zoeken"); buttonZoekenStock.setActionCommand("Zoeken"); buttonZoekenStock.addActionListener(this); JTextField zoekenStock = new JTextField(10); zoekenStock.setText("Zoeken..."); zoekenStock.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { if (zoekenStock.getText().equals("Zoeken...")) { zoekenStock.setText(""); } } public void focusLost(java.awt.event.FocusEvent evt) { if (zoekenStock.getText().isEmpty()) { zoekenStock.setText("Zoeken..."); } } }); zoekenStock.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { filterStock(voorraadList, productList.getProducts()); } @Override public void removeUpdate(DocumentEvent e) { filterStock(voorraadList, productList.getProducts()); } @Override public void changedUpdate(DocumentEvent e) { filterStock(voorraadList, productList.getProducts()); } public void filterStock(JList<Product> product, List<Product> productList) { ArrayList<Product> foundStocks = new ArrayList<>(); try { int orderID = Integer.parseInt(zoekenStock.getText()); for (Product foundStock : productList) { if (String.valueOf(foundStock.getId()).equals(String.valueOf(orderID))) { foundStocks.add(foundStock); } } // if (foundStocks.size() >0){ product.setListData(foundStocks.toArray(new Product[0])); // // } } catch (NumberFormatException e) { String orderNaam = zoekenStock.getText(); if (orderNaam.equals("Zoeken...")) { foundStocks.addAll(productList); } else { for (Product foundStock : productList) { if (String.valueOf(foundStock.getName()).contains(String.valueOf(orderNaam))) { foundStocks.add(foundStock); } } product.setListData(foundStocks.toArray(new Product[0])); } } product.setListData(foundStocks.toArray(new Product[0])); if(foundStocks.size() == 0) { zoekenStock.setBackground(Color.RED); } else { zoekenStock.setBackground(Color.white); } } }); JLabel selectedProductLabel = new JLabel(" "); voorraadList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if(voorraadList.getSelectedIndex() != 0) { selectedProductLabel.setText(productList.getProducts().get(voorraadList.getSelectedIndex()).toString()); } else { selectedProductLabel.setText(String.valueOf(voorraadList.getModel().getElementAt(0))); } index = voorraadList.getSelectedIndex(); } }); selectedStockScreen.add(buttonAanpassenStock); selectedStockScreen.add(buttonZoekenStock); selectedStockScreen.add(zoekenStock); selectedStockScreen.add(selectedProductLabel); StockPanel.add(selectedStockScreen, BorderLayout.SOUTH); root.add("Voorraad", StockPanel); // Setup OrderScreen orderList = new OrderList(); orderList.getOrdersFromDatabase(); JPanel OrderPanel = new JPanel(); OrderPanel.setLayout(new BorderLayout()); orderResult =orderList.getOrders(); orders = new JList(orderResult.toArray()); JScrollPane scrollPaneOrderScreen = new JScrollPane(orders); scrollPaneOrderScreen.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneOrderScreen.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPaneOrderScreen.getVerticalScrollBar().setUnitIncrement(16); scrollPaneOrderScreen.setSize(new Dimension(this.getHeight(), 1500)); OrderPanel.add(scrollPaneOrderScreen, BorderLayout.WEST); root.add("Order", OrderPanel); //setup orderinfo scherm JPanel ProductView = new JPanel(); ProductView.setLayout(new BoxLayout(ProductView, BoxLayout.Y_AXIS)); OrderPanel.add(ProductView, BorderLayout.CENTER); selectedOrder = orderResult.get(0); JLabel OrderNummer = new JLabel(); ProductView.add(OrderNummer); orderLines = new JList(selectedOrder.getOrderLines().toArray()); JScrollPane scrollpaneOrderLines = new JScrollPane(orderLines); ProductView.add(scrollpaneOrderLines); ProductView.setVisible(false); JPanel adressLines = new JPanel(); adressLines.setLayout(new GridLayout(15, 1)); adressLines.setPreferredSize(new Dimension(this.getWidth()/4, this.getHeight())); JPanel adressLinesPanel = new JPanel(); adressLinesPanel.setLayout(new BorderLayout()); adressLinesPanel.add(adressLines, BorderLayout.CENTER); OrderPanel.add(adressLinesPanel, BorderLayout.EAST); JLabel naam = new JLabel(); adressLines.add(naam); JLabel adres = new JLabel(); adressLines.add(adres); JLabel postcode = new JLabel(); adressLines.add(postcode); JLabel woonplaats = new JLabel(); adressLines.add(woonplaats); JLabel telnr = new JLabel(); adressLines.add(telnr); JPanel adressLinesKnoppen = new JPanel(); adressLinesKnoppen.setLayout(new GridLayout(1, 2)); adressLinesKnoppen.setPreferredSize(new Dimension(adressLinesPanel.getWidth(), 25)); adressLinesPanel.add(adressLinesKnoppen, BorderLayout.SOUTH); JButton pickOrder = new JButton("Order Picken"); adressLinesKnoppen.add(pickOrder); aanpassenOrderLine = new JButton("Product aanpassen"); aanpassenOrderLine.setActionCommand("AanpassenOrder"); aanpassenOrderLine.addActionListener(this); adressLinesKnoppen.add(aanpassenOrderLine); PakbonPrinten = new JButton("Pakbon"); PakbonPrinten.setActionCommand("PakbonPrinten"); PakbonPrinten.addActionListener(this); adressLinesKnoppen.add(PakbonPrinten); adressLinesPanel.setVisible(false); orders.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { int selectedIndex = orders.getSelectedIndex(); if(selectedIndex != 0) { selectedOrder = orderList.getOrders().get(selectedIndex); } else { selectedOrder = (Order) orders.getModel().getElementAt(0); } // selectedOrder =<SUF> orderLines.clearSelection(); orderLines.setListData(selectedOrder.getOrderLines().toArray()); OrderNummer.setText("Ordernummer: " + selectedOrder.getId()); naam.setText("Naam: " + selectedOrder.getCustomer().getName()); adres.setText("Adres: " + selectedOrder.getCustomer().getAddressLine2()); postcode.setText("Postcode: " + selectedOrder.getCustomer().getPostalCode()); woonplaats.setText("Woonplaats: " + selectedOrder.getCustomer().getCity()); telnr.setText("Telefoonnummer: " + selectedOrder.getCustomer().getName()); ProductView.setVisible(true); adressLinesPanel.setVisible(true); OrderPanel.revalidate(); OrderPanel.repaint(); } }); orderLines.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { selectedOrderLine = selectedOrder.getOrderLines().get(orderLines.getSelectedIndex()); } }); //setup zoekbalk JButton buttonAanpassenPickDatum = new JButton("Pickdatum aanpassen"); buttonAanpassenPickDatum.setActionCommand("AanpassenPickDatum"); buttonAanpassenPickDatum.addActionListener(this); JButton buttonzoekenOrder = new JButton("Zoeken"); buttonzoekenOrder.setActionCommand("Zoeken"); buttonzoekenOrder.addActionListener(this); zoekenOrder = new JTextField(10); zoekenOrder.setText("Zoeken..."); zoekenOrder.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { if (zoekenOrder.getText().equals("Zoeken...")) { zoekenOrder.setText(""); } } public void focusLost(java.awt.event.FocusEvent evt) { if (zoekenOrder.getText().isEmpty()) { zoekenOrder.setText("Zoeken..."); } } }); zoekenOrder.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { filterOrder(orders, orderResult); } @Override public void removeUpdate(DocumentEvent e) { filterOrder(orders, orderResult); } @Override public void changedUpdate(DocumentEvent e) { filterOrder(orders, orderResult); } public void filterOrder(JList<Order> order, List<Order> orderList) { ArrayList<Order> foundOrders = new ArrayList<>(); try { int orderID = Integer.parseInt(zoekenOrder.getText()); for (Order foundOrder : orderList) { if (String.valueOf(foundOrder.getId()).equals(String.valueOf(orderID))) { foundOrders.add(foundOrder); } } order.setListData(foundOrders.toArray(new Order[0])); } catch (NumberFormatException e) { String orderNaam = zoekenOrder.getText(); if (orderNaam.equals("Zoeken...")) { foundOrders.addAll(orderList); }else if (orderNaam.equals("")){ foundOrders.addAll(orderList); } else{ order.setListData(foundOrders.toArray(new Order[0])); } } order.setListData(foundOrders.toArray(new Order[0])); if(foundOrders.size() == 0) { zoekenOrder.setBackground(Color.RED); } else { zoekenOrder.setBackground(Color.white); } } }); JPanel selectedOrderScreen = new JPanel(new FlowLayout(FlowLayout.LEFT)); selectedOrderScreen.add(buttonAanpassenPickDatum); selectedOrderScreen.add(buttonzoekenOrder); selectedOrderScreen.add(zoekenOrder); OrderPanel.add(selectedOrderScreen, BorderLayout.SOUTH); root.add("Orders", OrderPanel); // Setup WeergaveScreen JPanel WeergavePanel = new JPanel(); JScrollPane scrollPaneWeergaveScreen = new JScrollPane(WeergavePanel); WeergavePanel.setLayout(new BoxLayout(WeergavePanel, BoxLayout.Y_AXIS)); WeergavePanel.add(Box.createVerticalGlue()); scrollPaneWeergaveScreen.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneWeergaveScreen.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); JLabel WeergaveLabel = new JLabel("Weergave"); WeergavePanel.add(WeergaveLabel); root.add("Weergave", scrollPaneWeergaveScreen); // Setup HelpScreen JPanel HelpPanel = new JPanel(); JScrollPane scrollPaneHelpScreen = new JScrollPane(HelpPanel); HelpPanel.setLayout(new BoxLayout(HelpPanel, BoxLayout.Y_AXIS)); HelpPanel.add(Box.createVerticalGlue()); scrollPaneHelpScreen.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneHelpScreen.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); JLabel HelpLabel = new JLabel("Help"); HelpPanel.add(HelpLabel); root.add("Help", scrollPaneHelpScreen); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Voorraad")){ cardLayout.show(root, "Voorraad"); } else if (e.getActionCommand().equals("Orders")){ cardLayout.show(root, "Orders"); } else if (e.getActionCommand().equals("Weergave")){ cardLayout.show(root, "Weergave"); } else if (e.getActionCommand().equals("Help")){ cardLayout.show(root, "Help"); } else if (e.getActionCommand().equals("AanpassenStock")){ StockScreenEditPopup popup = new StockScreenEditPopup(productList.getProducts().get(index), "Change stock of '" + productList.getProducts().get(index).getName() + "'", productList.getProducts().get(index).getStock()); // productList.getProducts().get(index).setStockFromDatabase(); // this.voorraadList.revalidate(); } else if (e.getActionCommand().equals("AanpassenOrder")){ try { aanpassenOrderLine.setBackground(null); int voorraad = selectedOrderLine.getProduct().getStock(); OrderScreenEditPopup popup = new OrderScreenEditPopup(selectedOrderLine, "Change order " + selectedOrder.getId() + ", orderline " + selectedOrderLine.getId(), voorraad); } catch (NullPointerException npe) { aanpassenOrderLine.setBackground(new Color(255, 0, 0)); } } else if (e.getActionCommand().equals("AanpassenPickDatum")) { SetPickingPopup popup = new SetPickingPopup(selectedOrder.setPickingCompletedWhen(), selectedOrder.getId()); } else if (e.getActionCommand().equals("PakbonPrinten")) { try { PakbonScreenPopup popup = new PakbonScreenPopup(selectedOrder, "Pakbon van ' " + selectedOrder.getId() + " ' "); } catch (IOException ex) { throw new RuntimeException(ex); } // productList.getProducts().get(index).setStockFromDatabase(); // this.voorraadList.revalidate(); } this.voorraadList.revalidate(); this.orders.revalidate(); this.revalidate(); } public String ShortenString(String string, int length){ if (string.length() < length){ return string; } else { return string.substring(0, length) + "..."; } } }
47486_1
package app; import entities.animal_entities.Carnivore; import entities.animal_entities.Herbivore; import entities.animal_entities.Omnivore; import entities.plant_entities.*; import service.ForestNotebook; import java.util.HashSet; import java.util.Set; // Notebook voor de wakkere wandelaar public class NatureApp { // xtra duidelijkheid print statements private static void separator() { System.out.println("\n=============\n"); } public static void main(String[] args) { ForestNotebook notebook = new ForestNotebook(); Flower duizendblad = new Flower("Duizendblad"); notebook.addPlant(duizendblad); duizendblad.setHeight(21.6); duizendblad.setSmell(Scent.MUSKY); Bush bosAardbei = new Bush("Bosaardbei", 36.8); notebook.addPlant(bosAardbei); bosAardbei.setFruit("Aardbei"); bosAardbei.setLeafType(LeafType.SPEAR); Weed robertsKruid = new Weed("Robertskruid", 8.3); notebook.addPlant(robertsKruid); robertsKruid.setArea(830); Flower wolligeBoterbloem = new Flower("Wollige boterbloem", 15.2); notebook.addPlant(wolligeBoterbloem); wolligeBoterbloem.setSmell(Scent.ORANGE); Tree winterLinde = new Tree("Winterlinde", 580); notebook.addPlant(winterLinde); winterLinde.setLeafType(LeafType.HAND); Tree berk = new Tree("Berk", 465); notebook.addPlant(berk); berk.setLeafType(LeafType.SPEAR); Bush wildeLiguster = new Bush("Wilde liguster", 120); notebook.addPlant(wildeLiguster); wildeLiguster.setFruit("Bessen"); wildeLiguster.setLeafType(LeafType.HEART); Set<Plant> knaagdierenDieet = new HashSet<>(); Set<Plant> vogelGourmet = new HashSet<>(); Set<Plant> otherCuisine = new HashSet<>(); knaagdierenDieet.add(wildeLiguster); knaagdierenDieet.add(robertsKruid); knaagdierenDieet.add(bosAardbei); vogelGourmet.add(winterLinde); vogelGourmet.add(berk); vogelGourmet.add(wildeLiguster); otherCuisine.add(wildeLiguster); otherCuisine.add(bosAardbei); otherCuisine.add(wolligeBoterbloem); otherCuisine.add(duizendblad); Herbivore bosmuis = new Herbivore("Bosmuis", 0.22, 0.053, 0.105); bosmuis.setPlantDiet(knaagdierenDieet); notebook.addAnimal(bosmuis); Herbivore edelHert = new Herbivore("Edelhert", 180, 196, 209); edelHert.setPlantDiet(otherCuisine); notebook.addAnimal(edelHert); Carnivore vos = new Carnivore("Vos", 40, 70, 130); vos.setMaxFoodSize(200); notebook.addAnimal(vos); Herbivore noordseVleermuis = new Herbivore("Noordse vleermuis", 0.11, 0.04, 0.066); noordseVleermuis.setPlantDiet(knaagdierenDieet); notebook.addAnimal(noordseVleermuis); Omnivore haas = new Omnivore("Haas", 4, 0.53, 0.46); haas.setPlantDiet(otherCuisine); haas.setMaxFoodSize(25); notebook.addAnimal(haas); Carnivore boomMarter = new Carnivore("Boommarter", 1.2, 0.15, 0.41); boomMarter.setMaxFoodSize(50); notebook.addAnimal(boomMarter); Omnivore mol = new Omnivore("Mol", 0.08, 0.03, 0.15); mol.setPlantDiet(knaagdierenDieet); mol.setMaxFoodSize(10); notebook.addAnimal(mol); Herbivore pimpelmees = new Herbivore("Pimpelmees", 0.02, 0.05, 0.02); pimpelmees.setPlantDiet(vogelGourmet); notebook.addAnimal(pimpelmees); Herbivore merel = new Herbivore("Merel", 0.025, 0.08, 0.02); merel.setPlantDiet(vogelGourmet); notebook.addAnimal(merel); Herbivore vink = new Herbivore("Vink", 0.1, 0.12, 0.03); vink.setPlantDiet(vogelGourmet); vink.addPlantToDiet(bosAardbei); notebook.addAnimal(vink); notebook.printNotebook(); separator(); notebook.sortAnimalsByName(); notebook.sortPlantsByName(); notebook.printNotebook(); separator(); notebook.moreInfoAnimals(); separator(); notebook.moreInfoPlants(); } }
TheBonoboShow/JavaFundamentals
src/app/NatureApp.java
1,363
// xtra duidelijkheid print statements
line_comment
nl
package app; import entities.animal_entities.Carnivore; import entities.animal_entities.Herbivore; import entities.animal_entities.Omnivore; import entities.plant_entities.*; import service.ForestNotebook; import java.util.HashSet; import java.util.Set; // Notebook voor de wakkere wandelaar public class NatureApp { // xtra duidelijkheid<SUF> private static void separator() { System.out.println("\n=============\n"); } public static void main(String[] args) { ForestNotebook notebook = new ForestNotebook(); Flower duizendblad = new Flower("Duizendblad"); notebook.addPlant(duizendblad); duizendblad.setHeight(21.6); duizendblad.setSmell(Scent.MUSKY); Bush bosAardbei = new Bush("Bosaardbei", 36.8); notebook.addPlant(bosAardbei); bosAardbei.setFruit("Aardbei"); bosAardbei.setLeafType(LeafType.SPEAR); Weed robertsKruid = new Weed("Robertskruid", 8.3); notebook.addPlant(robertsKruid); robertsKruid.setArea(830); Flower wolligeBoterbloem = new Flower("Wollige boterbloem", 15.2); notebook.addPlant(wolligeBoterbloem); wolligeBoterbloem.setSmell(Scent.ORANGE); Tree winterLinde = new Tree("Winterlinde", 580); notebook.addPlant(winterLinde); winterLinde.setLeafType(LeafType.HAND); Tree berk = new Tree("Berk", 465); notebook.addPlant(berk); berk.setLeafType(LeafType.SPEAR); Bush wildeLiguster = new Bush("Wilde liguster", 120); notebook.addPlant(wildeLiguster); wildeLiguster.setFruit("Bessen"); wildeLiguster.setLeafType(LeafType.HEART); Set<Plant> knaagdierenDieet = new HashSet<>(); Set<Plant> vogelGourmet = new HashSet<>(); Set<Plant> otherCuisine = new HashSet<>(); knaagdierenDieet.add(wildeLiguster); knaagdierenDieet.add(robertsKruid); knaagdierenDieet.add(bosAardbei); vogelGourmet.add(winterLinde); vogelGourmet.add(berk); vogelGourmet.add(wildeLiguster); otherCuisine.add(wildeLiguster); otherCuisine.add(bosAardbei); otherCuisine.add(wolligeBoterbloem); otherCuisine.add(duizendblad); Herbivore bosmuis = new Herbivore("Bosmuis", 0.22, 0.053, 0.105); bosmuis.setPlantDiet(knaagdierenDieet); notebook.addAnimal(bosmuis); Herbivore edelHert = new Herbivore("Edelhert", 180, 196, 209); edelHert.setPlantDiet(otherCuisine); notebook.addAnimal(edelHert); Carnivore vos = new Carnivore("Vos", 40, 70, 130); vos.setMaxFoodSize(200); notebook.addAnimal(vos); Herbivore noordseVleermuis = new Herbivore("Noordse vleermuis", 0.11, 0.04, 0.066); noordseVleermuis.setPlantDiet(knaagdierenDieet); notebook.addAnimal(noordseVleermuis); Omnivore haas = new Omnivore("Haas", 4, 0.53, 0.46); haas.setPlantDiet(otherCuisine); haas.setMaxFoodSize(25); notebook.addAnimal(haas); Carnivore boomMarter = new Carnivore("Boommarter", 1.2, 0.15, 0.41); boomMarter.setMaxFoodSize(50); notebook.addAnimal(boomMarter); Omnivore mol = new Omnivore("Mol", 0.08, 0.03, 0.15); mol.setPlantDiet(knaagdierenDieet); mol.setMaxFoodSize(10); notebook.addAnimal(mol); Herbivore pimpelmees = new Herbivore("Pimpelmees", 0.02, 0.05, 0.02); pimpelmees.setPlantDiet(vogelGourmet); notebook.addAnimal(pimpelmees); Herbivore merel = new Herbivore("Merel", 0.025, 0.08, 0.02); merel.setPlantDiet(vogelGourmet); notebook.addAnimal(merel); Herbivore vink = new Herbivore("Vink", 0.1, 0.12, 0.03); vink.setPlantDiet(vogelGourmet); vink.addPlantToDiet(bosAardbei); notebook.addAnimal(vink); notebook.printNotebook(); separator(); notebook.sortAnimalsByName(); notebook.sortPlantsByName(); notebook.printNotebook(); separator(); notebook.moreInfoAnimals(); separator(); notebook.moreInfoPlants(); } }
198931_6
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.pool.ha.node; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.nodes.GroupMember; import org.apache.curator.retry.RetryForever; import java.io.IOException; import java.io.StringWriter; import java.util.List; import java.util.Properties; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * A register which is used to register a node to an ephemeral node. * * @author DigitalSonic */ public class ZookeeperNodeRegister { private static final Log LOG = LogFactory.getLog(ZookeeperNodeRegister.class); private final Lock lock = new ReentrantLock(); private String zkConnectString; private String path = "/ha-druid-datasources"; private CuratorFramework client; private GroupMember member; private boolean privateZkClient; // Should I close the client? /** * Init a CuratorFramework if there's no CuratorFramework provided. */ public void init() { if (client == null) { client = CuratorFrameworkFactory.builder() .connectionTimeoutMs(5000) .connectString(zkConnectString) .retryPolicy(new RetryForever(10000)) .sessionTimeoutMs(30000) .build(); client.start(); privateZkClient = true; } } /** * Register a Node which has a Properties as the payload. * <pre> * CAUTION: only one node can be registered, * if you want to register another one, * call deregister first * </pre> * * @param payload The information used to generate the payload Properties * @return true, register successfully; false, skip the registeration */ public boolean register(String nodeId, List<ZookeeperNodeInfo> payload) { if (payload == null || payload.isEmpty()) { return false; } lock.lock(); try { createPathIfNotExisted(); if (member != null) { LOG.warn("GroupMember has already registered. Please deregister first."); return false; } String payloadString = getPropertiesString(payload); member = new GroupMember(client, path, nodeId, payloadString.getBytes()); member.start(); LOG.info("Register Node[" + nodeId + "] in path[" + path + "]."); return true; } finally { lock.unlock(); } } /** * Close the current GroupMember. */ public void deregister() { if (member != null) { member.close(); member = null; } if (client != null && privateZkClient) { client.close(); } } /** * @see #deregister() */ public void destroy() { deregister(); } private void createPathIfNotExisted() { try { if (client.checkExists().forPath(path) == null) { LOG.info("Path[" + path + "] is NOT existed, create it."); client.create().creatingParentsIfNeeded().forPath(path); } } catch (Exception e) { LOG.error("Can NOT check the path.", e); } } private String getPropertiesString(List<ZookeeperNodeInfo> payload) { Properties properties = new Properties(); for (ZookeeperNodeInfo n : payload) { if (n.getHost() != null) { properties.setProperty(n.getPrefix() + "host", n.getHost()); } if (n.getPort() != null) { properties.setProperty(n.getPrefix() + "port", n.getPort().toString()); } if (n.getDatabase() != null) { properties.setProperty(n.getPrefix() + "database", n.getDatabase()); } if (n.getUsername() != null) { properties.setProperty(n.getPrefix() + "username", n.getUsername()); } if (n.getPassword() != null) { properties.setProperty(n.getPrefix() + "password", n.getPassword()); } } StringWriter sw = new StringWriter(); try { properties.store(sw, ""); } catch (IOException e) { LOG.error("Why Properties.store goes wrong?", e); } return sw.toString(); } public void setClient(CuratorFramework client) { if (client != null) { this.client = client; privateZkClient = false; } } public CuratorFramework getClient() { return client; } public String getZkConnectString() { return zkConnectString; } public void setZkConnectString(String zkConnectString) { this.zkConnectString = zkConnectString; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
wenshao/druid
core/src/main/java/com/alibaba/druid/pool/ha/node/ZookeeperNodeRegister.java
1,443
/** * @see #deregister() */
block_comment
nl
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.pool.ha.node; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.nodes.GroupMember; import org.apache.curator.retry.RetryForever; import java.io.IOException; import java.io.StringWriter; import java.util.List; import java.util.Properties; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * A register which is used to register a node to an ephemeral node. * * @author DigitalSonic */ public class ZookeeperNodeRegister { private static final Log LOG = LogFactory.getLog(ZookeeperNodeRegister.class); private final Lock lock = new ReentrantLock(); private String zkConnectString; private String path = "/ha-druid-datasources"; private CuratorFramework client; private GroupMember member; private boolean privateZkClient; // Should I close the client? /** * Init a CuratorFramework if there's no CuratorFramework provided. */ public void init() { if (client == null) { client = CuratorFrameworkFactory.builder() .connectionTimeoutMs(5000) .connectString(zkConnectString) .retryPolicy(new RetryForever(10000)) .sessionTimeoutMs(30000) .build(); client.start(); privateZkClient = true; } } /** * Register a Node which has a Properties as the payload. * <pre> * CAUTION: only one node can be registered, * if you want to register another one, * call deregister first * </pre> * * @param payload The information used to generate the payload Properties * @return true, register successfully; false, skip the registeration */ public boolean register(String nodeId, List<ZookeeperNodeInfo> payload) { if (payload == null || payload.isEmpty()) { return false; } lock.lock(); try { createPathIfNotExisted(); if (member != null) { LOG.warn("GroupMember has already registered. Please deregister first."); return false; } String payloadString = getPropertiesString(payload); member = new GroupMember(client, path, nodeId, payloadString.getBytes()); member.start(); LOG.info("Register Node[" + nodeId + "] in path[" + path + "]."); return true; } finally { lock.unlock(); } } /** * Close the current GroupMember. */ public void deregister() { if (member != null) { member.close(); member = null; } if (client != null && privateZkClient) { client.close(); } } /** * @see #deregister() <SUF>*/ public void destroy() { deregister(); } private void createPathIfNotExisted() { try { if (client.checkExists().forPath(path) == null) { LOG.info("Path[" + path + "] is NOT existed, create it."); client.create().creatingParentsIfNeeded().forPath(path); } } catch (Exception e) { LOG.error("Can NOT check the path.", e); } } private String getPropertiesString(List<ZookeeperNodeInfo> payload) { Properties properties = new Properties(); for (ZookeeperNodeInfo n : payload) { if (n.getHost() != null) { properties.setProperty(n.getPrefix() + "host", n.getHost()); } if (n.getPort() != null) { properties.setProperty(n.getPrefix() + "port", n.getPort().toString()); } if (n.getDatabase() != null) { properties.setProperty(n.getPrefix() + "database", n.getDatabase()); } if (n.getUsername() != null) { properties.setProperty(n.getPrefix() + "username", n.getUsername()); } if (n.getPassword() != null) { properties.setProperty(n.getPrefix() + "password", n.getPassword()); } } StringWriter sw = new StringWriter(); try { properties.store(sw, ""); } catch (IOException e) { LOG.error("Why Properties.store goes wrong?", e); } return sw.toString(); } public void setClient(CuratorFramework client) { if (client != null) { this.client = client; privateZkClient = false; } } public CuratorFramework getClient() { return client; } public String getZkConnectString() { return zkConnectString; } public void setZkConnectString(String zkConnectString) { this.zkConnectString = zkConnectString; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
156490_18
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.util; import io.undertow.UndertowMessages; import io.undertow.server.handlers.Cookie; /** * Class that contains static constants and utility methods for legacy Set-Cookie format. * Porting from JBossWeb and Tomcat code. * * Note that in general we do not use system properties for configuration, however as these are * legacy options that are not widely used an exception has been made in this case. * */ public final class LegacyCookieSupport { // --------------------------------------------------------------- Constants /** * If true, separators that are not explicitly dis-allowed by the v0 cookie * spec but are disallowed by the HTTP spec will be allowed in v0 cookie * names and values. These characters are: \"()/:<=>?@[\\]{} Note that the * inclusion of / depend on the value of {@link #FWD_SLASH_IS_SEPARATOR}. * * Defaults to false. */ static final boolean ALLOW_HTTP_SEPARATORS_IN_V0 = Boolean.getBoolean("io.undertow.legacy.cookie.ALLOW_HTTP_SEPARATORS_IN_V0"); /** * If set to true, the <code>/</code> character will be treated as a * separator. Default is false. */ private static final boolean FWD_SLASH_IS_SEPARATOR = Boolean.getBoolean("io.undertow.legacy.cookie.FWD_SLASH_IS_SEPARATOR"); /** * If set to true, the <code,</code> character will be treated as a * separator in Cookie: headers. */ static final boolean COMMA_IS_SEPARATOR = Boolean.getBoolean("io.undertow.legacy.cookie.COMMA_IS_SEPARATOR"); /** * The list of separators that apply to version 0 cookies. To quote the * spec, these are comma, semi-colon and white-space. The HTTP spec * definition of linear white space is [CRLF] 1*( SP | HT ) */ private static final char[] V0_SEPARATORS = {',', ';', ' ', '\t'}; private static final boolean[] V0_SEPARATOR_FLAGS = new boolean[128]; /** * The list of separators that apply to version 1 cookies. This may or may * not include '/' depending on the setting of * {@link #FWD_SLASH_IS_SEPARATOR}. */ private static final char[] HTTP_SEPARATORS; private static final boolean[] HTTP_SEPARATOR_FLAGS = new boolean[128]; static { /* Excluding the '/' char by default violates the RFC, but it looks like a lot of people put '/' in unquoted values: '/': ; //47 '\t':9 ' ':32 '\"':34 '(':40 ')':41 ',':44 ':':58 ';':59 '<':60 '=':61 '>':62 '?':63 '@':64 '[':91 '\\':92 ']':93 '{':123 '}':125 */ if (FWD_SLASH_IS_SEPARATOR) { HTTP_SEPARATORS = new char[]{'\t', ' ', '\"', '(', ')', ',', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}'}; } else { HTTP_SEPARATORS = new char[]{'\t', ' ', '\"', '(', ')', ',', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}'}; } for (int i = 0; i < 128; i++) { V0_SEPARATOR_FLAGS[i] = false; HTTP_SEPARATOR_FLAGS[i] = false; } for (char V0_SEPARATOR : V0_SEPARATORS) { V0_SEPARATOR_FLAGS[V0_SEPARATOR] = true; } for (char HTTP_SEPARATOR : HTTP_SEPARATORS) { HTTP_SEPARATOR_FLAGS[HTTP_SEPARATOR] = true; } } // ----------------------------------------------------------------- Methods /** * Returns true if the byte is a separator as defined by V0 of the cookie * spec. */ private static boolean isV0Separator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c)); } } return V0_SEPARATOR_FLAGS[c]; } private static boolean isV0Token(String value) { if( value==null) return false; int i = 0; int len = value.length(); if (alreadyQuoted(value)) { i++; len--; } for (; i < len; i++) { char c = value.charAt(i); if (isV0Separator(c)) return true; } return false; } /** * Returns true if the byte is a separator as defined by V1 of the cookie * spec, RFC2109. * @throws IllegalArgumentException if a control character was supplied as * input */ static boolean isHttpSeparator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c)); } } return HTTP_SEPARATOR_FLAGS[c]; } private static boolean isHttpToken(String value) { if( value==null) return false; int i = 0; int len = value.length(); if (alreadyQuoted(value)) { i++; len--; } for (; i < len; i++) { char c = value.charAt(i); if (isHttpSeparator(c)) return true; } return false; } private static boolean alreadyQuoted(String value) { if (value==null || value.length() < 2) return false; return (value.charAt(0)=='\"' && value.charAt(value.length()-1)=='\"'); } /** * Quotes values if required. * @param buf * @param value */ public static void maybeQuote(StringBuilder buf, String value) { if (value==null || value.length()==0) { buf.append("\"\""); } else if (alreadyQuoted(value)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,1,value.length()-1)); buf.append('"'); } else if ((isHttpToken(value) && !ALLOW_HTTP_SEPARATORS_IN_V0) || (isV0Token(value) && ALLOW_HTTP_SEPARATORS_IN_V0)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); } else { buf.append(value); } } /** * Escapes any double quotes in the given string. * * @param s the input string * @param beginIndex start index inclusive * @param endIndex exclusive * @return The (possibly) escaped string */ private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) { if (s == null || s.length() == 0 || s.indexOf('"') == -1) { return s; } StringBuilder b = new StringBuilder(); for (int i = beginIndex; i < endIndex; i++) { char c = s.charAt(i); if (c == '\\' ) { b.append(c); //ignore the character after an escape, just append it if (++i>=endIndex) throw UndertowMessages.MESSAGES.invalidEscapeCharacter(); b.append(s.charAt(i)); } else if (c == '"') b.append('\\').append('"'); else b.append(c); } return b.toString(); } public static int adjustedCookieVersion(Cookie cookie) { /* * The spec allows some latitude on when to send the version attribute * with a Set-Cookie header. To be nice to clients, we'll make sure the * version attribute is first. That means checking the various things * that can cause us to switch to a v1 cookie first. *_ * Note that by checking for tokens we will also throw an exception if a * control character is encountered. */ int version = cookie.getVersion(); String value = cookie.getValue(); String path = cookie.getPath(); String domain = cookie.getDomain(); String comment = cookie.getComment(); // If it is v0, check if we need to switch if (version == 0 && (!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(value) || ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(value))) { // HTTP token in value - need to use v1 version = 1; } if (version == 0 && comment != null) { // Using a comment makes it a v1 cookie version = 1; } if (version == 0 && (!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(path) || ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(path))) { // HTTP token in path - need to use v1 version = 1; } if (version == 0 && (!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(domain) || ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(domain))) { // HTTP token in domain - need to use v1 version = 1; } return version; } // ------------------------------------------------------------- Constructor private LegacyCookieSupport() { // Utility class. Don't allow instances to be created. } }
undertow-io/undertow
core/src/main/java/io/undertow/util/LegacyCookieSupport.java
2,655
// HTTP token in domain - need to use v1
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.util; import io.undertow.UndertowMessages; import io.undertow.server.handlers.Cookie; /** * Class that contains static constants and utility methods for legacy Set-Cookie format. * Porting from JBossWeb and Tomcat code. * * Note that in general we do not use system properties for configuration, however as these are * legacy options that are not widely used an exception has been made in this case. * */ public final class LegacyCookieSupport { // --------------------------------------------------------------- Constants /** * If true, separators that are not explicitly dis-allowed by the v0 cookie * spec but are disallowed by the HTTP spec will be allowed in v0 cookie * names and values. These characters are: \"()/:<=>?@[\\]{} Note that the * inclusion of / depend on the value of {@link #FWD_SLASH_IS_SEPARATOR}. * * Defaults to false. */ static final boolean ALLOW_HTTP_SEPARATORS_IN_V0 = Boolean.getBoolean("io.undertow.legacy.cookie.ALLOW_HTTP_SEPARATORS_IN_V0"); /** * If set to true, the <code>/</code> character will be treated as a * separator. Default is false. */ private static final boolean FWD_SLASH_IS_SEPARATOR = Boolean.getBoolean("io.undertow.legacy.cookie.FWD_SLASH_IS_SEPARATOR"); /** * If set to true, the <code,</code> character will be treated as a * separator in Cookie: headers. */ static final boolean COMMA_IS_SEPARATOR = Boolean.getBoolean("io.undertow.legacy.cookie.COMMA_IS_SEPARATOR"); /** * The list of separators that apply to version 0 cookies. To quote the * spec, these are comma, semi-colon and white-space. The HTTP spec * definition of linear white space is [CRLF] 1*( SP | HT ) */ private static final char[] V0_SEPARATORS = {',', ';', ' ', '\t'}; private static final boolean[] V0_SEPARATOR_FLAGS = new boolean[128]; /** * The list of separators that apply to version 1 cookies. This may or may * not include '/' depending on the setting of * {@link #FWD_SLASH_IS_SEPARATOR}. */ private static final char[] HTTP_SEPARATORS; private static final boolean[] HTTP_SEPARATOR_FLAGS = new boolean[128]; static { /* Excluding the '/' char by default violates the RFC, but it looks like a lot of people put '/' in unquoted values: '/': ; //47 '\t':9 ' ':32 '\"':34 '(':40 ')':41 ',':44 ':':58 ';':59 '<':60 '=':61 '>':62 '?':63 '@':64 '[':91 '\\':92 ']':93 '{':123 '}':125 */ if (FWD_SLASH_IS_SEPARATOR) { HTTP_SEPARATORS = new char[]{'\t', ' ', '\"', '(', ')', ',', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}'}; } else { HTTP_SEPARATORS = new char[]{'\t', ' ', '\"', '(', ')', ',', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}'}; } for (int i = 0; i < 128; i++) { V0_SEPARATOR_FLAGS[i] = false; HTTP_SEPARATOR_FLAGS[i] = false; } for (char V0_SEPARATOR : V0_SEPARATORS) { V0_SEPARATOR_FLAGS[V0_SEPARATOR] = true; } for (char HTTP_SEPARATOR : HTTP_SEPARATORS) { HTTP_SEPARATOR_FLAGS[HTTP_SEPARATOR] = true; } } // ----------------------------------------------------------------- Methods /** * Returns true if the byte is a separator as defined by V0 of the cookie * spec. */ private static boolean isV0Separator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c)); } } return V0_SEPARATOR_FLAGS[c]; } private static boolean isV0Token(String value) { if( value==null) return false; int i = 0; int len = value.length(); if (alreadyQuoted(value)) { i++; len--; } for (; i < len; i++) { char c = value.charAt(i); if (isV0Separator(c)) return true; } return false; } /** * Returns true if the byte is a separator as defined by V1 of the cookie * spec, RFC2109. * @throws IllegalArgumentException if a control character was supplied as * input */ static boolean isHttpSeparator(final char c) { if (c < 0x20 || c >= 0x7f) { if (c != 0x09) { throw UndertowMessages.MESSAGES.invalidControlCharacter(Integer.toString(c)); } } return HTTP_SEPARATOR_FLAGS[c]; } private static boolean isHttpToken(String value) { if( value==null) return false; int i = 0; int len = value.length(); if (alreadyQuoted(value)) { i++; len--; } for (; i < len; i++) { char c = value.charAt(i); if (isHttpSeparator(c)) return true; } return false; } private static boolean alreadyQuoted(String value) { if (value==null || value.length() < 2) return false; return (value.charAt(0)=='\"' && value.charAt(value.length()-1)=='\"'); } /** * Quotes values if required. * @param buf * @param value */ public static void maybeQuote(StringBuilder buf, String value) { if (value==null || value.length()==0) { buf.append("\"\""); } else if (alreadyQuoted(value)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,1,value.length()-1)); buf.append('"'); } else if ((isHttpToken(value) && !ALLOW_HTTP_SEPARATORS_IN_V0) || (isV0Token(value) && ALLOW_HTTP_SEPARATORS_IN_V0)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); } else { buf.append(value); } } /** * Escapes any double quotes in the given string. * * @param s the input string * @param beginIndex start index inclusive * @param endIndex exclusive * @return The (possibly) escaped string */ private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) { if (s == null || s.length() == 0 || s.indexOf('"') == -1) { return s; } StringBuilder b = new StringBuilder(); for (int i = beginIndex; i < endIndex; i++) { char c = s.charAt(i); if (c == '\\' ) { b.append(c); //ignore the character after an escape, just append it if (++i>=endIndex) throw UndertowMessages.MESSAGES.invalidEscapeCharacter(); b.append(s.charAt(i)); } else if (c == '"') b.append('\\').append('"'); else b.append(c); } return b.toString(); } public static int adjustedCookieVersion(Cookie cookie) { /* * The spec allows some latitude on when to send the version attribute * with a Set-Cookie header. To be nice to clients, we'll make sure the * version attribute is first. That means checking the various things * that can cause us to switch to a v1 cookie first. *_ * Note that by checking for tokens we will also throw an exception if a * control character is encountered. */ int version = cookie.getVersion(); String value = cookie.getValue(); String path = cookie.getPath(); String domain = cookie.getDomain(); String comment = cookie.getComment(); // If it is v0, check if we need to switch if (version == 0 && (!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(value) || ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(value))) { // HTTP token in value - need to use v1 version = 1; } if (version == 0 && comment != null) { // Using a comment makes it a v1 cookie version = 1; } if (version == 0 && (!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(path) || ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(path))) { // HTTP token in path - need to use v1 version = 1; } if (version == 0 && (!ALLOW_HTTP_SEPARATORS_IN_V0 && isHttpToken(domain) || ALLOW_HTTP_SEPARATORS_IN_V0 && isV0Token(domain))) { // HTTP token<SUF> version = 1; } return version; } // ------------------------------------------------------------- Constructor private LegacyCookieSupport() { // Utility class. Don't allow instances to be created. } }
149877_11
package com.redditandroiddevelopers.tamagotchi.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g2d.stbtt.TrueTypeFontFactory; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.ClickListener; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.redditandroiddevelopers.tamagotchi.TamagotchiAssets.TextureAtlasAsset; import com.redditandroiddevelopers.tamagotchi.TamagotchiGame; import com.redditandroiddevelopers.tamagotchi.creatures.Creature1; import com.redditandroiddevelopers.tamagotchi.ui.DragListener; import com.redditandroiddevelopers.tamagotchi.ui.DraggableImage; import com.redditandroiddevelopers.tamagotchi.utils.FontHelper; /** * This screen instance will represent the main game screen where your creature * will live.<br> * This is where the user will spend most of the time. */ public class MainGameScreen extends CommonScreen implements ClickListener, DragListener { private static final String TAG = "Tamagotchi:MainGameScreen"; private static final String GRP_BACKGROUND = "background"; private static final String GRP_FOREGROUND = "foreground"; private static final String GRP_OVERLAY = "overlay"; private static final String GRP_BACKGROUND_DISTANT = "background_distant"; private static final String GRP_BACKGROUND_NEAR = "background_near"; private static final String GRP_UI = "ui"; private static final String GRP_TOP_BUTTONS = "top_buttons"; private static final String GRP_STATUS_PANEL = "status_panel"; private static final int FOOD = 0; private static final int TOILET = 1; private static final int SHOWER = 2; private static final int LIGHT = 3; private static final int NUM_BUTTONS = 4; private Button[] buttons; private DraggableImage btnDrag; private Label fpsLabel; private Creature1 creature; /** * Creates a new instance of the MainGameScreen. * * @param game Needs a TamagotchiGame instance. */ public MainGameScreen(TamagotchiGame game) { super(game); } @Override protected final Stage createStage(SpriteBatch batch) { return new Stage(game.config.stageWidth, game.config.stageHeight, false, batch); } @Override public final void show() { super.show(); layout(); } /** * Creates the basic layout of the screen. */ private void layout() { /* * TODO: Add basic status mockup that can be pulled down TODO: Add * creature TODO: Add background TODO: Add layers for background and the * main stage TODO: Add overlays, e.g. for speech bubbles */ /* add groups for better readability and flexibility */ // create main groups final Group backgroundGroup = new Group(GRP_BACKGROUND); final Group foregroundGroup = new Group(GRP_FOREGROUND); final Group overlayGroup = new Group(GRP_OVERLAY); // create sub groups final Group bgDistantGroup = new Group(GRP_BACKGROUND_DISTANT); final Group bgNearGroup = new Group(GRP_BACKGROUND_NEAR); final Group uiGroup = new Group(GRP_UI); final Group topButtonsGroup = new Group(GRP_TOP_BUTTONS); final Group statusPanelGroup = new Group(GRP_STATUS_PANEL); /* load textures */ // load texture atlas final TextureAtlas textureAtlas = game.assets.getAsset(TextureAtlasAsset.MAIN_GAME); // get texture regions from loaded texture atlas final TextureRegion planetsBackgroundTextureRegion = textureAtlas .findRegion("PlanetsBackground"); final TextureRegion hillsMidgroundTextureRegion = textureAtlas.findRegion("HillsMidground"); final TextureRegion hillsForegroundTextureRegion = textureAtlas .findRegion("HillsForeground"); final TextureRegion groundTextureRegion = textureAtlas.findRegion("StaticGround"); final TextureRegion creatureDefaultTextureRegion = textureAtlas.findRegion("PetDefault"); final TextureRegion swipeArrowTextureRegion = textureAtlas.findRegion("LeftSwipeArrow"); /* prepare layout */ // add background Image bgPlanetsBackground = new Image(planetsBackgroundTextureRegion); Image bgHillsMidground = new Image(hillsMidgroundTextureRegion); Image bgHillsForeground = new Image(hillsForegroundTextureRegion); Image bgGround = new Image(groundTextureRegion); // add creature creature = new Creature1(creatureDefaultTextureRegion, "creature"); creature.setClickListener(this); creature.x = 400; creature.y = 50; // create buttons names final String[] interactButtonIDs = new String[] { "MainButtonFood", "MainButtonToilet", "MainButtonShower", "MainButtonSleepOff" }; // load texture regions for buttons in top right corner final TextureRegion[] interactButtonTextureRegions = new TextureRegion[interactButtonIDs.length]; for (int i = 0; i < interactButtonIDs.length; i++) { interactButtonTextureRegions[i] = textureAtlas.findRegion(interactButtonIDs[i]); } // set margin between buttons final int marginBetweenButtons = 10; // position buttons within group and add them to the 'topButtonsGroup' final int width = interactButtonTextureRegions[0].getRegionWidth() + marginBetweenButtons; buttons = new Button[NUM_BUTTONS]; for (int i = 0; i < NUM_BUTTONS; i++) { final Button button = new Button(interactButtonTextureRegions[i]); button.x = width * i; button.setClickListener(this); topButtonsGroup.addActor(button); buttons[i] = button; } // adjust width of 'topButtons' group topButtonsGroup.width = width * topButtonsGroup.getActors().size(); // position topButtons in top right corner topButtonsGroup.x = stage.right() - topButtonsGroup.width; topButtonsGroup.y = stage.top() - width; // add drag down status panel button btnDrag = new DraggableImage(swipeArrowTextureRegion); btnDrag.setClickListener(this); btnDrag.setDragListener(this); statusPanelGroup.addActor(btnDrag); // add an FPS label (subject to configuration) if (game.config.logFps) { final String FONT_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789][_!$%#@|\\/?-+=()*&.:;,{}\"�`'<>"; BitmapFont font = TrueTypeFontFactory.createBitmapFont( Gdx.files.internal("fonts/Roboto-Regular.ttf"), FONT_CHARACTERS, stage.width(), stage.height(), 25.0f, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); final Label.LabelStyle labelStyle = new Label.LabelStyle( font, Color.RED); fpsLabel = new Label("FPS: " + Gdx.graphics.getFramesPerSecond(), labelStyle); fpsLabel.y = -15; } /* Prepare sub groups */ // add sub groups to the 'ui' group uiGroup.addActor(statusPanelGroup); uiGroup.addActor(topButtonsGroup); // sub groups to the 'background' group bgDistantGroup.addActor(bgPlanetsBackground); bgDistantGroup.addActor(bgHillsMidground); bgDistantGroup.addActor(bgHillsForeground); bgNearGroup.y = -50; bgDistantGroup.y = bgNearGroup.y + bgGround.height; bgNearGroup.addActor(bgGround); /* Prepare main groups */ // add groups to 'background' backgroundGroup.addActor(bgDistantGroup); backgroundGroup.addActor(bgNearGroup); // add groups to 'foreground' // add creature to main group foregroundGroup.addActor(creature); // add groups to 'overlay' overlayGroup.addActor(uiGroup); // add an FPS label (subject to configuration) if (game.config.logFps) { final BitmapFont font = FontHelper.createBitmapFont(FontHelper.TTF_ROBOTO_REGULAR, 25f, stage); final Label.LabelStyle labelStyle = new Label.LabelStyle( font, Color.RED); fpsLabel = new Label("FPS: " + Gdx.graphics.getFramesPerSecond(), labelStyle); fpsLabel.y = -15; overlayGroup.addActor(fpsLabel); } /* Add main groups to stage */ stage.addActor(backgroundGroup); stage.addActor(foregroundGroup); stage.addActor(overlayGroup); } @Override public void update(float delta) { creature.lifeCycle(); if (fpsLabel != null) { assert game.config.logFps; fpsLabel.setText("FPS: " + Gdx.graphics.getFramesPerSecond()); } super.update(delta); } @Override public final void click(Actor actor, float x, float y) { // touch input was received, time to find the culprit if (actor == buttons[FOOD]) { Gdx.app.debug(TAG, "Touch on food button"); creature.moveBy(-100f, 1f); } else if (actor == buttons[TOILET]) { Gdx.app.debug(TAG, "Touch on toilet button"); creature.moveBy(100f, 1f); } else if (actor == buttons[SHOWER]) { Gdx.app.debug(TAG, "Touch on shower button"); creature.roll(-200, 1f); } else if (actor == buttons[LIGHT]) { Gdx.app.debug(TAG, "Touch on light button"); creature.roll(200, 1f); } else if (actor == creature) { creature.jump(); } else if (actor == btnDrag) { Gdx.app.debug(TAG, "Touch on arrow"); // do nothing, handle in drag() } else { Gdx.app.error(TAG, "Unknown actor"); assert false; } } @Override public void drag(Actor a, float x, float y, int pointer) { if (a == btnDrag) { /* * TODO: detect precise touch point and use it when moving the group * Currently, it snaps to the bottom line of the texture when * dragging starts. In order to make it look better, we need to * apply an offset for the correct touch point. */ stage.findActor(GRP_STATUS_PANEL).x += x; } } @Override public void loadResources() { game.assets.loadAsset(TextureAtlasAsset.MAIN_GAME); } @Override public void unloadResources() { game.assets.unloadAsset(TextureAtlasAsset.MAIN_GAME); } }
RedditAndroidDev/Tamagotchi
Tamagotchi/src/com/redditandroiddevelopers/tamagotchi/screens/MainGameScreen.java
2,883
// set margin between buttons
line_comment
nl
package com.redditandroiddevelopers.tamagotchi.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g2d.stbtt.TrueTypeFontFactory; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.ClickListener; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.redditandroiddevelopers.tamagotchi.TamagotchiAssets.TextureAtlasAsset; import com.redditandroiddevelopers.tamagotchi.TamagotchiGame; import com.redditandroiddevelopers.tamagotchi.creatures.Creature1; import com.redditandroiddevelopers.tamagotchi.ui.DragListener; import com.redditandroiddevelopers.tamagotchi.ui.DraggableImage; import com.redditandroiddevelopers.tamagotchi.utils.FontHelper; /** * This screen instance will represent the main game screen where your creature * will live.<br> * This is where the user will spend most of the time. */ public class MainGameScreen extends CommonScreen implements ClickListener, DragListener { private static final String TAG = "Tamagotchi:MainGameScreen"; private static final String GRP_BACKGROUND = "background"; private static final String GRP_FOREGROUND = "foreground"; private static final String GRP_OVERLAY = "overlay"; private static final String GRP_BACKGROUND_DISTANT = "background_distant"; private static final String GRP_BACKGROUND_NEAR = "background_near"; private static final String GRP_UI = "ui"; private static final String GRP_TOP_BUTTONS = "top_buttons"; private static final String GRP_STATUS_PANEL = "status_panel"; private static final int FOOD = 0; private static final int TOILET = 1; private static final int SHOWER = 2; private static final int LIGHT = 3; private static final int NUM_BUTTONS = 4; private Button[] buttons; private DraggableImage btnDrag; private Label fpsLabel; private Creature1 creature; /** * Creates a new instance of the MainGameScreen. * * @param game Needs a TamagotchiGame instance. */ public MainGameScreen(TamagotchiGame game) { super(game); } @Override protected final Stage createStage(SpriteBatch batch) { return new Stage(game.config.stageWidth, game.config.stageHeight, false, batch); } @Override public final void show() { super.show(); layout(); } /** * Creates the basic layout of the screen. */ private void layout() { /* * TODO: Add basic status mockup that can be pulled down TODO: Add * creature TODO: Add background TODO: Add layers for background and the * main stage TODO: Add overlays, e.g. for speech bubbles */ /* add groups for better readability and flexibility */ // create main groups final Group backgroundGroup = new Group(GRP_BACKGROUND); final Group foregroundGroup = new Group(GRP_FOREGROUND); final Group overlayGroup = new Group(GRP_OVERLAY); // create sub groups final Group bgDistantGroup = new Group(GRP_BACKGROUND_DISTANT); final Group bgNearGroup = new Group(GRP_BACKGROUND_NEAR); final Group uiGroup = new Group(GRP_UI); final Group topButtonsGroup = new Group(GRP_TOP_BUTTONS); final Group statusPanelGroup = new Group(GRP_STATUS_PANEL); /* load textures */ // load texture atlas final TextureAtlas textureAtlas = game.assets.getAsset(TextureAtlasAsset.MAIN_GAME); // get texture regions from loaded texture atlas final TextureRegion planetsBackgroundTextureRegion = textureAtlas .findRegion("PlanetsBackground"); final TextureRegion hillsMidgroundTextureRegion = textureAtlas.findRegion("HillsMidground"); final TextureRegion hillsForegroundTextureRegion = textureAtlas .findRegion("HillsForeground"); final TextureRegion groundTextureRegion = textureAtlas.findRegion("StaticGround"); final TextureRegion creatureDefaultTextureRegion = textureAtlas.findRegion("PetDefault"); final TextureRegion swipeArrowTextureRegion = textureAtlas.findRegion("LeftSwipeArrow"); /* prepare layout */ // add background Image bgPlanetsBackground = new Image(planetsBackgroundTextureRegion); Image bgHillsMidground = new Image(hillsMidgroundTextureRegion); Image bgHillsForeground = new Image(hillsForegroundTextureRegion); Image bgGround = new Image(groundTextureRegion); // add creature creature = new Creature1(creatureDefaultTextureRegion, "creature"); creature.setClickListener(this); creature.x = 400; creature.y = 50; // create buttons names final String[] interactButtonIDs = new String[] { "MainButtonFood", "MainButtonToilet", "MainButtonShower", "MainButtonSleepOff" }; // load texture regions for buttons in top right corner final TextureRegion[] interactButtonTextureRegions = new TextureRegion[interactButtonIDs.length]; for (int i = 0; i < interactButtonIDs.length; i++) { interactButtonTextureRegions[i] = textureAtlas.findRegion(interactButtonIDs[i]); } // set margin<SUF> final int marginBetweenButtons = 10; // position buttons within group and add them to the 'topButtonsGroup' final int width = interactButtonTextureRegions[0].getRegionWidth() + marginBetweenButtons; buttons = new Button[NUM_BUTTONS]; for (int i = 0; i < NUM_BUTTONS; i++) { final Button button = new Button(interactButtonTextureRegions[i]); button.x = width * i; button.setClickListener(this); topButtonsGroup.addActor(button); buttons[i] = button; } // adjust width of 'topButtons' group topButtonsGroup.width = width * topButtonsGroup.getActors().size(); // position topButtons in top right corner topButtonsGroup.x = stage.right() - topButtonsGroup.width; topButtonsGroup.y = stage.top() - width; // add drag down status panel button btnDrag = new DraggableImage(swipeArrowTextureRegion); btnDrag.setClickListener(this); btnDrag.setDragListener(this); statusPanelGroup.addActor(btnDrag); // add an FPS label (subject to configuration) if (game.config.logFps) { final String FONT_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789][_!$%#@|\\/?-+=()*&.:;,{}\"�`'<>"; BitmapFont font = TrueTypeFontFactory.createBitmapFont( Gdx.files.internal("fonts/Roboto-Regular.ttf"), FONT_CHARACTERS, stage.width(), stage.height(), 25.0f, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); final Label.LabelStyle labelStyle = new Label.LabelStyle( font, Color.RED); fpsLabel = new Label("FPS: " + Gdx.graphics.getFramesPerSecond(), labelStyle); fpsLabel.y = -15; } /* Prepare sub groups */ // add sub groups to the 'ui' group uiGroup.addActor(statusPanelGroup); uiGroup.addActor(topButtonsGroup); // sub groups to the 'background' group bgDistantGroup.addActor(bgPlanetsBackground); bgDistantGroup.addActor(bgHillsMidground); bgDistantGroup.addActor(bgHillsForeground); bgNearGroup.y = -50; bgDistantGroup.y = bgNearGroup.y + bgGround.height; bgNearGroup.addActor(bgGround); /* Prepare main groups */ // add groups to 'background' backgroundGroup.addActor(bgDistantGroup); backgroundGroup.addActor(bgNearGroup); // add groups to 'foreground' // add creature to main group foregroundGroup.addActor(creature); // add groups to 'overlay' overlayGroup.addActor(uiGroup); // add an FPS label (subject to configuration) if (game.config.logFps) { final BitmapFont font = FontHelper.createBitmapFont(FontHelper.TTF_ROBOTO_REGULAR, 25f, stage); final Label.LabelStyle labelStyle = new Label.LabelStyle( font, Color.RED); fpsLabel = new Label("FPS: " + Gdx.graphics.getFramesPerSecond(), labelStyle); fpsLabel.y = -15; overlayGroup.addActor(fpsLabel); } /* Add main groups to stage */ stage.addActor(backgroundGroup); stage.addActor(foregroundGroup); stage.addActor(overlayGroup); } @Override public void update(float delta) { creature.lifeCycle(); if (fpsLabel != null) { assert game.config.logFps; fpsLabel.setText("FPS: " + Gdx.graphics.getFramesPerSecond()); } super.update(delta); } @Override public final void click(Actor actor, float x, float y) { // touch input was received, time to find the culprit if (actor == buttons[FOOD]) { Gdx.app.debug(TAG, "Touch on food button"); creature.moveBy(-100f, 1f); } else if (actor == buttons[TOILET]) { Gdx.app.debug(TAG, "Touch on toilet button"); creature.moveBy(100f, 1f); } else if (actor == buttons[SHOWER]) { Gdx.app.debug(TAG, "Touch on shower button"); creature.roll(-200, 1f); } else if (actor == buttons[LIGHT]) { Gdx.app.debug(TAG, "Touch on light button"); creature.roll(200, 1f); } else if (actor == creature) { creature.jump(); } else if (actor == btnDrag) { Gdx.app.debug(TAG, "Touch on arrow"); // do nothing, handle in drag() } else { Gdx.app.error(TAG, "Unknown actor"); assert false; } } @Override public void drag(Actor a, float x, float y, int pointer) { if (a == btnDrag) { /* * TODO: detect precise touch point and use it when moving the group * Currently, it snaps to the bottom line of the texture when * dragging starts. In order to make it look better, we need to * apply an offset for the correct touch point. */ stage.findActor(GRP_STATUS_PANEL).x += x; } } @Override public void loadResources() { game.assets.loadAsset(TextureAtlasAsset.MAIN_GAME); } @Override public void unloadResources() { game.assets.unloadAsset(TextureAtlasAsset.MAIN_GAME); } }
201092_24
package at.favre.lib.armadillo; import android.content.SharedPreferences; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.security.SecureRandom; import java.util.HashSet; import java.util.Random; import java.util.Set; import at.favre.lib.bytes.Bytes; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assume.assumeFalse; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @SuppressWarnings("deprecation") public abstract class ASecureSharedPreferencesTest { private static final String DEFAULT_PREF_NAME = "test-prefs"; SharedPreferences preferences; @Before public void setup() { try { preferences = create(DEFAULT_PREF_NAME, null).build(); } catch (Exception e) { e.printStackTrace(); throw e; } } @After public void tearDown() { preferences.edit().clear().commit(); } protected abstract Armadillo.Builder create(String name, char[] pw); protected abstract boolean isKitKatOrBelow(); @Test public void simpleMultipleStringGet() { SharedPreferences preferences = create("manytest", null).build(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 100; j++) { String content = "testäI/_²~" + Bytes.random(64 + j).encodeHex(); preferences.edit().putString("k" + j, content).commit(); assertEquals(content, preferences.getString("k" + j, null)); } } } @Test public void simpleGetString() { putAndTestString(preferences, "string1", 1); putAndTestString(preferences, "string2", 16); putAndTestString(preferences, "string3", 200); } @Test public void simpleGetStringApply() { String content = Bytes.random(16).encodeBase64(); preferences.edit().putString("d", content).apply(); assertEquals(content, preferences.getString("d", null)); } private String putAndTestString(SharedPreferences preferences, String key, int length) { String content = Bytes.random(length).encodeBase64(); preferences.edit().putString(key, content).commit(); assertTrue(preferences.contains(key)); assertEquals(content, preferences.getString(key, null)); return content; } @Test public void simpleGetInt() { int content = 3782633; preferences.edit().putInt("int", content).commit(); assertTrue(preferences.contains("int")); assertEquals(content, preferences.getInt("int", 0)); } @Test public void simpleGetLong() { long content = 3782633654323456L; preferences.edit().putLong("long", content).commit(); assertTrue(preferences.contains("long")); assertEquals(content, preferences.getLong("long", 0)); } @Test public void simpleGetFloat() { float content = 728.1891f; preferences.edit().putFloat("float", content).commit(); assertTrue(preferences.contains("float")); assertEquals(content, preferences.getFloat("float", 0), 0.001); } @Test public void simpleGetBoolean() { preferences.edit().putBoolean("boolean", true).commit(); assertTrue(preferences.contains("boolean")); assertTrue(preferences.getBoolean("boolean", false)); preferences.edit().putBoolean("boolean2", false).commit(); assertFalse(preferences.getBoolean("boolean2", true)); } @Test public void simpleGetStringSet() { addStringSet(preferences, 1); addStringSet(preferences, 7); addStringSet(preferences, 128); } private void addStringSet(SharedPreferences preferences, int count) { Set<String> set = new HashSet<>(count); for (int i = 0; i < count; i++) { set.add(Bytes.random(32).encodeBase36() + "input" + i); } preferences.edit().putStringSet("stringSet" + count, set).commit(); assertTrue(preferences.contains("stringSet" + count)); assertEquals(set, preferences.getStringSet("stringSet" + count, null)); } @Test public void testGetDefaults() { assertNull(preferences.getString("s", null)); assertNull(preferences.getStringSet("s", null)); assertFalse(preferences.getBoolean("s", false)); assertEquals(2, preferences.getInt("s", 2)); assertEquals(2, preferences.getLong("s", 2)); assertEquals(2f, preferences.getFloat("s", 2f), 0.0001); } @Test public void testRemove() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertTrue(preferences.getAll().size() >= count); for (int i = 0; i < count; i++) { preferences.edit().remove("string" + i).commit(); assertNull(preferences.getString("string" + i, null)); } } @Test public void testPutNullString() { String id = "testPutNullString"; putAndTestString(preferences, id, new Random().nextInt(32) + 1); preferences.edit().putString(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testPutNullStringSet() { String id = "testPutNullStringSet"; addStringSet(preferences, 8); preferences.edit().putStringSet(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testClear() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertFalse(preferences.getAll().isEmpty()); preferences.edit().clear().commit(); assertTrue(preferences.getAll().isEmpty()); String newContent = putAndTestString(preferences, "new", new Random().nextInt(32) + 1); assertFalse(preferences.getAll().isEmpty()); preferences = create(DEFAULT_PREF_NAME, null).build(); assertEquals(newContent, preferences.getString("new", null)); } @Test public void testInitializeTwice() { SharedPreferences sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s2", 24); } @Test public void testContainsAfterReinitialization() { SharedPreferences sharedPreferences = create("twice", null).build(); String t = putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("twice", null).build(); assertEquals(t, sharedPreferences.getString("s", null)); putAndTestString(sharedPreferences, "s2", 24); } @Test public void simpleStringGetWithPkdf2Password() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new PBKDF2KeyStretcher(1000, null)).build()); } @Test public void simpleStringGetWithBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(7)).build()); } @Test public void simpleStringGetWithBrokenBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(6)).build()); } @Test public void simpleStringGetWithUnicodePw() { preferenceSmokeTest(create("withPw", "ö案äü_ß²áèµÿA2ijʥ".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void simpleStringGetWithFastKDF() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void testWithCompression() { preferenceSmokeTest(create("compressed", null).compress().build()); } @Test public void testWithDifferentFingerprint() { preferenceSmokeTest(create("fingerprint", null) .encryptionFingerprint(Bytes.random(16).array()).build()); preferenceSmokeTest(create("fingerprint2", null) .encryptionFingerprint(new TestEncryptionFingerprint(new byte[16])).build()); } @Test public void testWithDifferentContentDigest() { preferenceSmokeTest(create("contentDigest1", null) .contentKeyDigest(8).build()); preferenceSmokeTest(create("contentDigest2", null) .contentKeyDigest(Bytes.random(16).array()).build()); preferenceSmokeTest(create("contentDigest3", null) .contentKeyDigest((providedMessage, usageName) -> Bytes.from(providedMessage).append(usageName).encodeUtf8()).build()); } @Test public void testWithSecureRandom() { preferenceSmokeTest(create("secureRandom", null) .secureRandom(new SecureRandom()).build()); } @Test public void testEncryptionStrength() { preferenceSmokeTest(create("secureRandom", null) .encryptionKeyStrength(AuthenticatedEncryption.STRENGTH_HIGH).build()); } @Test public void testProvider() { preferenceSmokeTest(create("provider", null) .securityProvider(null).build()); } @Test public void testWithNoObfuscation() { preferenceSmokeTest(create("obfuscate", null) .dataObfuscatorFactory(new NoObfuscator.Factory()).build()); } @Test public void testSetEncryption() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); preferenceSmokeTest(create("enc", null) .symmetricEncryption(new AesGcmEncryption()).build()); } @Test public void testRecoveryPolicy() { preferenceSmokeTest(create("recovery", null) .recoveryPolicy(true, true).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy(new SimpleRecoveryPolicy.Default(true, true)).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy((e, keyHash, base64Encrypted, pwUsed, sharedPreferences) -> System.out.println(e + " " + keyHash + " " + base64Encrypted + " " + pwUsed)).build()); } @Test public void testCustomProtocolVersion() { preferenceSmokeTest(create("protocol", null) .cryptoProtocolVersion(14221).build()); } void preferenceSmokeTest(SharedPreferences preferences) { putAndTestString(preferences, "string", new Random().nextInt(500) + 1); assertNull(preferences.getString("string2", null)); long contentLong = new Random().nextLong(); preferences.edit().putLong("long", contentLong).commit(); assertEquals(contentLong, preferences.getLong("long", 0)); float contentFloat = new Random().nextFloat(); preferences.edit().putFloat("float", contentFloat).commit(); assertEquals(contentFloat, preferences.getFloat("float", 0), 0.001); boolean contentBoolean = new Random().nextBoolean(); preferences.edit().putBoolean("boolean", contentBoolean).commit(); assertEquals(contentBoolean, preferences.getBoolean("boolean", !contentBoolean)); addStringSet(preferences, new Random().nextInt(31) + 1); preferences.edit().remove("string").commit(); assertNull(preferences.getString("string", null)); preferences.edit().remove("float").commit(); assertEquals(-1, preferences.getFloat("float", -1), 0.00001); } @Test public void testChangePassword() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordWithEnabledDerivedPwCache() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), true); } @Test public void testChangePasswordFromNullPassword() { testChangePassword("testChangePasswordFromNullPassword", null, "pw2".toCharArray(), false); } @Test public void testChangePasswordToNullPassword() { testChangePassword("testChangePasswordToNullPassword", "pw1".toCharArray(), null, false); } @Test public void testChangePasswordFromEmptyPassword() { testChangePassword("testChangePasswordFromEmptyPassword", "".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordToEmptyPassword() { testChangePassword("testChangePasswordToEmptyPassword", "pw1".toCharArray(), "".toCharArray(), false); } private void testChangePassword(String name, char[] currentPassword, char[] newPassword, boolean enableCache) { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and change to new one, all the values should be accessible pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.changePassword(clonePassword(newPassword)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw, should be accessible pref = create(name, clonePassword(newPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw, should throw exception, since cannot decrypt pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } private char[] clonePassword(char[] password) { return password == null ? null : password.clone(); } @Test public void testChangePasswordAndKeyStretchingFunction() { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and old ksFn; change to new one, all the values should be accessible pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.changePassword("pw2".toCharArray(), new ArmadilloBcryptKeyStretcher(8)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and new ksFn, should be accessible pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } // open with old pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testInvalidPasswordShouldNotBeAccessible() { // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with invalid pw, should throw exception, since cannot decrypt pref = create("testInvalidPassword", "pw2".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getInt("k2", 0); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getBoolean("k3", false); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testUpgradeToNewerProtocolVersion() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); // open new preference with old encryption config ArmadilloSharedPreferences pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // add some data pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again with encryption config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); // overwrite old data pref.edit().putInt("k2", 2).commit(); // add some data pref.edit().putString("j1", "string2").putInt("j2", 3).putBoolean("j3", false).commit(); pref.close(); // open again with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals("string2", pref.getString("j1", null)); assertEquals(3, pref.getInt("j2", 0)); assertFalse(pref.getBoolean("j3", true)); pref.close(); // open again with new config WITHOUT old config as support config (removing in the builder) pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .clearAdditionalDecryptionProtocolConfigs() // test remove support protocols in builder .build(); // check overwritten data assertEquals(2, pref.getInt("k2", 0)); try { pref.getString("k1", null); fail("should throw exception, since should not be able to decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testSameKeyDifferentTypeShouldOverwrite() { //this is a similar behavior to normal shared preferences SharedPreferences pref = create("testSameKeyDifferentTypeShouldOverwrite", null).build(); pref.edit().putInt("id", 1).commit(); pref.edit().putString("id", "testNotInt").commit(); TestCase.assertEquals("testNotInt", pref.getString("id", null)); try { pref.getInt("id", -1); TestCase.fail("string should be overwritten with int"); } catch (Exception ignored) { } } }
patrickfav/armadillo
armadillo/src/sharedTest/java/at/favre/lib/armadillo/ASecureSharedPreferencesTest.java
6,160
// check overwritten data
line_comment
nl
package at.favre.lib.armadillo; import android.content.SharedPreferences; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.security.SecureRandom; import java.util.HashSet; import java.util.Random; import java.util.Set; import at.favre.lib.bytes.Bytes; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assume.assumeFalse; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @SuppressWarnings("deprecation") public abstract class ASecureSharedPreferencesTest { private static final String DEFAULT_PREF_NAME = "test-prefs"; SharedPreferences preferences; @Before public void setup() { try { preferences = create(DEFAULT_PREF_NAME, null).build(); } catch (Exception e) { e.printStackTrace(); throw e; } } @After public void tearDown() { preferences.edit().clear().commit(); } protected abstract Armadillo.Builder create(String name, char[] pw); protected abstract boolean isKitKatOrBelow(); @Test public void simpleMultipleStringGet() { SharedPreferences preferences = create("manytest", null).build(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 100; j++) { String content = "testäI/_²~" + Bytes.random(64 + j).encodeHex(); preferences.edit().putString("k" + j, content).commit(); assertEquals(content, preferences.getString("k" + j, null)); } } } @Test public void simpleGetString() { putAndTestString(preferences, "string1", 1); putAndTestString(preferences, "string2", 16); putAndTestString(preferences, "string3", 200); } @Test public void simpleGetStringApply() { String content = Bytes.random(16).encodeBase64(); preferences.edit().putString("d", content).apply(); assertEquals(content, preferences.getString("d", null)); } private String putAndTestString(SharedPreferences preferences, String key, int length) { String content = Bytes.random(length).encodeBase64(); preferences.edit().putString(key, content).commit(); assertTrue(preferences.contains(key)); assertEquals(content, preferences.getString(key, null)); return content; } @Test public void simpleGetInt() { int content = 3782633; preferences.edit().putInt("int", content).commit(); assertTrue(preferences.contains("int")); assertEquals(content, preferences.getInt("int", 0)); } @Test public void simpleGetLong() { long content = 3782633654323456L; preferences.edit().putLong("long", content).commit(); assertTrue(preferences.contains("long")); assertEquals(content, preferences.getLong("long", 0)); } @Test public void simpleGetFloat() { float content = 728.1891f; preferences.edit().putFloat("float", content).commit(); assertTrue(preferences.contains("float")); assertEquals(content, preferences.getFloat("float", 0), 0.001); } @Test public void simpleGetBoolean() { preferences.edit().putBoolean("boolean", true).commit(); assertTrue(preferences.contains("boolean")); assertTrue(preferences.getBoolean("boolean", false)); preferences.edit().putBoolean("boolean2", false).commit(); assertFalse(preferences.getBoolean("boolean2", true)); } @Test public void simpleGetStringSet() { addStringSet(preferences, 1); addStringSet(preferences, 7); addStringSet(preferences, 128); } private void addStringSet(SharedPreferences preferences, int count) { Set<String> set = new HashSet<>(count); for (int i = 0; i < count; i++) { set.add(Bytes.random(32).encodeBase36() + "input" + i); } preferences.edit().putStringSet("stringSet" + count, set).commit(); assertTrue(preferences.contains("stringSet" + count)); assertEquals(set, preferences.getStringSet("stringSet" + count, null)); } @Test public void testGetDefaults() { assertNull(preferences.getString("s", null)); assertNull(preferences.getStringSet("s", null)); assertFalse(preferences.getBoolean("s", false)); assertEquals(2, preferences.getInt("s", 2)); assertEquals(2, preferences.getLong("s", 2)); assertEquals(2f, preferences.getFloat("s", 2f), 0.0001); } @Test public void testRemove() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertTrue(preferences.getAll().size() >= count); for (int i = 0; i < count; i++) { preferences.edit().remove("string" + i).commit(); assertNull(preferences.getString("string" + i, null)); } } @Test public void testPutNullString() { String id = "testPutNullString"; putAndTestString(preferences, id, new Random().nextInt(32) + 1); preferences.edit().putString(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testPutNullStringSet() { String id = "testPutNullStringSet"; addStringSet(preferences, 8); preferences.edit().putStringSet(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testClear() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertFalse(preferences.getAll().isEmpty()); preferences.edit().clear().commit(); assertTrue(preferences.getAll().isEmpty()); String newContent = putAndTestString(preferences, "new", new Random().nextInt(32) + 1); assertFalse(preferences.getAll().isEmpty()); preferences = create(DEFAULT_PREF_NAME, null).build(); assertEquals(newContent, preferences.getString("new", null)); } @Test public void testInitializeTwice() { SharedPreferences sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s2", 24); } @Test public void testContainsAfterReinitialization() { SharedPreferences sharedPreferences = create("twice", null).build(); String t = putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("twice", null).build(); assertEquals(t, sharedPreferences.getString("s", null)); putAndTestString(sharedPreferences, "s2", 24); } @Test public void simpleStringGetWithPkdf2Password() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new PBKDF2KeyStretcher(1000, null)).build()); } @Test public void simpleStringGetWithBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(7)).build()); } @Test public void simpleStringGetWithBrokenBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(6)).build()); } @Test public void simpleStringGetWithUnicodePw() { preferenceSmokeTest(create("withPw", "ö案äü_ß²áèµÿA2ijʥ".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void simpleStringGetWithFastKDF() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void testWithCompression() { preferenceSmokeTest(create("compressed", null).compress().build()); } @Test public void testWithDifferentFingerprint() { preferenceSmokeTest(create("fingerprint", null) .encryptionFingerprint(Bytes.random(16).array()).build()); preferenceSmokeTest(create("fingerprint2", null) .encryptionFingerprint(new TestEncryptionFingerprint(new byte[16])).build()); } @Test public void testWithDifferentContentDigest() { preferenceSmokeTest(create("contentDigest1", null) .contentKeyDigest(8).build()); preferenceSmokeTest(create("contentDigest2", null) .contentKeyDigest(Bytes.random(16).array()).build()); preferenceSmokeTest(create("contentDigest3", null) .contentKeyDigest((providedMessage, usageName) -> Bytes.from(providedMessage).append(usageName).encodeUtf8()).build()); } @Test public void testWithSecureRandom() { preferenceSmokeTest(create("secureRandom", null) .secureRandom(new SecureRandom()).build()); } @Test public void testEncryptionStrength() { preferenceSmokeTest(create("secureRandom", null) .encryptionKeyStrength(AuthenticatedEncryption.STRENGTH_HIGH).build()); } @Test public void testProvider() { preferenceSmokeTest(create("provider", null) .securityProvider(null).build()); } @Test public void testWithNoObfuscation() { preferenceSmokeTest(create("obfuscate", null) .dataObfuscatorFactory(new NoObfuscator.Factory()).build()); } @Test public void testSetEncryption() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); preferenceSmokeTest(create("enc", null) .symmetricEncryption(new AesGcmEncryption()).build()); } @Test public void testRecoveryPolicy() { preferenceSmokeTest(create("recovery", null) .recoveryPolicy(true, true).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy(new SimpleRecoveryPolicy.Default(true, true)).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy((e, keyHash, base64Encrypted, pwUsed, sharedPreferences) -> System.out.println(e + " " + keyHash + " " + base64Encrypted + " " + pwUsed)).build()); } @Test public void testCustomProtocolVersion() { preferenceSmokeTest(create("protocol", null) .cryptoProtocolVersion(14221).build()); } void preferenceSmokeTest(SharedPreferences preferences) { putAndTestString(preferences, "string", new Random().nextInt(500) + 1); assertNull(preferences.getString("string2", null)); long contentLong = new Random().nextLong(); preferences.edit().putLong("long", contentLong).commit(); assertEquals(contentLong, preferences.getLong("long", 0)); float contentFloat = new Random().nextFloat(); preferences.edit().putFloat("float", contentFloat).commit(); assertEquals(contentFloat, preferences.getFloat("float", 0), 0.001); boolean contentBoolean = new Random().nextBoolean(); preferences.edit().putBoolean("boolean", contentBoolean).commit(); assertEquals(contentBoolean, preferences.getBoolean("boolean", !contentBoolean)); addStringSet(preferences, new Random().nextInt(31) + 1); preferences.edit().remove("string").commit(); assertNull(preferences.getString("string", null)); preferences.edit().remove("float").commit(); assertEquals(-1, preferences.getFloat("float", -1), 0.00001); } @Test public void testChangePassword() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordWithEnabledDerivedPwCache() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), true); } @Test public void testChangePasswordFromNullPassword() { testChangePassword("testChangePasswordFromNullPassword", null, "pw2".toCharArray(), false); } @Test public void testChangePasswordToNullPassword() { testChangePassword("testChangePasswordToNullPassword", "pw1".toCharArray(), null, false); } @Test public void testChangePasswordFromEmptyPassword() { testChangePassword("testChangePasswordFromEmptyPassword", "".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordToEmptyPassword() { testChangePassword("testChangePasswordToEmptyPassword", "pw1".toCharArray(), "".toCharArray(), false); } private void testChangePassword(String name, char[] currentPassword, char[] newPassword, boolean enableCache) { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and change to new one, all the values should be accessible pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.changePassword(clonePassword(newPassword)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw, should be accessible pref = create(name, clonePassword(newPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw, should throw exception, since cannot decrypt pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } private char[] clonePassword(char[] password) { return password == null ? null : password.clone(); } @Test public void testChangePasswordAndKeyStretchingFunction() { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and old ksFn; change to new one, all the values should be accessible pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.changePassword("pw2".toCharArray(), new ArmadilloBcryptKeyStretcher(8)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and new ksFn, should be accessible pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } // open with old pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testInvalidPasswordShouldNotBeAccessible() { // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with invalid pw, should throw exception, since cannot decrypt pref = create("testInvalidPassword", "pw2".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getInt("k2", 0); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getBoolean("k3", false); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testUpgradeToNewerProtocolVersion() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); // open new preference with old encryption config ArmadilloSharedPreferences pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // add some data pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again with encryption config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); // overwrite old data pref.edit().putInt("k2", 2).commit(); // add some data pref.edit().putString("j1", "string2").putInt("j2", 3).putBoolean("j3", false).commit(); pref.close(); // open again with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals("string2", pref.getString("j1", null)); assertEquals(3, pref.getInt("j2", 0)); assertFalse(pref.getBoolean("j3", true)); pref.close(); // open again with new config WITHOUT old config as support config (removing in the builder) pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .clearAdditionalDecryptionProtocolConfigs() // test remove support protocols in builder .build(); // check overwritten<SUF> assertEquals(2, pref.getInt("k2", 0)); try { pref.getString("k1", null); fail("should throw exception, since should not be able to decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testSameKeyDifferentTypeShouldOverwrite() { //this is a similar behavior to normal shared preferences SharedPreferences pref = create("testSameKeyDifferentTypeShouldOverwrite", null).build(); pref.edit().putInt("id", 1).commit(); pref.edit().putString("id", "testNotInt").commit(); TestCase.assertEquals("testNotInt", pref.getString("id", null)); try { pref.getInt("id", -1); TestCase.fail("string should be overwritten with int"); } catch (Exception ignored) { } } }
179559_1
package fr.imie.servlet; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import fr.imie.formation.DTO.CompetenceDTO; import fr.imie.formation.DTO.NiveauDTO; import fr.imie.formation.DTO.ProjetDTO; import fr.imie.formation.DTO.PromotionDTO; import fr.imie.formation.DTO.UtilisateurDTO; import fr.imie.formation.factory.DAOFactory1; import fr.imie.formation.services.exceptions.ServiceException; import fr.imie.formation.transactionalFramework.exception.TransactionalConnectionException; /** * Servlet implementation class UserServlet */ @WebServlet("/UserForm") public class UserForm extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UserForm() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Affichage utilisateur if (request.getParameter("numligneutil") != null && request.getParameter("update") == null && request.getParameter("delete") == null) { int ligne = Integer.valueOf(request.getParameter("numligneutil")); Object listObj = session.getAttribute("listeUtilisateur"); Object listObj1 = session.getAttribute("ListeNivUtil"); Object listObj2 =session.getAttribute("listeUtil"); UtilisateurDTO utilisateur = null; if (listObj1 != null) { List<NiveauDTO> listNiveau = (List<NiveauDTO>) listObj1; utilisateur = listNiveau.get(ligne).getUtilisateur(); session.removeAttribute("ListeNivUtil"); } else if (listObj2 != null) { List<UtilisateurDTO> listUtil = (List<UtilisateurDTO>) listObj2; utilisateur = listUtil.get(ligne); session.removeAttribute("listeUtil"); } else { List<UtilisateurDTO> listUtilisateur = (List<UtilisateurDTO>) listObj; utilisateur = listUtilisateur.get(ligne); session.removeAttribute("listeUtilisateur"); } try { UtilisateurDTO utilisateurDTO = DAOFactory1.getInstance() .createUtilisateurService(null) .readUtilisateur(utilisateur); request.setAttribute("utilisateur", utilisateurDTO); List<NiveauDTO> listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(utilisateurDTO); request.setAttribute("ListeCompNiv", listCompNiv); List<ProjetDTO> listUtilProjet = DAOFactory1.getInstance() .createProjetService(null) .readProjetByUtilisateur(utilisateurDTO); request.setAttribute("ListeUtilProjet", listUtilProjet); List<ProjetDTO >listeProjetForInvit = DAOFactory1.getInstance().createProjetService(null).readAllProjets(); //request.setAttribute("listeProjetForInvit", listeProjetForInvit); request.setAttribute("listeProjetForInvit", listeProjetForInvit); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.getRequestDispatcher("./UserRead.jsp").forward(request, response); } // création utilisateur else if (request.getParameter("create") != null && request.getParameter("create").equals("creer")) { List<PromotionDTO> listPromo = null; List<NiveauDTO> listNiveau =null; List<CompetenceDTO> listComp = null; try { listPromo = DAOFactory1.getInstance() .createPromotionService(null).readAllPromotion(); listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence(); listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau(); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("ListePromo", listPromo); request.setAttribute("ListeComp", listComp); request.setAttribute("ListeNiveau", listNiveau); request.getRequestDispatcher("./UserCreate.jsp").forward(request, response); } // modification utilisateur else if (request.getParameter("update") != null && request.getParameter("update").equals("modifier")) { request.setAttribute("utilisateur", getUser(request.getParameter("numUtilisateur"))); List<ProjetDTO> listUtilProjet = null; List<PromotionDTO> listPromo = null; List<NiveauDTO> listCompNiv = null; List<NiveauDTO> listNiveau =null; List<CompetenceDTO> listComp = null; try { listUtilProjet = DAOFactory1 .getInstance() .createProjetService(null) .readProjetByUtilisateur( getUser(request.getParameter("numUtilisateur"))); listPromo = DAOFactory1.getInstance() .createPromotionService(null).readAllPromotion(); listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtilisateur"))); listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence(); listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau(); } catch (TransactionalConnectionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } request.setAttribute("ListeCompNiv", listCompNiv); request.setAttribute("ListeUtilProjet", listUtilProjet); request.setAttribute("ListePromo", listPromo); request.setAttribute("ListeComp", listComp); request.setAttribute("ListeNiveau", listNiveau); request.getRequestDispatcher("./UserUpdate.jsp").forward(request, response); } // suppression utilisateur else if (request.getParameter("delete") != null & request.getParameter("delete").equals("supprimer")) { request.setAttribute("utilisateur", getUser(request.getParameter("numUtilisateur"))); request.getRequestDispatcher("./UserDelete.jsp").forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Modifier un utilisateur if (request.getParameter("updateAction") != null && request.getParameter("updateAction").equals("Confirmer")) { UtilisateurDTO utilisateurUpdate = getUser(request .getParameter("numUtilisateur")); utilisateurUpdate.setNom(request.getParameter("nom")); utilisateurUpdate.setPrenom(request.getParameter("prenom")); String userDateNaisParam = request.getParameter("dateNaissance"); Date userDateNais = new Date(); try { userDateNais = new SimpleDateFormat("dd/MM/yyyy") .parse(userDateNaisParam); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } utilisateurUpdate.setDateNaissance(userDateNais); utilisateurUpdate.setAdresse(request.getParameter("adresse")); utilisateurUpdate.setTel(request.getParameter("tel")); utilisateurUpdate.setMail(request.getParameter("mail")); String promoParam = request.getParameter("promotion"); PromotionDTO promo = new PromotionDTO(); Integer promoNum = null; if (promoParam != null) { promoNum = Integer.valueOf(promoParam); } if (promoNum != null) { PromotionDTO promoUpdate = new PromotionDTO(); promoUpdate.setNum(promoNum); try { promo = DAOFactory1.getInstance() .createPromotionService(null) .readPromotion(promoUpdate); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } } utilisateurUpdate.setPromotion(promo); utilisateurUpdate.setLogin(request.getParameter("login")); utilisateurUpdate.setPassword(request.getParameter("password")); try { DAOFactory1.getInstance().createUtilisateurService(null) .updateUtilisateur(utilisateurUpdate); List<NiveauDTO> listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(utilisateurUpdate); List<ProjetDTO> listUtilProjet = DAOFactory1.getInstance() .createProjetService(null) .readProjetByUtilisateur(utilisateurUpdate); request.setAttribute("ListeCompNiv", listCompNiv); request.setAttribute("ListeUtilProjet", listUtilProjet); //request.setAttribute("action", "updateAction"); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("utilisateur", utilisateurUpdate); request.getRequestDispatcher("./UserRead.jsp").forward(request, response); } //Ajout des compétences d'un utilisateur else if (request.getParameter("updateAction") != null && request.getParameter("updateAction").equals("Enregistrer")){ UtilisateurDTO util = getUser(request.getParameter("numUtil")); NiveauDTO niveau = getNiveau(request.getParameter("niveau")); CompetenceDTO comp = getComp(request.getParameter("comp")); List<ProjetDTO> listUtilProjet = null; List<PromotionDTO> listPromo = null; List<NiveauDTO> listCompNiv = null; List<NiveauDTO> listNiveau =null; List<CompetenceDTO> listComp = null; try { DAOFactory1.getInstance().createCompetenceNiveauService(null).addCompUtil(util, comp, niveau); listUtilProjet = DAOFactory1 .getInstance() .createProjetService(null) .readProjetByUtilisateur( getUser(request.getParameter("numUtil"))); listPromo = DAOFactory1.getInstance() .createPromotionService(null).readAllPromotion(); listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtil"))); listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence(); listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau(); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("ListeCompNiv", listCompNiv); request.setAttribute("ListeUtilProjet", listUtilProjet); request.setAttribute("ListePromo", listPromo); request.setAttribute("ListeComp", listComp); request.setAttribute("ListeNiveau", listNiveau); request.setAttribute("utilisateur", getUser(request.getParameter("numUtil"))); request.getRequestDispatcher("./UserUpdate.jsp").forward(request, response); } //Modification des compétences d'un utilisateur else if (request.getParameter("updateAction") != null && request.getParameter("updateAction").equals("Ok")){ UtilisateurDTO util = getUser(request.getParameter("numUtil")); NiveauDTO niveau = getNiveau(request.getParameter("niveau")); CompetenceDTO comp = getComp(request.getParameter("comp")); List<ProjetDTO> listUtilProjet = null; List<PromotionDTO> listPromo = null; List<NiveauDTO> listCompNiv = null; List<NiveauDTO> listNiveau =null; List<CompetenceDTO> listComp = null; try { DAOFactory1.getInstance().createCompetenceNiveauService(null).updateCompUtil(util, comp, niveau); listUtilProjet = DAOFactory1 .getInstance() .createProjetService(null) .readProjetByUtilisateur( getUser(request.getParameter("numUtil"))); listPromo = DAOFactory1.getInstance() .createPromotionService(null).readAllPromotion(); listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtil"))); listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence(); listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau(); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("ListeCompNiv", listCompNiv); request.setAttribute("ListeUtilProjet", listUtilProjet); request.setAttribute("ListePromo", listPromo); request.setAttribute("ListeComp", listComp); request.setAttribute("ListeNiveau", listNiveau); request.setAttribute("utilisateur", getUser(request.getParameter("numUtil"))); request.getRequestDispatcher("./UserUpdate.jsp").forward(request, response); } // Ajouter un utilisateur else if (request.getParameter("createAction") != null && request.getParameter("createAction").equals("ajouter")) { UtilisateurDTO utilisateurCreate = new UtilisateurDTO(); utilisateurCreate.setNom(request.getParameter("nom")); utilisateurCreate.setPrenom(request.getParameter("prenom")); String userDateNaisParam = request.getParameter("dateNaissance"); Date userDateNais = new Date(); try { userDateNais = new SimpleDateFormat("dd/MM/yyyy") .parse(userDateNaisParam); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } utilisateurCreate.setDateNaissance(userDateNais); utilisateurCreate.setAdresse(request.getParameter("adresse")); utilisateurCreate.setTel(request.getParameter("tel")); utilisateurCreate.setMail(request.getParameter("mail")); String promoParam = request.getParameter("promotion"); PromotionDTO promo = new PromotionDTO(); Integer promoNum = null; if (promoParam != null) { promoNum = Integer.valueOf(promoParam); } if (promoNum != null) { PromotionDTO promoUpdate = new PromotionDTO(); promoUpdate.setNum(promoNum); try { promo = DAOFactory1.getInstance() .createPromotionService(null) .readPromotion(promoUpdate); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } } utilisateurCreate.setPromotion(promo); utilisateurCreate.setLogin(request.getParameter("login")); utilisateurCreate.setPassword(request.getParameter("password")); try { DAOFactory1.getInstance().createUtilisateurService(null) .createUtilisateur(utilisateurCreate); request.setAttribute("action", "createAction"); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("utilisateur", utilisateurCreate); request.getRequestDispatcher("./UserRead.jsp").forward(request, response); } // Supprimer un utilisateur else if (request.getParameter("deleteAction") != null && request.getParameter("deleteAction").equals("supprimer")) { UtilisateurDTO utilisateurDelete = getUser(request .getParameter("numUtilisateur")); try { DAOFactory1.getInstance().createUtilisateurService(null) .deleteUtilisateur(utilisateurDelete); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.sendRedirect("./ListUserView"); } } private UtilisateurDTO getUser(String requestNumUtilisateur) { UtilisateurDTO utilisateurDTO = new UtilisateurDTO(); int numUtilisateur = Integer.valueOf(requestNumUtilisateur); UtilisateurDTO utilisateurTemp = new UtilisateurDTO(); utilisateurTemp.setNum(numUtilisateur); try { utilisateurDTO = DAOFactory1.getInstance() .createUtilisateurService(null) .readUtilisateur(utilisateurTemp); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return utilisateurDTO; } private CompetenceDTO getComp(String requestNumComp) { CompetenceDTO compDTO = new CompetenceDTO(); int numComp = Integer.valueOf(requestNumComp); CompetenceDTO compTemp = new CompetenceDTO(); compTemp.setNum(numComp); try { compDTO = DAOFactory1.getInstance() .createCompetenceNiveauService(null).readCompetence(compTemp); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return compDTO; } private NiveauDTO getNiveau(String requestNumNiveau) { NiveauDTO niveauDTO = new NiveauDTO(); int numComp = Integer.valueOf(requestNumNiveau); NiveauDTO niveauTemp = new NiveauDTO(); niveauTemp.setNum(numComp); try { niveauDTO = DAOFactory1.getInstance() .createCompetenceNiveauService(null).readNiveau(niveauTemp); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return niveauDTO; } }
old-sources/DLCDI08-ICompetence-G3
Servlets/src/fr/imie/servlet/UserForm.java
4,571
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
package fr.imie.servlet; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import fr.imie.formation.DTO.CompetenceDTO; import fr.imie.formation.DTO.NiveauDTO; import fr.imie.formation.DTO.ProjetDTO; import fr.imie.formation.DTO.PromotionDTO; import fr.imie.formation.DTO.UtilisateurDTO; import fr.imie.formation.factory.DAOFactory1; import fr.imie.formation.services.exceptions.ServiceException; import fr.imie.formation.transactionalFramework.exception.TransactionalConnectionException; /** * Servlet implementation class UserServlet */ @WebServlet("/UserForm") public class UserForm extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() <SUF>*/ public UserForm() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Affichage utilisateur if (request.getParameter("numligneutil") != null && request.getParameter("update") == null && request.getParameter("delete") == null) { int ligne = Integer.valueOf(request.getParameter("numligneutil")); Object listObj = session.getAttribute("listeUtilisateur"); Object listObj1 = session.getAttribute("ListeNivUtil"); Object listObj2 =session.getAttribute("listeUtil"); UtilisateurDTO utilisateur = null; if (listObj1 != null) { List<NiveauDTO> listNiveau = (List<NiveauDTO>) listObj1; utilisateur = listNiveau.get(ligne).getUtilisateur(); session.removeAttribute("ListeNivUtil"); } else if (listObj2 != null) { List<UtilisateurDTO> listUtil = (List<UtilisateurDTO>) listObj2; utilisateur = listUtil.get(ligne); session.removeAttribute("listeUtil"); } else { List<UtilisateurDTO> listUtilisateur = (List<UtilisateurDTO>) listObj; utilisateur = listUtilisateur.get(ligne); session.removeAttribute("listeUtilisateur"); } try { UtilisateurDTO utilisateurDTO = DAOFactory1.getInstance() .createUtilisateurService(null) .readUtilisateur(utilisateur); request.setAttribute("utilisateur", utilisateurDTO); List<NiveauDTO> listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(utilisateurDTO); request.setAttribute("ListeCompNiv", listCompNiv); List<ProjetDTO> listUtilProjet = DAOFactory1.getInstance() .createProjetService(null) .readProjetByUtilisateur(utilisateurDTO); request.setAttribute("ListeUtilProjet", listUtilProjet); List<ProjetDTO >listeProjetForInvit = DAOFactory1.getInstance().createProjetService(null).readAllProjets(); //request.setAttribute("listeProjetForInvit", listeProjetForInvit); request.setAttribute("listeProjetForInvit", listeProjetForInvit); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.getRequestDispatcher("./UserRead.jsp").forward(request, response); } // création utilisateur else if (request.getParameter("create") != null && request.getParameter("create").equals("creer")) { List<PromotionDTO> listPromo = null; List<NiveauDTO> listNiveau =null; List<CompetenceDTO> listComp = null; try { listPromo = DAOFactory1.getInstance() .createPromotionService(null).readAllPromotion(); listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence(); listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau(); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("ListePromo", listPromo); request.setAttribute("ListeComp", listComp); request.setAttribute("ListeNiveau", listNiveau); request.getRequestDispatcher("./UserCreate.jsp").forward(request, response); } // modification utilisateur else if (request.getParameter("update") != null && request.getParameter("update").equals("modifier")) { request.setAttribute("utilisateur", getUser(request.getParameter("numUtilisateur"))); List<ProjetDTO> listUtilProjet = null; List<PromotionDTO> listPromo = null; List<NiveauDTO> listCompNiv = null; List<NiveauDTO> listNiveau =null; List<CompetenceDTO> listComp = null; try { listUtilProjet = DAOFactory1 .getInstance() .createProjetService(null) .readProjetByUtilisateur( getUser(request.getParameter("numUtilisateur"))); listPromo = DAOFactory1.getInstance() .createPromotionService(null).readAllPromotion(); listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtilisateur"))); listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence(); listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau(); } catch (TransactionalConnectionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } request.setAttribute("ListeCompNiv", listCompNiv); request.setAttribute("ListeUtilProjet", listUtilProjet); request.setAttribute("ListePromo", listPromo); request.setAttribute("ListeComp", listComp); request.setAttribute("ListeNiveau", listNiveau); request.getRequestDispatcher("./UserUpdate.jsp").forward(request, response); } // suppression utilisateur else if (request.getParameter("delete") != null & request.getParameter("delete").equals("supprimer")) { request.setAttribute("utilisateur", getUser(request.getParameter("numUtilisateur"))); request.getRequestDispatcher("./UserDelete.jsp").forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Modifier un utilisateur if (request.getParameter("updateAction") != null && request.getParameter("updateAction").equals("Confirmer")) { UtilisateurDTO utilisateurUpdate = getUser(request .getParameter("numUtilisateur")); utilisateurUpdate.setNom(request.getParameter("nom")); utilisateurUpdate.setPrenom(request.getParameter("prenom")); String userDateNaisParam = request.getParameter("dateNaissance"); Date userDateNais = new Date(); try { userDateNais = new SimpleDateFormat("dd/MM/yyyy") .parse(userDateNaisParam); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } utilisateurUpdate.setDateNaissance(userDateNais); utilisateurUpdate.setAdresse(request.getParameter("adresse")); utilisateurUpdate.setTel(request.getParameter("tel")); utilisateurUpdate.setMail(request.getParameter("mail")); String promoParam = request.getParameter("promotion"); PromotionDTO promo = new PromotionDTO(); Integer promoNum = null; if (promoParam != null) { promoNum = Integer.valueOf(promoParam); } if (promoNum != null) { PromotionDTO promoUpdate = new PromotionDTO(); promoUpdate.setNum(promoNum); try { promo = DAOFactory1.getInstance() .createPromotionService(null) .readPromotion(promoUpdate); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } } utilisateurUpdate.setPromotion(promo); utilisateurUpdate.setLogin(request.getParameter("login")); utilisateurUpdate.setPassword(request.getParameter("password")); try { DAOFactory1.getInstance().createUtilisateurService(null) .updateUtilisateur(utilisateurUpdate); List<NiveauDTO> listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(utilisateurUpdate); List<ProjetDTO> listUtilProjet = DAOFactory1.getInstance() .createProjetService(null) .readProjetByUtilisateur(utilisateurUpdate); request.setAttribute("ListeCompNiv", listCompNiv); request.setAttribute("ListeUtilProjet", listUtilProjet); //request.setAttribute("action", "updateAction"); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("utilisateur", utilisateurUpdate); request.getRequestDispatcher("./UserRead.jsp").forward(request, response); } //Ajout des compétences d'un utilisateur else if (request.getParameter("updateAction") != null && request.getParameter("updateAction").equals("Enregistrer")){ UtilisateurDTO util = getUser(request.getParameter("numUtil")); NiveauDTO niveau = getNiveau(request.getParameter("niveau")); CompetenceDTO comp = getComp(request.getParameter("comp")); List<ProjetDTO> listUtilProjet = null; List<PromotionDTO> listPromo = null; List<NiveauDTO> listCompNiv = null; List<NiveauDTO> listNiveau =null; List<CompetenceDTO> listComp = null; try { DAOFactory1.getInstance().createCompetenceNiveauService(null).addCompUtil(util, comp, niveau); listUtilProjet = DAOFactory1 .getInstance() .createProjetService(null) .readProjetByUtilisateur( getUser(request.getParameter("numUtil"))); listPromo = DAOFactory1.getInstance() .createPromotionService(null).readAllPromotion(); listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtil"))); listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence(); listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau(); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("ListeCompNiv", listCompNiv); request.setAttribute("ListeUtilProjet", listUtilProjet); request.setAttribute("ListePromo", listPromo); request.setAttribute("ListeComp", listComp); request.setAttribute("ListeNiveau", listNiveau); request.setAttribute("utilisateur", getUser(request.getParameter("numUtil"))); request.getRequestDispatcher("./UserUpdate.jsp").forward(request, response); } //Modification des compétences d'un utilisateur else if (request.getParameter("updateAction") != null && request.getParameter("updateAction").equals("Ok")){ UtilisateurDTO util = getUser(request.getParameter("numUtil")); NiveauDTO niveau = getNiveau(request.getParameter("niveau")); CompetenceDTO comp = getComp(request.getParameter("comp")); List<ProjetDTO> listUtilProjet = null; List<PromotionDTO> listPromo = null; List<NiveauDTO> listCompNiv = null; List<NiveauDTO> listNiveau =null; List<CompetenceDTO> listComp = null; try { DAOFactory1.getInstance().createCompetenceNiveauService(null).updateCompUtil(util, comp, niveau); listUtilProjet = DAOFactory1 .getInstance() .createProjetService(null) .readProjetByUtilisateur( getUser(request.getParameter("numUtil"))); listPromo = DAOFactory1.getInstance() .createPromotionService(null).readAllPromotion(); listCompNiv = DAOFactory1.getInstance() .createCompetenceNiveauService(null) .readCompetenceNiveauUtilisateur(getUser(request.getParameter("numUtil"))); listComp = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllCompetence(); listNiveau = DAOFactory1.getInstance().createCompetenceNiveauService(null).readAllNomNiveau(); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("ListeCompNiv", listCompNiv); request.setAttribute("ListeUtilProjet", listUtilProjet); request.setAttribute("ListePromo", listPromo); request.setAttribute("ListeComp", listComp); request.setAttribute("ListeNiveau", listNiveau); request.setAttribute("utilisateur", getUser(request.getParameter("numUtil"))); request.getRequestDispatcher("./UserUpdate.jsp").forward(request, response); } // Ajouter un utilisateur else if (request.getParameter("createAction") != null && request.getParameter("createAction").equals("ajouter")) { UtilisateurDTO utilisateurCreate = new UtilisateurDTO(); utilisateurCreate.setNom(request.getParameter("nom")); utilisateurCreate.setPrenom(request.getParameter("prenom")); String userDateNaisParam = request.getParameter("dateNaissance"); Date userDateNais = new Date(); try { userDateNais = new SimpleDateFormat("dd/MM/yyyy") .parse(userDateNaisParam); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } utilisateurCreate.setDateNaissance(userDateNais); utilisateurCreate.setAdresse(request.getParameter("adresse")); utilisateurCreate.setTel(request.getParameter("tel")); utilisateurCreate.setMail(request.getParameter("mail")); String promoParam = request.getParameter("promotion"); PromotionDTO promo = new PromotionDTO(); Integer promoNum = null; if (promoParam != null) { promoNum = Integer.valueOf(promoParam); } if (promoNum != null) { PromotionDTO promoUpdate = new PromotionDTO(); promoUpdate.setNum(promoNum); try { promo = DAOFactory1.getInstance() .createPromotionService(null) .readPromotion(promoUpdate); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } } utilisateurCreate.setPromotion(promo); utilisateurCreate.setLogin(request.getParameter("login")); utilisateurCreate.setPassword(request.getParameter("password")); try { DAOFactory1.getInstance().createUtilisateurService(null) .createUtilisateur(utilisateurCreate); request.setAttribute("action", "createAction"); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("utilisateur", utilisateurCreate); request.getRequestDispatcher("./UserRead.jsp").forward(request, response); } // Supprimer un utilisateur else if (request.getParameter("deleteAction") != null && request.getParameter("deleteAction").equals("supprimer")) { UtilisateurDTO utilisateurDelete = getUser(request .getParameter("numUtilisateur")); try { DAOFactory1.getInstance().createUtilisateurService(null) .deleteUtilisateur(utilisateurDelete); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.sendRedirect("./ListUserView"); } } private UtilisateurDTO getUser(String requestNumUtilisateur) { UtilisateurDTO utilisateurDTO = new UtilisateurDTO(); int numUtilisateur = Integer.valueOf(requestNumUtilisateur); UtilisateurDTO utilisateurTemp = new UtilisateurDTO(); utilisateurTemp.setNum(numUtilisateur); try { utilisateurDTO = DAOFactory1.getInstance() .createUtilisateurService(null) .readUtilisateur(utilisateurTemp); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return utilisateurDTO; } private CompetenceDTO getComp(String requestNumComp) { CompetenceDTO compDTO = new CompetenceDTO(); int numComp = Integer.valueOf(requestNumComp); CompetenceDTO compTemp = new CompetenceDTO(); compTemp.setNum(numComp); try { compDTO = DAOFactory1.getInstance() .createCompetenceNiveauService(null).readCompetence(compTemp); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return compDTO; } private NiveauDTO getNiveau(String requestNumNiveau) { NiveauDTO niveauDTO = new NiveauDTO(); int numComp = Integer.valueOf(requestNumNiveau); NiveauDTO niveauTemp = new NiveauDTO(); niveauTemp.setNum(numComp); try { niveauDTO = DAOFactory1.getInstance() .createCompetenceNiveauService(null).readNiveau(niveauTemp); } catch (TransactionalConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } return niveauDTO; } }
208534_13
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2023 Cloud Software Group, Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.olap.xmla; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeaders; import javax.xml.soap.Name; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFactory; import javax.xml.soap.SOAPFault; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPPart; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRDataset; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRRuntimeException; import net.sf.jasperreports.engine.JRValueParameter; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.query.JRAbstractQueryExecuter; import net.sf.jasperreports.olap.JRMdxQueryExecuterFactory; import net.sf.jasperreports.olap.JROlapDataSource; import net.sf.jasperreports.olap.result.JROlapResult; /** * @author Michael Gunther (m.guenther at users.sourceforge.net) * @author Lucian Chirita ([email protected]) * @author swood */ public class JRXmlaQueryExecuter extends JRAbstractQueryExecuter { private static final Log log = LogFactory.getLog(JRXmlaQueryExecuter.class); public static final String EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT = "data.olap.xmla.cannot.retrieve.element"; public static final String EXCEPTION_MESSAGE_KEY_MESSAGE_CALL_FAILED = "data.olap.xmla.message.call.failed"; public static final String EXCEPTION_MESSAGE_KEY_XMLA_NO_LEVEL_NAME = "data.olap.xmla.no.level.name"; public static final String EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT = "data.olap.xmla.null.element"; private static final String SLICER_AXIS_NAME = "SlicerAxis"; private static final String MDD_URI = "urn:schemas-microsoft-com:xml-analysis:mddataset"; private static final String XMLA_URI = "urn:schemas-microsoft-com:xml-analysis"; private static final String LEVEL_UNIQUE_NAME_PATTERN_DEFINITION = "\\[[^\\]]+\\]\\.\\[([^\\]]+)\\]"; private static final Pattern LEVEL_UNIQUE_NAME_PATTERN = Pattern.compile(LEVEL_UNIQUE_NAME_PATTERN_DEFINITION); private static final int LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP = 1; private static final String HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN_DEFINITION = LEVEL_UNIQUE_NAME_PATTERN_DEFINITION + "\\.\\[([^\\]]+)\\]"; private static final Pattern HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN = Pattern.compile(HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN_DEFINITION); private static final int HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP = 2; private SOAPFactory sf; private SOAPConnection connection; private JRXmlaResult xmlaResult; /** * */ public JRXmlaQueryExecuter( JasperReportsContext jasperReportsContext, JRDataset dataset, Map<String, ? extends JRValueParameter> parametersMap ) { super(jasperReportsContext, dataset, parametersMap); parseQuery(); } @Override protected String getCanonicalQueryLanguage() { return JRMdxQueryExecuterFactory.CANONICAL_LANGUAGE; } @Override protected String getParameterReplacement(String parameterName) { return String.valueOf(getParameterValue(parameterName)); } public JROlapResult getResult() { try { this.sf = SOAPFactory.newInstance(); this.connection = createSOAPConnection(); SOAPMessage queryMessage = createQueryMessage(); URL soapURL = new URL(getSoapUrl()); SOAPMessage resultMessage = executeQuery(queryMessage, soapURL); xmlaResult = new JRXmlaResult(); parseResult(resultMessage); } catch (MalformedURLException | SOAPException e) { throw new JRRuntimeException(e); } return xmlaResult; } @Override public JRDataSource createDatasource() throws JRException { getResult(); return new JROlapDataSource(dataset, xmlaResult); } protected String getSoapUrl() throws MalformedURLException { String soapUrl; String xmlaUrl = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_URL); String user = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_USER, true); if (user == null || user.length() == 0) { soapUrl = xmlaUrl; } else { URL url = new URL(xmlaUrl); soapUrl = url.getProtocol() + "://" + user; String password = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_PASSWORD, true); if (password != null && password.length() > 0) { soapUrl += ":" + password; } soapUrl += "@" + url.getHost(); if (url.getPort() != -1) { soapUrl += ":" + url.getPort(); } soapUrl += url.getPath(); } return soapUrl; } @Override public boolean cancelQuery() throws JRException { return false; } @Override public void close() { if (connection != null) { try { connection.close(); } catch (SOAPException e) { throw new JRRuntimeException(e); } connection = null; } } protected SOAPConnection createSOAPConnection() { try { SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance(); return scf.createConnection(); } catch (UnsupportedOperationException | SOAPException e) { throw new JRRuntimeException(e); } } protected SOAPMessage createQueryMessage() { String queryStr = getQueryString(); if (log.isDebugEnabled()) { log.debug("MDX query: " + queryStr); } try { MessageFactory mf = MessageFactory.newInstance(); SOAPMessage message = mf.createMessage(); MimeHeaders mh = message.getMimeHeaders(); mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\""); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody body = envelope.getBody(); Name nEx = envelope.createName("Execute", "", XMLA_URI); SOAPElement eEx = body.addChildElement(nEx); // add the parameters // COMMAND parameter // <Command> // <Statement>queryStr</Statement> // </Command> Name nCom = envelope.createName("Command", "", XMLA_URI); SOAPElement eCommand = eEx.addChildElement(nCom); Name nSta = envelope.createName("Statement", "", XMLA_URI); SOAPElement eStatement = eCommand.addChildElement(nSta); eStatement.addTextNode(queryStr); // <Properties> // <PropertyList> // <DataSourceInfo>dataSource</DataSourceInfo> // <Catalog>catalog</Catalog> // <Format>Multidimensional</Format> // <AxisFormat>TupleFormat</AxisFormat> // </PropertyList> // </Properties> Map<String, String> paraList = new HashMap<>(); String datasource = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_DATASOURCE); paraList.put("DataSourceInfo", datasource); String catalog = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_CATALOG); paraList.put("Catalog", catalog); paraList.put("Format", "Multidimensional"); paraList.put("AxisFormat", "TupleFormat"); addParameterList(envelope, eEx, "Properties", "PropertyList", paraList); message.saveChanges(); if (log.isDebugEnabled()) { log.debug("XML/A query message: \n" + prettyPrintSOAP(message.getSOAPPart().getEnvelope())); } return message; } catch (SOAPException e) { throw new JRRuntimeException(e); } } protected void addParameterList(SOAPEnvelope envelope, SOAPElement eParent, String typeName, String listName, Map<String, String> params) throws SOAPException { Name nPara = envelope.createName(typeName, "", XMLA_URI); SOAPElement eType = eParent.addChildElement(nPara); nPara = envelope.createName(listName, "", XMLA_URI); SOAPElement eList = eType.addChildElement(nPara); if (params == null) { return; } for (Iterator<Map.Entry<String, String>> entryIt = params.entrySet().iterator(); entryIt.hasNext();) { Map.Entry<String, String> entry = entryIt.next(); String tag = entry.getKey(); String value = entry.getValue(); nPara = envelope.createName(tag, "", XMLA_URI); SOAPElement eTag = eList.addChildElement(nPara); eTag.addTextNode(value); } } /** * Sends the SOAP Message over the connection and returns the * Result-SOAP-Message * * @return Reply-Message */ protected SOAPMessage executeQuery(SOAPMessage message, URL url) { try { return connection.call(message, url); } catch (SOAPException e) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_MESSAGE_CALL_FAILED, (Object[])null, e); } } /** * Parses the result-Message into this class's structure * * @param reply * The reply-Message from the Server */ protected void parseResult(SOAPMessage reply) throws SOAPException { SOAPPart soapPart = reply.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); SOAPElement eElement = null; if (log.isDebugEnabled()) { log.debug("XML/A result envelope: " + prettyPrintSOAP(soapEnvelope)); } SOAPFault fault = soapBody.getFault(); if (fault != null) { handleResultFault(fault); } Name eName = soapEnvelope.createName("ExecuteResponse", "", XMLA_URI); // Get the ExecuteResponse-Node Iterator<?> responseElements = soapBody.getChildElements(eName); if (responseElements.hasNext()) { Object eObj = responseElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"ExecuteResponse"}); } eElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"ExecuteResponse"}); } // Get the return-Node Name rName = soapEnvelope.createName("return", "", XMLA_URI); Iterator<?> returnElements = eElement.getChildElements(rName); SOAPElement returnElement = null; if (returnElements.hasNext()) { Object eObj = returnElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"return"}); } returnElement = (SOAPElement) eObj; } else { // Should be old-Microsoft XMLA-SDK. Try without m-prefix Name rName2 = soapEnvelope.createName("return", "", ""); returnElements = eElement.getChildElements(rName2); if (returnElements.hasNext()) { Object eObj = returnElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"return"}); } returnElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"return"}); } } // Get the root-Node Name rootName = soapEnvelope.createName("root", "", MDD_URI); SOAPElement rootElement = null; Iterator<?> rootElements = returnElement.getChildElements(rootName); if (rootElements.hasNext()) { Object eObj = rootElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"root"}); } rootElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"root"}); } // Get the OlapInfo-Node Name olapInfoName = soapEnvelope.createName("OlapInfo", "", MDD_URI); SOAPElement olapInfoElement = null; Iterator<?> olapInfoElements = rootElement.getChildElements(olapInfoName); if (olapInfoElements.hasNext()) { Object eObj = olapInfoElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"OlapInfo"}); } olapInfoElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"OlapInfo"}); } parseOLAPInfoElement(olapInfoElement); // Get the Axes Element Name axesName = soapEnvelope.createName("Axes", "", MDD_URI); SOAPElement axesElement = null; Iterator<?> axesElements = rootElement.getChildElements(axesName); if (axesElements.hasNext()) { Object eObj = axesElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"Axes"}); } axesElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"Axes"}); } parseAxesElement(axesElement); // Get the CellData Element Name cellDataName = soapEnvelope.createName("CellData", "", MDD_URI); SOAPElement cellDataElement = null; Iterator<?> cellDataElements = rootElement.getChildElements(cellDataName); if (cellDataElements.hasNext()) { Object eObj = cellDataElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"CellData"}); } cellDataElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"CellData"}); } parseCellDataElement(cellDataElement); } protected void handleResultFault(SOAPFault fault) { StringBuilder errorMsg = new StringBuilder(); errorMsg.append("XML/A fault: "); String faultString = fault.getFaultString(); if (faultString != null) { errorMsg.append(faultString); errorMsg.append("; "); } String faultActor = fault.getFaultActor(); if (faultActor != null) { errorMsg.append("Actor: "); errorMsg.append(faultActor); errorMsg.append("; "); } String faultCode = fault.getFaultCode(); if (faultCode != null) { errorMsg.append("Code: "); errorMsg.append(faultCode); errorMsg.append("; "); } throw new JRRuntimeException(errorMsg.toString()); } protected void parseOLAPInfoElement(SOAPElement olapInfoElement) throws SOAPException { // CubeInfo-Element is not needed // Get the AxesInfo-Node Name axesInfoName = sf.createName("AxesInfo", "", MDD_URI); SOAPElement axesElement = null; Iterator<?> axesInfoElements = olapInfoElement.getChildElements(axesInfoName); if (axesInfoElements.hasNext()) { Object axesObj = axesInfoElements.next(); if (axesObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"AxesInfo"}); } axesElement = (SOAPElement) axesObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"AxesInfo"}); } parseAxesInfoElement(axesElement); // CellInfo is not needed } protected void parseAxesInfoElement(SOAPElement axesInfoElement) throws SOAPException { // Cycle over AxisInfo-Elements Name axisInfoName = sf.createName("AxisInfo", "", MDD_URI); Iterator<?> itAxis = axesInfoElement.getChildElements(axisInfoName); while (itAxis.hasNext()) { SOAPElement axisElement = (SOAPElement) itAxis.next(); Name name = sf.createName("name"); String axisName = axisElement.getAttributeValue(name); if (axisName.equals(SLICER_AXIS_NAME)) { continue; } JRXmlaResultAxis axis = new JRXmlaResultAxis(axisName); xmlaResult.addAxis(axis); if (log.isDebugEnabled()) { log.debug("adding axis: " + axis.getAxisName()); } // retrieve the hierarchies by <HierarchyInfo> name = sf.createName("HierarchyInfo", "", MDD_URI); Iterator<?> itHierInfo = axisElement.getChildElements(name); while (itHierInfo.hasNext()) { SOAPElement eHierInfo = (SOAPElement) itHierInfo.next(); handleHierInfo(axis, eHierInfo); } } } protected void parseAxesElement(SOAPElement axesElement) throws SOAPException { // Cycle over Axis-Elements Name aName = sf.createName("Axis", "", MDD_URI); Iterator<?> itAxis = axesElement.getChildElements(aName); while (itAxis.hasNext()) { SOAPElement axisElement = (SOAPElement) itAxis.next(); Name name = sf.createName("name"); String axisName = axisElement.getAttributeValue(name); if (axisName.equals(SLICER_AXIS_NAME)) { continue; } // LookUp for the Axis JRXmlaResultAxis axis = xmlaResult.getAxisByName(axisName); // retrieve the tuples by <Tuples> name = sf.createName("Tuples", "", MDD_URI); Iterator<?> itTuples = axisElement.getChildElements(name); if (itTuples.hasNext()) { SOAPElement eTuples = (SOAPElement) itTuples.next(); handleTuplesElement(axis, eTuples); } } } protected void parseCellDataElement(SOAPElement cellDataElement) throws SOAPException { Name name = sf.createName("Cell", "", MDD_URI); Iterator<?> itCells = cellDataElement.getChildElements(name); while (itCells.hasNext()) { SOAPElement cellElement = (SOAPElement) itCells.next(); Name errorName = sf.createName("Error", "", MDD_URI); Iterator<?> errorElems = cellElement.getChildElements(errorName); if (errorElems.hasNext()) { handleCellErrors(errorElems); } Name ordinalName = sf.createName("CellOrdinal"); String cellOrdinal = cellElement.getAttributeValue(ordinalName); Object value = null; Iterator<?> valueElements = cellElement.getChildElements(sf.createName("Value", "", MDD_URI)); if (valueElements.hasNext()) { SOAPElement valueElement = (SOAPElement) valueElements.next(); String valueType = valueElement.getAttribute("xsi:type"); if (valueType.equals("xsd:int")) { value = Long.valueOf(valueElement.getValue()); } else if ( valueType.equals("xsd:double") || valueType.equals("xsd:decimal") ) { value = Double.valueOf(valueElement.getValue()); } else { value = valueElement.getValue(); } } String fmtValue = ""; Iterator<?> fmtValueElements = cellElement.getChildElements(sf.createName("FmtValue", "", MDD_URI)); if (fmtValueElements.hasNext()) { SOAPElement fmtValueElement = ((SOAPElement) fmtValueElements.next()); fmtValue = fmtValueElement.getValue(); } int pos = Integer.parseInt(cellOrdinal); JRXmlaCell cell = new JRXmlaCell(value, fmtValue); xmlaResult.setCell(cell, pos); } } protected void handleCellErrors(Iterator<?> errorElems) throws SOAPException { SOAPElement errorElem = (SOAPElement) errorElems.next(); StringBuilder errorMsg = new StringBuilder(); errorMsg.append("Cell error: "); Iterator<?> descriptionElems = errorElem.getChildElements(sf.createName("Description", "", MDD_URI)); if (descriptionElems.hasNext()) { SOAPElement descrElem = (SOAPElement) descriptionElems.next(); errorMsg.append(descrElem.getValue()); errorMsg.append("; "); } Iterator<?> sourceElems = errorElem.getChildElements(sf.createName("Source", "", MDD_URI)); if (sourceElems.hasNext()) { SOAPElement sourceElem = (SOAPElement) sourceElems.next(); errorMsg.append("Source: "); errorMsg.append(sourceElem.getValue()); errorMsg.append("; "); } Iterator<?> codeElems = errorElem.getChildElements(sf.createName("ErrorCode", "", MDD_URI)); if (codeElems.hasNext()) { SOAPElement codeElem = (SOAPElement) codeElems.next(); errorMsg.append("Code: "); errorMsg.append(codeElem.getValue()); errorMsg.append("; "); } throw new JRRuntimeException(errorMsg.toString()); } protected void handleHierInfo(JRXmlaResultAxis axis, SOAPElement hierInfoElement) throws SOAPException { Name name = sf.createName("name"); String dimName = hierInfoElement.getAttributeValue(name); // Get the Dimension Name if (log.isDebugEnabled()) { log.debug("Adding hierarchy: " + dimName); } JRXmlaHierarchy hier = new JRXmlaHierarchy(dimName); axis.addHierarchy(hier); } protected void handleTuplesElement(JRXmlaResultAxis axis, SOAPElement tuplesElement) throws SOAPException { Name tName = sf.createName("Tuple", "", MDD_URI); for (Iterator<?> itTuple = tuplesElement.getChildElements(tName); itTuple.hasNext();) { SOAPElement eTuple = (SOAPElement) itTuple.next(); handleTupleElement(axis, eTuple); } } protected void handleTupleElement(JRXmlaResultAxis axis, SOAPElement tupleElement) throws SOAPException { JRXmlaMemberTuple tuple = new JRXmlaMemberTuple(axis.getHierarchiesOnAxis().length); Name memName = sf.createName("Member", "", MDD_URI); Iterator<?> itMember = tupleElement.getChildElements(memName); int memNum = 0; while (itMember.hasNext()) { SOAPElement memElement = (SOAPElement) itMember.next(); Name name = sf.createName("Hierarchy", "", ""); String hierName = memElement.getAttributeValue(name); String uName = ""; Iterator<?> uNameElements = memElement.getChildElements(sf.createName("UName", "", MDD_URI)); if (uNameElements.hasNext()) { uName = ((SOAPElement) uNameElements.next()).getValue(); } String caption = ""; Iterator<?> captionElements = memElement.getChildElements(sf.createName("Caption", "", MDD_URI)); if (captionElements.hasNext()) { caption = ((SOAPElement) captionElements.next()).getValue(); } String lName = ""; Iterator<?> lNameElements = memElement.getChildElements(sf.createName("LName", "", MDD_URI)); if (lNameElements.hasNext()) { String levelUniqueName = ((SOAPElement) lNameElements.next()).getValue(); Matcher matcher = LEVEL_UNIQUE_NAME_PATTERN.matcher(levelUniqueName); if (matcher.matches()) { lName = matcher.group(LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP); } else { matcher = HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN.matcher(levelUniqueName); if (matcher.matches()) { lName = matcher.group(HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP); } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NO_LEVEL_NAME, new Object[]{levelUniqueName}); } } } int lNum = 0; Iterator<?> lNumElements = memElement.getChildElements(sf.createName("LNum", "", MDD_URI)); if (lNumElements.hasNext()) { lNum = Integer.parseInt(((SOAPElement) lNumElements.next()).getValue()); } JRXmlaMember member = new JRXmlaMember(caption, uName, hierName, lName, lNum); if (log.isDebugEnabled()) { log.debug("Adding member: axis - " + axis.getAxisName() + " hierName - " + hierName + " lName - " + lName + " uName - " + uName); } tuple.setMember(memNum++, member); } axis.addTuple(tuple); } protected String prettyPrintSOAP(SOAPElement element) { final StringWriter sw = new StringWriter(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform( new DOMSource(element), new StreamResult(sw)); } catch (TransformerException e) { throw new JRRuntimeException(e); } return sw.toString(); } }
TIBCOSoftware/jasperreports
jasperreports/src/net/sf/jasperreports/olap/xmla/JRXmlaQueryExecuter.java
7,400
// CubeInfo-Element is not needed
line_comment
nl
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2023 Cloud Software Group, Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.olap.xmla; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeaders; import javax.xml.soap.Name; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFactory; import javax.xml.soap.SOAPFault; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPPart; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRDataset; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRRuntimeException; import net.sf.jasperreports.engine.JRValueParameter; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.query.JRAbstractQueryExecuter; import net.sf.jasperreports.olap.JRMdxQueryExecuterFactory; import net.sf.jasperreports.olap.JROlapDataSource; import net.sf.jasperreports.olap.result.JROlapResult; /** * @author Michael Gunther (m.guenther at users.sourceforge.net) * @author Lucian Chirita ([email protected]) * @author swood */ public class JRXmlaQueryExecuter extends JRAbstractQueryExecuter { private static final Log log = LogFactory.getLog(JRXmlaQueryExecuter.class); public static final String EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT = "data.olap.xmla.cannot.retrieve.element"; public static final String EXCEPTION_MESSAGE_KEY_MESSAGE_CALL_FAILED = "data.olap.xmla.message.call.failed"; public static final String EXCEPTION_MESSAGE_KEY_XMLA_NO_LEVEL_NAME = "data.olap.xmla.no.level.name"; public static final String EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT = "data.olap.xmla.null.element"; private static final String SLICER_AXIS_NAME = "SlicerAxis"; private static final String MDD_URI = "urn:schemas-microsoft-com:xml-analysis:mddataset"; private static final String XMLA_URI = "urn:schemas-microsoft-com:xml-analysis"; private static final String LEVEL_UNIQUE_NAME_PATTERN_DEFINITION = "\\[[^\\]]+\\]\\.\\[([^\\]]+)\\]"; private static final Pattern LEVEL_UNIQUE_NAME_PATTERN = Pattern.compile(LEVEL_UNIQUE_NAME_PATTERN_DEFINITION); private static final int LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP = 1; private static final String HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN_DEFINITION = LEVEL_UNIQUE_NAME_PATTERN_DEFINITION + "\\.\\[([^\\]]+)\\]"; private static final Pattern HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN = Pattern.compile(HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN_DEFINITION); private static final int HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP = 2; private SOAPFactory sf; private SOAPConnection connection; private JRXmlaResult xmlaResult; /** * */ public JRXmlaQueryExecuter( JasperReportsContext jasperReportsContext, JRDataset dataset, Map<String, ? extends JRValueParameter> parametersMap ) { super(jasperReportsContext, dataset, parametersMap); parseQuery(); } @Override protected String getCanonicalQueryLanguage() { return JRMdxQueryExecuterFactory.CANONICAL_LANGUAGE; } @Override protected String getParameterReplacement(String parameterName) { return String.valueOf(getParameterValue(parameterName)); } public JROlapResult getResult() { try { this.sf = SOAPFactory.newInstance(); this.connection = createSOAPConnection(); SOAPMessage queryMessage = createQueryMessage(); URL soapURL = new URL(getSoapUrl()); SOAPMessage resultMessage = executeQuery(queryMessage, soapURL); xmlaResult = new JRXmlaResult(); parseResult(resultMessage); } catch (MalformedURLException | SOAPException e) { throw new JRRuntimeException(e); } return xmlaResult; } @Override public JRDataSource createDatasource() throws JRException { getResult(); return new JROlapDataSource(dataset, xmlaResult); } protected String getSoapUrl() throws MalformedURLException { String soapUrl; String xmlaUrl = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_URL); String user = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_USER, true); if (user == null || user.length() == 0) { soapUrl = xmlaUrl; } else { URL url = new URL(xmlaUrl); soapUrl = url.getProtocol() + "://" + user; String password = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_PASSWORD, true); if (password != null && password.length() > 0) { soapUrl += ":" + password; } soapUrl += "@" + url.getHost(); if (url.getPort() != -1) { soapUrl += ":" + url.getPort(); } soapUrl += url.getPath(); } return soapUrl; } @Override public boolean cancelQuery() throws JRException { return false; } @Override public void close() { if (connection != null) { try { connection.close(); } catch (SOAPException e) { throw new JRRuntimeException(e); } connection = null; } } protected SOAPConnection createSOAPConnection() { try { SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance(); return scf.createConnection(); } catch (UnsupportedOperationException | SOAPException e) { throw new JRRuntimeException(e); } } protected SOAPMessage createQueryMessage() { String queryStr = getQueryString(); if (log.isDebugEnabled()) { log.debug("MDX query: " + queryStr); } try { MessageFactory mf = MessageFactory.newInstance(); SOAPMessage message = mf.createMessage(); MimeHeaders mh = message.getMimeHeaders(); mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\""); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody body = envelope.getBody(); Name nEx = envelope.createName("Execute", "", XMLA_URI); SOAPElement eEx = body.addChildElement(nEx); // add the parameters // COMMAND parameter // <Command> // <Statement>queryStr</Statement> // </Command> Name nCom = envelope.createName("Command", "", XMLA_URI); SOAPElement eCommand = eEx.addChildElement(nCom); Name nSta = envelope.createName("Statement", "", XMLA_URI); SOAPElement eStatement = eCommand.addChildElement(nSta); eStatement.addTextNode(queryStr); // <Properties> // <PropertyList> // <DataSourceInfo>dataSource</DataSourceInfo> // <Catalog>catalog</Catalog> // <Format>Multidimensional</Format> // <AxisFormat>TupleFormat</AxisFormat> // </PropertyList> // </Properties> Map<String, String> paraList = new HashMap<>(); String datasource = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_DATASOURCE); paraList.put("DataSourceInfo", datasource); String catalog = (String) getParameterValue(JRXmlaQueryExecuterFactory.PARAMETER_XMLA_CATALOG); paraList.put("Catalog", catalog); paraList.put("Format", "Multidimensional"); paraList.put("AxisFormat", "TupleFormat"); addParameterList(envelope, eEx, "Properties", "PropertyList", paraList); message.saveChanges(); if (log.isDebugEnabled()) { log.debug("XML/A query message: \n" + prettyPrintSOAP(message.getSOAPPart().getEnvelope())); } return message; } catch (SOAPException e) { throw new JRRuntimeException(e); } } protected void addParameterList(SOAPEnvelope envelope, SOAPElement eParent, String typeName, String listName, Map<String, String> params) throws SOAPException { Name nPara = envelope.createName(typeName, "", XMLA_URI); SOAPElement eType = eParent.addChildElement(nPara); nPara = envelope.createName(listName, "", XMLA_URI); SOAPElement eList = eType.addChildElement(nPara); if (params == null) { return; } for (Iterator<Map.Entry<String, String>> entryIt = params.entrySet().iterator(); entryIt.hasNext();) { Map.Entry<String, String> entry = entryIt.next(); String tag = entry.getKey(); String value = entry.getValue(); nPara = envelope.createName(tag, "", XMLA_URI); SOAPElement eTag = eList.addChildElement(nPara); eTag.addTextNode(value); } } /** * Sends the SOAP Message over the connection and returns the * Result-SOAP-Message * * @return Reply-Message */ protected SOAPMessage executeQuery(SOAPMessage message, URL url) { try { return connection.call(message, url); } catch (SOAPException e) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_MESSAGE_CALL_FAILED, (Object[])null, e); } } /** * Parses the result-Message into this class's structure * * @param reply * The reply-Message from the Server */ protected void parseResult(SOAPMessage reply) throws SOAPException { SOAPPart soapPart = reply.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); SOAPElement eElement = null; if (log.isDebugEnabled()) { log.debug("XML/A result envelope: " + prettyPrintSOAP(soapEnvelope)); } SOAPFault fault = soapBody.getFault(); if (fault != null) { handleResultFault(fault); } Name eName = soapEnvelope.createName("ExecuteResponse", "", XMLA_URI); // Get the ExecuteResponse-Node Iterator<?> responseElements = soapBody.getChildElements(eName); if (responseElements.hasNext()) { Object eObj = responseElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"ExecuteResponse"}); } eElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"ExecuteResponse"}); } // Get the return-Node Name rName = soapEnvelope.createName("return", "", XMLA_URI); Iterator<?> returnElements = eElement.getChildElements(rName); SOAPElement returnElement = null; if (returnElements.hasNext()) { Object eObj = returnElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"return"}); } returnElement = (SOAPElement) eObj; } else { // Should be old-Microsoft XMLA-SDK. Try without m-prefix Name rName2 = soapEnvelope.createName("return", "", ""); returnElements = eElement.getChildElements(rName2); if (returnElements.hasNext()) { Object eObj = returnElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"return"}); } returnElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"return"}); } } // Get the root-Node Name rootName = soapEnvelope.createName("root", "", MDD_URI); SOAPElement rootElement = null; Iterator<?> rootElements = returnElement.getChildElements(rootName); if (rootElements.hasNext()) { Object eObj = rootElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"root"}); } rootElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"root"}); } // Get the OlapInfo-Node Name olapInfoName = soapEnvelope.createName("OlapInfo", "", MDD_URI); SOAPElement olapInfoElement = null; Iterator<?> olapInfoElements = rootElement.getChildElements(olapInfoName); if (olapInfoElements.hasNext()) { Object eObj = olapInfoElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"OlapInfo"}); } olapInfoElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"OlapInfo"}); } parseOLAPInfoElement(olapInfoElement); // Get the Axes Element Name axesName = soapEnvelope.createName("Axes", "", MDD_URI); SOAPElement axesElement = null; Iterator<?> axesElements = rootElement.getChildElements(axesName); if (axesElements.hasNext()) { Object eObj = axesElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"Axes"}); } axesElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"Axes"}); } parseAxesElement(axesElement); // Get the CellData Element Name cellDataName = soapEnvelope.createName("CellData", "", MDD_URI); SOAPElement cellDataElement = null; Iterator<?> cellDataElements = rootElement.getChildElements(cellDataName); if (cellDataElements.hasNext()) { Object eObj = cellDataElements.next(); if (eObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"CellData"}); } cellDataElement = (SOAPElement) eObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"CellData"}); } parseCellDataElement(cellDataElement); } protected void handleResultFault(SOAPFault fault) { StringBuilder errorMsg = new StringBuilder(); errorMsg.append("XML/A fault: "); String faultString = fault.getFaultString(); if (faultString != null) { errorMsg.append(faultString); errorMsg.append("; "); } String faultActor = fault.getFaultActor(); if (faultActor != null) { errorMsg.append("Actor: "); errorMsg.append(faultActor); errorMsg.append("; "); } String faultCode = fault.getFaultCode(); if (faultCode != null) { errorMsg.append("Code: "); errorMsg.append(faultCode); errorMsg.append("; "); } throw new JRRuntimeException(errorMsg.toString()); } protected void parseOLAPInfoElement(SOAPElement olapInfoElement) throws SOAPException { // CubeInfo-Element is<SUF> // Get the AxesInfo-Node Name axesInfoName = sf.createName("AxesInfo", "", MDD_URI); SOAPElement axesElement = null; Iterator<?> axesInfoElements = olapInfoElement.getChildElements(axesInfoName); if (axesInfoElements.hasNext()) { Object axesObj = axesInfoElements.next(); if (axesObj == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[]{"AxesInfo"}); } axesElement = (SOAPElement) axesObj; } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT, new Object[]{"AxesInfo"}); } parseAxesInfoElement(axesElement); // CellInfo is not needed } protected void parseAxesInfoElement(SOAPElement axesInfoElement) throws SOAPException { // Cycle over AxisInfo-Elements Name axisInfoName = sf.createName("AxisInfo", "", MDD_URI); Iterator<?> itAxis = axesInfoElement.getChildElements(axisInfoName); while (itAxis.hasNext()) { SOAPElement axisElement = (SOAPElement) itAxis.next(); Name name = sf.createName("name"); String axisName = axisElement.getAttributeValue(name); if (axisName.equals(SLICER_AXIS_NAME)) { continue; } JRXmlaResultAxis axis = new JRXmlaResultAxis(axisName); xmlaResult.addAxis(axis); if (log.isDebugEnabled()) { log.debug("adding axis: " + axis.getAxisName()); } // retrieve the hierarchies by <HierarchyInfo> name = sf.createName("HierarchyInfo", "", MDD_URI); Iterator<?> itHierInfo = axisElement.getChildElements(name); while (itHierInfo.hasNext()) { SOAPElement eHierInfo = (SOAPElement) itHierInfo.next(); handleHierInfo(axis, eHierInfo); } } } protected void parseAxesElement(SOAPElement axesElement) throws SOAPException { // Cycle over Axis-Elements Name aName = sf.createName("Axis", "", MDD_URI); Iterator<?> itAxis = axesElement.getChildElements(aName); while (itAxis.hasNext()) { SOAPElement axisElement = (SOAPElement) itAxis.next(); Name name = sf.createName("name"); String axisName = axisElement.getAttributeValue(name); if (axisName.equals(SLICER_AXIS_NAME)) { continue; } // LookUp for the Axis JRXmlaResultAxis axis = xmlaResult.getAxisByName(axisName); // retrieve the tuples by <Tuples> name = sf.createName("Tuples", "", MDD_URI); Iterator<?> itTuples = axisElement.getChildElements(name); if (itTuples.hasNext()) { SOAPElement eTuples = (SOAPElement) itTuples.next(); handleTuplesElement(axis, eTuples); } } } protected void parseCellDataElement(SOAPElement cellDataElement) throws SOAPException { Name name = sf.createName("Cell", "", MDD_URI); Iterator<?> itCells = cellDataElement.getChildElements(name); while (itCells.hasNext()) { SOAPElement cellElement = (SOAPElement) itCells.next(); Name errorName = sf.createName("Error", "", MDD_URI); Iterator<?> errorElems = cellElement.getChildElements(errorName); if (errorElems.hasNext()) { handleCellErrors(errorElems); } Name ordinalName = sf.createName("CellOrdinal"); String cellOrdinal = cellElement.getAttributeValue(ordinalName); Object value = null; Iterator<?> valueElements = cellElement.getChildElements(sf.createName("Value", "", MDD_URI)); if (valueElements.hasNext()) { SOAPElement valueElement = (SOAPElement) valueElements.next(); String valueType = valueElement.getAttribute("xsi:type"); if (valueType.equals("xsd:int")) { value = Long.valueOf(valueElement.getValue()); } else if ( valueType.equals("xsd:double") || valueType.equals("xsd:decimal") ) { value = Double.valueOf(valueElement.getValue()); } else { value = valueElement.getValue(); } } String fmtValue = ""; Iterator<?> fmtValueElements = cellElement.getChildElements(sf.createName("FmtValue", "", MDD_URI)); if (fmtValueElements.hasNext()) { SOAPElement fmtValueElement = ((SOAPElement) fmtValueElements.next()); fmtValue = fmtValueElement.getValue(); } int pos = Integer.parseInt(cellOrdinal); JRXmlaCell cell = new JRXmlaCell(value, fmtValue); xmlaResult.setCell(cell, pos); } } protected void handleCellErrors(Iterator<?> errorElems) throws SOAPException { SOAPElement errorElem = (SOAPElement) errorElems.next(); StringBuilder errorMsg = new StringBuilder(); errorMsg.append("Cell error: "); Iterator<?> descriptionElems = errorElem.getChildElements(sf.createName("Description", "", MDD_URI)); if (descriptionElems.hasNext()) { SOAPElement descrElem = (SOAPElement) descriptionElems.next(); errorMsg.append(descrElem.getValue()); errorMsg.append("; "); } Iterator<?> sourceElems = errorElem.getChildElements(sf.createName("Source", "", MDD_URI)); if (sourceElems.hasNext()) { SOAPElement sourceElem = (SOAPElement) sourceElems.next(); errorMsg.append("Source: "); errorMsg.append(sourceElem.getValue()); errorMsg.append("; "); } Iterator<?> codeElems = errorElem.getChildElements(sf.createName("ErrorCode", "", MDD_URI)); if (codeElems.hasNext()) { SOAPElement codeElem = (SOAPElement) codeElems.next(); errorMsg.append("Code: "); errorMsg.append(codeElem.getValue()); errorMsg.append("; "); } throw new JRRuntimeException(errorMsg.toString()); } protected void handleHierInfo(JRXmlaResultAxis axis, SOAPElement hierInfoElement) throws SOAPException { Name name = sf.createName("name"); String dimName = hierInfoElement.getAttributeValue(name); // Get the Dimension Name if (log.isDebugEnabled()) { log.debug("Adding hierarchy: " + dimName); } JRXmlaHierarchy hier = new JRXmlaHierarchy(dimName); axis.addHierarchy(hier); } protected void handleTuplesElement(JRXmlaResultAxis axis, SOAPElement tuplesElement) throws SOAPException { Name tName = sf.createName("Tuple", "", MDD_URI); for (Iterator<?> itTuple = tuplesElement.getChildElements(tName); itTuple.hasNext();) { SOAPElement eTuple = (SOAPElement) itTuple.next(); handleTupleElement(axis, eTuple); } } protected void handleTupleElement(JRXmlaResultAxis axis, SOAPElement tupleElement) throws SOAPException { JRXmlaMemberTuple tuple = new JRXmlaMemberTuple(axis.getHierarchiesOnAxis().length); Name memName = sf.createName("Member", "", MDD_URI); Iterator<?> itMember = tupleElement.getChildElements(memName); int memNum = 0; while (itMember.hasNext()) { SOAPElement memElement = (SOAPElement) itMember.next(); Name name = sf.createName("Hierarchy", "", ""); String hierName = memElement.getAttributeValue(name); String uName = ""; Iterator<?> uNameElements = memElement.getChildElements(sf.createName("UName", "", MDD_URI)); if (uNameElements.hasNext()) { uName = ((SOAPElement) uNameElements.next()).getValue(); } String caption = ""; Iterator<?> captionElements = memElement.getChildElements(sf.createName("Caption", "", MDD_URI)); if (captionElements.hasNext()) { caption = ((SOAPElement) captionElements.next()).getValue(); } String lName = ""; Iterator<?> lNameElements = memElement.getChildElements(sf.createName("LName", "", MDD_URI)); if (lNameElements.hasNext()) { String levelUniqueName = ((SOAPElement) lNameElements.next()).getValue(); Matcher matcher = LEVEL_UNIQUE_NAME_PATTERN.matcher(levelUniqueName); if (matcher.matches()) { lName = matcher.group(LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP); } else { matcher = HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN.matcher(levelUniqueName); if (matcher.matches()) { lName = matcher.group(HIERARCHY_LEVEL_UNIQUE_NAME_PATTERN_NAME_GROUP); } else { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_XMLA_NO_LEVEL_NAME, new Object[]{levelUniqueName}); } } } int lNum = 0; Iterator<?> lNumElements = memElement.getChildElements(sf.createName("LNum", "", MDD_URI)); if (lNumElements.hasNext()) { lNum = Integer.parseInt(((SOAPElement) lNumElements.next()).getValue()); } JRXmlaMember member = new JRXmlaMember(caption, uName, hierName, lName, lNum); if (log.isDebugEnabled()) { log.debug("Adding member: axis - " + axis.getAxisName() + " hierName - " + hierName + " lName - " + lName + " uName - " + uName); } tuple.setMember(memNum++, member); } axis.addTuple(tuple); } protected String prettyPrintSOAP(SOAPElement element) { final StringWriter sw = new StringWriter(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform( new DOMSource(element), new StreamResult(sw)); } catch (TransformerException e) { throw new JRRuntimeException(e); } return sw.toString(); } }
75990_3
package WortTrainer3; import java.util.Arrays; public class WortListe { private WortEintrag[] worteintrag = new WortEintrag[1]; /** * Constructor * @param we einen WortEintrag der platz 0 im array einnimmt, * @param size größe des arrays */ public WortListe() { WortEintrag wort = new WortEintrag("Wort", "https://wort.at"); worteintrag[0] = wort; } /** * Fuegt ein Wort zum array hinzu * @param we worteintrag * @return */ public void addWort(String wort, String url) { // Macht eine Kopie die um eins größer ist als das vorige WortEintrag[] temp = Arrays.copyOf(worteintrag, worteintrag.length + 1); worteintrag = temp; for(int i = 0; i < this.worteintrag.length; i++) { if(worteintrag[i] == null) { WortEintrag worteintrag = new WortEintrag(wort, url); temp[i] = worteintrag; break; } } } /** * get objekt worteintrag aus dem array * @param index * @return */ public WortEintrag getWortEintrag(int index) { if(index > this.worteintrag.length || index < 0) { throw new IllegalArgumentException("Der übergebene Index existiert nicht"); } return this.worteintrag[index]; } /** * Löscht ein Wort aus dem Array * @param wort das übergebene Wort * @return ob es funktioniert hat oder nicht */ public boolean loeschWortEintrag(String wort) { if(wort.length() >= 2) { for(int i = 0; i < this.worteintrag.length;i++) { if(this.worteintrag[i] != null && this.worteintrag[i].getWort().equals(wort)) { this.worteintrag[i] = null; return true; } } } else { throw new IllegalArgumentException("Das Wort muss mehr als 2 zeichen haben"); } return false; } /** * Alle Worteinträge aus dem Array werden ausgegeben */ @Override public String toString() { String s = ""; for(int i = 0; i < this.worteintrag.length;i++) { if(this.worteintrag[i] != null) { s += this.worteintrag[i].toString(); if(i < this.worteintrag.length - 1) { s += "\n"; } } } return s; } /** * Gibt die Länge vom array zurück * @return länge vom array */ public int getLength() { return worteintrag.length; } }
ayildirim-tgm/WortTrainer3
WortListe.java
787
/** * get objekt worteintrag aus dem array * @param index * @return */
block_comment
nl
package WortTrainer3; import java.util.Arrays; public class WortListe { private WortEintrag[] worteintrag = new WortEintrag[1]; /** * Constructor * @param we einen WortEintrag der platz 0 im array einnimmt, * @param size größe des arrays */ public WortListe() { WortEintrag wort = new WortEintrag("Wort", "https://wort.at"); worteintrag[0] = wort; } /** * Fuegt ein Wort zum array hinzu * @param we worteintrag * @return */ public void addWort(String wort, String url) { // Macht eine Kopie die um eins größer ist als das vorige WortEintrag[] temp = Arrays.copyOf(worteintrag, worteintrag.length + 1); worteintrag = temp; for(int i = 0; i < this.worteintrag.length; i++) { if(worteintrag[i] == null) { WortEintrag worteintrag = new WortEintrag(wort, url); temp[i] = worteintrag; break; } } } /** * get objekt worteintrag<SUF>*/ public WortEintrag getWortEintrag(int index) { if(index > this.worteintrag.length || index < 0) { throw new IllegalArgumentException("Der übergebene Index existiert nicht"); } return this.worteintrag[index]; } /** * Löscht ein Wort aus dem Array * @param wort das übergebene Wort * @return ob es funktioniert hat oder nicht */ public boolean loeschWortEintrag(String wort) { if(wort.length() >= 2) { for(int i = 0; i < this.worteintrag.length;i++) { if(this.worteintrag[i] != null && this.worteintrag[i].getWort().equals(wort)) { this.worteintrag[i] = null; return true; } } } else { throw new IllegalArgumentException("Das Wort muss mehr als 2 zeichen haben"); } return false; } /** * Alle Worteinträge aus dem Array werden ausgegeben */ @Override public String toString() { String s = ""; for(int i = 0; i < this.worteintrag.length;i++) { if(this.worteintrag[i] != null) { s += this.worteintrag[i].toString(); if(i < this.worteintrag.length - 1) { s += "\n"; } } } return s; } /** * Gibt die Länge vom array zurück * @return länge vom array */ public int getLength() { return worteintrag.length; } }