file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
TieBreaker.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/TieBreaker.java
package dk.aau.cs.ds306e18.tournament.model; import dk.aau.cs.ds306e18.tournament.model.format.Format; import dk.aau.cs.ds306e18.tournament.model.stats.Stats; import java.util.ArrayList; import java.util.List; import java.util.Map; public enum TieBreaker { // Goal diff -> goals scored -> seed GOAL_DIFF("Goal difference", (A, B, format) -> { Stats stataA = format == null ? A.getStatsManager().getGlobalStats() : A.getStatsManager().getStats(format); Stats statsB = format == null ? B.getStatsManager().getGlobalStats() : B.getStatsManager().getStats(format); int comparison = Integer.compare(stataA.getGoalDifference(), statsB.getGoalDifference()); if (comparison == 0) { // Goal diff is same, use goals scored comparison = Integer.compare(stataA.getGoals(), statsB.getGoals()); if (comparison == 0) { // Goals scores is same, use seed comparison = Integer.compare(B.getInitialSeedValue(), A.getInitialSeedValue()); } } return comparison; }), // Goals scored -> seed GOALS_SCORED("Goals scored", (A, B, format) -> { Stats stataA = format == null ? A.getStatsManager().getGlobalStats() : A.getStatsManager().getStats(format); Stats statsB = format == null ? B.getStatsManager().getGlobalStats() : B.getStatsManager().getStats(format); int comparison = Integer.compare(stataA.getGoals(), statsB.getGoals()); if (comparison == 0) { // Goals scores is same, use seed comparison = Integer.compare(B.getInitialSeedValue(), A.getInitialSeedValue()); } return comparison; }), SEED("By seed", (A, B, format) -> { return Integer.compare(B.getInitialSeedValue(), A.getInitialSeedValue()); }) ; private interface TieBreakerFunction { /** Should return 1 if team A wins, -1 if team B wins, and preferable never 0. The comparison will use stats * from the given stage/format. If format is null, global stats are used. */ int compare(Team A, Team B, Format format); } private final String uiName; private final TieBreakerFunction compareFunction; TieBreaker(String uiName, TieBreakerFunction compareFunction) { this.uiName = uiName; this.compareFunction = compareFunction; } /** * Compares the teams in a list and returns a new list where the teams has been sorted based on the tiebreaker. * Stats are taken from the given format. If format is null, global stats are used instead. */ public List<Team> compareAll(List<Team> teams, Format format) { ArrayList<Team> sorted = new ArrayList<>(teams); sorted.sort((a, b) -> a == b ? 0 : compare(a, b, format) ? -1 : 1); return sorted; } /** * Returns a list of teams sorted by their points, and if two teams' points are equal, this tiebreaker has been used * to determine the better team of the two. Stats are taken from the given format. If format is null, * global stats are used instead. */ public List<Team> compareWithPoints(List<Team> teams, Map<Team, Integer> pointsMap, Format format) { List<Team> sorted = new ArrayList<>(teams); sorted.sort((a, b) -> { if (a == b) return 0; int comparison = Integer.compare(pointsMap.get(b), pointsMap.get(a)); if (comparison == 0) { return compare(a, b, format) ? -1 : 1; } return comparison; }); return sorted; } @Override public String toString() { return uiName; } /** * Returns true if teamA wins over teamB in the tie breaker. Stats are taken from the given format. If format is * null, global stats are used instead. */ public boolean compare(Team teamA, Team teamB, Format format) { int comparison = compareFunction.compare(teamA, teamB, format); if (comparison == 0) { // Tie breaking was somehow not enough, use hash as last option comparison = Integer.compare(teamA.hashCode(), teamB.hashCode()); } return comparison > 0; } }
4,356
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
PsyonixBotFromConfig.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/PsyonixBotFromConfig.java
package dk.aau.cs.ds306e18.tournament.model; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotSkill; import dk.aau.cs.ds306e18.tournament.rlbot.configuration.BotType; public class PsyonixBotFromConfig extends BotFromConfig { private BotSkill skill; public PsyonixBotFromConfig(String pathToConfig, BotSkill skill) { super(pathToConfig); this.skill = skill; } @Override public BotType getBotType() { return BotType.PSYONIX; } @Override public BotSkill getBotSkill() { return skill; } }
570
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Series.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/match/Series.java
package dk.aau.cs.ds306e18.tournament.model.match; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.utility.ListExt; import java.util.*; import java.util.function.Consumer; /** * <p>A Series of matches between two teams. Teams might be temporarily unknown as they are winner or loser of * other Series. The method {@code isReadyToPlay()} returns true, when both teams are is known and ready.</p> * <p>When the Series get marked as has been played, and it is possible to retrieve * the winner and the loser.</p> */ public final class Series { public enum Status { NOT_PLAYABLE, READY_TO_BE_PLAYED, HAS_BEEN_PLAYED } public enum Outcome { UNKNOWN, TEAM_ONE_WINS, TEAM_TWO_WINS, DRAW } private static int nextId = 0; private final int id; private int identifier = 0; /** For longer series, e.g. best of 3 */ private int length = 1; private List<Optional<Integer>> teamOneScores = new ArrayList<>(Collections.singletonList(Optional.empty())); private List<Optional<Integer>> teamTwoScores = new ArrayList<>(Collections.singletonList(Optional.empty())); private boolean played = false; private Team teamOne, teamTwo; private boolean teamOneIsBlue = true; transient private Series teamOneFromSeries, teamTwoFromSeries; private boolean teamOneWasWinnerInPreviousMatch, teamTwoWasWinnerInPreviousMatch; transient private Series winnerDestination, loserDestination; private boolean winnerGoesToTeamOne, loserGoesToTeamOne; transient private List<MatchPlayedListener> playedListeners = new LinkedList<>(); transient private List<MatchChangeListener> changeListeners = new LinkedList<>(); /** * Construct an empty Series. */ public Series() { id = nextId++; } /** * Construct an empty Series with a given length. */ public Series(int length) { id = nextId++; setSeriesLength(length, false); } /** * Construct a Series where both Teams are known from the start. */ public Series(Team teamOne, Team teamTwo) { id = nextId++; this.teamOne = teamOne; this.teamTwo = teamTwo; } /** * Construct a Series with a given length where both Teams are known from the start. */ public Series(int length, Team teamOne, Team teamTwo) { id = nextId++; setSeriesLength(length, false); this.teamOne = teamOne; this.teamTwo = teamTwo; } /** Set the identifier. The match is referenced to by that identifier. E.g. "Winner of 5", where 5 is the identifier. */ public void setIdentifier(int identifier) { this.identifier = identifier; notifyMatchChangeListeners(); } /** Get the identifier. The match is referenced to by that identifier. E.g. "Winner of 5", where 5 is the identifier. */ public int getIdentifier() { return identifier; } /** * Set team one of this Match. Returns the Match itself, which allows chaining. */ public Series setTeamOne(Team one) { if (played) throw new IllegalStateException("Match has already been played."); if (teamOneFromSeries != null) { // Remove connection to the fromMatch if (teamOneWasWinnerInPreviousMatch) setTeamOneToWinnerOf(null); else setTeamOneToLoserOf(null); } teamOne = one; notifyMatchChangeListeners(); return this; } /** * Set team two of this Match. Returns the Match itself, which allows chaining. */ public Series setTeamTwo(Team two) { if (played) throw new IllegalStateException("Match has already been played."); if (teamTwoFromSeries != null) { // Remove connection to the fromMatch if (teamTwoWasWinnerInPreviousMatch) setTeamTwoToWinnerOf(null); else setTeamTwoToLoserOf(null); } teamTwo = two; notifyMatchChangeListeners(); return this; } /** * Set team one of this Match to use the winner of another Match. Any previous connection or definition of * team one will be removed. Returns the Match itself, which allows chaining. */ public Series setTeamOneToWinnerOf(Series series) { if (played) throw new IllegalStateException("Match has already been played."); if (series == this) throw new IllegalArgumentException("A match can not have a connection to itself."); if (teamOneFromSeries != null) { // This match no longer wants anything from the previous fromMatch if (teamOneWasWinnerInPreviousMatch) teamOneFromSeries.winnerDestination = null; else teamOneFromSeries.loserDestination = null; } if (series == null) { // Remove any connection teamOneFromSeries = null; teamOne = null; } else { // Assumption: winners can only go to one match. So we check if the winner currently goes somewhere else // and removes that connection if (series.winnerDestination != null) { if (series.winnerGoesToTeamOne) series.winnerDestination.setTeamOneToWinnerOf(null); else series.winnerDestination.setTeamTwoToWinnerOf(null); } // Add new connection teamOneFromSeries = series; teamOneWasWinnerInPreviousMatch = true; series.winnerDestination = this; series.winnerGoesToTeamOne = true; if (series.hasBeenPlayed()) teamOne = series.getWinner(); else teamOne = null; series.notifyMatchChangeListeners(); } notifyMatchChangeListeners(); return this; } /** * Set team one of this Match to use the loser of another Match. Any previous connection or definition of * the team one will be removed. Returns the Match itself, which allows chaining. */ public Series setTeamOneToLoserOf(Series series) { if (played) throw new IllegalStateException("Match has already been played."); if (series == this) throw new IllegalArgumentException("A match can not have a connection to itself."); if (teamOneFromSeries != null) { // This match no longer wants anything from the previous fromMatch if (teamOneWasWinnerInPreviousMatch) teamOneFromSeries.winnerDestination = null; else teamOneFromSeries.loserDestination = null; } if (series == null) { // Remove any connection teamOneFromSeries = null; teamOne = null; } else { // Assumption: losers can only go to one match. So we check if the loser currently goes somewhere else // and removes that connection if (series.loserDestination != null) { if (series.loserGoesToTeamOne) series.loserDestination.setTeamOneToLoserOf(null); else series.loserDestination.setTeamTwoToLoserOf(null); } // Add new connection teamOneFromSeries = series; teamOneWasWinnerInPreviousMatch = false; series.loserDestination = this; series.loserGoesToTeamOne = true; if (series.hasBeenPlayed()) teamOne = series.getLoser(); else teamOne = null; series.notifyMatchChangeListeners(); } notifyMatchChangeListeners(); return this; } /** * Set team two of this Match to use the winner of another Match. Any previous connection or definition of * team two will be removed. Returns the Match itself, which allows chaining. */ public Series setTeamTwoToWinnerOf(Series series) { if (played) throw new IllegalStateException("Match has already been played."); if (series == this) throw new IllegalArgumentException("A match can not have a connection to itself."); if (teamTwoFromSeries != null) { // This match no longer wants anything from the previous fromMatch if (teamTwoWasWinnerInPreviousMatch) teamTwoFromSeries.winnerDestination = null; else teamTwoFromSeries.loserDestination = null; } if (series == null) { // Remove any connection teamTwoFromSeries = null; teamTwo = null; } else { // Assumption: winners can only go to one match. So we check if the winner currently goes somewhere else // and removes that connection if (series.winnerDestination != null) { if (series.winnerGoesToTeamOne) series.winnerDestination.setTeamOneToWinnerOf(null); else series.winnerDestination.setTeamTwoToWinnerOf(null); } // Add new connection teamTwoFromSeries = series; teamTwoWasWinnerInPreviousMatch = true; series.winnerDestination = this; series.winnerGoesToTeamOne = false; if (series.hasBeenPlayed()) teamTwo = series.getWinner(); else teamTwo = null; series.notifyMatchChangeListeners(); } notifyMatchChangeListeners(); return this; } /** * Set team two of this Match to use the loser of another Match. Any previous connection or definition of * team two will be removed. Returns the Match itself, which allows chaining. */ public Series setTeamTwoToLoserOf(Series series) { if (played) throw new IllegalStateException("Match has already been played."); if (series == this) throw new IllegalArgumentException("A match can not have a connection to itself."); if (teamTwoFromSeries != null) { // This match no longer wants anything from the previous fromMatch if (teamTwoWasWinnerInPreviousMatch) teamTwoFromSeries.winnerDestination = null; else teamTwoFromSeries.loserDestination = null; } if (series == null) { // Remove any connection teamTwoFromSeries = null; teamTwo = null; } else { // Assumption: losers can only go to one match. So we check if the loser currently goes somewhere else // and removes that connection if (series.loserDestination != null) { if (series.loserGoesToTeamOne) series.loserDestination.setTeamOneToLoserOf(null); else series.loserDestination.setTeamTwoToLoserOf(null); } // Add new connection teamTwoFromSeries = series; teamTwoWasWinnerInPreviousMatch = false; series.loserDestination = this; series.loserGoesToTeamOne = false; if (series.hasBeenPlayed()) teamTwo = series.getLoser(); else teamTwo = null; series.notifyMatchChangeListeners(); } notifyMatchChangeListeners(); return this; } /** * Set team one of this Match to use the winner of another Match. This ignores any previous connections * and states. Use with caution. TODO: Serialize connections in a way that does not require a call to this function. */ public void reconnectTeamOneToWinnerOf(Series other) { teamOneFromSeries = other; teamOneWasWinnerInPreviousMatch = true; other.winnerDestination = this; other.winnerGoesToTeamOne = true; } /** * Set team one of this Match to use the loser of another Match. This ignores any previous connections * and states. Use with caution. TODO: Serialize connections in a way that does not require a call to this function. */ public void reconnectTeamOneToLoserOf(Series other) { teamOneFromSeries = other; teamOneWasWinnerInPreviousMatch = false; other.loserDestination = this; other.loserGoesToTeamOne = true; } /** * Set team two of this Match to use the winner of another Match. This ignores any previous connections * and states. Use with caution. TODO: Serialize connections in a way that does not require a call to this function. */ public void reconnectTeamTwoToWinnerOf(Series other) { teamTwoFromSeries = other; teamTwoWasWinnerInPreviousMatch = true; other.winnerDestination = this; other.winnerGoesToTeamOne = false; } /** * Set team two of this Match to use the loser of another Match. This ignores any previous connections * and states. Use with caution. TODO: Serialize connections in a way that does not require a call to this function. */ public void reconnectTeamTwoToLoserOf(Series other) { teamTwoFromSeries = other; teamTwoWasWinnerInPreviousMatch = false; other.loserDestination = this; other.loserGoesToTeamOne = false; } /** * Returns true when both Teams are known and ready, even if the Series has already been played. */ public boolean isReadyToPlay() { return teamOne != null && teamTwo != null; } public Team getWinner() { switch (getOutcome()) { case UNKNOWN: throw new IllegalStateException("Series has not been played."); case DRAW: throw new IllegalStateException("Series ended in draw."); case TEAM_ONE_WINS: return getTeamOne(); case TEAM_TWO_WINS: return getTeamTwo(); } return null; } public Team getLoser() { switch (getOutcome()) { case UNKNOWN: throw new IllegalStateException("Series has not been played."); case DRAW: throw new IllegalStateException("Series ended in draw."); case TEAM_ONE_WINS: return getTeamTwo(); case TEAM_TWO_WINS: return getTeamOne(); } return null; } /** Returns the status of the match; NOT_PLAYABLE, READY_TO_BE_PLAYED, or HAS_BEEN_PLAYED. See getOutcome for the outcome. */ public Status getStatus() { if (!isReadyToPlay()) { return Status.NOT_PLAYABLE; } else if (!played) { return Status.READY_TO_BE_PLAYED; } else { return Status.HAS_BEEN_PLAYED; } } /** Returns the outcome of the match; UNKNOWN, TEAM_ONE_WINS, or TEAM_TWO_WINS. See getStatus for the status. */ public Outcome getOutcome() { if (getStatus() != Status.HAS_BEEN_PLAYED) return Outcome.UNKNOWN; else return winnerIfScores(teamOneScores, teamTwoScores); } /** * Returns a list of all Matches that must be finished before this Match is playable, including itself. * The matches will be ordered after breadth-first search approach. If the order is reversed, the order will be * the logical order of playing the Matches, with the root as the last Match. */ public ArrayList<Series> getTreeAsListBFS() { // Breadth-first search can be performed using a queue LinkedList<Series> queue = new LinkedList<>(); ArrayList<Series> list = new ArrayList<>(); Set<Series> marked = new HashSet<>(); queue.add(this); marked.add(this); Consumer<Series> addFunction = (m) -> { if (m != null && !marked.contains(m)) { // We check if both parent matches are marked (or null) to be sure we create the correct order if ((m.winnerDestination == null || marked.contains(m.winnerDestination)) && (m.loserDestination == null || marked.contains(m.loserDestination))) { queue.add(m); marked.add(m); } } }; // Matches are polled from the queue until it is empty while (!queue.isEmpty()) { Series series = queue.poll(); list.add(series); // Enqueue child matches, if any // Team two is added first - this means the final order will be the reverse of the logical // order of playing matches addFunction.accept(series.teamTwoFromSeries); addFunction.accept(series.teamOneFromSeries); } return list; } /** * Returns a list of all Matches that must be finished before this Match is playable, including itself. * The Matches will be ordered after pre-order depth-first search approach. */ public ArrayList<Series> getTreeAsListDFS() { // Depth-first search can be performed using a stack LinkedList<Series> stack = new LinkedList<>(); ArrayList<Series> series = new ArrayList<>(); stack.push(this); // Matches are popped from the stack until it is empty while (!stack.isEmpty()) { Series serie = stack.pop(); series.add(serie); // Push child matches, if any if (serie.teamOneFromSeries != null) stack.push(serie.teamOneFromSeries); if (serie.teamTwoFromSeries != null) stack.push(serie.teamTwoFromSeries); } return series; } /** * Returns true if the other Match must be concluded before this match is playable. */ public boolean dependsOn(Series otherSeries) { if (this == otherSeries) return false; // If this match depends on the other match, this match must be a parent (or parent of a parent of a // parent ... ect) of the other match. // A queue contain all unchecked parent matches. LinkedList<Series> queue = new LinkedList<>(); queue.push(otherSeries); // Matches are polled from the queue until it is empty. // Depending on bracket structure some matches might be checked multiple times. while (!queue.isEmpty()) { Series series = queue.poll(); if (this == series) return true; // Enqueue parent matches, if any if (series.winnerDestination != null) queue.push(series.winnerDestination); if (series.loserDestination != null) queue.push(series.loserDestination); } return false; } /** * Change the Series length. Any current scores are kept. The Series length must be a positive odd number. * This can change the the outcome of the match so a force reset of subsequent series might be needed. */ public void setSeriesLength(int length, boolean forceResetSubsequentSeries) { if (!hasAnyNonZeroScore()) { // We can do it directly without checking scores this.length = length; teamOneScores = ListExt.nOf(length, Optional::empty); teamTwoScores = ListExt.nOf(length, Optional::empty); notifyMatchChangeListeners(); } else { if (this.length > length) { // Series has been shortened setScores(length, teamOneScores.subList(0, length), teamTwoScores.subList(0, length), played, forceResetSubsequentSeries); } else { // Series has been extended List<Optional<Integer>> newTeamOneScores = new ArrayList<>(teamOneScores); List<Optional<Integer>> newTeamTwoScores = new ArrayList<>(teamTwoScores); int newMatchesCount = length - this.length; for (int i = 0; i < newMatchesCount; i++) { newTeamOneScores.add(Optional.empty()); newTeamTwoScores.add(Optional.empty()); } setScores(length, newTeamOneScores, newTeamTwoScores, false, forceResetSubsequentSeries); } } } public int getSeriesLength() { return length; } /** * @return the number of won matches needed to win this series. */ public int requiredNumberOfMatchesWonToWin() { return (int) Math.ceil(length * 0.5); } /** * @return the number of won matches needed to win a series with the given length. */ public static int requiredNumberOfMatchesWonToWin(int seriesLength) { return (int) Math.ceil(seriesLength * 0.5); } public void setHasBeenPlayed(boolean hasBeenPlayed) { setScores(length, teamOneScores, teamTwoScores, hasBeenPlayed, false); } public void setTeamOneScores(List<Optional<Integer>> teamOneScores) { setScores(length, teamOneScores, teamTwoScores, played, false); } public void setTeamTwoScores(List<Optional<Integer>> teamTwoScores) { setScores(length, teamOneScores, teamTwoScores, played, false); } /** * Set the score of the first match in the series which is still missing scores for both teams. If no such * match exists, an IllegalStateException is thrown. */ public void setScoresOfUnplayedMatch(int teamOneScore, int teamTwoScore) { int match = 0; for (; match < length; match++) { if (teamOneScores.get(match).isEmpty() && teamTwoScores.get(match).isEmpty()) { break; } } if (match >= length) throw new IllegalStateException("No match is missing scores for both teams"); setScores(teamOneScore, teamTwoScore, match); } /** * Set the scores of a particular match in the series. */ public void setScores(int teamOneScore, int teamTwoScore, int match) { setScores(Optional.of(teamOneScore), Optional.of(teamTwoScore), match); } /** * Set the scores of a particular match in the series. */ public void setScores(Optional<Integer> teamOneScore, Optional<Integer> teamTwoScore, int match) { if (match < 0 || match >= length) throw new IndexOutOfBoundsException("Invalid match index. Series has " + length + " matches"); List<Optional<Integer>> newTeamOneScores = new ArrayList<>(teamOneScores); List<Optional<Integer>> newTeamTwoScores = new ArrayList<>(teamTwoScores); newTeamOneScores.set(match, teamOneScore); newTeamTwoScores.set(match, teamTwoScore); setScores(newTeamOneScores, newTeamTwoScores); } public void setScores(List<Optional<Integer>> teamOneScores, List<Optional<Integer>> teamTwoScores) { setScores(length, teamOneScores, teamTwoScores, played, false); } public void setScores(List<Optional<Integer>> teamOneScores, List<Optional<Integer>> teamTwoScores, boolean hasBeenPlayed) { setScores(length, teamOneScores, teamTwoScores, hasBeenPlayed, false); } public void setScores(int seriesLength, List<Optional<Integer>> teamOneScores, List<Optional<Integer>> teamTwoScores, boolean hasBeenPlayed, boolean forceResetSubsequentSeries) { if (!isReadyToPlay()) throw new IllegalStateException("Match is not playable"); if (seriesLength <= 0) throw new IllegalArgumentException("Series length must be at least one."); if (seriesLength % 2 == 0) throw new IllegalArgumentException("Series must have an odd number of matches."); if (seriesLength != teamOneScores.size()) throw new IllegalArgumentException("Wrong number of team one scores (team one: " + teamOneScores.size() + ") given for a series of length " + seriesLength); if (seriesLength != teamTwoScores.size()) throw new IllegalArgumentException("Wrong number of team one scores (team one: " + teamTwoScores.size() + ") given for a series of length " + seriesLength); boolean outcomeChanging = willOutcomeChange(teamOneScores, teamTwoScores, hasBeenPlayed); if (outcomeChanging) { // Are there any subsequent matches that has been played? if ((winnerDestination != null && winnerDestination.hasAnyNonZeroScore()) || loserDestination != null && loserDestination.hasAnyNonZeroScore()) { // A subsequent match has scores that are not 0. We can only proceed with force if (forceResetSubsequentSeries) { if (winnerDestination != null) winnerDestination.forceReset(); if (loserDestination != null) loserDestination.forceReset(); } else { throw new MatchResultDependencyException(); } } } // Retract if there might be a new winner/loser if (played && outcomeChanging) { retractWinnerAndLoser(); } // Apply changes length = seriesLength; played = hasBeenPlayed; this.teamOneScores = teamOneScores; this.teamTwoScores = teamTwoScores; // Transfer because there might be a new winner/loser if (played && outcomeChanging) { transferWinnerAndLoser(); } notifyMatchChangeListeners(); notifyMatchPlayedListeners(); } /** * @return true if any of the matches scores are neither missing or 0 */ public boolean hasAnyNonZeroScore() { for (int i = 0; i < length; i++) { Optional<Integer> teamOneScore = teamOneScores.get(i); Optional<Integer> teamTwoScore = teamOneScores.get(i); if (teamOneScore.isPresent() && teamOneScore.get() != 0) return true; if (teamTwoScore.isPresent() && teamTwoScore.get() != 0) return true; } return false; } /** * Change all matches' result to be 0-0 and the series to be not played. If any series that depends on this * series, those will also be reset. */ public void forceReset() { setScores(length, ListExt.nOf(length, Optional::empty), ListExt.nOf(length, Optional::empty), false, true); } /** * Sets scores of all matches in the series to 0-0. The number of matches (length of the series) remain the same. * This is not possible if any match depends on it and in that case a MatchResultDependencyException is thrown. */ public void softReset() { setScores(length, ListExt.nOf(length, Optional::empty), ListExt.nOf(length, Optional::empty), false, false); } /** Returns true if the outcome and thus the state of this match change, if it had the given score instead. */ public boolean willOutcomeChange(List<Optional<Integer>> altTeamOneScores, List<Optional<Integer>> altTeamTwoScores, boolean altHasBeenPlayed) { if (this.played != altHasBeenPlayed) { return true; } // Was not played before, and is not played now. In this case we don't care about score. Nothing changes if (!altHasBeenPlayed) { return false; } // Check if winner stays the same Outcome currentOutcome = winnerIfScores(teamOneScores, teamTwoScores); Outcome altOutcome = winnerIfScores(altTeamOneScores, altTeamTwoScores); return currentOutcome != altOutcome; } /** * Returns the outcome of the series if the given scores were the scores of the series and assuming the series * has been played an is over. Draws are possible. */ public static Outcome winnerIfScores(List<Optional<Integer>> teamOneScores, List<Optional<Integer>> teamTwoScores) { if (teamOneScores.size() != teamTwoScores.size()) throw new IllegalArgumentException("Not the same amout of scores"); // Count wins int oneWins = 0; int twoWins = 0; int unknown = 0; for (int i = 0; i < teamOneScores.size(); i++) { if (!teamOneScores.get(i).isPresent() || !teamTwoScores.get(i).isPresent()) unknown++; else if (teamOneScores.get(i).get() > teamTwoScores.get(i).get()) oneWins++; else if (teamOneScores.get(i).get() < teamTwoScores.get(i).get()) twoWins++; } int req = requiredNumberOfMatchesWonToWin(teamOneScores.size()); if (oneWins == twoWins && unknown == 0) return Outcome.DRAW; if (oneWins < req && twoWins < req) return Outcome.UNKNOWN; if (oneWins > twoWins) return Outcome.TEAM_ONE_WINS; if (oneWins < twoWins) return Outcome.TEAM_TWO_WINS; return Outcome.DRAW; } /** * Let the following matches know, that the winner or loser now found. */ private void transferWinnerAndLoser() { if (winnerDestination != null) { if (winnerDestination.isReadyToPlay()) winnerDestination.softReset(); // There can be leftover scores if (winnerGoesToTeamOne) winnerDestination.teamOne = getWinner(); else winnerDestination.teamTwo = getWinner(); winnerDestination.notifyMatchChangeListeners(); } if (loserDestination != null) { if (loserDestination.isReadyToPlay()) loserDestination.softReset(); // There can be leftover scores if (loserGoesToTeamOne) loserDestination.teamOne = getLoser(); else loserDestination.teamTwo = getLoser(); loserDestination.notifyMatchChangeListeners(); } } /** * Let the following matches know, that the winner or loser is no longer defined. */ private void retractWinnerAndLoser() { if (winnerDestination != null) { if (winnerDestination.isReadyToPlay()) winnerDestination.softReset(); // There can be leftover scores if (winnerGoesToTeamOne) winnerDestination.teamOne = null; else winnerDestination.teamTwo = null; winnerDestination.notifyMatchChangeListeners(); } if (loserDestination != null) { if (loserDestination.isReadyToPlay()) loserDestination.softReset(); // There can be leftover scores if (loserGoesToTeamOne) loserDestination.teamOne = null; else loserDestination.teamTwo = null; loserDestination.notifyMatchChangeListeners(); } } /** * Returns true if the match is currently playable and both teams consists of one bot. */ public boolean isOneVsOne() { return (isReadyToPlay() && teamOne.size() == 1 && teamTwo.size() == 1); } public List<Optional<Integer>> getTeamOneScores() { return new ArrayList<>(teamOneScores); } public List<Optional<Integer>> getTeamTwoScores() { return new ArrayList<>(teamTwoScores); } public List<Optional<Integer>> getBlueScores() { return teamOneIsBlue ? getTeamOneScores() : getTeamTwoScores(); } public List<Optional<Integer>> getOrangeScores() { return teamOneIsBlue ? getTeamTwoScores() : getTeamOneScores(); } public Optional<Integer> getTeamOneScore(int matchIndex) { return teamOneScores.get(matchIndex); } public Optional<Integer> getTeamTwoScore(int matchIndex) { return teamTwoScores.get(matchIndex); } public Optional<Integer> getBlueScore(int matchIndex) { return teamOneIsBlue ? getTeamOneScore(matchIndex) : getTeamTwoScore(matchIndex); } public Optional<Integer> getOrangeScore(int matchIndex) { return teamOneIsBlue ? getTeamTwoScore(matchIndex) : getTeamOneScore(matchIndex); } public boolean hasBeenPlayed() { return played; } public boolean isTeamOneBlue() { return teamOneIsBlue; } public void setTeamOneToBlue(boolean teamOneIsBlue) { this.teamOneIsBlue = teamOneIsBlue; notifyMatchChangeListeners(); } /** * Returns team one or null if team one is unknown. */ public Team getTeamOne() { return teamOne; } /** * Returns team two or null if team two is unknown. */ public Team getTeamTwo() { return teamTwo; } /** * Returns blue team or null if blue team is unknown. */ public Team getBlueTeam() { return teamOneIsBlue ? getTeamOne() : getTeamTwo(); } /** * Returns orange team or null if orange team is unknown. */ public Team getOrangeTeam() { return teamOneIsBlue ? getTeamTwo() : getTeamOne(); } /** Returns team one's name. If team one is null, then "Winner/Loser of .." or "TBD" is returned. */ public String getTeamOneAsString() { if (teamOne == null) { if (teamOneFromSeries != null) { return (teamOneWasWinnerInPreviousMatch ? "Winner of " : "Loser of ") + teamOneFromSeries.getIdentifier(); } return "TBD"; } return teamOne.getTeamName(); } /** Returns team two's name. If team two is null, then "Winner/Loser of .." or "TBD" is returned. */ public String getTeamTwoAsString() { if (teamTwo == null) { if (teamTwoFromSeries != null) { return (teamTwoWasWinnerInPreviousMatch ? "Winner of " : "Loser of ") + teamTwoFromSeries.getIdentifier(); } return "TBD"; } return teamTwo.getTeamName(); } /** Returns the blue team's name. If blue team is null, then "Winner/Loser of .." or "TBD" is returned. */ public String getBlueTeamAsString() { return teamOneIsBlue ? getTeamOneAsString() : getTeamTwoAsString(); } /** Returns the orange team's name. If orange team is null, then "Winner/Loser of .." or "TBD" is returned. */ public String getOrangeTeamAsString() { return teamOneIsBlue ? getTeamTwoAsString() : getTeamOneAsString(); } public Series getTeamOneFromSeries() { return teamOneFromSeries; } public Series getTeamTwoFromSeries() { return teamTwoFromSeries; } public Series getWinnerDestination() { return winnerDestination; } public Series getLoserDestination() { return loserDestination; } public boolean wasTeamOneWinnerInPreviousMatch() { return teamOneWasWinnerInPreviousMatch; } public boolean wasTeamTwoWinnerInPreviousMatch() { return teamTwoWasWinnerInPreviousMatch; } public boolean doesWinnerGoToTeamOne() { return winnerGoesToTeamOne; } public boolean doesLoserGoToTeamOne() { return loserGoesToTeamOne; } /** Listeners registered here will be notified when the match is played or reset. */ public void registerMatchPlayedListener(MatchPlayedListener listener) { playedListeners.add(listener); } public void unregisterMatchPlayedListener(MatchPlayedListener listener) { playedListeners.remove(listener); } protected void notifyMatchPlayedListeners() { for (MatchPlayedListener listener : playedListeners) { listener.onMatchPlayed(this); } } /** Listeners registered here will be notified when any value in the match changes. */ public void registerMatchChangeListener(MatchChangeListener listener) { changeListeners.add(listener); } public void unregisterMatchChangeListener(MatchChangeListener listener) { changeListeners.remove(listener); } protected void notifyMatchChangeListeners() { for (MatchChangeListener listener : changeListeners) { listener.onMatchChanged(this); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Series series = (Series) o; return id == series.id && getTeamOneScores().equals(series.getTeamOneScores()) && getTeamTwoScores().equals(series.getTeamTwoScores()) && played == series.played && teamOneIsBlue == series.teamOneIsBlue && teamOneWasWinnerInPreviousMatch == series.teamOneWasWinnerInPreviousMatch && teamTwoWasWinnerInPreviousMatch == series.teamTwoWasWinnerInPreviousMatch && winnerGoesToTeamOne == series.winnerGoesToTeamOne && loserGoesToTeamOne == series.loserGoesToTeamOne && Objects.equals(getTeamOne(), series.getTeamOne()) && Objects.equals(getTeamTwo(), series.getTeamTwo()); } @Override public int hashCode() { return Objects.hash(id, getTeamOneScores(), getTeamTwoScores(), played, teamOneIsBlue, getTeamOne(), getTeamTwo(), teamOneWasWinnerInPreviousMatch, teamTwoWasWinnerInPreviousMatch, winnerGoesToTeamOne, loserGoesToTeamOne); } @Override public String toString() { return "Match:{" + getTeamOneAsString() + " (" + teamOneScores + ") vs (" + teamTwoScores + ") " + getTeamTwoAsString() + ", status: " + getStatus() + "}"; } }
36,519
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MatchPlayedListener.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/match/MatchPlayedListener.java
package dk.aau.cs.ds306e18.tournament.model.match; public interface MatchPlayedListener { void onMatchPlayed(Series series); }
133
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MatchChangeListener.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/match/MatchChangeListener.java
package dk.aau.cs.ds306e18.tournament.model.match; public interface MatchChangeListener { void onMatchChanged(Series series); }
134
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
MatchResultDependencyException.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/match/MatchResultDependencyException.java
package dk.aau.cs.ds306e18.tournament.model.match; /** Thrown to indicate that a match result cannot change because a subsequent match depends on it. */ public class MatchResultDependencyException extends RuntimeException { @Override public String getMessage() { return "Could not change result. A subsequent match depends on current outcome."; } }
371
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StatsTracker.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/stats/StatsTracker.java
package dk.aau.cs.ds306e18.tournament.model.stats; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.match.MatchChangeListener; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * This class tracks the stats (wins, loses, goals, etc) for a single team over a set of series. The class uses the * MatchChangeListener interface to get updates about new stats. */ class StatsTracker implements MatchChangeListener { private Team team; private Stats stats; private Set<Series> trackedSeries = new HashSet<>(); /** * Create a Stats object to track stats for the given team. * @param team the team to track stats for. */ public StatsTracker(Team team) { this.team = team; stats = new Stats(team); } /** * Recalculates the stats by check each tracked series. StatsChangeListeners are notified afterwards. */ public void recalculate() { int wins = 0; int loses = 0; int goals = 0; int goalsConceded = 0; for (Series series : trackedSeries) { // If the team is in the series, add the relevant stats if (series.getTeamOne() == team) { goals += series.getTeamOneScores().stream().mapToInt(x -> x.orElse(0)).sum(); goalsConceded += series.getTeamTwoScores().stream().mapToInt(x -> x.orElse(0)).sum(); if (series.hasBeenPlayed()) { if (series.getWinner() == team) { wins++; } else { loses++; } } } else if (series.getTeamTwo() == team) { goals += series.getTeamTwoScores().stream().mapToInt(x -> x.orElse(0)).sum(); goalsConceded += series.getTeamOneScores().stream().mapToInt(x -> x.orElse(0)).sum(); if (series.hasBeenPlayed()) { if (series.getWinner() == team) { wins++; } else { loses++; } } } } stats.set(wins, loses, goals, goalsConceded); } /** * Returns a set of all the tracked series. Changes to the set does not affect the Stats. */ public Set<Series> getTrackedSeries() { return new HashSet<>(trackedSeries); } /** * Remove all tracked matches and essentially resets the stats. StatsChangeListeners are notified. */ public void clearTrackedMatches() { trackedSeries.clear(); recalculate(); } /** * Starts tracking stats from the given series. The associated team does not need to be a participant of the * given series. StatsChangeListeners are notified. * @param series a series to track stats from */ public void trackSeries(Series series) { trackedSeries.add(series); series.registerMatchChangeListener(this); recalculate(); } /** * Stops tracking stats from the given series. StatsChangeListeners are notified. * @param series a series to stop tracking stats from */ public void untrackSeries(Series series) { trackedSeries.remove(series); series.unregisterMatchChangeListener(this); recalculate(); } /** * Starts tracking stats from the given series. The associated team does not need to be a participant of the * given matches. StatsChangeListeners are notified. * @param matches a collection of series to track stats from. */ public void trackAllSeries(Collection<? extends Series> matches) { for (Series series : matches) { trackedSeries.add(series); series.registerMatchChangeListener(this); } recalculate(); } /** * Stops tracking stats from the given series. StatsChangeListeners are notified. * @param matches a collection of series to stop tracking stats from. */ public void untrackAllSeries(Collection<? extends Series> matches) { for (Series series : matches) { trackedSeries.remove(series); series.unregisterMatchChangeListener(this); } recalculate(); } @Override public void onMatchChanged(Series series) { recalculate(); } public Team getTeam() { return team; } public Stats getStats() { return stats; } }
4,577
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StatsChangeListener.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/stats/StatsChangeListener.java
package dk.aau.cs.ds306e18.tournament.model.stats; /** * StatsChangeListener can be notified when a Stats object changes, for instance when a tracked match changes or * when a new match is tracked or when a match is no longer tracked, thus potentially changing the stats. */ public interface StatsChangeListener { void statsChanged(Stats stats); }
357
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StatsManager.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/stats/StatsManager.java
package dk.aau.cs.ds306e18.tournament.model.stats; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.format.Format; import dk.aau.cs.ds306e18.tournament.model.match.Series; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Map; /** * Class for tracking all stats for a Team for individual Stages and globally across all Stages. */ public class StatsManager implements StatsChangeListener { private Team team; private StatsTracker globalStatsTracker; private Map<Format, StatsTracker> formatStats = new IdentityHashMap<>(); /** * Create a StatsManager for the given team. */ public StatsManager(Team team) { this.team = team; globalStatsTracker = new StatsTracker(team); } /** * Returns the team's stats across all Stages. Register as a StatsChangeListener to be notified when these * stats updates. */ public Stats getGlobalStats() { return globalStatsTracker.getStats(); } /** * Returns the team's stats for the given format. Register as a StatsChangeListener to be notified when these * stats updates. */ public Stats getStats(Format format) { return getTracker(format).getStats(); } /** * Start tracking stats from the given series. */ public void trackSeries(Format format, Series series) { getTracker(format).trackSeries(series); recalculateGlobalStats(); } /** * Stop tracking stats from the given series. */ public void untrackSeries(Format format, Series series) { getTracker(format).untrackSeries(series); recalculateGlobalStats(); } /** * Start tracking stats from the given series. */ public void trackAllSeries(Format format, Collection<? extends Series> matches) { getTracker(format).trackAllSeries(matches); recalculateGlobalStats(); } /** * Stop tracking stats from the given series. */ public void untrackAllSeries(Format format, Collection<? extends Series> matches) { getTracker(format).untrackAllSeries(matches); recalculateGlobalStats(); } private StatsTracker getTracker(Format format) { return formatStats.computeIfAbsent(format, k -> { StatsTracker tracker = new StatsTracker(team); tracker.getStats().registerStatsChangeListener(this); return tracker; }); } /** * Recalculate the global stats. StatsChangeListeners for the global stats are notified. */ private void recalculateGlobalStats() { // Since all matches comes from a unique format, we just add the stats for each format to get the global stats. int wins = 0; int loses = 0; int goals = 0; int goalsConceded = 0; for (Format format : formatStats.keySet()) { Stats stats = getStats(format); wins += stats.getWins(); loses += stats.getLoses(); goals += stats.getGoals(); goalsConceded += stats.getGoalsConceded(); } globalStatsTracker.getStats().set(wins, loses, goals, goalsConceded); } @Override public void statsChanged(Stats stats) { recalculateGlobalStats(); } }
3,335
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Stats.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/stats/Stats.java
package dk.aau.cs.ds306e18.tournament.model.stats; import dk.aau.cs.ds306e18.tournament.model.Team; import java.util.HashSet; import java.util.Set; /** * This class holds the stats (wins, loses, goals, etc) for a single team. It provides an observer pattern * with StatsChangeListener and notifies listeners whenever there are potential stats changes. */ public class Stats { private Team team; private int wins = 0; private int loses = 0; private int goals = 0; private int goalsConceded = 0; private Set<StatsChangeListener> statsChangeListeners = new HashSet<>(); /** * Create a Stats object to track stats for the given team. * @param team the team to track stats for. */ public Stats(Team team) { this.team = team; } /** * Sets the stats. Should only be called by StatsTracker. StatsChangeListeners are notified. */ void set(int wins, int loses, int goals, int goalsConceded) { this.wins = wins; this.loses = loses; this.goals = goals; this.goalsConceded = goalsConceded; notifyStatsChangeListeners(); } /** * Listeners registered will be notified when the stats changes, for instance when a tracked match changes or * when a new match tracked or a match is no longer tracked, thus potentially changing the stats. */ public void registerStatsChangeListener(StatsChangeListener listener) { statsChangeListeners.add(listener); } public void unregisterStatsChangeListener(StatsChangeListener listener) { statsChangeListeners.remove(listener); } private void notifyStatsChangeListeners() { for (StatsChangeListener listener : statsChangeListeners) { listener.statsChanged(this); } } public Team getTeam() { return team; } public int getWins() { return wins; } public int getLoses() { return loses; } public int getGoals() { return goals; } public int getGoalsConceded() { return goalsConceded; } public int getGoalDifference() { return goals - goalsConceded; } }
2,187
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StageStatusChangeListener.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/StageStatusChangeListener.java
package dk.aau.cs.ds306e18.tournament.model.format; public interface StageStatusChangeListener { void onStageStatusChanged(Format format, StageStatus oldStatus, StageStatus newStatus); }
193
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SingleEliminationFormat.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/SingleEliminationFormat.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.match.MatchPlayedListener; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.SingleEliminationNode; import javafx.scene.Node; import java.util.*; import java.util.stream.Collectors; import static dk.aau.cs.ds306e18.tournament.utility.PowMath.log2; import static dk.aau.cs.ds306e18.tournament.utility.PowMath.pow2; public class SingleEliminationFormat implements Format, MatchPlayedListener { private StageStatus status = StageStatus.PENDING; private int defaultSeriesLength = 1; private ArrayList<Team> seededTeams; private Series finalSeries; private Series[] bracket; private int rounds; transient private List<StageStatusChangeListener> statusChangeListeners = new LinkedList<>(); @Override public void start(List<Team> seededTeams, boolean doSeeding) { this.seededTeams = new ArrayList<>(seededTeams); rounds = log2(seededTeams.size()); generateBracket(); seedBracket(seededTeams, doSeeding); giveMatchesIdentifiers(); status = StageStatus.RUNNING; finalSeries.registerMatchPlayedListener(this); setupStatsTracking(); } /** Generates a single-elimination bracket structure. Matches are referenced by setting winner of from earlier matches. * Matches are accessed through finalMatch (the root) or the array upperBracketMatchesArray. */ private void generateBracket() { int matchesInFirstRound = pow2(rounds - 1); int numberOfMatches = pow2(rounds) - 1; bracket = new Series[numberOfMatches]; for(int i = numberOfMatches - 1; i >= 0; i--) { // Creates empty matches for first round if(i >= numberOfMatches - matchesInFirstRound) { bracket[i] = new Series(defaultSeriesLength); } // Creates the remaining matches which contains winners from their left- and right child-indexes. else { bracket[i] = new Series(defaultSeriesLength) .setTeamOneToWinnerOf(bracket[getLeftIndex(i)]) .setTeamTwoToWinnerOf(bracket[getRightIndex(i)]); } } finalSeries = bracket[0]; } /** Seeds the single-elimination bracket with teams to give better placements. * If there are an insufficient amount of teams, the team(s) with the best seeding(s) will be placed in the next round instead. * @param seededTeams a list containing the teams in the tournament * @param doSeeding whether or not to use seeding. If false, the reordering of teams is skipped. */ private void seedBracket(List<Team> seededTeams, boolean doSeeding) { List<Team> seedList = new ArrayList<>(seededTeams); //Create needed amount of byes to match with the empty matches ArrayList<Team> byeList = addByes(seededTeams.size()); seedList.addAll(byeList); if (doSeeding) { //Reorders list with fair seeding method seedList = Seeding.fairSeedList(seedList); } //Places the teams in the bracket, and removes unnecessary matches placeTeamsInBracket(seedList, byeList); } /** Places the teams in the bracket and removes unnecessary matches * @param seedList a list of seeded teams in a fair seeding order * @param byeList a list of dummy teams */ private void placeTeamsInBracket(List<Team> seedList, ArrayList<Team> byeList) { int seedMatchIndex = finalSeries.getTreeAsListBFS().size() - 1; int numberOfTeams = seedList.size(); for (int teamIndex = 0; teamIndex < numberOfTeams; teamIndex = teamIndex + 2) { // If the matchup would be between a team and a bye, the team will be placed at its parent match // The match in the first round will be deleted(null) if (byeList.contains(seedList.get(teamIndex)) || byeList.contains(seedList.get(teamIndex + 1))) { int matchCheckIndex = getParentIndex(seedMatchIndex); if (getLeftIndex(matchCheckIndex) == seedMatchIndex) { bracket[getParentIndex(seedMatchIndex)].setTeamOne(seedList.get(teamIndex)); } else { bracket[getParentIndex(seedMatchIndex)].setTeamTwo(seedList.get(teamIndex)); } bracket[seedMatchIndex] = null; seedMatchIndex--; } // If there are no byes in the match up, place the teams vs each other as intended else { bracket[seedMatchIndex].setTeamOne(seedList.get(teamIndex)); bracket[seedMatchIndex].setTeamTwo(seedList.get(teamIndex+1)); seedMatchIndex--; } } } /** Add the needed amount of byes * @param numberOfTeams the amount of teams in the stage * @return byeList, an arrayList containing dummy teams */ private ArrayList<Team> addByes(int numberOfTeams){ int numberOfByes = pow2(rounds) - numberOfTeams; ArrayList<Team> byeList = new ArrayList<>(); while (byeList.size() < numberOfByes) { byeList.add(new Team("bye" + byeList.size(), new ArrayList<>(), 999, "")); } return byeList; } /** Gives the matches identifiers. */ private void giveMatchesIdentifiers() { List<Series> treeAsListBFS = finalSeries.getTreeAsListBFS(); int index = 1; for (int i = treeAsListBFS.size() - 1; i >= 0; i--) { treeAsListBFS.get(i).setIdentifier(index++); } } private int getParentIndex(int i) { if (i == 0) { return -1; } else { return Math.floorDiv(i + 1, 2) - 1; } } private int getLeftIndex(int i){ return 2 * (i + 1); } private int getRightIndex(int i) { return 2 * (i + 1) - 1; } private void setupStatsTracking() { List<Series> allSeries = getAllSeries(); for (Team team : seededTeams) { team.getStatsManager().trackAllSeries(this, allSeries); } } public int getRounds() { return rounds; } @Override public StageStatus getStatus() { return status; } @Override public List<Series> getAllSeries() { return finalSeries.getTreeAsListBFS(); } @Override public List<Series> getUpcomingMatches() { return finalSeries.getTreeAsListBFS().stream().filter(c -> c.getStatus().equals(Series.Status.READY_TO_BE_PLAYED) && !c.hasBeenPlayed()).collect(Collectors.toList()); } @Override public List<Series> getPendingMatches() { return finalSeries.getTreeAsListBFS().stream().filter(c -> c.getStatus().equals(Series.Status.NOT_PLAYABLE)).collect(Collectors.toList()); } @Override public List<Series> getCompletedMatches() { return finalSeries.getTreeAsListBFS().stream().filter(Series::hasBeenPlayed).collect(Collectors.toList()); } public Series[] getMatchesAsArray() { return this.bracket; } @Override public void onMatchPlayed(Series series) { // Was it last match? StageStatus oldStatus = status; if (finalSeries.hasBeenPlayed()) { status = StageStatus.CONCLUDED; } else { status = StageStatus.RUNNING; } // Notify listeners if status changed if (oldStatus != status) { notifyStatusListeners(oldStatus, status); } } @Override public void registerStatusChangedListener(StageStatusChangeListener listener) { statusChangeListeners.add(listener); } @Override public void unregisterStatusChangedListener(StageStatusChangeListener listener) { statusChangeListeners.remove(listener); } /** Let listeners know, that the status has changed */ private void notifyStatusListeners(StageStatus oldStatus, StageStatus newStatus) { for (StageStatusChangeListener listener : statusChangeListeners) { listener.onStageStatusChanged(this, oldStatus, newStatus); } } /** Determines the teams with the best performances in the current stage * @param count amount of teams to return * @param tieBreaker a tiebreaker to decide the best teams if their are placed the same * @return a list containing the best placed teams in the tournament */ @Override public List<Team> getTopTeams(int count, TieBreaker tieBreaker) { List<Team> topTeams = new ArrayList<>(); List<Team> tempWinnerTeams = new ArrayList<>(); List<Team> tempLoserTeams = new ArrayList<>(); List<Series> matchesBFS = finalSeries.getTreeAsListBFS(); int numberOfMatches = matchesBFS.size(); int roundUpperBoundIndex = 1, currentMatchIndex = 0; if(count > seededTeams.size()){ count = seededTeams.size();} // Will run until enough teams has been found while (topTeams.size() < count) { // places the losers and winners of the round into two different temporary lists while (currentMatchIndex < roundUpperBoundIndex && currentMatchIndex < numberOfMatches) { Series current = matchesBFS.get(currentMatchIndex); if (!topTeams.contains(current.getWinner())) { tempWinnerTeams.add(current.getWinner()); } if (!topTeams.contains(current.getLoser())) { tempLoserTeams.add(current.getLoser()); } currentMatchIndex++; } // Sorts the teams accordingly to the tiebreaker if (tempWinnerTeams.size() > 1) { tempWinnerTeams = tieBreaker.compareAll(tempWinnerTeams, this); } if (tempLoserTeams.size() > 1) { tempLoserTeams = tieBreaker.compareAll(tempLoserTeams, this); } // Winners will be placed before the losers, and the lists will be cleared topTeams.addAll(tempWinnerTeams); tempWinnerTeams.clear(); topTeams.addAll(tempLoserTeams); tempLoserTeams.clear(); // New round for the loop to iterate roundUpperBoundIndex = getRightIndex(roundUpperBoundIndex); } // If there are too many teams, remove teams while (topTeams.size() > count) { topTeams.remove(topTeams.size() - 1); } return topTeams; } @Override public void setDefaultSeriesLength(int seriesLength) { if (seriesLength <= 0) throw new IllegalArgumentException("Series length must be at least one."); if (seriesLength % 2 == 0) throw new IllegalArgumentException("Series must have an odd number of matches."); defaultSeriesLength = seriesLength; } @Override public int getDefaultSeriesLength() { return defaultSeriesLength; } @Override public SingleEliminationNode getBracketFXNode(BracketOverviewTabController boc) { return new SingleEliminationNode(this, boc); } @Override public Node getSettingsFXNode() { return null; } /** Repairs match-structure after deserialization */ @Override public void postDeserializationRepair() { // Find final match this.finalSeries = this.bracket[0]; finalSeries.registerMatchPlayedListener(this); // Reconnect all matches for (int i = 0; i < bracket.length; i++) { if (bracket[i] != null) { // Blue is winner from left match, if such a match exists int leftIndex = getLeftIndex(i); if (leftIndex < bracket.length) { Series leftSeries = bracket[leftIndex]; if (leftSeries != null) { bracket[i].reconnectTeamOneToWinnerOf(leftSeries); } } // Orange is winner from right match, if such a match exists int rightIndex = getRightIndex(i); if (rightIndex < bracket.length) { Series rightSeries = bracket[rightIndex]; if (rightSeries != null) { bracket[i].reconnectTeamTwoToWinnerOf(rightSeries); } } } } setupStatsTracking(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SingleEliminationFormat that = (SingleEliminationFormat) o; return rounds == that.rounds && status == that.status && Objects.equals(seededTeams, that.seededTeams) && Objects.equals(finalSeries, that.finalSeries) && Arrays.equals(bracket, that.bracket); } @Override public int hashCode() { int result = Objects.hash(status, seededTeams, finalSeries, rounds); result = 31 * result + Arrays.hashCode(bracket); return result; } }
13,459
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Format.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/Format.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.ModelCoupledUI; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import javafx.scene.Node; import java.util.List; public interface Format { /** * Starts the stage with the given list of teams. The teams should seeded after the order in the list. */ void start(List<Team> seededTeams, boolean doSeeding); /** * Set the default series length (best of x) */ void setDefaultSeriesLength(int seriesLength); /** * Get the default series length (best of x) */ int getDefaultSeriesLength(); /** * Returns the status of the format. */ StageStatus getStatus(); /** * Returns a list of the teams that performed best this stage. They are sorted after performance, with best team first. */ List<Team> getTopTeams(int count, TieBreaker tieBreaker); /** * Returns a list of all the matches in this stage. */ List<Series> getAllSeries(); /** * Returns a list of all the matches that are ready to be played, but haven't played yet. */ List<Series> getUpcomingMatches(); /** * Returns a list of all planned matches, that can't be played yet. */ List<Series> getPendingMatches(); /** * Returns a list of all the matches that have been played. */ List<Series> getCompletedMatches(); /** * Listeners registered here will be notified when the status changes */ void registerStatusChangedListener(StageStatusChangeListener listener); void unregisterStatusChangedListener(StageStatusChangeListener listener); /** * Returns a Node of the stage. This node contains a reference to it self and other functionality to display the stage. */ <T extends Node & ModelCoupledUI> T getBracketFXNode(BracketOverviewTabController bracketOverview); /** * Returns a Node with the settings specific to this format. Can return null. */ Node getSettingsFXNode(); /** * Repairs structure of matches after deserialization. */ void postDeserializationRepair(); }
2,362
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
StageStatus.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/StageStatus.java
package dk.aau.cs.ds306e18.tournament.model.format; public enum StageStatus { PENDING, RUNNING, CONCLUDED }
113
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
RoundRobinGroup.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/RoundRobinGroup.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.match.Series; import java.util.ArrayList; import java.util.List; public class RoundRobinGroup { private ArrayList<Team> teams; private ArrayList<ArrayList<Series>> rounds; public RoundRobinGroup(List<Team> teams) { this.teams = new ArrayList<>(teams); } public void setRounds(ArrayList<ArrayList<Series>> round){ this.rounds = round; } public ArrayList<Team> getTeams() { return teams; } public ArrayList<Series> getMatches() { ArrayList<Series> series = new ArrayList<>(); for (ArrayList<Series> round : rounds) series.addAll(round); return series; } public ArrayList<ArrayList<Series>> getRounds() { return rounds; } }
894
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
Seeding.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/Seeding.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.utility.PowMath; import java.util.ArrayList; import java.util.List; public class Seeding { /** Generates a sequence of integers (from 0 to n - 1) that follows this pattern: [0, 7, 3, 4, 1, 6, 2, 5]. * n must be a power of two. */ public static List<Integer> generateFairOrder(int n) { if (Integer.bitCount(n) != 1) throw new IllegalArgumentException("n must be a power of two."); List<Integer> ints = new ArrayList<>(n); for (int i = 0; i < n; i++) { ints.set(i, i); } return fairSeedList(ints); } /** Generates a sequence of integers (from 0 to 2^n - 1) that follows this pattern: [0, 7, 3, 4, 1, 6, 2, 5]. * The size of the list will be 2^n. */ public static List<Integer> generateFairOrderPow(int n) { return generateFairOrder((int) Math.pow(2, n)); } /** Returns a new list that contains the same as the given list but the elements has been reordered. * [1, 2, 3, 4] becomes [1, 4, 2, 3]. And [1, 2, 3, 4, 5, 6, 7, 8] becomes [1, 8, 4, 5, 2, 7, 3, 6]. * @param list a list, which size is a power of two. */ public static <T> List<T> fairSeedList(List<T> list) { if (!PowMath.isPowOf2(list.size())) throw new AssertionError("Size of list (" + list.size() + ") is not a power of two."); if (Integer.bitCount(list.size()) != 1) throw new IllegalArgumentException("The size of the list must be a power of two."); list = new ArrayList<>(list); int slice = 1; int halfSize = list.size() / 2; while (slice < halfSize) { List<T> temp = new ArrayList<>(list); list.clear(); while (temp.size() > 0) { int lastIndex = temp.size(); list.addAll(temp.subList(0, slice)); list.addAll(temp.subList(lastIndex - slice, lastIndex)); temp.removeAll(temp.subList(lastIndex - slice, lastIndex)); temp.removeAll(temp.subList(0, slice)); } slice *= 2; } return list; } /** * Takes a list of elements and returns a new list with the same elements, but rearranged so by alternately picking * the first element, and then the last element, until a new list is constructed. I.e. [1, 2, 3, 4] becomes * [1, 4, 2, 3], and [1, 2, 3, 4, 5, 6, 7] becomes [1, 7, 2, 6, 3, 5, 4]. * @param list a list of any size */ public static <T> List<T> simplePairwiseSeedList(List<T> list) { int n = list.size(); int pairs = n / 2; int i = 0; List<T> newList = new ArrayList<>(); while (i < pairs) { newList.add(list.get(i)); newList.add(list.get(n - i - 1)); i++; } // In case list size is odd, add middle element if (n % 2 == 1) { newList.add(list.get(n / 2)); } return newList; } }
3,108
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
RoundRobinFormat.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/RoundRobinFormat.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.match.MatchPlayedListener; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.RoundRobinNode; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.RoundRobinSettingsNode; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import javafx.scene.Node; import java.util.*; import java.util.stream.Collectors; public class RoundRobinFormat implements Format, MatchPlayedListener { private static final Team DUMMY_TEAM = new Team("Dummy", new ArrayList<>(), 0, "Dummy team description"); private StageStatus status = StageStatus.PENDING; private int defaultSeriesLength = 1; private ArrayList<Team> teams; transient private ArrayList<Series> series; private ArrayList<RoundRobinGroup> groups; private int numberOfGroups = 1; transient private List<StageStatusChangeListener> statusChangeListeners = new LinkedList<>(); /** Start the round robin format. * @param seededTeams arraylist of all the teams in the round robin. * @param doSeeding whether or not to group teams based on their seed. */ public void start(List<Team> seededTeams, boolean doSeeding) { teams = new ArrayList<>(seededTeams); ArrayList<Team> teams = new ArrayList<>(seededTeams); if (seededTeams.size() <= 1) { series = new ArrayList<>(); groups = new ArrayList<>(); status = StageStatus.CONCLUDED; } else { // Clamp the number of groups to something that is okay (at least 2 teams per group) if (numberOfGroups < 1) numberOfGroups = 1; else if (numberOfGroups > teams.size() / 2) numberOfGroups = teams.size() / 2; status = StageStatus.RUNNING; createGroupsAndMatches(teams, doSeeding); series = extractMatchesFromGroups(); setupStatsTracking(); } } @Override public StageStatus getStatus() { return status; } @Override public List<Team> getTopTeams(int count, TieBreaker tieBreaker) { /* Sort the teams of each group by their performance. Then pick the top X teams as follows: 1st from group 0, 1st from group 1, ... 1st from group N-1, 2nd from group 0, 2nd from group 1, ... Until X teams has been picked or every team was picked. However, the first groups might be smaller if the number of teams is not divisible by the number groups. Therefore we skip those when they are empty. */ HashMap<Team, Integer> pointsMap = getTeamPointsMap(); List<List<Team>> sortedGroups = groups.stream() .map((group) -> tieBreaker.compareWithPoints(group.getTeams(), pointsMap, this)) .collect(Collectors.toList()); List<Team> topTeams = new ArrayList<>(); int left = Math.min(count, teams.size()); int nextGroupToTakeFrom = 0; int indexToTake = 0; while (left > 0) { List<Team> group = sortedGroups.get(nextGroupToTakeFrom); // Are there more teams in this group? if (group.size() > indexToTake) { topTeams.add(group.get(indexToTake)); left--; } nextGroupToTakeFrom++; if (nextGroupToTakeFrom == groups.size()) { // Wrap around at last group and pick next best team from the groups nextGroupToTakeFrom = 0; indexToTake++; } } return topTeams; } /** This function populates the groups list and generates the matches for each group. */ private void createGroupsAndMatches(ArrayList<Team> teams, boolean doSeeding) { groups = new ArrayList<>(); int groupSize = teams.size() / numberOfGroups; int leftoverTeams = teams.size() % numberOfGroups; if (doSeeding) { // With seeding // Pick teams evenly for (int i = 0; i < numberOfGroups; i++) { // Pick every numberOfGroups'th team ArrayList<Team> teamsForGroup = new ArrayList<>(); for (int j = 0; j < groupSize; j++) { teamsForGroup.add(teams.get(i + j * numberOfGroups)); } // When team count is not divisible by group count, the leftover teams are added to the lowest seeded groups if (i >= numberOfGroups - leftoverTeams) { teamsForGroup.add(teams.get(teams.size() - numberOfGroups + i)); } RoundRobinGroup group = new RoundRobinGroup(teamsForGroup); group.setRounds(generateMatches(group.getTeams())); groups.add(group); } } else { // Without seeding // Pick clusters of teams int t = 0; for (int i = 0; i < numberOfGroups; i++) { // Some groups may be bigger if team count is not divisible by number of groups // The first group(s) will be the small ones int size = groupSize; if (i >= numberOfGroups - leftoverTeams) { size++; } RoundRobinGroup group = new RoundRobinGroup(teams.subList(t, t + size)); group.setRounds(generateMatches(group.getTeams())); groups.add(group); t += size; } } } /** * Creates all matches with each team changing color between each of their matches, algorithm based on berger tables. * @return an list of list of matches with the given teams. Each nested list is a round of matches. */ private ArrayList<ArrayList<Series>> generateMatches(ArrayList<Team> t) { // Add dummy team if team count is odd - berger tables only work for an even number. // The matches with dummy teams are removed later ArrayList<Team> teams = new ArrayList<>(t); if (t.size() % 2 != 0) { teams.add(DUMMY_TEAM); } int nextTeamOneIndex, nextTeamTwoIndex; Series[][] table = new Series[teams.size() - 1][teams.size() / 2]; HashMap<Team, Integer> map = createIdHashMap(teams); //number of rounds needed for (int round = 0; round < teams.size() - 1; round++) { //number of matches per round for (int match = 0; match < teams.size() / 2; match++) { //create first round, which is not based on previous rounds if (round == 0) { table[round][match] = createNewMatch(teams.get(match), teams.get(teams.size() - (match + 1))); } //hardcoding team with highest id (numberOfTeams - 1 ) to first match each round //the other team is found by berger tables rules (findIdOfNextTeam) on the id of the team in the same match, //but previous round else if (match == 0) { //else become team two if ((round % 2) == 0) { nextTeamOneIndex = findIdOfNextTeam(map.get(table[round - 1][match].getTeamTwo()), teams.size()); table[round][match] = createNewMatch(teams.get(nextTeamOneIndex - 1), (teams.get(teams.size() - 1))); //if uneven round, team with highest id becomes team one } else { nextTeamTwoIndex = findIdOfNextTeam(map.get(table[round - 1][match].getTeamOne()), teams.size()); table[round][match] = createNewMatch((teams.get(teams.size() - 1)), teams.get(nextTeamTwoIndex - 1)); } } else { //if not the first round, or first match, find both teams by findIdOfNextTeam according to berger tables, //on previous teams nextTeamOneIndex = findIdOfNextTeam(map.get(table[round - 1][match].getTeamOne()), teams.size()); nextTeamTwoIndex = findIdOfNextTeam(map.get(table[round - 1][match].getTeamTwo()), teams.size()); table[round][match] = createNewMatch(teams.get(nextTeamOneIndex - 1), (teams.get(nextTeamTwoIndex - 1))); } } } // Find matches that does not contain the dummy team ArrayList<ArrayList<Series>> matches = new ArrayList<>(); for (int i = 0; i < table.length; i++) { matches.add(new ArrayList<>()); for (int j = 0; j < table[i].length; j++) { if (!table[i][j].getTeamTwo().equals(DUMMY_TEAM) && !table[i][j].getTeamOne().equals(DUMMY_TEAM)) { matches.get(i).add(table[i][j]); } } } return matches; } /** * Generates a hashMap containing the given teams and an unique integer(id). * This will be used in the berger tables. * * @param teams a list of all teams in the bracket. * @return a hashMap containing the teams an a unique id. */ private HashMap<Team, Integer> createIdHashMap(ArrayList<Team> teams) { HashMap<Team, Integer> map = new HashMap<>(); for (int m = 0; m < teams.size(); m++) { map.put(teams.get(m), m + 1); } return map; } /** * @return a new match from the given parameters. And adds listener. */ private Series createNewMatch(Team team1, Team team2) { Series series = new Series(defaultSeriesLength, team1, team2); series.registerMatchPlayedListener(this); return series; } /** * Find new team, by adding n/2 to the team in the same place in previous round, if this exceeds n-1, * instead subtract n/2 - 1. * * @param id of the team in the match in the previous round. * @return the id of the team that should be in this match, according to last. */ public int findIdOfNextTeam(int id, int limit) { if ((id + (limit / 2)) > (limit - 1)) { return id - ((limit / 2) - 1); } else return id + (limit / 2); } /** * @return a list of all matches contained in the Round Robin Groups */ private ArrayList<Series> extractMatchesFromGroups() { ArrayList<Series> listOfAllSeries = new ArrayList<>(); for (RoundRobinGroup group : groups) { listOfAllSeries.addAll(group.getMatches()); } return listOfAllSeries; } private void setupStatsTracking() { List<Series> allSeries = getAllSeries(); for (Team team : teams) { team.getStatsManager().trackAllSeries(this, allSeries); } } @Override public List<Series> getAllSeries() { return series; } @Override public List<Series> getUpcomingMatches() { return getAllSeries().stream().filter(match -> !match.hasBeenPlayed()).collect(Collectors.toList()); } @Override public List<Series> getPendingMatches() { return new ArrayList<>(); // Round robin never has pending matches } @Override public List<Series> getCompletedMatches() { return getAllSeries().stream().filter(Series::hasBeenPlayed).collect(Collectors.toList()); } @Override public void onMatchPlayed(Series series) { // Has last possible match been played? StageStatus oldStatus = status; if (getUpcomingMatches().size() == 0) status = StageStatus.CONCLUDED; else status = StageStatus.RUNNING; // Notify listeners if status changed if (oldStatus != status) { nofityStatusListeners(status, oldStatus); } } @Override public void registerStatusChangedListener(StageStatusChangeListener listener) { statusChangeListeners.add(listener); } @Override public void unregisterStatusChangedListener(StageStatusChangeListener listener) { statusChangeListeners.remove(listener); } /** Let listeners know, that the status has changed */ private void nofityStatusListeners(StageStatus oldStatus, StageStatus newStatus) { for (StageStatusChangeListener listener : statusChangeListeners) { listener.onStageStatusChanged(this, oldStatus, newStatus); } } /** * @return a hashMap containing the teams and their points. */ public HashMap<Team, Integer> getTeamPointsMap() { //Get list of all completed matches List<Series> completedSeries = getCompletedMatches(); //Calculate team wins HashMap<Team, Integer> teamPoints = new HashMap<>(); for (Team team : teams) teamPoints.put(team, 0); //Run through all matches and give points for win. for (Series series : completedSeries) { Team winningTeam = series.getWinner(); //+1 for winning //TODO Should we do more? teamPoints.put(winningTeam, teamPoints.get(winningTeam) + 1); } return teamPoints; } /** * @param numberOfGroups sets the number of groups in the format. Sanity check for at least 1 group */ public void setNumberOfGroups(int numberOfGroups) { if (status != StageStatus.PENDING) throw new IllegalStateException("The matches are already generated."); this.numberOfGroups = Math.max(numberOfGroups, 1); } public int getNumberOfGroups() { return numberOfGroups; } public ArrayList<RoundRobinGroup> getGroups() { return groups; } public static Team getDummyTeam() { return DUMMY_TEAM; } @Override public void setDefaultSeriesLength(int seriesLength) { if (seriesLength <= 0) throw new IllegalArgumentException("Series length must be at least one."); if (seriesLength % 2 == 0) throw new IllegalArgumentException("Series must have an odd number of matches."); defaultSeriesLength = seriesLength; } @Override public int getDefaultSeriesLength() { return defaultSeriesLength; } @Override public RoundRobinNode getBracketFXNode(BracketOverviewTabController boc) { return new RoundRobinNode(this, boc); } @Override public Node getSettingsFXNode() { return new RoundRobinSettingsNode(this); } @Override public void postDeserializationRepair() { series = extractMatchesFromGroups(); for (Series series : series) series.registerMatchPlayedListener(this); setupStatsTracking(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RoundRobinFormat that = (RoundRobinFormat) o; return Objects.equals(series, that.series); } @Override public int hashCode() { return Objects.hash(series); } }
15,279
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
SwissFormat.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/SwissFormat.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.model.Tournament; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.match.MatchChangeListener; import dk.aau.cs.ds306e18.tournament.model.match.MatchPlayedListener; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.SwissNode; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.SwissSettingsNode; import dk.aau.cs.ds306e18.tournament.utility.Alerts; import javafx.scene.Node; import java.util.*; import java.util.stream.Collectors; public class SwissFormat implements Format, MatchChangeListener, MatchPlayedListener { private StageStatus status = StageStatus.PENDING; private int defaultSeriesLength = 1; private ArrayList<Team> teams; private ArrayList<ArrayList<Series>> rounds = new ArrayList<>(); private int maxRoundsPossible; private int roundCount = 4; private boolean doSeeding; transient private IdentityHashMap<Team, Integer> teamPoints; transient private List<StageStatusChangeListener> statusChangeListeners = new LinkedList<>(); @Override public void start(List<Team> teams, boolean doSeeding) { rounds = new ArrayList<>(); maxRoundsPossible = getMaxRoundsPossible(teams.size()); roundCount = maxRoundsPossible < roundCount ? maxRoundsPossible : roundCount; teamPoints = createPointsMap(teams); this.teams = new ArrayList<>(teams); this.doSeeding = doSeeding; status = StageStatus.RUNNING; startNextRound(); // Generate the first round } @Override public StageStatus getStatus() { return status; } @Override public List<Team> getTopTeams(int count, TieBreaker tieBreaker) { return tieBreaker.compareWithPoints(teams, getTeamPointsMap(), this).subList(0, count); } /** * Creates the hashMap that stores the "swiss" points for the teams. */ private IdentityHashMap<Team, Integer> createPointsMap(List<Team> teams) { IdentityHashMap<Team, Integer> pointsMap = new IdentityHashMap<>(); for (Team team : teams) pointsMap.put(team, 0); return pointsMap; } /** * Creates a new round of swiss, with the current teams. * * @return true if a round was generated and false if a new round could not be generated. */ public boolean startNextRound() { if (!canStartNextRound()) return false; createNextRound(); return true; } /** * @return true if it is allowed to generate a new round. */ public boolean canStartNextRound() { if (status == StageStatus.PENDING) { return false; } else if (status == StageStatus.CONCLUDED) { return false; } else if (!hasUnstartedRounds()) { //Is it legal to create another round? return false; } else if (getUpcomingMatches().size() != 0) { //Has all matches been played? return false; } return true; } /** * Takes a list of teams and sorts it based on their points in the given hashMap. * * @param teamList a list of teams. * @param teamPoints a hashMap containing teams as key and their points as value. * @return the given list sorted based on the given points. */ private List<Team> getOrderedTeamsListFromPoints(ArrayList<Team> teamList, Map<Team, Integer> teamPoints) { if (rounds.size() == 0) return new ArrayList<>(teamList); else return Tournament.get().getTieBreaker().compareWithPoints(teamList, teamPoints, this); } /** * Creates the matches for the next round. This is done so that no team will play the same opponents twice, * and with the teams with the closest amount of points. * Credit for algorithm: Amanda. */ private void createNextRound() { List<Team> orderedTeamList; // Use seeding for first round. if (doSeeding && rounds.size() == 0) { // Best seed should play against worst seed, // second best against second worst, etc. // Create seeded list fitting the algorithm below orderedTeamList = Seeding.simplePairwiseSeedList(teams); } else { // Create ordered list of team, based on points. orderedTeamList = getOrderedTeamsListFromPoints(teams, teamPoints); } ArrayList<Series> createdSeries; int badTries = 0; while (true) { createdSeries = new ArrayList<>(); List<Team> remaingTeams = new ArrayList<>(orderedTeamList); int acceptedRematches = badTries; // Create matches while there is more than 1 team in the list. while (remaingTeams.size() > 1) { Team team1 = remaingTeams.get(0); Team team2 = null; // Find the next team that has not played team1 yet. for (int i = 1; i < remaingTeams.size(); i++) { team2 = remaingTeams.get(i); // Has the two selected teams played each other before? // Due to previous bad tries we might accept rematches. Note: short circuiting if (!hasTheseTeamsPlayedBefore(team1, team2) || 0 < acceptedRematches--) { Series series = new Series(defaultSeriesLength, team1, team2); createdSeries.add(series); break; // Two valid teams has been found, and match has been created. } } remaingTeams.remove(team1); remaingTeams.remove(team2); } if (createdSeries.size() == orderedTeamList.size() / 2) { break; // Round was fully constructed } else { badTries++; } } // Alert users about rematches. TODO Fix the algorithm. Replace it with Blossom algorithm, good luck! if (badTries > 0) { Alerts.errorNotification("Bad round", "Accepted " + badTries + " rematches due to a bad algorithm."); Main.LOGGER.log(System.Logger.Level.ERROR, "Bad round: Accepted " + badTries + " rematches due to a bad algorithm."); } // Register self as listener for (Series m : createdSeries) { m.registerMatchPlayedListener(this); m.registerMatchChangeListener(this); } // Track stats from the new matches for (Team team : teams) { team.getStatsManager().trackAllSeries(this, createdSeries); } rounds.add(createdSeries); } /** * Checks if the two given teams has played a match against each other. * Returns a boolean based on that comparison. * * @param team1 one of the two teams for the check. * @param team2 one of the two teams for the check. * @return true if the two given teams has played before, and false if that is not the case. */ private boolean hasTheseTeamsPlayedBefore(Team team1, Team team2) { List<Series> series = getCompletedMatches(); for (Series serie : series) { Team teamOne = serie.getTeamOne(); Team teamTwo = serie.getTeamTwo(); //Compare the current match's teams with the two given teams. if (team1 == teamOne && team2 == teamTwo || team1 == teamTwo && team2 == teamOne) return true; } return false; } @Override public List<Series> getAllSeries() { ArrayList<Series> series = new ArrayList<>(); for (ArrayList<Series> list : rounds) { series.addAll(list); } return series; } @Override public List<Series> getUpcomingMatches() { return getAllSeries().stream().filter(match -> !match.hasBeenPlayed()).collect(Collectors.toList()); } @Override public List<Series> getPendingMatches() { return getAllSeries().stream().filter(match -> match.getStatus() == Series.Status.NOT_PLAYABLE).collect(Collectors.toList()); } @Override public List<Series> getCompletedMatches() { return getAllSeries().stream().filter(Series::hasBeenPlayed).collect(Collectors.toList()); } public int getMaxRoundsPossible() { return maxRoundsPossible; } /** * Returns the max number of rounds that can be played with the given number of teams. */ public static int getMaxRoundsPossible(int numberOfTeams) { if (numberOfTeams == 0) return 0; return (numberOfTeams % 2 == 0) ? numberOfTeams - 1 : numberOfTeams; } public int getRoundCount() { return roundCount; } public void setRoundCount(int roundCount) { if (status != StageStatus.PENDING) throw new IllegalStateException("Swiss stage has already started."); if (roundCount < 1) throw new IllegalArgumentException("There must be at least one round."); this.roundCount = roundCount; } public boolean hasUnstartedRounds() { return rounds.size() < roundCount; } /** * @return the latest generated round. Or null if there are no rounds generated. */ public List<Series> getLatestRound() { if (rounds.size() == 0) return null; return new ArrayList<>(rounds.get(rounds.size() - 1)); } /** * @return a hashMap containing the teams and their points. */ public IdentityHashMap<Team, Integer> getTeamPointsMap() { return teamPoints; } @Override public void setDefaultSeriesLength(int seriesLength) { if (seriesLength <= 0) throw new IllegalArgumentException("Series length must be at least one."); if (seriesLength % 2 == 0) throw new IllegalArgumentException("Series must have an odd number of matches."); defaultSeriesLength = seriesLength; } @Override public int getDefaultSeriesLength() { return defaultSeriesLength; } @Override public SwissNode getBracketFXNode(BracketOverviewTabController boc) { return new SwissNode(this, boc); } @Override public Node getSettingsFXNode() { return new SwissSettingsNode(this); } /** * @return an arraylist of the current created rounds. */ public ArrayList<ArrayList<Series>> getRounds() { ArrayList<ArrayList<Series>> roundsCopy = new ArrayList<>(rounds.size()); for (ArrayList<Series> r : rounds) { roundsCopy.add(new ArrayList<>(r)); } return roundsCopy; } /** * Checks a given team for every completed match if they have been a loser or winner. Then assigning their points * based upon their win/loss ratio. A win gives 1 point. * By going through all completed matches we can assure proper point giving due to recalculations. * * @param team The given team to check, calculate and then assign point for. */ private void calculateAndAssignTeamPoints(Team team) { int points = 0; for (Series series : getCompletedMatches()) { if (series.getWinner().equals(team)) { points += 1; } } teamPoints.put(team, points); } public List<Team> getTeams() { return teams; } @Override public void onMatchPlayed(Series series) { // Has last possible match been played? StageStatus oldStatus = status; if (!hasUnstartedRounds() && getUpcomingMatches().size() == 0) { status = StageStatus.CONCLUDED; } else { status = StageStatus.RUNNING; } // Notify listeners if status changed if (oldStatus != status) { nofityStatusListeners(status, oldStatus); } } @Override public void onMatchChanged(Series series) { // Calculate and assign points for each team in the match. calculateAndAssignTeamPoints(series.getTeamOne()); calculateAndAssignTeamPoints(series.getTeamTwo()); } @Override public void registerStatusChangedListener(StageStatusChangeListener listener) { statusChangeListeners.add(listener); } @Override public void unregisterStatusChangedListener(StageStatusChangeListener listener) { statusChangeListeners.remove(listener); } /** Let listeners know, that the status has changed */ private void nofityStatusListeners(StageStatus oldStatus, StageStatus newStatus) { for (StageStatusChangeListener listener : statusChangeListeners) { listener.onStageStatusChanged(this, oldStatus, newStatus); } } @Override public void postDeserializationRepair() { for (Series series : getAllSeries()) { series.registerMatchPlayedListener(this); series.registerMatchChangeListener(this); } teamPoints = createPointsMap(teams); for (Team team : teams) { calculateAndAssignTeamPoints(team); team.getStatsManager().trackAllSeries(this, getAllSeries()); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SwissFormat that = (SwissFormat) o; return getMaxRoundsPossible() == that.getMaxRoundsPossible() && Objects.equals(getRounds(), that.getRounds()) && Objects.equals(teams, that.teams); } @Override public int hashCode() { return Objects.hash(getRounds(), getMaxRoundsPossible(), teamPoints); } }
13,999
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
DoubleEliminationFormat.java
/FileExtraction/Java_unseen/ds306e18_cleopetra/src/main/java/dk/aau/cs/ds306e18/tournament/model/format/DoubleEliminationFormat.java
package dk.aau.cs.ds306e18.tournament.model.format; import dk.aau.cs.ds306e18.tournament.Main; import dk.aau.cs.ds306e18.tournament.model.Team; import dk.aau.cs.ds306e18.tournament.model.TieBreaker; import dk.aau.cs.ds306e18.tournament.model.match.Series; import dk.aau.cs.ds306e18.tournament.model.match.MatchPlayedListener; import dk.aau.cs.ds306e18.tournament.ui.BracketOverviewTabController; import dk.aau.cs.ds306e18.tournament.ui.bracketObjects.DoubleEliminationNode; import javafx.scene.Node; import java.util.*; import java.util.stream.Collectors; import static dk.aau.cs.ds306e18.tournament.utility.PowMath.log2; import static dk.aau.cs.ds306e18.tournament.utility.PowMath.pow2; public class DoubleEliminationFormat implements Format, MatchPlayedListener { private StageStatus status = StageStatus.PENDING; private int defaultSeriesLength = 1; private List<Team> teams; private int upperBracketRounds; private Series finalSeries; private Series extraSeries; private Series[] upperBracket; private Series[] lowerBracket; private boolean isExtraMatchNeeded; transient private List<StageStatusChangeListener> statusChangeListeners = new LinkedList<>(); @Override public void start(List<Team> seededTeams, boolean doSeeding) { teams = new ArrayList<>(seededTeams); generateBracket(seededTeams, doSeeding); status = StageStatus.RUNNING; setupStatsTracking(); } /** Generates the complete double elimination bracket given a list of teams ordered by seed. If doSeeding is false * the teams will just be insert without taking their seed into account. */ private void generateBracket(List<Team> seededTeams, boolean doSeeding) { upperBracketRounds = log2(seededTeams.size()); generateUpperBracket(); generateLowerBracket(); generateGrandFinals(); // Create byes int teamCount = pow2(upperBracketRounds); List<Team> teams = new ArrayList<>(seededTeams); List<Team> byes = new ArrayList<>(); while (byes.size() + teams.size() < teamCount) { byes.add(new Team("Bye" + byes.size(), null, 999, "")); } teams.addAll(byes); insertTeams(teams, doSeeding); removeByes(byes); giveMatchesIdentifiers(); } /** Generates the matches in the upper bracket and connects them. All the matches will be empty. */ private void generateUpperBracket() { int matchesInFirstRound = pow2(upperBracketRounds - 1); int numberOfMatches = pow2(upperBracketRounds) - 1; upperBracket = new Series[numberOfMatches]; for(int i = numberOfMatches - 1; i >= 0; i--) { // Creates empty matches for first round if(i >= numberOfMatches - matchesInFirstRound) { upperBracket[i] = new Series(defaultSeriesLength); } // Creates the remaining matches which contains winners from their left- and right child-indexes. else { upperBracket[i] = new Series(defaultSeriesLength) .setTeamOneToWinnerOf(upperBracket[getUpperBracketLeftIndex(i)]) .setTeamTwoToWinnerOf(upperBracket[getUpperBracketRightIndex(i)]); } } } /** Generates all the matches in the lower bracket and connects them to the upper bracket matches. Also creates * the final match and the extra match. */ private void generateLowerBracket() { // When theres only one match in upper bracket, because there are only two teams, then we cannot make a lower bracket if (upperBracket.length == 1) { lowerBracket = new Series[0]; return; } int matchesInCurrentRound = pow2(upperBracketRounds - 2); int ubLoserIndex = upperBracket.length - 1; List<Series> lowerBracketSeries = new ArrayList<>(); // For the first lower bracket round, use losers from first round in upper bracket for (int i = 0; i < matchesInCurrentRound; i++) { lowerBracketSeries.add(new Series(defaultSeriesLength) .setTeamOneToLoserOf(upperBracket[ubLoserIndex--]) .setTeamTwoToLoserOf(upperBracket[ubLoserIndex--])); } int lbWinnerIndex = 0; int rounds = 2 * upperBracketRounds - 2; // For the remaining lower bracket rounds, alternate between: // - odd rounds: using winners from lower bracket against loser from upper bracket. // - even rounds: using only winners of prior lower bracket round for (int i = 1; i < rounds; i++) { if (i % 2 == 1) { // Odd round // Every other odd round we take winners in the opposite order int dir = -1; if (i % 4 == 1) { ubLoserIndex = ubLoserIndex - matchesInCurrentRound + 1; dir = 1; } for (int j = 0; j < matchesInCurrentRound; j++) { lowerBracketSeries.add(new Series(defaultSeriesLength) .setTeamOneToWinnerOf(lowerBracketSeries.get(lbWinnerIndex++)) .setTeamTwoToLoserOf(upperBracket[ubLoserIndex])); ubLoserIndex += dir; } // Reset behaviour for every other odd round if (i % 4 == 1) { ubLoserIndex = ubLoserIndex - matchesInCurrentRound - 1; } } else { // Even round // The amount of matches is halved in even rounds as no teams arrive to the loser bracket matchesInCurrentRound /= 2; for (int j = 0; j < matchesInCurrentRound; j++) { lowerBracketSeries.add(new Series(defaultSeriesLength) .setTeamOneToWinnerOf(lowerBracketSeries.get(lbWinnerIndex++)) .setTeamTwoToWinnerOf(lowerBracketSeries.get(lbWinnerIndex++))); } } } // Creates an array of lower bracket matches lowerBracket = lowerBracketSeries.toArray(new Series[0]); } private void generateGrandFinals() { // If there are two teams, then there is no lower bracket if (lowerBracket.length == 0) { // The final is just a rematch finalSeries = new Series(defaultSeriesLength) .setTeamOneToLoserOf(upperBracket[0]) .setTeamTwoToWinnerOf(upperBracket[0]); } else { // The final is the winner of upper bracket versus winner of lower bracket finalSeries = new Series(defaultSeriesLength) .setTeamOneToWinnerOf(upperBracket[0]) .setTeamTwoToWinnerOf(lowerBracket[lowerBracket.length-1]); } // The extra is takes the winner and loser of the final match, but it should not be played if the loser of // the final match has already lost twice extraSeries = new Series(defaultSeriesLength) .setTeamOneToWinnerOf(finalSeries) .setTeamTwoToLoserOf(finalSeries); finalSeries.registerMatchPlayedListener(this); extraSeries.registerMatchPlayedListener(this); } /** Inserts the teams in the correct starting positions. If doSeeding is false * the teams will just be insert without taking their seed into account. */ private void insertTeams(List<Team> teams, boolean doSeeding) { // Create byes int teamCount = pow2(upperBracketRounds); // Seeding if (doSeeding) { teams = Seeding.fairSeedList(teams); } // Inserting int matchIndex = upperBracket.length - 1; for (int i = 0; i < teamCount; i += 2, matchIndex--) { upperBracket[matchIndex] .setTeamOne(teams.get(i)) .setTeamTwo(teams.get(i + 1)); } } /** Removes matches containing byes. */ private void removeByes(List<Team> byes) { // Remove byes from upper bracket int ubFirstRoundMatchCount = pow2(upperBracketRounds - 1); for (int i = 0; i < ubFirstRoundMatchCount; i++) { int ubIndex = upperBracket.length - i - 1; Series m = upperBracket[ubIndex]; // We know team two is the bye, if there is any if (byes.contains(m.getTeamTwo())) { // This is a bye match in upper bracket // Resolve match and remove references to this match upperBracket[ubIndex] = null; if (m.doesWinnerGoToTeamOne()) { m.getWinnerDestination().setTeamOne(m.getTeamOne()); } else { m.getWinnerDestination().setTeamTwo(m.getTeamOne()); } if (m.doesLoserGoToTeamOne()) { m.getLoserDestination().setTeamOne(m.getTeamTwo()); } else { m.getLoserDestination().setTeamTwo(m.getTeamTwo()); } } } if (lowerBracket.length > 0) { // Remove byes from lower bracket int lbFirstRoundMatchCount = pow2(upperBracketRounds - 2); for (int i = 0; i < lbFirstRoundMatchCount; i++) { Series m = lowerBracket[i]; // Team two can only be a bye if team one also is a bye, so we test team two first if (byes.contains(m.getTeamTwo())) { // Both teams are byes // Remove matches from bracket lowerBracket[i] = null; for (int j = 0; j < lbFirstRoundMatchCount * 2; j++) { if (lowerBracket[j] == m.getWinnerDestination()) { lowerBracket[j] = null; break; } } // Sets the winner destination of m's winner destination to receive the loser that m's // winner destination should have received Series wd = m.getWinnerDestination(); if (wd.doesWinnerGoToTeamOne()) { wd.getWinnerDestination().setTeamOneToLoserOf(wd.getTeamTwoFromSeries()); } else { wd.getWinnerDestination().setTeamTwoToLoserOf(wd.getTeamTwoFromSeries()); } } else if (byes.contains(m.getTeamOne())) { // Only team one is a bye. Team two is the loser of a match in upper bracket. // Resolve match and remove references to this match lowerBracket[i] = null; m.getWinnerDestination().setTeamOneToLoserOf(m.getTeamTwoFromSeries()); } } } } /** Gives the matches identifiers. */ private void giveMatchesIdentifiers() { int nextIdentifier = 1; // We give upper bracket the small identifiers as those matches always can be played first for (int i = upperBracket.length - 1; i >= 0; i--) { if (upperBracket[i] != null) { upperBracket[i].setIdentifier(nextIdentifier++); } } for (int i = 0; i < lowerBracket.length; i++) { if (lowerBracket[i] != null) { lowerBracket[i].setIdentifier(nextIdentifier++); } } finalSeries.setIdentifier(nextIdentifier++); extraSeries.setIdentifier(nextIdentifier); } private void setupStatsTracking() { List<Series> allSeries = getAllSeries(); for (Team team : teams) { team.getStatsManager().trackAllSeries(this, allSeries); } } @Override public StageStatus getStatus() { return status; } @Override public List<Team> getTopTeams(int count, TieBreaker tieBreaker) { // The easiest way to find the best performing teams in double elimination is to count how many wins and loses // each team has and then use the tie breaker to rank them based on that HashMap<Team, Integer> pointsMap = new HashMap<>(); List<Series> allSeries = getAllSeries(); for (Series series : allSeries) { if (series.hasBeenPlayed()) { // +1 point to the winner Team winner = series.getWinner(); int wins = 0; if (pointsMap.containsKey(winner)) { wins = pointsMap.get(winner); } pointsMap.put(winner, wins + 1); // -1 point to the loser Team loser = series.getLoser(); int loses = 0; if (pointsMap.containsKey(loser)) { loses = pointsMap.get(loser); } pointsMap.put(loser, loses - 1); } } return tieBreaker.compareWithPoints(teams, pointsMap, this).subList(0, count); } /** Recalculates the isExtraMatchNeeded boolean. The extra match is needed if the loser of the final match has only * lost once. It will always be set to false if the final match has not been played. */ public void determineIfExtraMatchNeeded() { if (!finalSeries.hasBeenPlayed()) { isExtraMatchNeeded = false; return; } HashMap<Team, Integer> loses = getLosesMap(); Team finalMatchLoser = finalSeries.getLoser(); if (loses.containsKey(finalMatchLoser)) { // The team has either lost once or twice // If it is only once, we need an extra match isExtraMatchNeeded = loses.get(finalMatchLoser) == 1; } else { isExtraMatchNeeded = false; } } public boolean isExtraMatchNeeded() { return isExtraMatchNeeded; } /** Returns a hash that maps teams to an integers describing how many times they have lost in this stage. */ public HashMap<Team, Integer> getLosesMap() { HashMap<Team, Integer> losesMap = new HashMap<>(); for (Series series : getAllSeries()) { if (series.hasBeenPlayed()) { Team loser = series.getLoser(); int loses = 0; if (losesMap.containsKey(loser)) { loses = losesMap.get(loser); } losesMap.put(loser, loses + 1); } } return losesMap; } @Override public List<Series> getAllSeries() { return extraSeries.getTreeAsListBFS(); } @Override public List<Series> getUpcomingMatches() { return getAllSeries().stream().filter(m -> m.getStatus().equals(Series.Status.READY_TO_BE_PLAYED) && !m.hasBeenPlayed() && (m != extraSeries || isExtraMatchNeeded)) // extra match is only an upcoming match if needed .collect(Collectors.toList()); } @Override public List<Series> getPendingMatches() { return getAllSeries().stream().filter(m -> m.getStatus().equals(Series.Status.NOT_PLAYABLE) && m != extraSeries) // extra match is never pending. It is either not needed, or needed AND playable .collect(Collectors.toList()); } @Override public List<Series> getCompletedMatches() { return getAllSeries().stream().filter(Series::hasBeenPlayed).collect(Collectors.toList()); } public Series getFinalSeries() { return finalSeries; } public Series getExtraSeries() { return extraSeries; } public int getUpperBracketRounds() { return upperBracketRounds; } public Series[] getUpperBracket() { return upperBracket; } public Series[] getLowerBracket() { return lowerBracket; } @Override public void registerStatusChangedListener(StageStatusChangeListener listener) { statusChangeListeners.add(listener); } @Override public void unregisterStatusChangedListener(StageStatusChangeListener listener) { statusChangeListeners.remove(listener); } /** Let listeners know, that the status has changed */ private void notifyStatusListeners(StageStatus oldStatus, StageStatus newStatus) { for (StageStatusChangeListener listener : statusChangeListeners) { listener.onStageStatusChanged(this, oldStatus, newStatus); } } @Override public DoubleEliminationNode getBracketFXNode(BracketOverviewTabController bracketOverview) { return new DoubleEliminationNode(this, bracketOverview); } @Override public Node getSettingsFXNode() { return null; } /** Repairs match-structure after deserialization. */ @Override public void postDeserializationRepair() { repairUpperBracket(); repairLowerBracket(); repairGrandFinals(); setupStatsTracking(); } /** Reconnect upper bracket post deserialization. */ private void repairUpperBracket() { for (int i = 0; i < upperBracket.length; i++) { if (upperBracket[i] != null) { // Team one is winner from left match, if such a match exists int leftIndex = getUpperBracketLeftIndex(i); if (leftIndex < upperBracket.length) { Series leftSeries = upperBracket[leftIndex]; if (leftSeries != null) { upperBracket[i].reconnectTeamOneToWinnerOf(leftSeries); } } // Team two is winner from right match, if such a match exists int rightIndex = getUpperBracketRightIndex(i); if (rightIndex < upperBracket.length) { Series rightSeries = upperBracket[rightIndex]; if (rightSeries != null) { upperBracket[i].reconnectTeamTwoToWinnerOf(rightSeries); } } } } } /** Reconnect lower bracket post deserialization. */ private void repairLowerBracket() { if (lowerBracket.length == 0) { return; } int matchesInCurrentRound = pow2(upperBracketRounds - 2); int next = 0; // index of the next match from lower bracket we want to reconnect int ubLoserIndex = upperBracket.length - 1; // For the first lower bracket round, use losers from first round in upper bracket while (next < matchesInCurrentRound) { if (lowerBracket[next] != null) { lowerBracket[next].reconnectTeamOneToLoserOf(upperBracket[ubLoserIndex]); lowerBracket[next].reconnectTeamTwoToLoserOf(upperBracket[ubLoserIndex - 1]); } next++; ubLoserIndex -= 2; } int lbWinnerIndex = 0; int rounds = 2 * upperBracketRounds - 2; // For the remaining lower bracket rounds, alternate between: // - odd rounds: using winners from lower bracket against loser from upper bracket. // - even rounds: using only winners of prior lower bracket round for (int r = 1; r < rounds; r++) { if (r % 2 == 1) { // Odd round // Every other odd round we take winners in the opposite order int dir = -1; if (r % 4 == 1) { ubLoserIndex = ubLoserIndex - matchesInCurrentRound + 1; dir = 1; } for (int j = 0; j < matchesInCurrentRound; j++) { if (lowerBracket[next] == null) { if (r == 1) { // This lower-bracket round one match is gone due to two byes. // We fix this in the following even round } else { Main.LOGGER.log(System.Logger.Level.ERROR, "Deserialization error: Only the first two rounds of a double-elimination lower bracket may contain a null match."); } } else if (lowerBracket[lbWinnerIndex] == null && r == 1) { // The prior lower-bracket round one match is gone due to a bye. We know the team two was the bye // and we can calculate which upper-bracket match team one should come from int ubAltLoser = upperBracket.length - (lbWinnerIndex * 2 + 2); lowerBracket[next].reconnectTeamOneToLoserOf(upperBracket[ubAltLoser]); lowerBracket[next].reconnectTeamTwoToLoserOf(upperBracket[ubLoserIndex]); } else { lowerBracket[next].reconnectTeamOneToWinnerOf(lowerBracket[lbWinnerIndex]); lowerBracket[next].reconnectTeamTwoToLoserOf(upperBracket[ubLoserIndex]); } lbWinnerIndex++; ubLoserIndex += dir; next++; } // Reset behaviour for every other odd round if (r % 4 == 1) { ubLoserIndex = ubLoserIndex - matchesInCurrentRound - 1; } } else { // Even round // The amount of matches is halved in even rounds as no teams arrive to the loser bracket matchesInCurrentRound /= 2; for (int j = 0; j < matchesInCurrentRound; j++) { if (lowerBracket[lbWinnerIndex] == null) { // This branch had two byes, so we calculate which loser from upper bracket we need int ubAltLoser = lbWinnerIndex - 1; lowerBracket[next].reconnectTeamOneToLoserOf(upperBracket[ubAltLoser]); } else { lowerBracket[next].reconnectTeamOneToWinnerOf(lowerBracket[lbWinnerIndex]); } if (lowerBracket[lbWinnerIndex + 1] == null) { // This branch had two byes, so we calculate which loser from upper bracket we need int ubAltLoser = lbWinnerIndex; lowerBracket[next].reconnectTeamTwoToLoserOf(upperBracket[ubAltLoser]); } else { lowerBracket[next].reconnectTeamTwoToWinnerOf(lowerBracket[lbWinnerIndex + 1]); } lbWinnerIndex += 2; next++; } } } } /** Reconnect final and extra match post deserialization. */ private void repairGrandFinals() { if (lowerBracket.length == 0) { // If there is no lower bracket, there are only two teams and final match is just a rematch of upper bracket finalSeries.reconnectTeamOneToLoserOf(upperBracket[0]); finalSeries.reconnectTeamTwoToWinnerOf(upperBracket[0]); } else { finalSeries.reconnectTeamOneToWinnerOf(upperBracket[0]); finalSeries.reconnectTeamTwoToWinnerOf(lowerBracket[lowerBracket.length - 1]); } extraSeries.reconnectTeamOneToWinnerOf(finalSeries); extraSeries.reconnectTeamTwoToLoserOf(finalSeries); // Listeners finalSeries.registerMatchPlayedListener(this); extraSeries.registerMatchPlayedListener(this); } /** Given an index of a match in upper bracket, this returns the index of match to the left */ private int getUpperBracketLeftIndex(int i) { return 2 * (i + 1); } /** Given an index of a match in upper bracket, this returns the index of match to the left */ private int getUpperBracketRightIndex(int i) { return 2 * (i + 1) - 1; } /** Given an index of a match in upper bracket, this returns the index of parent match */ private int getUpperBracketParentIndex(int i) { if (i == 0) { return -1; } else { return Math.floorDiv(i + 1, 2) - 1; } } @Override public void onMatchPlayed(Series series) { StageStatus oldStatus = status; boolean oldExtraMatchNeeded = isExtraMatchNeeded; if (series == finalSeries) { // This event was a change to the final. Determine if we need an extra match and set status accordingly determineIfExtraMatchNeeded(); if (!finalSeries.hasBeenPlayed() || isExtraMatchNeeded) { status = StageStatus.RUNNING; } else { status = StageStatus.CONCLUDED; } } else if (series == extraSeries && extraSeries.hasBeenPlayed() && isExtraMatchNeeded) { // The extra match has been played status = StageStatus.CONCLUDED; } else { // The final or extra match has not been played status = StageStatus.RUNNING; } // Notify listeners if status changed if (oldStatus != status || oldExtraMatchNeeded != isExtraMatchNeeded) { notifyStatusListeners(oldStatus, status); } } @Override public void setDefaultSeriesLength(int seriesLength) { if (seriesLength <= 0) throw new IllegalArgumentException("Series length must be at least one."); if (seriesLength % 2 == 0) throw new IllegalArgumentException("Series must have an odd number of matches."); defaultSeriesLength = seriesLength; } @Override public int getDefaultSeriesLength() { return defaultSeriesLength; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DoubleEliminationFormat that = (DoubleEliminationFormat) o; return upperBracketRounds == that.upperBracketRounds && isExtraMatchNeeded == that.isExtraMatchNeeded && status == that.status && Objects.equals(teams, that.teams) && Objects.equals(finalSeries, that.finalSeries) && Objects.equals(extraSeries, that.extraSeries) && Arrays.equals(upperBracket, that.upperBracket) && Arrays.equals(lowerBracket, that.lowerBracket); } @Override public int hashCode() { int result = Objects.hash(status, teams, upperBracketRounds, finalSeries, extraSeries, isExtraMatchNeeded); result = 31 * result + Arrays.hashCode(upperBracket); result = 31 * result + Arrays.hashCode(lowerBracket); return result; } }
26,911
Java
.java
ds306e18/cleopetra
9
3
14
2018-12-21T21:32:21Z
2024-05-05T19:05:17Z
IWBundleStarter.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/IWBundleStarter.java
/* * $Id: IWBundleStarter.java,v 1.5 2008/10/20 11:57:10 laddi Exp $ * Created on 2.11.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWBundleStartable; import com.idega.manager.view.ManagerViewManager; /** * * Last modified: $Date: 2008/10/20 11:57:10 $ by $Author: laddi $ * * @author <a href="mailto:tryggvil@idega.com">Tryggvi Larusson</a> * @version $Revision: 1.5 $ */ public class IWBundleStarter implements IWBundleStartable { /** * */ public IWBundleStarter() { // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see com.idega.idegaweb.IWBundleStartable#start(com.idega.idegaweb.IWBundle) */ public void start(IWBundle starterBundle) { addManagerViews(starterBundle); } /* (non-Javadoc) * @see com.idega.idegaweb.IWBundleStartable#stop(com.idega.idegaweb.IWBundle) */ public void stop(IWBundle starterBundle) { // TODO Auto-generated method stub } public void addManagerViews(IWBundle bundle){ ManagerViewManager managerViewManager = ManagerViewManager.getInstance(bundle.getApplication()); managerViewManager.initializeStandardNodes(bundle); // DefaultViewNode articleNode = new DefaultViewNode("article",contentNode); // articleNode.setJspUri(bundle.getJSPURI("articles.jsp")); // DefaultViewNode createNewArticleNode = new DefaultViewNode("create",articleNode); // //createNewArticleNode.setJspUri("/idegaweb/bundles/com.idega.webface.bundle/jsp/createarticle.jsp"); // String jspUri = bundle.getJSPURI("createarticle.jsp"); // createNewArticleNode.setJspUri(jspUri); // // DefaultViewNode previewArticlesNode = new DefaultViewNode("preview",articleNode); // //previewArticlesNode.setJspUri("/idegaweb/bundles/com.idega.webface.bundle/jsp/previewarticle.jsp"); // previewArticlesNode.setJspUri(bundle.getJSPURI("previewarticle.jsp")); // //DefaultViewNode listArticlesNode = new ApplicationViewNode("listarticles",articleNode); // // DefaultViewNode listArticlesNode = new DefaultViewNode("list",articleNode); // //previewArticlesNode.setJspUri("/idegaweb/bundles/com.idega.webface.bundle/jsp/previewarticle.jsp"); // listArticlesNode.setJspUri(bundle.getJSPURI("listarticles.jsp")); // //DefaultViewNode listArticlesNode = new ApplicationViewNode("listarticles",articleNode); // // DefaultViewNode searchArticlesNode = new DefaultViewNode("search",articleNode); // //previewArticlesNode.setJspUri("/idegaweb/bundles/com.idega.webface.bundle/jsp/previewarticle.jsp"); // searchArticlesNode.setJspUri(bundle.getJSPURI("searcharticle.jsp")); // //DefaultViewNode listArticlesNode = new ApplicationViewNode("listarticles",articleNode); // } }
2,871
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
RealPom.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/RealPom.java
/* * $Id: RealPom.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 15, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.data; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.util.FileUtil; import com.idega.util.IWTimestamp; import com.idega.util.StringHandler; import com.idega.util.xml.XMLData; import com.idega.xml.XMLElement; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class RealPom extends Pom { public static final String BUNDLES_GROUP_ID = "bundles"; public static final String SNAPSHOT = "SNAPSHOT"; public static final String BUNDLE_SUFFIX = ".bundle"; public static final String POM_FILE = "project.xml"; private static final String EXTEND = "extend"; private static final String GROUP_ID = "groupId"; private static final String NAME = "name"; static final String ARTIFACT_ID = "artifactId"; private static final String CURRENT_VERSION = "currentVersion"; private static final String DEPENDENCY = "dependency"; private static final String MANIFEST_PATH = "./META-INF/MANIFEST.MF"; private static final String BASE_PROJECT_PATH = "../com.idega.core.bundle"; private static final String BASE_PROJECT_VARIABLE = "${base.project.dir}"; // public static String convertFileName(String fileName) { // // e.g. com.idega.manager-1.0.1-SNAPSHOT.jar // if (isSnapshot(fileName)) { // String[] partOfFileName = fileName.split(ManagerConstants.ARTIFACT_ID_VERSION_SEPARATOR); // StringBuffer buffer = new StringBuffer(partOfFileName[0]); // buffer.append(ManagerConstants.ARTIFACT_ID_VERSION_SEPARATOR); // buffer.append(SNAPSHOT); // buffer.append('.'); // buffer.append(ManagerConstants.JAR_EXTENSION); // // e.g. com.idega.manager-SNAPSHOT.jar // return buffer.toString(); // } // return fileName; // } public static RealPom getInstalledPomOfGroupBundles(File projectFile) throws IOException { RealPom pom = getPom(projectFile); pom.setIsInstalled(true); // save time.... pom.groupId = BUNDLES_GROUP_ID; return pom; } public static RealPom getPom(File projectFile) throws IOException { XMLData pomData = createXMLData(projectFile); return new RealPom(pomData, projectFile); } public static XMLData createXMLData(File projectFile) throws IOException { XMLData pomData = XMLData.getInstanceForFile(projectFile); // handle extensions String superPom = pomData.getDocument().getRootElement().getTextTrim(EXTEND); //TODO thi: where can I fetch the value of the variable? if (superPom != null) { // replace if variable exists superPom = StringHandler.replace(superPom, BASE_PROJECT_VARIABLE, BASE_PROJECT_PATH); File superPomFile = FileUtil.getFileRelativeToFile(projectFile, superPom); if (superPomFile.exists()) { XMLData superPomData = createXMLData(superPomFile); // concat pomData and superPomData pomData.add(superPomData); } } return pomData; } public static boolean isSnapshot(String version) { return StringHandler.contains(version.toUpperCase(), SNAPSHOT); } // are we navigating in an eclipse project or on a web server? private boolean isEclipseProject = false; boolean isInstalled = false; protected File projectFile = null; private XMLData xmlData = null; private XMLElement root = null; private String groupId = null; private String artifactId = null; private String currentVersion = null; private boolean snapshot = false; private IWTimestamp timesstamp = null; private List dependencies = null; protected RealPom(XMLData xmlData, File projectFile) throws IOException { this.projectFile = projectFile; this.xmlData =xmlData ; initialize(); } private void initialize() throws IOException { // initilaize snapshot variable getCurrentVersion(); initializeTimestamp(); } private void initializeTimestamp() throws IOException { IWTimestamp timestamp = null; // try to get timestamp from origin file File originFile = FileUtil.getFileRelativeToFile(this.projectFile, ManagerConstants.ORIGIN_FILE); if (originFile.exists()) { BufferedReader fileReader = null; try { fileReader = new BufferedReader(new FileReader(originFile)); String orignFileName = fileReader.readLine(); timestamp = getTimestampFromFileName(orignFileName); } finally { try { if (fileReader != null) { fileReader.close(); } } catch (IOException io) { // do not hide an existing exception } } } if (timestamp == null) { // failed? try to get timestamp from corresponding MANIFEST_FILE File manifestFile = FileUtil.getFileRelativeToFile(this.projectFile, MANIFEST_PATH); if (manifestFile.exists()) { long dateValue = manifestFile.lastModified(); Date date = new Date(dateValue); timestamp = new IWTimestamp(date); } } setTimestamp(timestamp); } public void setTimestamp(IWTimestamp timestamp) { this.timesstamp = timestamp; } public String getGroupId() { if (this.groupId == null) { this.groupId = getRoot().getTextTrim(GROUP_ID); } return this.groupId; } public String getArtifactId() { if (this.artifactId == null) { this.artifactId = getRoot().getTextTrim(ARTIFACT_ID); } return this.artifactId; } public boolean isSnapshot() { return this.snapshot; } public String getCurrentVersion() { if (this.currentVersion == null) { this.currentVersion = getRoot().getTextTrim(CURRENT_VERSION); // sometimes a version is not set if (this.currentVersion == null) { this.currentVersion = ""; } this.snapshot = RealPom.isSnapshot(this.currentVersion); if (this.snapshot) { this.currentVersion = StringHandler.remove(this.currentVersion, SNAPSHOT); this.currentVersion = StringHandler.remove(this.currentVersion, "-"); } } return this.currentVersion; } private XMLElement getRoot() { if (this.root == null) { this.root = this.xmlData.getDocument().getRootElement(); } return this.root; } public List getDependencies() { return getDependencies(this); } public List getDependencies(Pom dependant) { if (this.dependencies == null) { this.dependencies = new ArrayList(); List elements = getRoot().getChildrenRecursive(DEPENDENCY); Iterator iterator = elements.iterator(); while (iterator.hasNext()) { XMLElement element = (XMLElement) iterator.next(); Dependency dependency = Dependency.getInstanceForElement(dependant, element); this.dependencies.add(dependency); } } return this.dependencies; } public Pom getPom(DependencyPomBundle dependency) throws IOException { String dependencyArtifactId = dependency.getArtifactId(); String moduleName = (isEclipseProject()) ? dependencyArtifactId : StringHandler.concat(dependencyArtifactId, BUNDLE_SUFFIX); File bundlesFolder = getBundlesFolder(this.projectFile); File module = new File(bundlesFolder, moduleName); File dependencyProjectFile = new File(module, RealPom.POM_FILE); RealPom pom = RealPom.getPom(dependencyProjectFile); pom.setEclipseProject(isEclipseProject()); pom.setIsInstalled(isInstalled()); return pom; } protected File getBundlesFolder(File startFile) { return startFile.getParentFile().getParentFile(); } public File getBundleArchive(DependencyPomBundle dependency) { return null; } public IWTimestamp getTimestamp() { return this.timesstamp; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getArtifactId()).append(" ").append(this.currentVersion).append(" ").append(this.timesstamp); return buffer.toString(); } public boolean isInstalled() { return this.isInstalled; } public void setIsInstalled(boolean isInstalled) { this.isInstalled = isInstalled; } public boolean isBundle() { return BUNDLES_GROUP_ID.equalsIgnoreCase(getGroupId()); } public Pom getPom() { return this; } public File getBundleArchive() { return null; } public boolean isIncluded() { return false; } public String getNameForLabel(IWResourceBundle resourceBundle) { String tempName = getRoot().getTextTrim(NAME); String tempArtifactId = getRoot().getTextTrim(ARTIFACT_ID); StringBuffer buffer = new StringBuffer(); buffer.append(tempName).append(" '"); buffer.append(tempArtifactId).append("'"); return buffer.toString(); } public String getCurrentVersionForLabel(IWResourceBundle resourceBundle) { String tempCurrentVersion = getRoot().getTextTrim(CURRENT_VERSION); String version = resourceBundle.getLocalizedString("man_manager_version","Version"); StringBuffer buffer = new StringBuffer(); buffer.append(version).append(" ").append(tempCurrentVersion); return buffer.toString(); } public boolean isEclipseProject() { return this.isEclipseProject; } public void setEclipseProject(boolean isEclipseProject) { this.isEclipseProject = isEclipseProject; } }
9,440
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
SimpleProxyPomList.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/SimpleProxyPomList.java
/* * Created on Apr 13, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.data; import java.util.ArrayList; import java.util.List; import com.idega.manager.maven1.business.RepositoryBrowser; /** * <p> * TODO thomas Describe Type SimpleProxyPomList * </p> * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class SimpleProxyPomList { private List simplePomProxies = null; private RepositoryBrowser repositoryBrowser = null; private ProxyPom representative = null; public SimpleProxyPomList(RepositoryBrowser repositoryBrowser) { this.repositoryBrowser = repositoryBrowser; this.simplePomProxies = new ArrayList(); } public void add(String[] simpleProxyPom) { if (this.representative == null) { ProxyPom proxyPom = ProxyPom.getInstanceOfGroupBundlesForSimpleProxyPom(simpleProxyPom, this.repositoryBrowser); if (proxyPom.shouldBeIgnored()) { return; } this.representative = proxyPom; } this.simplePomProxies.add(simpleProxyPom); } public boolean isEmpty() { return this.simplePomProxies.isEmpty(); } public ProxyPom getRepresentative() { return this.representative; } public List getSimpleProxies() { return this.simplePomProxies; } public RepositoryBrowser getRepositoryBrowser() { return this.repositoryBrowser; } }
1,531
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
RepositoryLogin.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/RepositoryLogin.java
/* * Created on Feb 15, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.data; import java.net.PasswordAuthentication; import org.apache.maven.wagon.authentication.AuthenticationInfo; /** * @author thomas * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class RepositoryLogin { public static RepositoryLogin getInstanceWithoutAuthentication(String repository) { RepositoryLogin login = new RepositoryLogin(); login.initialize(repository); return login; } public static RepositoryLogin getInstanceWithAuthentication(String repository, String userName, String password) { RepositoryLogin login = new RepositoryLogin(); login.initialize(repository, userName,password); return login; } private RepositoryLogin() { // empty } private String repository = null; private PasswordAuthentication passwordAuthentication = null; private AuthenticationInfo authenticationInfo = null; private void initialize(String repository) { this.repository = repository; } private void initialize(String repository, String userName, String password) { initialize(repository); this.passwordAuthentication = new PasswordAuthentication(userName, password.toCharArray()); this.authenticationInfo = new AuthenticationInfo(); this.authenticationInfo.setUserName(userName); this.authenticationInfo.setPassword(password); } /** * @return Returns the passwordAuthentication. */ public PasswordAuthentication getPasswordAuthentication() { return this.passwordAuthentication; } public AuthenticationInfo getAuthenticationInfo() { return this.authenticationInfo; } /** * @return Returns the repository. */ public String getRepository() { return this.repository; } }
1,931
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
Module.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/Module.java
/* * $Id: Module.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 30, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.data; import java.io.File; import java.io.IOException; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.util.VersionComparator; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public interface Module { int compare(Module module, VersionComparator versionComparator) throws IOException; int compare(Dependency dependency, VersionComparator versionComparator) throws IOException; int compare(DependencyPomBundle dependencyPomBundle, VersionComparator versionComparator) throws IOException; int compare(Pom pom, VersionComparator versionComparator) throws IOException; boolean isIncluded(); boolean isInstalled(); void setIsInstalled(boolean isInstalled); boolean isSnapshot(); String getGroupId(); String getArtifactId(); String getCurrentVersion(); String getJarFileName(); // returns the unchanged original version string String getCurrentVersionForLabel(IWResourceBundle resourceBundle); String getNameForLabel(IWResourceBundle resourceBundle); Pom getPom() throws IOException; File getBundleArchive() throws IOException; }
1,520
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ProxyPom.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/ProxyPom.java
/* * $Id: ProxyPom.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 22, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.data; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.business.RepositoryBrowser; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.util.IWTimestamp; import com.idega.util.StringHandler; /** * This class is a proxy for a real pom file. * It is initialised with a filename with arbitrary extension, that is it can be * initialised either * with a file name referring to a pom file like com.idega.block.article-20041109.112340.pom * or * with a file name referring to a iwbar file like com.idega.block.article-20041109.112340.iwbar * or * with a file name without an extension like * com.idega.block.article-20041109.112340 * * In any case the reference to the real subject is resolved by pointing to the real pom file. * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class ProxyPom extends Pom { // see examples: // com.idega.block.article-20041109.112340.pom // com.idega.core-1.9.1.pom // com.idega.content-SNAPSHOT.pom public static final String POM_EXTENSION = ".pom"; public static final String IWBAR_EXTENSION = ".iwbar"; private static Logger getLogger(){ return Logger.getLogger(ProxyPom.class.getName()); } private RealPom realSubject = null; private RepositoryBrowser repositoryBrowser = null; // Note : file name is stored without extension! private String fileName = null; private String groupId = null; private String artifactId = null; private String currentVersion = null; private boolean snapshot = false; private IWTimestamp timestamp = null; boolean isInstalled = false; private File bundleArchive = null; // better performance public static String[] getSimpleProxyPom(StringBuffer nameOfFileWithoutExtension) { return Pom.splitFileName(nameOfFileWithoutExtension); } public static ProxyPom getInstanceOfGroupBundlesForSimpleProxyPom(String[] simpleProxyPom, RepositoryBrowser repositoryBrowser) { return new ProxyPom(RealPom.BUNDLES_GROUP_ID, simpleProxyPom, repositoryBrowser); } public static ProxyPom getInstanceOfGroupBundlesWithoutFileExtension(String nameOfFileWithoutExtension, RepositoryBrowser repositoryBrowser) { return new ProxyPom(RealPom.BUNDLES_GROUP_ID, nameOfFileWithoutExtension, repositoryBrowser); } public static ProxyPom getInstanceOfGroupBundlesWithFileExtension(String nameOfFile, RepositoryBrowser repositoryBrowser) { String nameOfFileWithoutExtension = StringHandler.cutExtension(nameOfFile); return getInstanceOfGroupBundlesWithoutFileExtension(nameOfFileWithoutExtension, repositoryBrowser); } private ProxyPom(String groupId, String[] primitiveProxyPom, RepositoryBrowser repositoryBrowser) { this.groupId = groupId; this.repositoryBrowser = repositoryBrowser; initialize(primitiveProxyPom); } private ProxyPom(String groupId, String nameOfFileWithoutExtension, RepositoryBrowser repositoryBrowser) { this.groupId = groupId; this.repositoryBrowser = repositoryBrowser; this.fileName = nameOfFileWithoutExtension; String[] primitiveProxyPom = splitFileName(nameOfFileWithoutExtension); initialize(primitiveProxyPom); } private void initialize(String[] primitiveProxyPom) { this.artifactId = primitiveProxyPom[0]; String tempVersion = null; try { tempVersion = primitiveProxyPom[1]; if (this.fileName == null) { StringBuffer buffer = new StringBuffer(primitiveProxyPom[0]); buffer.append(ManagerConstants.ARTIFACT_ID_VERSION_SEPARATOR); buffer.append(primitiveProxyPom[1]); this.fileName = buffer.toString(); } } // usually does not happen catch (ArrayIndexOutOfBoundsException ex) { tempVersion = "no version available"; if (this.fileName == null) { this.fileName = primitiveProxyPom[0]; } } // is it a snapshot? // com.idega.content-SNAPSHOT.pom if (RealPom.isSnapshot(tempVersion)) { this.snapshot = true; this.currentVersion = tempVersion; } else { // is it a snapshot with a timestamp? // com.idega.block.article-20041109.112340.pom // parse timestamp this.timestamp = parseVersion(tempVersion); if (this.timestamp != null) { this.currentVersion = ""; this.snapshot = true; } } // is it a version? // com.idega.core-1.9.1.pom if (this.timestamp == null) { this.currentVersion = tempVersion; } } public String getGroupId() { return this.groupId; } public String getArtifactId() { return this.artifactId; } public String getCurrentVersion() { return this.currentVersion; } public boolean isSnapshot() { return this.snapshot; } public IWTimestamp getTimestamp() { return this.timestamp; } public String getFileName() { return this.fileName; } private RealPom getRealSubject() { if (this.realSubject == null) { String fileNameWithPomExtension = StringHandler.concat(getFileName(), POM_EXTENSION); try { File pomFile = this.repositoryBrowser.getPom(fileNameWithPomExtension); this.realSubject = RealPom.getPom(pomFile); } catch (IOException ex) { this.realSubject = null; getLogger().log(Level.WARNING, "[PomProxy] Could not download real subject: "+ getFileName() , ex); } } return this.realSubject; } public Pom getPom(DependencyPomBundle dependency) throws IOException { StringBuffer buffer = constructFileName(dependency, POM_EXTENSION); String pomFileName = this.repositoryBrowser.convertPomNameIfNecessary(buffer.toString()); return ProxyPom.getInstanceOfGroupBundlesWithFileExtension(pomFileName, this.repositoryBrowser); } public File getBundleArchive(DependencyPomBundle dependency) throws IOException { StringBuffer buffer = constructFileName(dependency, IWBAR_EXTENSION); return this.repositoryBrowser.getBundleArchive(buffer.toString()); } private StringBuffer constructFileName(DependencyPomBundle dependency, String useExtension) { String dependencyArtifactId = dependency.getArtifactId(); StringBuffer buffer = new StringBuffer(dependencyArtifactId); buffer.append(ManagerConstants.ARTIFACT_ID_VERSION_SEPARATOR); String version = dependency.getCurrentVersion(); version = RealPom.isSnapshot(version) ? RealPom.SNAPSHOT : version; return buffer.append(version).append(useExtension); } public List getDependencies() throws IOException { RealPom pom = getRealSubject(); if (pom == null) { // in this case we really need the real subject throw new IOException("[ProxyPom] Could not get my real subject. " + this.toString()); } return pom.getDependencies(this); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(this.artifactId).append(" ").append(this.fileName); return buffer.toString(); } public boolean isInstalled() { return this.isInstalled; } public void setIsInstalled(boolean isInstalled) { this.isInstalled = isInstalled; } public Pom getPom() { return this; } public File getBundleArchive() throws IOException { if (this.bundleArchive == null) { String fileNameWithBundleArchiveExtension = StringHandler.concat(getFileName(), IWBAR_EXTENSION); File bundleArchivFile = this.repositoryBrowser.getBundleArchive(fileNameWithBundleArchiveExtension); this.bundleArchive = bundleArchivFile; } return this.bundleArchive; } public boolean isIncluded() { return false; } // a proxy that points to a file // like // com.idega.content-SNAPSHOT.pom // should be ignored because there is // a corresponding identical file with a // a name that contains the timestamp. public boolean shouldBeIgnored() { return (this.snapshot && this.timestamp == null); } public String getNameForLabel(IWResourceBundle resourceBundle) { RealPom pom = getRealSubject(); if (pom == null) { StringBuffer buffer = new StringBuffer(); buffer.append("'"); buffer.append(getArtifactId()).append("'"); return buffer.toString(); } return pom.getNameForLabel(resourceBundle); } public String getCurrentVersionForLabel(IWResourceBundle resourceBundle) { Locale locale = resourceBundle.getLocale(); StringBuffer buffer = new StringBuffer(); if (isSnapshot()) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM , DateFormat.MEDIUM , locale); buffer.append(resourceBundle.getLocalizedString("man_manager_build", "Build")); buffer.append(" "); buffer.append(dateFormat.format(this.timestamp.getDate())); } else { buffer.append(resourceBundle.getLocalizedString("man_manager_version", "Version")); buffer.append(" "); buffer.append(getCurrentVersion()); } return buffer.toString(); } }
9,214
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ApplicationRealPom.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/ApplicationRealPom.java
/* * Created on Mar 30, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.data; import java.io.File; import java.io.IOException; import com.idega.util.FileUtil; import com.idega.util.xml.XMLData; /** * <p> * TODO thomas Describe Type ApplicationRealPom * </p> * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class ApplicationRealPom extends RealPom { public static ApplicationRealPom getPomForApplication(File projectFile) throws IOException { XMLData pomData =RealPom.createXMLData(projectFile); return new ApplicationRealPom(pomData, projectFile); } protected ApplicationRealPom(XMLData xmlData, File projectFile) throws IOException { super(xmlData, projectFile); } protected File getBundlesFolder(File startFile) { if (isEclipseProject()) { return FileUtil.getFileRelativeToFile(startFile, "../.."); } return FileUtil.getFileRelativeToFile(startFile, "./idegaweb/bundles"); } }
1,161
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
Dependency.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/Dependency.java
/* * $Id: Dependency.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 19, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.data; import java.io.File; import java.io.IOException; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.util.VersionComparator; import com.idega.xml.XMLElement; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class Dependency extends ModulePomImpl { private static final String GROUP_ID = "groupId"; private static final String VERSION = "version"; private static final String JAR = "jar"; private static final String PROPERTIES = "properties"; private static final String INCLUDED_IN_BUNDLE = "idegaweb.bundle.include"; public static Dependency getInstanceForElement(Pom dependant, XMLElement element) { String tempGroupId = element.getTextTrim(GROUP_ID); Dependency dependency = null; if (DependencyPomBundle.GROUP_ID_BUNDLE.equalsIgnoreCase(tempGroupId)) { dependency = new DependencyPomBundle(); } else { dependency = new Dependency(); } String tempArtifactId = element.getTextTrim(RealPom.ARTIFACT_ID); String tempVersion = element.getTextTrim(VERSION); // sometimes version is not set, set version to an empty string if (tempVersion == null) { tempVersion = ""; } String tempJarFileName = element.getTextTrim(JAR); // note: in most cases this string will be null XMLElement propertiesElement = element.getChild(PROPERTIES); if (propertiesElement != null) { String tempIncludedInBundle = propertiesElement.getTextTrim(INCLUDED_IN_BUNDLE); if (tempIncludedInBundle != null) { // note: Boolean.getBoolean(String) does not work properly dependency.setIncludedInBundle((new Boolean(tempIncludedInBundle)).booleanValue()); } } dependency.setJarFileName(tempJarFileName); dependency.setDependantPom(dependant); dependency.setIsInstalled(dependant.isInstalled()); dependency.setGroupId(tempGroupId); dependency.setArtifactId(tempArtifactId); dependency.setCurrentVersion(tempVersion); return dependency; } String groupId = null; String artifactId = null; String version = null; String jarFileName = null; boolean includedInBundle = false; boolean isInstalled = false; Pom dependantPom = null; public String getArtifactId() { return this.artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public Pom getDependantPom() { return this.dependantPom; } public void setDependantPom(Pom dependantPom) { this.dependantPom = dependantPom; } public String getGroupId() { return this.groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getCurrentVersion() { return this.version; } public void setCurrentVersion(String version) { this.version = version; } public boolean isInstalled() { return this.isInstalled; } public void setIsInstalled(boolean isInstalled) { this.isInstalled = isInstalled; } public Pom getPom() throws IOException { return null; } public File getBundleArchive() throws IOException { return null; } public boolean isIncluded() { return true; } public boolean isSnapshot() { return false; } public int compare(Pom pom, VersionComparator versionComparator) throws IOException{ // not supported, it has never the same group id return -1; } public int compare(DependencyPomBundle dependencyPomBundle, VersionComparator versionComparator) throws IOException { // not supported, it has never the same group id return -1; } public int compare(Dependency dependency, VersionComparator versionComparator) { String version1 = getCurrentVersion(); String version2 = dependency.getCurrentVersion(); int result = versionComparator.compare(version1, version2); // if both are equal the installed one wins if (result == 0) { if (isInstalled() && dependency.isInstalled()) { return 0; } if (isInstalled()) { return 1; } if (dependency.isInstalled()) { return -1; } } return result; } // you can only compare a dependency with another dependency public int compare(Module module, VersionComparator versionComparator) throws IOException { // change algebraic sign of returned result return - (module.compare(this, versionComparator)); } public String getCurrentVersionForLabel(IWResourceBundle resourcreBundle) { return getCurrentVersion(); } public String getNameForLabel(IWResourceBundle resourceBundle) { StringBuffer buffer = new StringBuffer(); buffer.append(getArtifactId()); buffer.append(" ("); buffer.append(getGroupId()); buffer.append(")"); return buffer.toString(); } public String getJarFileName() { return this.jarFileName; } public void setJarFileName(String jarFileName) { this.jarFileName = jarFileName; } public static String getINCLUDED_IN_BUNDLE() { return INCLUDED_IN_BUNDLE; } public boolean isIncludedInBundle() { return this.includedInBundle; } public void setIncludedInBundle(boolean includedInBundle) { this.includedInBundle = includedInBundle; } }
5,390
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
DependencyPomBundle.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/DependencyPomBundle.java
/* * $Id: DependencyPomBundle.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Dec 1, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.data; import java.io.File; import java.io.IOException; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.util.VersionComparator; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class DependencyPomBundle extends Dependency { public static final String GROUP_ID_BUNDLE = "bundles"; Boolean isSnapshot = null; Pom pom = null; File bundleArchive = null; DependencyPomBundle() { // use the class method of Dependency } public Pom getPom() throws IOException { if (this.pom == null) { this.pom = getDependantPom().getPom(this); } return this.pom; } public File getBundleArchive() throws IOException { if (this.bundleArchive == null) { this.bundleArchive = getDependantPom().getBundleArchive(this); } return this.bundleArchive; } public boolean isIncluded() { return false; } public int compare(Module module, VersionComparator versionComparator) throws IOException { // change algebraic sign of returned result return - (module.compare(this, versionComparator)); } public int compare(Dependency dependency, VersionComparator versionComparator) { // not supported, it has never the same group id return -1; } public int compare(DependencyPomBundle dependencyPomBundle, VersionComparator versionComparator) throws IOException { // Case 1: both are snapshots if (isSnapshot() && dependencyPomBundle.isSnapshot()) { // compare timestamps Pom tempPom = dependencyPomBundle.getPom(); return compare(tempPom, versionComparator); } return compareModules(dependencyPomBundle, versionComparator); } public int compare(Pom aPom, VersionComparator versionComparator) throws IOException { // Case 1: both are snapshots if (isSnapshot() && aPom.isSnapshot()) { // compare timestamps Pom tempPom = getPom(); return tempPom.compare(aPom, versionComparator); } return compareModules(aPom, versionComparator); } public boolean isSnapshot() { if (this.isSnapshot == null) { String tempVersion = getCurrentVersion(); this.isSnapshot = new Boolean(RealPom.isSnapshot(tempVersion)); } return this.isSnapshot.booleanValue(); } public String getCurrentVersionForLabel(IWResourceBundle resourceBundle) { Pom tempPom = null; try { tempPom = getPom(); } catch (IOException ex) { String problem = resourceBundle.getLocalizedString("man_manager_could_not_ figure_out_version","Could not figure out version"); StringBuffer buffer = new StringBuffer(); buffer.append(problem); buffer.append(" "); buffer.append(getCurrentVersion()); return buffer.toString(); } return tempPom.getCurrentVersionForLabel(resourceBundle); } public String getNameForLabel(IWResourceBundle resourceBundle) { Pom tempPom = null; try { tempPom = getPom(); } catch (IOException ex) { String problem = resourceBundle.getLocalizedString("man_manager_could_not_ figure_out_name_for","Could not figure out name for"); StringBuffer buffer = new StringBuffer(); buffer.append(problem); buffer.append(" "); buffer.append(getArtifactId()); buffer.append(" ("); buffer.append(getGroupId()); buffer.append(")"); return buffer.toString(); } return tempPom.getNameForLabel(resourceBundle); } }
3,707
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
Pom.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/Pom.java
/* * $Id: Pom.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 26, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.data; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.manager.maven1.util.VersionComparator; import com.idega.util.IWTimestamp; import com.idega.util.StringHandler; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public abstract class Pom extends ModulePomImpl { public static final String POM_TIMESTAMP_FORMAT = "yyyyMMdd.HHmmss"; private static SimpleDateFormat dateParser = null; private static SimpleDateFormat getDateParser() { if (dateParser == null) { dateParser = new SimpleDateFormat(POM_TIMESTAMP_FORMAT); } return dateParser; } public abstract List getDependencies() throws IOException; public abstract Pom getPom(DependencyPomBundle dependency) throws IOException; public abstract File getBundleArchive(DependencyPomBundle dependency) throws IOException; public abstract boolean isSnapshot(); public abstract IWTimestamp getTimestamp(); public int compare(Dependency dependency, VersionComparator versionComparator) { // not supported, it has never the same group id return -1; } public int compare(Module module, VersionComparator versionComparator) throws IOException { // change the algebraic sign of the returned result return -(module.compare(this, versionComparator)); } public int compare(DependencyPomBundle dependency, VersionComparator versionComparator) throws IOException { // change the algebraic sign of the returned result return -(dependency.compare(this, versionComparator)); } public int compare(Pom aPom, VersionComparator versionComparator) { if (isSnapshot() && aPom.isSnapshot()) { IWTimestamp timestamp1 = getTimestamp(); IWTimestamp timestamp2 = aPom.getTimestamp(); return timestamp1.compareTo(timestamp2); } return compareModules(aPom, versionComparator); } /** * Returns timestamp from filename else null * */ protected IWTimestamp getTimestampFromFileName(String fileNameWithExtension) { String nameWithoutExtension = StringHandler.cutExtension(fileNameWithExtension); String[] partOfFileName = splitFileName(nameWithoutExtension); try { String version = partOfFileName[1]; if (RealPom.isSnapshot(version)) { // like: com.idega.content-SNAPSHOT.pom return null; } // like: com.idega.block.article-20041109.112340.pom return parseVersion(version); } // usually does not happen catch (ArrayIndexOutOfBoundsException ex) { return null; } } protected static String[] splitFileName(StringBuffer fileNameWithoutExtension) { // myfaces-1.0.5 -> myfaces, 1.0.5 // jaxen-1.0-FCS-full -> jaxen, 1.0-FCS-full int index = fileNameWithoutExtension.indexOf(ManagerConstants.ARTIFACT_ID_VERSION_SEPARATOR); try { String name = fileNameWithoutExtension.substring(0, index); index++; String version = fileNameWithoutExtension.substring(index, fileNameWithoutExtension.length()); String[] result = {name, version} ; return result; } // usually does not happen catch (StringIndexOutOfBoundsException ex) { String[] result = {fileNameWithoutExtension.toString()}; return result; } } protected String[] splitFileName(String fileNameWithoutExtension) { return Pom.splitFileName(new StringBuffer(fileNameWithoutExtension)); } protected static IWTimestamp parseVersion(String version) { SimpleDateFormat parser = Pom.getDateParser(); try { Date date = parser.parse(version); IWTimestamp timestamp = new IWTimestamp(date); return timestamp; } catch (ParseException ex) { // do nothing return null; } } }
4,137
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ModulePomImpl.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/data/ModulePomImpl.java
/* * Created on Mar 23, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.data; import com.idega.manager.maven1.util.VersionComparator; /** * <p> * TODO thomas Describe Type ModulePomImpl * </p> * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public abstract class ModulePomImpl implements Module { public String getJarFileName() { return null; } protected int compareModules(Module module, VersionComparator versionComparator) { if (! ( isSnapshot() || module.isSnapshot()) ) { // Case 2: both are not snapshots !!!! String version1 = getCurrentVersion(); String version2 = module.getCurrentVersion(); int result = versionComparator.compare(version1, version2); // if both are equal the installed one wins if (result == 0) { if ( isInstalled() && module.isInstalled()) { return 0; } if ( isInstalled()) { return 1; } if (module.isInstalled()) { return -1; } } return result; } // Case 3: only one of them are snapshots // ------------- that is you can not compare them --------------------- // or the result was zero // module that is not installed wins if ( isInstalled() && ! module.isInstalled()) { // that is: dependencyPomBundle is not installed return -1; } if (! isInstalled() && module.isInstalled()) { // that is: this is not installed return 1; } return 0; } }
1,631
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
VersionComparator.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/util/VersionComparator.java
/* * Created on Mar 14, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.util; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * <p> * TODO thomas Describe Type VersionComparator * </p> * Last modified: $Date: 2008/06/11 21:10:02 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class VersionComparator implements Comparator{ private static Map pattern; private static final Integer MAIN_DELIMITER = new Integer(-4242); private static final Integer ZERO = new Integer(0); private static String[] patternKeys = { "rc", "m", "pre", "alpha", "beta", "gamma", "delta" }; private static int[] patternValues = { -1, -2, -3, -10, -9, -8, -7 }; static { pattern = new HashMap(); for (int i = 0; i < patternKeys.length; i++) { String key = patternKeys[i]; Integer value = new Integer(patternValues[i]); pattern.put( key, value); } } private Map convertedVersions; // // only for testing // public static void test(String[] arg) { // VersionComparator comparator = new VersionComparator(); // List list1 = comparator.convertVersion("3.0RC2"); // //result: [[3], [0, -2, 2]] // List list2 = comparator.convertVersion("3.001RC3"); // //result: [[3], [1, -2, 3]] // List list3 = comparator.convertVersion("3.02.1234.123pre123"); // // result: [[3], [2], [1234], [123, -3, 123]] // List list4 = comparator.convertVersion("123.02abcdz-pre"); // // result: [[123], [2, -103, -102, -101, -100, -78], [-3]] // SortedSet map = new TreeSet(comparator); // map.add("3.01RC2"); // map.add("3"); // map.add("3.0RC2"); // map.add("3.1RC4"); // map.add("3.0m2"); // map.add("3.0.0"); // map.add("3.0.03"); // map.add("3.M1"); // Iterator iterator = map.iterator(); // while (iterator.hasNext()) { // System.out.println(iterator.next()); // } // } public int compare(String version1, String version2) { List list1 = getConvertedVersion(version1); List list2 = getConvertedVersion(version2); return compare(list1, list2); } public int compare(Object o1, Object o2) { return compare((String) o1, (String) o2); } public int compare(List convertedVersion1, List convertedVersion2) { int index = 0; int length1 = convertedVersion1.size(); int length2 = convertedVersion2.size(); while (true) { boolean indexLessThan1 = index < length1; boolean indexLessThan2 = index < length2; if ((! indexLessThan1) && (! indexLessThan2)) { return 0; } Integer integer1 = (indexLessThan1) ? (Integer) convertedVersion1.get(index) : ZERO; Integer integer2 = (indexLessThan2) ? (Integer) convertedVersion2.get(index) : ZERO; int result = integer1.compareTo(integer2); if (result != 0) { if (! ( ( ZERO.equals(integer1) && MAIN_DELIMITER.equals(integer2) ) || ( MAIN_DELIMITER.equals(integer1) && ZERO.equals(integer2) ) ) ) { return result; } } index++; } } private List getConvertedVersion(String version) { // caching and shortcut if (this.convertedVersions == null) { this.convertedVersions = new HashMap(); } List list = null; if (this.convertedVersions.containsKey(version)) { list = (List) this.convertedVersions.get(version); } else { list = convertVersion(version); this.convertedVersions.put(version, list); } return list; } private List convertVersion(String version) { List resultList = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(version, "-._"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); int index = 0; StringBuffer buffer = new StringBuffer(); boolean readingNumber = false; boolean readingString = false; while (index < token.length()) { char c = token.charAt(index); if (Character.isDigit(c)) { // reading number if (readingString) { addUnicodeValuesOfString(buffer, resultList); buffer = new StringBuffer(); readingString = false; } readingNumber = true; buffer.append(c); } else { // reading string if (readingNumber) { resultList.add(new Integer(buffer.toString())); buffer = new StringBuffer(); readingNumber = false; } readingString = true; buffer.append(c); // check for pattern String temp = buffer.toString(); temp = temp.toLowerCase(); if (pattern.containsKey(temp)) { resultList.add(pattern.get(temp)); readingString = false; buffer = new StringBuffer(); } } index++; } if (readingNumber) { resultList.add(new Integer(buffer.toString())); } else { addUnicodeValuesOfString(buffer, resultList); } resultList.add(MAIN_DELIMITER); } return resultList; } private void addUnicodeValuesOfString(StringBuffer buffer, List list) { for (int i=0; i < buffer.length(); i++) { char c = buffer.charAt(i); // shift the value to a negative number int k = c -200; Integer integerValue = new Integer(k); list.add(integerValue); } } }
5,288
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ManagerConstants.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/util/ManagerConstants.java
/* * Created on Jan 5, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.util; /** * @author thomas * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ManagerConstants { public static final String ARTIFACT_ID_VERSION_SEPARATOR = "-"; public static final String JAR_EXTENSION = "jar"; public static final String BUNDLE_EXTENSION = "bundle"; public static final String ORIGIN_FILE = "META-INF-ORIGIN"; // for testing use this one: user is "joeuser" pasword: "a.b.C.D" //public static final String IDEGA_REPOSITORY_URL = "http://www.rahul.net/joeuser/"; public static final String IDEGA_REPOSITORY_URL = "http://repository.idega.com/maven2/"; //public static final String BUNDLES_DEFAULT_GROUP="bundles"; public static final String BUNDLES_DEFAULT_GROUP="com.idega.block.addons"; // JSF input references public static final String JSF_COMPONENT_ID_MULTI_SELECT_1 = "form1:multiSelectListbox1"; // for input login; private static final String JSF_COMPONENT_ID_FORM = "loginManagerForm1"; public static final String JSF_COMPONENT_ID_REPOSITORY = "textField1"; public static final String JSF_COMPONENT_ID_REPOSITORY_PATH = JSF_COMPONENT_ID_FORM + ":" + JSF_COMPONENT_ID_REPOSITORY; public static final String JSF_COMPONENT_ID_USERNAME = "textField2"; public static final String JSF_COMPONENT_ID_USERNAME_PATH = JSF_COMPONENT_ID_FORM + ":" + JSF_COMPONENT_ID_USERNAME; public static final String JSF_COMPONENT_ID_PASSWORD = "secretField1"; public static final String JSF_COMPONENT_ID_PASSWORD_PATH = JSF_COMPONENT_ID_FORM + ":" + JSF_COMPONENT_ID_PASSWORD; // navigation rules public static final String ACTION_NEXT = "next"; public static final String ACTION_BACK = "back"; public static final String ACTION_CANCEL = "cancel"; public static final String ACTION_INSTALL_NEW_MODULES = "installNewModules"; public static final String ACTION_UPDATE_MODULES = "updateModules"; public static final String ACTION_BACK_INSTALL = "backInstall"; public static final String ACTION_BACK_UPDATE = "backUpdate"; // class references public static final String JSF_VALUE_REFERENCE_INSTALL_LIST_MANAGER = "#{InstallListManager}"; public static final String JSF_VALUE_REFERENCE_UPDATE_LIST_MANAGER = "#{UpdateListManager}"; public static final String JSF_VALUE_REFERENCE_MODULE_MANAGER = "#{ModuleManager}"; public static final String JSF_VALUE_REFERENCE_LOGIN_MANAGER = "#{LoginManager}"; public static final String JSF_VALUE_REFERENCE_INSTALL_OR_UPDATE_MANAGER = "#{InstallOrUpdateManager}"; public static final String JSF_VALUE_REFERENCE_INSTALL_NEW_MODULE_LIST_MANAGER = "#{InstallNewModuleListManager}"; }
2,872
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ManagerUtils.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/util/ManagerUtils.java
/* * $Id: ManagerUtils.java,v 1.1 2008/06/11 21:10:02 tryggvil Exp $ * Created on Nov 5, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.util; import java.io.File; import javax.faces.application.Application; import javax.faces.context.FacesContext; import javax.faces.el.ValueBinding; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.bean.InstallListManager; import com.idega.manager.bean.InstallNewModuleListManager; import com.idega.manager.bean.InstallOrUpdateManager; import com.idega.manager.bean.LoginManager; import com.idega.manager.bean.ModuleManager; import com.idega.manager.bean.UpdateListManager; import com.idega.manager.maven1.business.PomSorter; import com.idega.manager.maven1.data.RepositoryLogin; import com.idega.presentation.IWContext; /** * * Last modified: $Date: 2008/06/11 21:10:02 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class ManagerUtils { public static final String BUNDLE_IDENTIFIER = "com.idega.manager"; public static ManagerUtils getInstanceForCurrentContext() { return new ManagerUtils(); } public static InstallListManager getInstallListManager() { return (InstallListManager) getInstanceForCurrentContext().getValue(ManagerConstants.JSF_VALUE_REFERENCE_INSTALL_LIST_MANAGER); } public static UpdateListManager getUpdateListManager() { return (UpdateListManager) getInstanceForCurrentContext().getValue(ManagerConstants.JSF_VALUE_REFERENCE_UPDATE_LIST_MANAGER); } public static InstallNewModuleListManager getInstallNewModuleListManager() { return (InstallNewModuleListManager) getInstanceForCurrentContext().getValue(ManagerConstants.JSF_VALUE_REFERENCE_INSTALL_NEW_MODULE_LIST_MANAGER); } public static ModuleManager getModuleManager() { return (ModuleManager) getInstanceForCurrentContext().getValue(ManagerConstants.JSF_VALUE_REFERENCE_MODULE_MANAGER); } public static PomSorter getPomSorter() { InstallOrUpdateManager installOrUpdateManager = (InstallOrUpdateManager) getInstanceForCurrentContext().getValue(ManagerConstants.JSF_VALUE_REFERENCE_INSTALL_OR_UPDATE_MANAGER); return installOrUpdateManager.getPomSorter(); } public static RepositoryLogin getRepositoryLogin() { LoginManager loginManager = (LoginManager) getInstanceForCurrentContext().getValue(ManagerConstants.JSF_VALUE_REFERENCE_LOGIN_MANAGER); return loginManager.getRepositoryLogin(); } private FacesContext facesContext = null; private Application application = null; private IWContext context = null; private IWBundle bundle = null; private IWResourceBundle resourceBundle = null; private IdegawebDirectoryStructure idegawebDirectoryStructure; private ManagerUtils() { this.facesContext = FacesContext.getCurrentInstance(); this.application = this.facesContext.getApplication(); this.context = IWContext.getIWContext(this.facesContext); this.idegawebDirectoryStructure = new IdegawebDirectoryStructure(this.context); } public FacesContext getFacesContext() { return this.facesContext; } public IWContext getIWContext() { return this.context; } public Application getApplication() { return this.application; } public IWBundle getBundle() { if (this.bundle == null) { getBundleAndResourceBundle(); } return this.bundle; } public IWResourceBundle getResourceBundle(){ if (this.resourceBundle == null) { getBundleAndResourceBundle(); } return this.resourceBundle; } public IdegawebDirectoryStructure getIdegawebDirectoryStructure() { return this.idegawebDirectoryStructure; } public File getBundlesRealPath() { return this.idegawebDirectoryStructure.getBundlesRealPath(); } public File getWorkingDirectory() { return this.idegawebDirectoryStructure.getWorkingDirectory(); } public Object getValue(String valueRef) { ValueBinding binding = this.application.createValueBinding(valueRef); return binding.getValue(this.context); } private void getBundleAndResourceBundle() { this.bundle = this.context.getIWMainApplication().getBundle(BUNDLE_IDENTIFIER); this.resourceBundle = this.bundle.getResourceBundle(this.context.getExternalContext().getRequestLocale()); } }
4,430
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
IdegawebDirectoryStructure.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/util/IdegawebDirectoryStructure.java
/* * Created on Jan 4, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.util; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.idega.idegaweb.IWMainApplication; import com.idega.io.ZipInstaller; import com.idega.manager.maven1.data.Module; import com.idega.presentation.IWContext; /** * @author thomas * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class IdegawebDirectoryStructure { // keys private static final String BACKUP_FOLDER_KEY = "backupFolderKey"; private static final String WORKING_DIRECTORY_KEY= "auxiliaryManagerFolder"; private static final String APPLICATION_KEY = "application"; private static final String WEB_INF_KEY = "WEB_INF"; private static final String LIBRARY_KEY = "library"; private static final String TAG_LIBRARY_KEY ="tagLibrary"; private static final String FACES_CONFIG_FILE_KEY ="facesConfig"; private static final String DEPLOYMENT_DESCRIPTOR_FILE_KEY = "web"; private static final String APPLICATION_SPECIAL_KEY = "applicationSpecial"; private static final String BUNDLES_KEY = "bundles"; // real existing folders or files private static final String BACKUP_FOLDER = "backupManager"; private static final String WORKING_FOLDER = "auxiliaryManager"; private static final String FACES_CONFIG_FILE = "faces-config.xml"; private static final String WEB_DEPLOYMENT_FILE = "web.xml"; private static final String WEB_INF_FOLDER = "WEB-INF"; private static final String WEB_LIBRARY_FOLDER = "lib"; private static final String WEB_TAG_LIBRARY_FOLDER = "tld"; private IWContext context = null; private Map pathes = null; public IdegawebDirectoryStructure(IWContext context) { this.context = context; } public File getDeploymentDescriptor() { return getPath(DEPLOYMENT_DESCRIPTOR_FILE_KEY); } public File getFacesConfig() { return getPath(FACES_CONFIG_FILE_KEY); } public File getBundlesRealPath() { return getPath(BUNDLES_KEY); } public File getLibrary() { return getPath(LIBRARY_KEY); } public File getTagLibrary() { return getPath(TAG_LIBRARY_KEY); } public File getBackupDirectory() { File backupDirectory = getPath(BACKUP_FOLDER_KEY); if (! backupDirectory.exists()) { backupDirectory.mkdir(); } return backupDirectory; } public File getWorkingDirectory() { File workingDir = getPath(WORKING_DIRECTORY_KEY); if (! workingDir.exists()) { workingDir.mkdir(); } return workingDir; } public File getDeploymentDescriptor(Module module) throws IOException { File webInf = getWebInf(module); return new File(webInf, WEB_DEPLOYMENT_FILE); } public File getFacesConfig(Module module) throws IOException { File webInf = getWebInf(module); return new File(webInf, FACES_CONFIG_FILE); } public File getLibrary(Module module) throws IOException { File webInf = getWebInf(module); return new File(webInf, WEB_LIBRARY_FOLDER); } public File getTagLibrary(Module module) throws IOException { File webInf = getWebInf(module); return getTagLibraryFromWebInf(webInf); } public File getTagLibrary(File bundleFolder) { File webInf = getWebInf(bundleFolder); return getTagLibraryFromWebInf(webInf); } public File getExtractedArchive(Module module) throws IOException { File bundleArchive = module.getBundleArchive(); File temporaryInstallationFolder = bundleArchive.getParentFile(); String artifactId = module.getArtifactId(); File extractedArchive = new File (temporaryInstallationFolder, artifactId); if (! extractedArchive.exists()) { extractedArchive.mkdir(); ZipInstaller zipInstaller = new ZipInstaller(); zipInstaller.extract(bundleArchive, extractedArchive); String bundleArchiveName = bundleArchive.getName(); // write the name of the source file into the origin file File originFile = new File(extractedArchive, ManagerConstants.ORIGIN_FILE); // check first if file exist to avoid an exception if (! originFile.exists()) { FileWriter writer = null; try { originFile.createNewFile(); writer = new FileWriter(originFile); writer.write(bundleArchiveName); } finally { writer.close(); } } } return extractedArchive; } public File getCorrespondingFileFromWebInf(Module module, File fileInWebInf) throws IOException { String name = fileInWebInf.getName(); File webInf = getWebInf(module); return new File(webInf, name); } private File getWebInf(Module module) throws IOException { File extractedArchive = getExtractedArchive(module); return getWebInf(extractedArchive); } private File getWebInf(File bundleFolder) { return new File(bundleFolder, WEB_INF_FOLDER); } private File getTagLibraryFromWebInf(File webInf) { return new File(webInf, WEB_TAG_LIBRARY_FOLDER); } private File getPath(String key) { if (this.pathes == null) { initializePathes(); } return (File) this.pathes.get(key); } private void initializePathes() { this.pathes = new HashMap(); IWMainApplication mainApplication = this.context.getIWMainApplication(); File application = new File(mainApplication.getApplicationRealPath()); this.pathes.put(APPLICATION_KEY, application); File bundles = new File(mainApplication.getBundlesRealPath()); this.pathes.put(BUNDLES_KEY, bundles); File applicationSpecial = new File(mainApplication.getApplicationSpecialRealPath()); this.pathes.put(APPLICATION_SPECIAL_KEY, applicationSpecial); this.pathes.put(WORKING_DIRECTORY_KEY, new File(applicationSpecial, WORKING_FOLDER)); this.pathes.put(BACKUP_FOLDER_KEY, new File(applicationSpecial, BACKUP_FOLDER)); File webInf = new File(application, WEB_INF_FOLDER); this.pathes.put(WEB_INF_KEY, webInf); this.pathes.put(FACES_CONFIG_FILE_KEY, new File(webInf, FACES_CONFIG_FILE)); this.pathes.put(DEPLOYMENT_DESCRIPTOR_FILE_KEY, new File(webInf, WEB_DEPLOYMENT_FILE)); this.pathes.put(LIBRARY_KEY, new File(webInf, WEB_LIBRARY_FOLDER)); this.pathes.put(TAG_LIBRARY_KEY, new File(webInf, WEB_TAG_LIBRARY_FOLDER)); } }
6,301
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
MapCreator.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/freemind/MapCreator.java
/* * Created on Mar 29, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.freemind; import java.io.File; import java.io.IOException; import java.util.ArrayList; 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 javax.swing.JFileChooser; import javax.swing.JFrame; import com.idega.manager.maven1.data.ApplicationRealPom; import com.idega.manager.maven1.data.Dependency; import com.idega.manager.maven1.data.Module; import com.idega.manager.maven1.data.Pom; import com.idega.manager.maven1.data.RealPom; import com.idega.util.xml.XMLData; import com.idega.xml.XMLDocument; import com.idega.xml.XMLElement; /** * <p> * TODO thomas Describe Type MapCreator * </p> * Last modified: $Date: 2008/06/11 21:10:02 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class MapCreator { private int counter = 0; private Map artifactCounter = null; private Map artifactVersion = null; private Map artifactNode = null; private List artifactPom = null; private List artifactIsIncluded = null; private Set artifactIsNotIncluded = null; public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File("../")); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.showOpenDialog(frame); File workspace = chooser.getSelectedFile(); if (workspace != null) { File application = workspace; //new File(workspace, "applications/eplatform"); //File webApplication = new File(application, "target/eplatform"); MapCreator mapCreator = new MapCreator(); mapCreator.createMindMap(application, workspace, false, "webApp.mm"); //mapCreator.createMindMap(application, workspace, true, "workspace.mm"); } frame.dispose(); } private void createMindMap(File application, File workspace, boolean eclipseProject, String outputName) { // reset counter and map this.counter = 0; this.artifactCounter = new HashMap(); this.artifactVersion = new HashMap(); this.artifactNode = new HashMap(); this.artifactPom = new ArrayList(); this.artifactIsIncluded = new ArrayList(); this.artifactIsNotIncluded = new HashSet(); File projectFile = new File(application, RealPom.POM_FILE); if (projectFile.exists()) { try { RealPom pom = ApplicationRealPom.getPomForApplication(projectFile); pom.setEclipseProject(eclipseProject); String artifactId = pom.getArtifactId(); XMLData data = XMLData.getInstanceWithoutExistingFileSetNameSetRootName("weser", "map"); XMLDocument document = data.getDocument(); XMLElement root = document.getRootElement(); root.setAttribute("version","0.7.1"); XMLElement node = new XMLElement("node"); node.setAttribute("TEXT", artifactId); // root is set createBranches(node, pom); createNotIncludedNode(node); root.addContent(node); File output = new File(workspace, outputName); output.createNewFile(); data.writeToFile(output); } catch (IOException ex) { System.err.println("Could not open "+ projectFile.getPath()); } } } private void createBranches(XMLElement parentNode, Pom pom) throws IOException { List dependencies = pom.getDependencies(); Comparator comparator = new Comparator() { public int compare(Object o1, Object o2) { String artifactId1= ((Module) o1).getArtifactId(); String artifactId2 = ((Module) o2).getArtifactId(); return artifactId1.compareTo(artifactId2); } }; Collections.sort(dependencies, comparator); Iterator iterator = dependencies.iterator(); while (iterator.hasNext()) { String currentId = Integer.toString(this.counter++); Dependency dependency = (Dependency) iterator.next(); String dependencyArtifactId = dependency.getArtifactId(); String version = dependency.getCurrentVersion(); StringBuffer buffer = new StringBuffer(dependencyArtifactId).append(" ").append(version); if (dependency.isIncludedInBundle()) { if (this.artifactIsIncluded.contains(dependencyArtifactId)) { buffer.append(" INCLUDED AGAIN"); } else { if (this.artifactIsNotIncluded.contains(dependencyArtifactId)) { this.artifactIsNotIncluded.remove(dependencyArtifactId); } this.artifactIsIncluded.add(dependencyArtifactId); buffer.append(" INCLUDED"); } } else if ((! this.artifactIsIncluded.contains(dependencyArtifactId)) && (! dependencyArtifactId.startsWith("com.idega")) && (! dependencyArtifactId.startsWith("se.idega")) && (! dependencyArtifactId.startsWith("is.idega"))) { this.artifactIsNotIncluded.add(dependencyArtifactId); } if (this.artifactPom.contains(dependencyArtifactId)) { buffer.append(" -->"); } XMLElement dependencyNode = new XMLElement("node"); dependencyNode.setAttribute("POSITION", "RIGHT"); dependencyNode.setAttribute("ID", currentId); parentNode.addContent(dependencyNode); // update map if (this.artifactCounter.containsKey(dependencyArtifactId)) { // create a link to the existing node String destination = (String) this.artifactCounter.get(dependencyArtifactId); XMLElement arrow = new XMLElement("arrowlink"); arrow.setAttribute("ENDARROW","Default"); arrow.setAttribute("DESTINATION", destination); arrow.setAttribute("STARTARROW", "None"); // change color if there is an inconsistency String otherVersion = (String) this.artifactVersion.get(dependencyArtifactId); if (! version.equalsIgnoreCase(otherVersion) ) { XMLElement originNode = (XMLElement) this.artifactNode.get(dependencyArtifactId); originNode.setAttribute("COLOR", "#0000cc"); dependencyNode.setAttribute("COLOR","#ff0000"); arrow.setAttribute("COLOR","#ff0000"); } dependencyNode.addContent(arrow); } else { this.artifactCounter.put(dependencyArtifactId, currentId); this.artifactVersion.put(dependencyArtifactId, version); this.artifactNode.put(dependencyArtifactId, dependencyNode); Pom dependencyPom = dependency.getPom(); if (dependencyPom != null) { this.artifactPom.add(dependencyArtifactId); dependencyNode.setAttribute("FOLDED", "true"); dependencyNode.setAttribute("COLOR", "#990099"); createBranches(dependencyNode, dependencyPom); } } dependencyNode.setAttribute("TEXT", buffer.toString()); } } private void createNotIncludedNode(XMLElement parentNode) { XMLElement dependencyNode = new XMLElement("node"); dependencyNode.setAttribute("POSITION", "RIGHT"); dependencyNode.setAttribute("TEXT", "not included modules"); parentNode.addContent(dependencyNode); Iterator iterator = this.artifactIsNotIncluded.iterator(); while (iterator.hasNext()) { String dependencyArtifactId = (String) iterator.next(); XMLElement node = new XMLElement("node"); node.setAttribute("POSITION", "RIGHT"); node.setAttribute("TEXT", dependencyArtifactId); dependencyNode.addContent(node); } } }
7,369
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
PomSorter.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/PomSorter.java
/* * $Id: PomSorter.java,v 1.1 2008/06/11 21:10:02 tryggvil Exp $ * Created on Nov 22, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.business; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import com.idega.manager.maven1.data.Module; import com.idega.manager.maven1.data.Pom; import com.idega.manager.maven1.data.ProxyPom; import com.idega.manager.maven1.data.RealPom; import com.idega.manager.maven1.data.RepositoryLogin; import com.idega.manager.maven1.data.SimpleProxyPomList; import com.idega.manager.maven1.util.VersionComparator; /** * * Last modified: $Date: 2008/06/11 21:10:02 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class PomSorter { // map of installed bundles // key: artifactId (String) value: Pom (RealPom) SortedMap sortedInstalledPom = null; // map of sets of available updates for already installed modules // read from the iwbar folder in the repository // key: artifactId (String) value: SortedSet of Pom (TreeSet of ProxyPom) Map sortedRepositoryPomAvailableUpdates = null; // map of lists of available new modules (not yet installed) // read from the iwbar folder in the repository // for performance reasons "simple PomProxies" are stored, that are just String[2] arrays. // key: artifactId (String) value: List of simple ProxyPom (SimpleProxyList, that contains simple ProxyPoms]) Map sortedSimpleProxyList = null; // this list is used by the isValid() method. // A valid pom has an existing pom.file in the pom folder in the repository and // also an existing iwbar file in the iwbar folder in the repository. // for performance reason StringBuffer, not Strings, are stored // value: file name of a pom from the pom folder in the repository (StringBuffer) List pomFileNames = null; // this look up list is used by the beans to get the corresponding ProxyPom // by using the file name as identifier // key: fileName (String) value: pom (ProxyPom) Map fileNameRepositoryPom = null; // this list stores the necessary poms. // PomSorter works just as a container. The necessary poms are // not calculated within this class. // values: modules (Module) Map necessaryPoms = null; // this list is a subset of the list "necessaryPoms". It contains the modules that // have to be downloaded from the repository. The rest of the modules in the list // "necessaryPoms" are either already installed or included in other modules. SortedMap toBeInstalledPoms = null; // just a list of error messages List errorMessages = null; // version comparator works with caches, that is // a reused comparator works faster when dealing with the same versions again VersionComparator usedVersionComparator = null; // Not used at the moment // //key: artifactId String value: List of Files // Map bundlesTagLibraries = null; public void initializeInstalledPomsAndAvailableUpdates(RepositoryLogin repositoryLogin) throws IOException { VersionComparator versionComparator = getUsedVersionComparator(); findInstalledPoms(); findAvailableUpdates(repositoryLogin, versionComparator); } public void initializeInstalledPomsAndAvailableNewModules(RepositoryLogin repositoryLogin) throws IOException { findInstalledPoms(); findAvailableNewModules(repositoryLogin); } public void addSimpleProxyPomList(String key, SimpleProxyPomList simpleProxyPomList, Map pomMap) { VersionComparator versionComparator = getUsedVersionComparator(); // iterator over list Iterator iterator = simpleProxyPomList.getSimpleProxies().iterator(); RepositoryBrowser repositoryBrowser = simpleProxyPomList.getRepositoryBrowser(); while (iterator.hasNext()) { String[] simpleProxyPom = (String[]) iterator.next(); ProxyPom proxyPom = ProxyPom.getInstanceOfGroupBundlesForSimpleProxyPom(simpleProxyPom, repositoryBrowser); if (isValid(proxyPom)) { putPom(key, proxyPom, pomMap, versionComparator); } } } private void findInstalledPoms() { LocalBundlesBrowser localBrowser = new LocalBundlesBrowser(); // not used at the moment //bundlesTagLibraries = localBrowser.getTagLibrariesOfInstalledModules(); List installedPoms = localBrowser.getPomOfInstalledModules(); this.sortedInstalledPom = new TreeMap(); Iterator installedPomsIterator = installedPoms.iterator(); while (installedPomsIterator.hasNext()) { RealPom pom = (RealPom) installedPomsIterator.next(); String artifactId = pom.getArtifactId(); this.sortedInstalledPom.put(artifactId, pom); } } private void findAvailableUpdates(RepositoryLogin repositoryLogin, VersionComparator versionComparator) throws IOException { RepositoryBrowser repositoryBrowser = RepositoryBrowser.getInstanceForIdegaRepository(repositoryLogin); List allPoms = getAllPomsFromRepository(repositoryBrowser); this.sortedRepositoryPomAvailableUpdates = new HashMap(); Iterator allPomsIterator = allPoms.iterator(); while (allPomsIterator.hasNext()) { String[] simpleProxyPom = (String[]) allPomsIterator.next(); // simpleProxyPom[0] contains the artifactId if (this.sortedInstalledPom.containsKey(simpleProxyPom[0])) { RealPom pom = (RealPom) this.sortedInstalledPom.get(simpleProxyPom[0]); // fetch only poms that are newer than the installed ones // and fetch additionally versions if the installed one is a snapshot // convert to a ProxyPom ProxyPom proxy = ProxyPom.getInstanceOfGroupBundlesForSimpleProxyPom(simpleProxyPom, repositoryBrowser); if ( (isValid(proxy)) && (proxy.compare(pom, versionComparator) > 0 || (pom.isSnapshot() && ! proxy.isSnapshot()))) { putPom(simpleProxyPom[0], proxy, this.sortedRepositoryPomAvailableUpdates, versionComparator); } } } } private void findAvailableNewModules(RepositoryLogin repositoryLogin) throws IOException { RepositoryBrowser repositoryBrowser = RepositoryBrowser.getInstanceForIdegaRepository(repositoryLogin); List allPoms= getAllPomsFromRepository(repositoryBrowser); this.sortedSimpleProxyList = new TreeMap(); Iterator allPomsIterator = allPoms.iterator(); while (allPomsIterator.hasNext()) { String[] simpleProxyPom = (String[]) allPomsIterator.next(); // simpleProxyPom[0] contains the artifactId if (! this.sortedInstalledPom.containsKey(simpleProxyPom[0])) { putPrimitiveProxyPom(simpleProxyPom[0], simpleProxyPom, this.sortedSimpleProxyList, repositoryBrowser); } } } private boolean isValid(ProxyPom proxyPom) { if (proxyPom.shouldBeIgnored()) { return false; } String fileName = proxyPom.getFileName(); Iterator iterator = this.pomFileNames.iterator(); while (iterator.hasNext()) { StringBuffer buffer = (StringBuffer) iterator.next(); if (fileName.contentEquals(buffer)) { return true; } } return false; } private List getAllPomsFromRepository(RepositoryBrowser repositoryBrowser) throws IOException { this.pomFileNames = repositoryBrowser.getPomsScanningPomsFolder(); return repositoryBrowser.getSimplePomProxiesFromBundleArchivesFolder(); } private void putPrimitiveProxyPom(String artifactId, String[] simpleProxyPom, Map aMap, RepositoryBrowser repositoryBrowser) { SimpleProxyPomList simpleProxyPomList = (SimpleProxyPomList) aMap.get(artifactId); if (simpleProxyPomList == null) { simpleProxyPomList = new SimpleProxyPomList(repositoryBrowser); aMap.put(artifactId, simpleProxyPomList); } simpleProxyPomList.add(simpleProxyPom); } private void putPom(String key, ProxyPom value, Map pomMap, final VersionComparator versionComparator) { // first store in fileNameMap if (this.fileNameRepositoryPom == null) { this.fileNameRepositoryPom = new HashMap(); } String fileName = value.getFileName(); this.fileNameRepositoryPom.put(fileName, value); // second store in sorted map SortedSet pomSet = (SortedSet) pomMap.get(key); if (pomSet == null) { Comparator comparator = new Comparator() { public int compare(Object proxy1, Object proxy2) { Pom pom1 = (Pom) proxy1; Pom pom2 = (Pom) proxy2; return pom1.compare(pom2, versionComparator); } }; pomSet = new TreeSet(comparator); pomMap.put(key, pomSet); } pomSet.add(value); } // Not used at the moment // public Map getBundlesTagLibraries() { // return bundlesTagLibraries; // } public Map getRepositoryPoms() { return this.fileNameRepositoryPom; } public SortedMap getSortedInstalledPoms() { return this.sortedInstalledPom; } public Map getSortedRepositoryPomsOfAvailableUpdates() { return this.sortedRepositoryPomAvailableUpdates; } public Map getSortedSimpleProxyList() { return this.sortedSimpleProxyList; } public SortedMap getToBeInstalledPoms() { return this.toBeInstalledPoms; } public Map getNecessaryPoms() { return this.necessaryPoms; } public void setNecessaryPoms(List necessaryPoms) { this.toBeInstalledPoms = new TreeMap(); this.necessaryPoms = new HashMap(); Iterator iterator = necessaryPoms.iterator(); while (iterator.hasNext()) { Module module = (Module) iterator.next(); String key = module.getArtifactId(); if (! (module.isInstalled() || module.isIncluded())) { this.toBeInstalledPoms.put(key, module); } this.necessaryPoms.put(key, module); } } public List getErrorMessages() { return this.errorMessages; } public void setErrorMessages(List errorMessages) { this.errorMessages = errorMessages; } /** * * <p> * A version comparator works with a cache, that is a * reused comparator works faster * when dealing with the same versions again * </p> * @return */ public VersionComparator getUsedVersionComparator() { if (this.usedVersionComparator == null) { this.usedVersionComparator = new VersionComparator(); } return this.usedVersionComparator; } }
10,242
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
PomValidator.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/PomValidator.java
/* * $Id: PomValidator.java,v 1.1 2008/06/11 21:10:02 tryggvil Exp $ * Created on Nov 24, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.business; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.data.Module; /** * * Last modified: $Date: 2008/06/11 21:10:02 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class PomValidator { public void validateSelectedModuleNames(FacesContext context, UIComponent toValidate, Object value, IWResourceBundle resourceBundle) { // check if the user has chosen more than one version for the same artifact String[] selectedValues = (String[]) value; int length = selectedValues.length; // if nothing has been chosen, that is the lenght is zero, set an message if (length == 0) { String errorMessage = resourceBundle.getLocalizedString("man_val_choose_at_most_one_version_per_module","Choose at least one module"); setErrorMessage(context, (UIInput) toValidate, errorMessage); } } public void validateSelectedModules(FacesContext context, UIComponent toValidate, Object value, PomSorter pomSorter, IWResourceBundle resourceBundle) { // check if the user has chosen more than one version for the same artifact String[] selectedValues = (String[]) value; int length = selectedValues.length; Map repositoryPoms = pomSorter.getRepositoryPoms(); Set set = new HashSet(length); int i = 0; // if nothing has been chosen, that is the lenght is zero, set an message boolean go = (length == 0) ? false : true; while (( i < length) && go) { String fileName = selectedValues[i++]; Module module = (Module) repositoryPoms.get(fileName); String artifactId = module.getArtifactId(); // go is not set to false as long as the artifactId is not already in the set go = set.add(artifactId); } if (! go) { String errorMessage = resourceBundle.getLocalizedString("man_val_choose_at_most_one_version_per_module","Choose at most one version per module"); setErrorMessage(context, (UIInput) toValidate, errorMessage); } } private void setErrorMessage(FacesContext context, UIInput toValidate, String errorMessage) { toValidate.setValid(false); String id = toValidate.getClientId(context); // e.g. id = "form1:multiSelectListbox1" context.addMessage(id, new FacesMessage(errorMessage)); } }
2,794
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
DependencyMatrix.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/DependencyMatrix.java
/* * $Id: DependencyMatrix.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 26, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.business; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.data.Dependency; import com.idega.manager.maven1.data.Module; import com.idega.manager.maven1.data.Pom; import com.idega.manager.maven1.util.VersionComparator; import com.idega.util.datastructures.HashMatrix; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class DependencyMatrix { private IWResourceBundle resourceBundle = null; private List errorMessages = null; private HashMatrix moduleDependencies = null; private Collection notInstalledModules = null; private Collection installedModules = null; private List tempToBeInstalledModules = null; private List tempNecessaryModules = null; public static DependencyMatrix getInstance(Collection notInstalledModules, Collection installedModules, IWResourceBundle resourceBundle) { DependencyMatrix dependencyMatrix = new DependencyMatrix(); dependencyMatrix.notInstalledModules = notInstalledModules; dependencyMatrix.installedModules = installedModules; dependencyMatrix.resourceBundle = resourceBundle; return dependencyMatrix; } public List getListOfNecessaryModules(VersionComparator versionComparator) { Collection tempNotInstalled = this.notInstalledModules; Collection tempInstalled = this.installedModules; this.tempToBeInstalledModules = null; this.tempNecessaryModules = null; boolean go = true; // this loop removes modules that are obsolete to be installed // (e.g. another modules demands a newer version, the older version must not to be installed) while (go) { initializeMatrix(tempNotInstalled, tempInstalled); try { tryCalculateListOfModulesToBeInstalled(versionComparator); } catch (IOException ex) { String errorMessage = this.resourceBundle.getLocalizedString("man_manager_could_not_get_dependencies","Could not figure out dependencies" + ex.getMessage()); addErrorMessage(errorMessage); return this.tempNecessaryModules; } go = tempNotInstalled.retainAll(this.tempToBeInstalledModules); } return this.tempNecessaryModules; } public boolean hasErrors() { return ! (this.errorMessages == null || this.errorMessages.isEmpty()); } public List getErrorMessages() { return this.errorMessages; } private void tryCalculateListOfModulesToBeInstalled(VersionComparator versionComparator) throws IOException { this.tempToBeInstalledModules = new ArrayList(); this.tempNecessaryModules = new ArrayList(); // get a list of required modules Iterator iterator = this.moduleDependencies.firstKeySet().iterator(); while (iterator.hasNext()) { // x (also key) = dependencyKey String key = (String) iterator.next(); Map map = this.moduleDependencies.get(key); Iterator iteratorMap = map.keySet().iterator(); Module toBeInstalled = null; while (iteratorMap.hasNext()) { // y (also innerKey) = dependantKey String innerKey = (String) iteratorMap.next(); Module module = (Module) map.get(innerKey); if (toBeInstalled == null || (module.compare(toBeInstalled, versionComparator) > 0)) { toBeInstalled = module; } } // install only modules that are not installed and not included in other modules if (! (toBeInstalled.isInstalled() || toBeInstalled.isIncluded())) { this.tempToBeInstalledModules.add(toBeInstalled); } this.tempNecessaryModules.add(toBeInstalled); } } // e.g. returns "bundles_com.idega.block.article_installed" // e.g. returns "bundles_com.idega.block.article" private StringBuffer getKeyForDependant(Module module) { StringBuffer buffer = getKeyForDependency(module); if (module.isInstalled()) { buffer.append("_installed"); } return buffer; } // e.g. returns "bundles_com.idega.block.article" private StringBuffer getKeyForDependency(Module module) { String groupId = module.getGroupId(); String artifactId = module.getArtifactId(); StringBuffer buffer = new StringBuffer(groupId); buffer.append("_").append(artifactId); return buffer; } private HashMatrix getModuleDependencies() { if (this.moduleDependencies == null) { this.moduleDependencies = new HashMatrix(); } return this.moduleDependencies; } private void initializeMatrix(Collection tempNotInstalledModules, Collection tempInstalledModules) { this.errorMessages = null; addEntries(tempInstalledModules); addEntries(tempNotInstalledModules); } private void addEntries(Collection poms) { Iterator iterator = poms.iterator(); while (iterator.hasNext()) { Pom pom = (Pom) iterator.next(); addEntry(pom); } } private void addEntry(Pom pom) { HashMatrix matrix = getModuleDependencies(); addEntry(pom, pom, matrix); } private void addEntry(Pom dependant, Pom source, HashMatrix matrix) { // e.g. dependantKey "bundles_com.idega.block.article_installed" // e.g. dependantKey "bundles_com.idega.block.article" String dependantKey = getKeyForDependant(dependant).toString(); // e.g. dependencyKeyForDependant "bundles_com.idega.block.article" String dependencyKeyForDependant = getKeyForDependency(dependant).toString(); // x = dependencyKey, y = dependantKey this.moduleDependencies.put(dependencyKeyForDependant, dependantKey, dependant); List dependencies = null; try { dependencies = source.getDependencies(); } catch (IOException ex) { String errorMessage = this.resourceBundle.getLocalizedString("man_manager_could_not_get_dependencies","Could not figure out dependencies of ") + source.getArtifactId(); addErrorMessage(errorMessage); return; } Iterator iterator = dependencies.iterator(); while (iterator.hasNext()) { Dependency dependency = (Dependency) iterator.next(); String dependencyKey = getKeyForDependency(dependency).toString(); this.moduleDependencies.put(dependencyKey, dependantKey, dependency); Pom dependencyPom = null; try { dependencyPom = dependency.getPom(); } catch (IOException ex) { String errorMessage = this.resourceBundle.getLocalizedString("man_manager_could_not_get_dependencies","Could not figure out dependencies of ") + dependency.getArtifactId(); addErrorMessage(errorMessage); } if (dependencyPom != null) { // go further addEntry(dependant, dependencyPom, matrix); } } } private void addErrorMessage(String errorMessage) { if (this.errorMessages == null) { this.errorMessages = new ArrayList(); } this.errorMessages.add(errorMessage); } }
7,061
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
RepositoryBrowser.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/RepositoryBrowser.java
/* * $Id: RepositoryBrowser.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 16, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.business; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.ResourceDoesNotExistException; import org.apache.maven.wagon.TransferFailedException; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authentication.AuthenticationInfo; import org.apache.maven.wagon.authorization.AuthorizationException; import org.apache.maven.wagon.providers.http.LightweightHttpWagon; import org.apache.maven.wagon.repository.Repository; import org.doomdark.uuid.UUID; import org.doomdark.uuid.UUIDGenerator; import com.idega.manager.maven1.data.ProxyPom; import com.idega.manager.maven1.data.RealPom; import com.idega.manager.maven1.data.RepositoryLogin; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.manager.maven1.util.ManagerUtils; import com.idega.util.FileUtil; import com.idega.util.StringHandler; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class RepositoryBrowser { protected final static String SNAPSHOT_VERSION_SUFFIX = "snapshot-version"; protected final static char[] HTML_IWBAR_START_PATTERN = "r\">".toCharArray(); //"iwbar\">".toCharArray(); protected final static char[] HTML_POM_START_PATTERN = "m\">".toCharArray(); //"pom\">".toCharArray(); protected final static char[] HTML_FOLDER_START_PATTERN = "/\">".toCharArray(); //"pom\">".toCharArray(); protected final static char HTML_LINK_END_PATTERN = '<'; public static RepositoryBrowser getInstanceForIdegaRepository(RepositoryLogin repositoryLogin) { return new RepositoryBrowser(repositoryLogin); } static private Logger getLogger(){ return Logger.getLogger(ManagerUtils.class.getName()); } protected String identifier; protected File workingDirectory; protected RepositoryLogin repositoryLogin; protected String cachedBundlesPomsURL = null; protected String cachedBundlesIwbarsURL = null; // map of file names and files protected Map cachedDownloadedFiles = null; protected boolean useMaven2Layout=true; public RepositoryBrowser(RepositoryLogin repositoryLogin) { this.repositoryLogin = repositoryLogin; } /** Returns names of poms that have a corresponding iwbar file. * Sometimes only the pom file exist but not the corresponding iwbar file and vice versa. * * @return * @throws IOException */ public List getSimplePomProxiesFromBundleArchivesFolder() throws IOException { List iwbars = getPomsScanningBundleArchivesFolder(); // List pomFiles = getPomsScanningPomsFolder(); List poms = new ArrayList(iwbars.size()); Iterator iterator = iwbars.iterator(); while (iterator.hasNext()) { StringBuffer fileNameWithoutExtension = (StringBuffer) iterator.next(); // pom and corresponding jar file exist String[] simplePomProxy = ProxyPom.getSimpleProxyPom(fileNameWithoutExtension); poms.add(simplePomProxy); //ProxyPom pomProxy = ProxyPom.getInstanceOfGroupBundlesWithoutFileExtension(fileNameWithoutExtension, this); // if (! pomProxy.shouldBeIgnored()) { // poms.add(pomProxy); // } // } } return poms; } private List getPomsScanningBundleArchivesFolder() throws IOException { String urlAddress = getURLForBundlesArchives(); return getPomProxies(urlAddress, HTML_IWBAR_START_PATTERN,true); } public List getPomsScanningPomsFolder() throws IOException { return getPomsScanningPomsFolder(ManagerConstants.BUNDLES_DEFAULT_GROUP); } public List getPomsScanningPomsFolder(String groupId) throws IOException { String urlAddress = getURLForGroupPoms(groupId); return getPomProxies(urlAddress, HTML_POM_START_PATTERN,true); } /* if pomName is a snapshot like "com.idega.content-SNAPSHOT.pom" * read the corresponding version from * "com.idega.content-snapshot-version" * and download the corresponding file like * "com.idega.content-20041117.164329.pom" */ public String convertPomNameIfNecessary(String pomName) throws IOException { String urlAddress = getURLForBundlesPoms(); return convertPomNameIfNecessary(urlAddress, pomName); } /* if pomName is a snapshot like "com.idega.content-SNAPSHOT.pom" * read the corresponding version from * "com.idega.content-snapshot-version" * and download the corresponding file like * "com.idega.content-20041117.164329.pom" */ private String convertPomNameIfNecessary(String urlAddress, String pomName) throws IOException { return convertNameIfNecessary(urlAddress, pomName, ProxyPom.POM_EXTENSION); } private String convertBundleArchiveNameIfNecessary(String urlAddress, String archiveName) throws IOException { return convertNameIfNecessary(urlAddress, archiveName, ProxyPom.IWBAR_EXTENSION); } private String convertNameIfNecessary(String urlAddress, String pomName, String useExtension) throws IOException { int index = pomName.indexOf(RealPom.SNAPSHOT); // if pomName is a snapshot like "com.idega.content-SNAPSHOT.pom" // read the corresponding version from // "com.idega.content-snapshot-version" // and download the corresponding file like // "com.idega.content-20041117.164329.pom" if (index != -1) { // e.g. pomName = com.idega.content-SNAPSHOT.pom String fileName = pomName.substring(0,index); // e.g. fileName = com.idega.content- StringBuffer buffer = new StringBuffer(urlAddress); buffer.append(fileName); buffer.append(SNAPSHOT_VERSION_SUFFIX); // e.g. buffer = urlAddress + com.idega.content-snapshot-version String version = getContent(buffer.toString()); // e.g. version = 20041117.164329 // create new file name buffer = new StringBuffer(fileName); buffer.append(version); buffer.append(useExtension); // e.g. buffer = com.idega.content-20041117.164329.pom pomName = buffer.toString(); } return pomName; } public File getPom(String pomName) throws IOException { String urlAddress = getURLForBundlesPoms(); pomName = convertPomNameIfNecessary(urlAddress, pomName); return downloadFile(urlAddress, pomName); } public File getBundleArchive(String bundleArchiveName) throws IOException { String urlAddress = getURLForBundlesArchives(); bundleArchiveName = convertBundleArchiveNameIfNecessary(urlAddress, bundleArchiveName); return downloadFile(urlAddress, bundleArchiveName); } private String getURL(String group, String type) { String repository = this.repositoryLogin.getRepository(); StringBuffer buffer = new StringBuffer(repository); if (! repository.endsWith("/")) { buffer.append('/'); } buffer.append(group).append("/"); if(type!=null){ buffer.append(type).append("/"); } return buffer.toString(); } protected String getURLForBundlesArchives() { if (this.cachedBundlesIwbarsURL == null) { this.cachedBundlesIwbarsURL = getURL(ManagerConstants.BUNDLES_DEFAULT_GROUP, "iwbars"); } return this.cachedBundlesIwbarsURL; } protected String getURLForGroupPoms(String groupId) { String groupPath=groupId; groupPath = getGroupPath(groupId); if (this.cachedBundlesPomsURL == null ) { this.cachedBundlesPomsURL = getURL(groupPath, "poms"); } return this.cachedBundlesPomsURL; } protected String getURLForGroupFolder(String groupId) { String groupPath=groupId; groupPath = getGroupPath(groupId); String groupUrl = getURL(groupPath, null); return groupUrl; } private String getGroupPath(String groupId) { String groupPath = groupId; if(useMaven2Layout){ groupPath = groupId.replace('.', '/'); } return groupPath; } private String getURLForBundlesPoms() { return getURLForGroupPoms(ManagerConstants.BUNDLES_DEFAULT_GROUP); } /** Use this only for very small content otherwise * it will throw an OutOfMemoryError. * !! Be careful !! * * @param urlAddress * @return * @throws IOException */ private String getContent(String urlAddress) throws IOException { InputStreamReader inputStreamReader = null; StringBuffer buffer = null; try { buffer = new StringBuffer(); PasswordAuthentication passwordAuthentication = this.repositoryLogin.getPasswordAuthentication(); inputStreamReader = URLReadConnection.getReaderForURLWithAuthentication(urlAddress, passwordAuthentication); int charInt; while ((charInt = inputStreamReader.read()) != -1) { char c = (char) charInt; buffer.append(c); } } catch (MalformedURLException e) { getLogger().log(Level.WARNING, "[RepositoryBrowser] URL is malformed: "+ urlAddress , e); throw new IOException("[RepositoryBrowser] Could not connect to repository, most likely the URL is wrong"); } catch (IOException e) { getLogger().log(Level.WARNING, "[RepositoryBrowser] Could not open URL: "+ urlAddress , e); throw new IOException("[RepositoryBorwser] Could not connect to repository, most likely the repository server is down"); } finally { try { if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { // do not hide existing exception } } return buffer.toString(); } public List<StringBuffer> getFolderList(String urlAddress) throws IOException{ List<StringBuffer> folderList = getPomProxies(urlAddress, HTML_FOLDER_START_PATTERN,false); List<StringBuffer> newList = new ArrayList<StringBuffer>(); for(StringBuffer folder: folderList){ String folderString = folder.toString(); if(folderString.endsWith("/")){ folder = new StringBuffer(folderString.substring(0, folderString.length()-1)); } //Exclude the special folder Parent Directory: if(!folderString.equals("Parent Directory")){ newList.add(folder); } } return newList; } protected List<StringBuffer> getPomProxies(String urlAddress, char[] startPatternChar,boolean stripOutExtension) throws IOException { InputStreamReader inputStreamReader = null; StringBuffer nameBuffer = null; List<StringBuffer> poms = new ArrayList<StringBuffer>(); try { PasswordAuthentication passwordAuthentication = this.repositoryLogin.getPasswordAuthentication(); inputStreamReader = URLReadConnection.getReaderForURLWithAuthentication(urlAddress, passwordAuthentication); int charInt; int startPatternLength = startPatternChar.length; int patternCounter = 0; char patternChar =startPatternChar[0]; boolean read = false; int readIndex = -1; int dotIndex = 0; while ((charInt = inputStreamReader.read()) != -1) { char c = (char) charInt; // are we reading a name of a file at the moment? if (read) { readIndex++; // yes, we do..... // is the end of the name reached? if (c == HTML_LINK_END_PATTERN) { // yes it is, store the name and reset the buffer and read variable if(stripOutExtension){ nameBuffer = nameBuffer.delete(dotIndex, nameBuffer.length()); } poms.add(nameBuffer); nameBuffer = null; read = false; dotIndex = 0; readIndex = -1; } else { // do not append the extension of the name to the nameBuffer: // store the very last index of a dot if (c == '.') { dotIndex = readIndex; } // append character of name to dotBuffer nameBuffer.append(c); } } // check if the start pattern fits else if (c == patternChar) { if (++patternCounter == startPatternLength) { // startpattern discovered nameBuffer = new StringBuffer(); read = true; patternCounter = 0; } // search for the next character patternChar = startPatternChar[patternCounter]; } else if (patternCounter != 0) { // start again from the beginning patternChar = startPatternChar[0]; patternCounter = 0; } } } catch (MalformedURLException e) { getLogger().log(Level.WARNING, "[RepositoryBrowser] URL is malformed: "+ urlAddress , e); throw new IOException("[RepositoryBrowser] Could not connect to repository, most likely the URL is wrong"); } catch (IOException e) { getLogger().log(Level.WARNING, "[RepositoryBrowser] Could not open URL: "+ urlAddress , e); throw new IOException("[RepositoryBorwser] Could not connect to repository, most likely the repository server is down"); } finally { try { if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { // do not hide existing exception } } return poms; } private File downloadFile(String urlAddress, String fileName) throws IOException { // caching of already downloaded files // (the calling objects are also caching the file but sometimes two different objects are asking for the // same file) if (this.cachedDownloadedFiles == null) { this.cachedDownloadedFiles = new HashMap(); } if (this.cachedDownloadedFiles.containsKey(fileName)) { return (File) this.cachedDownloadedFiles.get(fileName); } File tempWorkingDirectory = getWorkingDirectory(); // clean the working directory // set time to 60 minutes FileUtil.deleteAllFilesAndFolderInFolderOlderThan(tempWorkingDirectory, 3600000); // set folder for this instance of repositoryBrowser // folder gets the name of the identifier File myFolder = new File(tempWorkingDirectory, getIdentifer()); if (! myFolder.exists()) { myFolder.mkdir(); } File destination = new File(myFolder, fileName); Wagon wagon = null; try { wagon = new LightweightHttpWagon(); Repository localRepository = new Repository(); AuthenticationInfo authenticationInfo = this.repositoryLogin.getAuthenticationInfo(); //localRepository.setAuthenticationInfo(authenticationInfo); localRepository.setUrl(urlAddress); if ( !destination.exists() ) { wagon.connect(localRepository,authenticationInfo); wagon.get(fileName, destination ); } } catch (TransferFailedException ex) { getLogger().log(Level.WARNING, "[RepositoryBrowser] Transfer failed: "+ urlAddress + fileName , ex); throw new IOException("[RepositoryBrowser] Could not download file. " + fileName); } catch (ConnectionException ex) { getLogger().log(Level.WARNING, "[RepositoryBrowser] Connection problems: "+ urlAddress + fileName , ex); throw new IOException("[RepositoryBrowser] Could not download file. " + fileName); } catch (AuthenticationException ex) { getLogger().log(Level.WARNING, "[RepositoryBrowser] Authentication problems: "+ urlAddress + fileName , ex); throw new IOException("[RepositoryBrowser] Could not download file. " + fileName); } catch (ResourceDoesNotExistException ex) { getLogger().log(Level.WARNING, "[RepositoryBrowser] File does not exist: "+ urlAddress + fileName , ex); throw new IOException("[RepositoryBrowser] Could not download file. " + fileName); } catch (AuthorizationException ex) { getLogger().log(Level.WARNING, "[RepositoryBrowser] Authorization problems: "+ urlAddress + fileName , ex); throw new IOException("[RepositoryBrowser] Could not download file. " + fileName); } finally { try { if (wagon != null) { wagon.disconnect(); } } catch (ConnectionException ex) { getLogger().log(Level.WARNING, "[RepositoryBrowser] Disconnection problems: "+ urlAddress + fileName , ex); } } this.cachedDownloadedFiles.put(fileName, destination); return destination; } private File getWorkingDirectory() { if (this.workingDirectory == null) { this.workingDirectory = ManagerUtils.getInstanceForCurrentContext().getWorkingDirectory(); } return this.workingDirectory; } private String getIdentifer() { if (this.identifier == null) { UUIDGenerator generator = UUIDGenerator.getInstance(); UUID uuid = generator.generateRandomBasedUUID(); this.identifier = uuid.toString(); this.identifier = StringHandler.remove(this.identifier, "-"); } return this.identifier; } } // public XMLDocument getDocument() { // // BufferedReader in = null; // try { // in = new BufferedReader(new InputStreamReader(new URL(getURL()).openStream())); // // String inputLine; // // while ((inputLine = in.readLine()) != null) // System.out.println(inputLine); // // in.close(); // org.w3c.dom.Document documentW3c = getTidy().parseDOM(in, null); // Document document = new DOMReader().read(documentW3c); // Element element = document.getRootElement(); // List list = element.elements(); // list.size(); // NodeList list = documentW3c.getChildNodes(); // int length = list.getLength(); // List values = new ArrayList(length); // for (int i = 0; i < length; i++) { // Node node = list.item(i); // String value = node.getNodeValue(); // values.add(value); // } // values.size(); // changing to XMLDocument // return null; //XMLDocument.valueOf(documentW3c); // } // catch (MalformedURLException ex) { // getLogger().log(Level.WARNING, "[RepositoryBrowser] URL is malformed: "+ getURL(),ex); // } // catch (IOException e) { // getLogger().log(Level.WARNING, "[RepositoryBrowser] Could not open URL: "+ getURL(), e); // } // finally // { // try { // in.close(); // } // catch (IOException ex) { // // do not hide existing exception // } // } // return null; // }
18,268
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
LocalBundlesBrowser.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/LocalBundlesBrowser.java
/* * $Id: LocalBundlesBrowser.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 22, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.business; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import com.idega.manager.maven1.data.RealPom; import com.idega.manager.maven1.util.IdegawebDirectoryStructure; import com.idega.manager.maven1.util.ManagerUtils; import com.idega.util.FileUtil; import com.idega.util.StringHandler; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class LocalBundlesBrowser { /** * Gets the default Logger. By default it uses the package and the class name to get the logger.<br> * This behaviour can be overridden in subclasses. * @return the default Logger */ static private Logger getLogger(){ return Logger.getLogger(ManagerUtils.class.getName()); } public Map getTagLibrariesOfInstalledModules() { IdegawebDirectoryStructure idegawebDirectoryStructure = ManagerUtils.getInstanceForCurrentContext().getIdegawebDirectoryStructure(); File tempBundlesPath = idegawebDirectoryStructure.getBundlesRealPath(); List bundles = FileUtil.getDirectoriesInDirectory(tempBundlesPath); if (bundles == null) { return null; } Map tagLibraries = new HashMap(bundles.size()); Iterator bundlesIterator = bundles.iterator(); while (bundlesIterator.hasNext()) { File bundleFolder = (File) bundlesIterator.next(); File library = idegawebDirectoryStructure.getTagLibrary(bundleFolder); List tlds = null; if (library.exists()) { tlds = FileUtil.getDirectoriesInDirectory(library); if (tlds.isEmpty()) { tlds = null; } } String bundleName = bundleFolder.getName(); // get rid of the bundle extension String artifactId = StringHandler.cutExtension(bundleName); tagLibraries.put(artifactId, tlds); } return tagLibraries; } public List getPomOfInstalledModules() { File tempBundlesPath = ManagerUtils.getInstanceForCurrentContext().getBundlesRealPath(); List bundles = FileUtil.getDirectoriesInDirectory(tempBundlesPath); if (bundles == null) { return null; } List poms = new ArrayList(bundles.size()); Iterator bundlesIterator = bundles.iterator(); while (bundlesIterator.hasNext()) { File folder = (File) bundlesIterator.next(); File projectFile = new File(folder, RealPom.POM_FILE); if (projectFile.exists()) { try { RealPom pom = RealPom.getInstalledPomOfGroupBundles(projectFile); poms.add(pom); } catch (IOException ex) { Logger logger = getLogger(); logger.log(Level.WARNING, "[ManagerUtils] POM file for module "+folder.getName()+" could not be parsed"); } } } return poms; } }
3,158
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
UserPasswordValidator.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/UserPasswordValidator.java
/* * Created on Feb 14, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.business; import java.io.IOException; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import com.idega.idegaweb.IWResourceBundle; /** * @author thomas * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class UserPasswordValidator { static private Logger getLogger(){ return Logger.getLogger(UserPasswordValidator.class.getName()); } public void validateUserPassword(FacesContext context, UIComponent toValidate, Object componentRepositoryURLValue, Object componentUserValue , Object componentPasswordValue, IWResourceBundle resourceBundle) { String repositoryURLValueString = (String) componentRepositoryURLValue; String errorMessage = null; try { URL repositoryURL = new URL(repositoryURLValueString); String user = (String) ((componentUserValue == null) ? "" : componentUserValue); String password = (String) ((componentPasswordValue == null) ? "" : componentPasswordValue); PasswordAuthentication userPassword = new PasswordAuthentication(user, password.toCharArray()); String error = URLReadConnection.authenticationValid(repositoryURL , userPassword); if (error == null) { // everything is fine return; } if (URLReadConnection.NOT_FOUND_ERROR.equals(error)) { errorMessage = resourceBundle.getLocalizedString("man_URL_could_not_be_found","Could not found URL"); } else if (URLReadConnection.UNAUTHORIZED_ERROR.equals(error)) { errorMessage = resourceBundle.getLocalizedString("man_username_or_password_is_wrong","Username or password is wrong"); } else if (URLReadConnection.FORBIDDEN_ERROR.equals(error)) { errorMessage = resourceBundle.getLocalizedString("man_forbidden","Access to forbidden"); } else if (URLReadConnection.NO_CONTENT_ERROR.equals(error)) { errorMessage = resourceBundle.getLocalizedString("man_no_content","URL does not point to any content"); } else { errorMessage = resourceBundle.getLocalizedString("man_unknown_problem_occurred","An unknown problem occurred when trying to login "); } } catch (MalformedURLException e) { getLogger().log(Level.WARNING, "[UserPasswordValidator] MalformedURLException", e); errorMessage = resourceBundle.getLocalizedString("man_url_malformed","URL is wrong"); } catch (IOException e) { getLogger().log(Level.WARNING, "[UserPasswordValidator] IOException", e); errorMessage = resourceBundle.getLocalizedString("man_unknown_problem_occurred","An unknown problem occurred when connecting to repository"); } setErrorMessage(context, (UIInput) toValidate, errorMessage); } private void setErrorMessage(FacesContext context, UIInput toValidate, String errorMessage) { toValidate.setValid(false); String id = toValidate.getClientId(context); // e.g. id = "form1:multiSelectListbox1" context.addMessage(id, new FacesMessage(errorMessage)); } }
3,429
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
Installer.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/Installer.java
/* * $Id: Installer.java,v 1.1 2008/06/11 21:10:01 tryggvil Exp $ * Created on Dec 3, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.maven1.business; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.doomdark.uuid.UUID; import org.doomdark.uuid.UUIDGenerator; import com.idega.manager.maven1.data.Module; import com.idega.manager.maven1.data.Pom; import com.idega.manager.maven1.data.RealPom; import com.idega.manager.maven1.util.IdegawebDirectoryStructure; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.manager.maven1.util.ManagerUtils; import com.idega.util.BundleFileMerger; import com.idega.util.FacesConfigMerger; import com.idega.util.FileUtil; import com.idega.util.StringHandler; import com.idega.util.WebXmlMerger; import com.idega.util.logging.LogFile; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.1 $ */ public class Installer { private static final int WAIT_PERIOD = 10000; private LogFile logFile = null; private File backupFolder = null; public static Installer getInstance(PomSorter pomSorter){ Installer installer = new Installer(); installer.initialize(pomSorter); return installer; } private PomSorter pomSorter = null; private IdegawebDirectoryStructure idegawebDirectoryStructure= null; private Installer() { // use the class method } private void initialize(PomSorter pomSorter) { this.pomSorter = pomSorter; this.idegawebDirectoryStructure = ManagerUtils.getInstanceForCurrentContext().getIdegawebDirectoryStructure(); } public void extractBundleArchives() throws IOException { Iterator iterator = this.pomSorter.getToBeInstalledPoms().values().iterator(); while (iterator.hasNext()) { Module module = (Module) iterator.next(); this.idegawebDirectoryStructure.getExtractedArchive(module); String artifactId = module.getArtifactId(); writeToLogger("Extracting bundle ", artifactId, " finished"); } } // from auxiliary folder public void mergeBundles() throws IOException { File bundlesFolder = this.idegawebDirectoryStructure.getBundlesRealPath(); Collection toBeInstalledModules = this.pomSorter.getToBeInstalledPoms().values(); Iterator moduleIterator = toBeInstalledModules.iterator(); while (moduleIterator.hasNext()) { Module module = (Module) moduleIterator.next(); File moduleArchive = this.idegawebDirectoryStructure.getExtractedArchive(module); String artifactId = module.getArtifactId(); StringBuffer buffer = new StringBuffer(artifactId); buffer.append('.').append(ManagerConstants.BUNDLE_EXTENSION); String bundleFolderName = buffer.toString(); // does an old version of the bundle exist? File target = new File(bundlesFolder, bundleFolderName); if (target.exists()) { FileUtil.backupToFolder(target, getBackupDirectory()); FileUtil.deleteContentOfFolder(target); } FileUtil.copyDirectoryRecursivelyKeepTimestamps(moduleArchive, target); writeToLogger("Merging bundle ", artifactId, " finished"); } } //from auxiliary folder public void mergeTagLibraries() throws IOException { File tagLibrary = this.idegawebDirectoryStructure.getTagLibrary(); FileUtil.backupToFolder(tagLibrary, getBackupDirectory()); // delete all files that are not necessary //TODO: !!!!! does not work, because the tag libraries are not stored in the bundle folders !!!!!! // cleanTagLibrary(tagLibrary); // add the new missing files to the tag library Iterator moduleIterator = this.pomSorter.getToBeInstalledPoms().values().iterator(); while (moduleIterator.hasNext()) { Module module = (Module) moduleIterator.next(); File moduleTagLibrary = this.idegawebDirectoryStructure.getTagLibrary(module); FileUtil.copyDirectoryRecursivelyKeepTimestamps(moduleTagLibrary, tagLibrary); String artifactId = module.getArtifactId(); writeToLogger("Merging tag library ", artifactId, " finished"); } } // // do not use this method // // !!!! does not work because the tag libraries are not stored in the bundle folders !!!!! // private void cleanTagLibrary(File tagLibrary) { // List existingTagLibraries = FileUtil.getFilesInDirectory(tagLibrary); // List filesToKeep = new ArrayList(); // Collection toBeInstalledArtifactIds = pomSorter.getToBeInstalledPoms().keySet(); // Map bundlesTagLibraries = pomSorter.getBundlesTagLibraries(); // Iterator iterator = bundlesTagLibraries.keySet().iterator(); // while (iterator.hasNext()) { // String artifactId = (String) iterator.next(); // // do not keep the tag libraries from bundles that will be installed // if (! toBeInstalledArtifactIds.contains(artifactId)) { // List tlds = (List) bundlesTagLibraries.get(artifactId); // if (tlds != null) { // filesToKeep.addAll(tlds); // } // } // } // // delete files // Iterator deleteIterator = existingTagLibraries.iterator(); // while (deleteIterator.hasNext()) { // File file = (File) deleteIterator.next(); // if (! filesToKeep.contains(file)) { // file.delete(); // } // } // } //from auxiliary folder public void mergeWebConfiguration() throws IOException { File webXml = this.idegawebDirectoryStructure.getDeploymentDescriptor(); BundleFileMerger merger = new WebXmlMerger(); mergeConfiguration(merger, webXml, true); writeToLogger("Merging web configuration finished", null, null); } public void mergeFacesConfiguration() throws IOException { File facesConfig = this.idegawebDirectoryStructure.getFacesConfig(); BundleFileMerger merger = new FacesConfigMerger(); mergeConfiguration(merger, facesConfig, false); writeToLogger("Merging faces configuration finished", null, null); } // from auxiliary folder private void mergeConfiguration(final BundleFileMerger merger, final File fileInWebInf, boolean useExternalThread ) throws IOException { // do not remove existing modules! merger.setIfRemoveOlderModules(false); FileUtil.backupToFolder(fileInWebInf, getBackupDirectory()); // set the target if (! useExternalThread) { // the simple way: write directly to the file mergeConfiguration(merger, fileInWebInf, fileInWebInf); } else { // the complicated way: write to a temp file then copy the file to the original one but wait 20 seconds // in this way, the application has enough time to finish the response String mergedFileName = fileInWebInf.getName(); mergedFileName = StringHandler.concat(mergedFileName, "_merged"); final File mergedFile = new File(getBackupDirectory(), mergedFileName); // seems to be a bug in merger (or is it a feature ?), source and output has to be the same FileUtil.copyFile(fileInWebInf, mergedFile); mergeConfiguration(merger, mergedFile, mergedFile); Thread thread = new Thread() { public void run() { try { System.out.println("[Installer] Start sleeping...."); sleep(WAIT_PERIOD); System.out.println("[Installer] Stop sleeping...application will restart pretty soon"); try { FileUtil.copyFile(mergedFile, fileInWebInf); } catch (FileNotFoundException ex) { // do nothing System.err.println("[[Installer] Could not copy new web.xml" + ex.getMessage()); } catch (IOException ex) { // do nothing System.err.println("[[Installer] Could not copy new web.xml" + ex.getMessage()); } } catch ( InterruptedException e ) { // do nothing } } }; thread.setDaemon(true); thread.start(); } } private void mergeConfiguration(BundleFileMerger merger, File sourceFile, File outputFile) throws IOException { merger.setOutputFile(outputFile); Iterator moduleIterator = this.pomSorter.getToBeInstalledPoms().values().iterator(); while (moduleIterator.hasNext()) { Module module = (Module) moduleIterator.next(); File tempSourceFile = this.idegawebDirectoryStructure.getCorrespondingFileFromWebInf(module, sourceFile); // not every module has a config file if (tempSourceFile.exists()) { String artifactId = module.getArtifactId(); String version = module.getCurrentVersion(); merger.addMergeInSourceFile(tempSourceFile, artifactId, version); } } merger.process(); } // from auxiliary folder public void mergeLibrary() throws IOException { File library = this.idegawebDirectoryStructure.getLibrary(); FileUtil.backupToFolder(library, getBackupDirectory()); // delete all files that are not necessary cleanLibrary(library); // add the new missing jars to the library Iterator moduleIterator = this.pomSorter.getToBeInstalledPoms().values().iterator(); while (moduleIterator.hasNext()) { Module module = (Module) moduleIterator.next(); File moduleLibrary = this.idegawebDirectoryStructure.getLibrary(module); FileUtil.copyDirectoryRecursivelyKeepTimestamps(moduleLibrary, library); String artifactId = module.getArtifactId(); writeToLogger("Merging library ", artifactId, " finished"); } } private void cleanLibrary(File library) throws IOException { // build a list of necessary file names... Map necessaryPomsMap = this.pomSorter.getNecessaryPoms(); Collection necessaryPoms = necessaryPomsMap.values(); Map necessaryFileNames = new HashMap(necessaryPoms.size()); List notInstalledYet = new ArrayList(); List containedFileNames = new ArrayList(); Iterator iterator = necessaryPoms.iterator(); while (iterator.hasNext()) { Module module = (Module) iterator.next(); // check if the name of the jar file is explicit defined String fileName = module.getJarFileName(); if (fileName == null) { fileName = getJarFileName(module); } if (module.isInstalled()) { necessaryFileNames.put(fileName, module.getArtifactId()); } else { // only for debugging notInstalledYet.add(fileName); } } List files = FileUtil.getFilesInDirectory(library); Iterator filesIterator = files.iterator(); List toBeDeletedFiles = new ArrayList(); while (filesIterator.hasNext()) { File file = (File) filesIterator.next(); String fileName = file.getName(); // if not necessary delete it if (! necessaryFileNames.containsKey(fileName)) { // delete jar file toBeDeletedFiles.add(file); } else { // only for debugging containedFileNames.add(fileName); necessaryFileNames.remove(fileName); } } // necessary files should be empty! // but sometimes Iterator toBeDeletedIterator = toBeDeletedFiles.iterator(); while (toBeDeletedIterator.hasNext()) { File file = (File) toBeDeletedIterator.next(); String fileName = file.getName(); String artifact = StringHandler.getFirstToken(fileName, "_-") ; if (! necessaryFileNames.containsValue(artifact)) { file.delete(); } } // only for debugging containedFileNames.size(); notInstalledYet.size(); toBeDeletedFiles.size(); } private String getJarFileName(Module module) throws IOException { String artifactId = module.getArtifactId(); // this is a little bit tricky and complicated.... // // If pom is not null, the module is a Dependency that refers to a bundle module // the version of the dependency could be "SNAPSHOT" but the real used one could have the version "1.0-SNAPSHOT". // In other words: // If the dependency is a snapshot the method module.getCurrentVersion returns "SNAPSHOT" (and this is actually the value // that is used in the project file of the dependant) but the // the method pom.getCurrentVersion() might either return null or "" or "1.0". // Therefore to get the right file name ask the real one! // // If the version is not "SNAPSHOT" // the method module.getCurrentVersion() and pom.getCurrentVersion() should return the same result. Pom pom = module.getPom(); String version = (pom == null) ? module.getCurrentVersion() : pom.getCurrentVersion(); StringBuffer buffer = new StringBuffer(artifactId); // sometimes the version is not set // if the version is equal to SNAPSHOT do not add the current version (avoiding file names like com.idega.block.article-SNAPSHOT-SNAPSHOT) if (version !=null && version.length() != 0 && ! version.equals(RealPom.SNAPSHOT)) { buffer.append(ManagerConstants.ARTIFACT_ID_VERSION_SEPARATOR); buffer.append(version); } if (module.isSnapshot()) { buffer.append(ManagerConstants.ARTIFACT_ID_VERSION_SEPARATOR); buffer.append(RealPom.SNAPSHOT); } buffer.append('.'); buffer.append(ManagerConstants.JAR_EXTENSION); return buffer.toString(); } public LogFile getLogFile() throws IOException { if (this.logFile == null) { File tempBackupFolder = getBackupDirectory(); File logDestination = new File(tempBackupFolder, "install.log"); this.logFile = new LogFile(logDestination); } return this.logFile; } private File getBackupDirectory() { if (this.backupFolder == null) { File folder = this.idegawebDirectoryStructure.getBackupDirectory(); this.backupFolder = new File(folder, getIdentifier()); } return this.backupFolder; } private void writeToLogger(String prefix, String main, String suffix) throws IOException { LogFile tempLogFile = getLogFile(); StringBuffer logBuffer = new StringBuffer(prefix); if (main != null) { logBuffer.append(main); } if (suffix != null) { logBuffer.append(suffix); } tempLogFile.logInfo(logBuffer.toString()); } private String getIdentifier() { UUIDGenerator generator = UUIDGenerator.getInstance(); UUID uuid = generator.generateTimeBasedUUID(); String identifier = uuid.toString(); return StringHandler.remove(identifier, "-"); } }
14,209
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
URLReadConnection.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/URLReadConnection.java
/* * Created on Feb 11, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.business; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import com.idega.util.StringHandler; /** * @author thomas * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class URLReadConnection { public static final String UNKNOWN_CONNECTION_ERROR = "unknown_connection_error"; public static final String NOT_FOUND_ERROR = "not_found_error"; public static final String FORBIDDEN_ERROR = "forbidden_error"; public static final String UNAUTHORIZED_ERROR = "unauthorized_error"; public static final String NO_CONTENT_ERROR = "no_content_error"; public static String authenticationValid(URL url, PasswordAuthentication passwordAuthentication) throws MalformedURLException, IOException { URLReadConnection conn = new URLReadConnection(); conn.url = url; conn.passwordAuthentication = passwordAuthentication; return conn.authenticationValid(); } public static InputStreamReader getReaderForURLWithoutAuthentication(URL url) throws MalformedURLException, IOException { return getReaderForURLWithAuthentication(url, null); } public static InputStreamReader getReaderForURLWithAuthentication(String url, PasswordAuthentication passwordAuthentication) throws MalformedURLException, IOException { return getReaderForURLWithAuthentication(new URL(url), passwordAuthentication); } public static InputStreamReader getReaderForURLWithAuthentication(URL url, PasswordAuthentication passwordAuthentication) throws IOException { URLReadConnection conn = new URLReadConnection(); conn.url = url; conn.passwordAuthentication = passwordAuthentication; return conn.getReader(); } private URL url = null; private PasswordAuthentication passwordAuthentication = null; private URLConnection connect() throws IOException { URLConnection con = this.url.openConnection(); if (this.passwordAuthentication != null) { con.setDoInput( true ); String base64UserPassword = getBase64UserPassword(); con.setRequestProperty( "Authorization", base64UserPassword); con.connect(); } return con; } private InputStreamReader getReader() throws IOException { URLConnection con = connect(); InputStream inputStream = con.getInputStream(); BufferedInputStream buffInputStream = new BufferedInputStream(inputStream); return new InputStreamReader(buffInputStream, "8859_1"); } private String authenticationValid() throws IOException { // check the most common errors URLConnection con = connect(); String state = con.getHeaderField(null); if (state == null) { return UNKNOWN_CONNECTION_ERROR; } state = state.toUpperCase(); if (StringHandler.contains(state, "200")) { // okay return null; } if (StringHandler.contains(state, "404")) { return NOT_FOUND_ERROR; } if (StringHandler.contains(state, "403")) { return FORBIDDEN_ERROR; } if (StringHandler.contains(state, "401")) { return UNAUTHORIZED_ERROR; } if (StringHandler.contains(state, "204")) { return NO_CONTENT_ERROR; } return UNKNOWN_CONNECTION_ERROR; } private String getBase64UserPassword() { String userName = this.passwordAuthentication.getUserName(); char[] password = this.passwordAuthentication.getPassword(); StringBuffer buffer = new StringBuffer(); buffer.append(userName).append(":").append(password); Charset charset = Charset.forName("ISO-8859-1"); ByteBuffer byteBuffer = charset.encode(buffer.toString()); byte[] byteArray = byteBuffer.array(); String encodedUser = new String(Base64.encodeBase64(byteArray)); // put Basic at the beginning buffer = new StringBuffer("Basic "); buffer.append(encodedUser); return buffer.toString(); } }
4,256
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ApplicationUpdater.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven1/business/ApplicationUpdater.java
/* * Created on Jan 20, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.maven1.business; import java.io.IOException; import java.util.logging.Level; import com.idega.util.logging.LogFile; /** * @author thomas * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ApplicationUpdater { private PomSorter pomSorter = null; private String errorMessage = null; public ApplicationUpdater(PomSorter pomSorter) { this.pomSorter = pomSorter; } public boolean installModules() { Installer installer = Installer.getInstance(this.pomSorter); LogFile logFile = null; try { logFile = installer.getLogFile(); } catch (IOException ex) { this.errorMessage = ex.getMessage(); return false; } try { logFile.log(Level.INFO, "Extracting bundle archives..."); installer.extractBundleArchives(); logFile.log(Level.INFO, "...extracting bundle archives finished"); // not needed: installer.mergeFacesConfiguration(); logFile.log(Level.INFO, "Merging library..."); installer.mergeLibrary(); logFile.log(Level.INFO, "...merging library finished"); // not needed: installer.mergeTagLibraries(); logFile.log(Level.INFO, "Merging bundles..."); installer.mergeBundles(); logFile.log(Level.INFO, "...merging bundles finished"); logFile.log(Level.INFO, "Merging web configuration..."); installer.mergeWebConfiguration(); logFile.log(Level.INFO, "...merging web configuration finished"); } catch (IOException ex) { this.errorMessage = ex.getMessage(); return false; } finally { logFile. close(); } return true; } public String getErrorMessage() { return this.errorMessage; } }
1,872
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ManagerViewManager.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/view/ManagerViewManager.java
/* * Created on Dec 29, 2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.idega.manager.view; import java.util.ArrayList; import java.util.Collection; import javax.faces.context.FacesContext; import com.idega.core.accesscontrol.business.StandardRoles; import com.idega.core.view.ApplicationViewNode; import com.idega.core.view.DefaultViewNode; import com.idega.core.view.KeyboardShortcut; import com.idega.core.view.ViewManager; import com.idega.core.view.ViewNode; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.repository.data.Instantiator; import com.idega.repository.data.Singleton; import com.idega.repository.data.SingletonRepository; /** * @author thomas * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ManagerViewManager implements Singleton { private static Instantiator instantiator = new Instantiator() { @Override public Object getInstance(Object parameter) { IWMainApplication iwma = null; if (parameter instanceof FacesContext) { iwma = IWMainApplication.getIWMainApplication((FacesContext) parameter); } else { iwma = (IWMainApplication) parameter; } return new ManagerViewManager(iwma); } }; private static final String BUNDLE_IDENTIFIER="com.idega.manager"; private ViewNode managerRootNode; private IWMainApplication iwma; protected ManagerViewManager(IWMainApplication iwma){ this.iwma=iwma; } public static ManagerViewManager getInstance(IWMainApplication iwma){ return (ManagerViewManager) SingletonRepository.getRepository().getInstance(ManagerViewManager.class, instantiator, iwma); } public static ManagerViewManager getInstance(FacesContext context){ return (ManagerViewManager) SingletonRepository.getRepository().getInstance(ManagerViewManager.class, instantiator, context); } public ViewManager getViewManager(){ return ViewManager.getInstance(this.iwma); } public ViewNode getManagerNode(){ IWBundle iwb = this.iwma.getBundle(BUNDLE_IDENTIFIER); //ViewNode content = root.getChild(CONTENT_ID); if(this.managerRootNode==null){ this.managerRootNode = initalizeManagerNode(iwb); } return this.managerRootNode; } public ViewNode initalizeManagerNode(IWBundle bundle){ ViewNode root = getViewManager().getWorkspaceRoot(); DefaultViewNode managerNode = new ApplicationViewNode("manager",root); managerNode.setJspUri(bundle.getJSPURI("Manager.jsp")); managerNode.setKeyboardShortcut(new KeyboardShortcut("6")); Collection roles = new ArrayList(); roles.add(StandardRoles.ROLE_KEY_ADMIN); managerNode.setAuthorizedRoles(roles); this.managerRootNode = managerNode; return this.managerRootNode; } public void initializeStandardNodes(IWBundle bundle){ ViewNode contentNode = initalizeManagerNode(bundle); // login manager / step 1 DefaultViewNode loginNode = new DefaultViewNode("install", contentNode); loginNode.setJspUri(bundle.getJSPURI("LoginManager.jsp")); loginNode.setName("#{localizedStrings['com.idega.manager']['install_update']}"); // update and install /step 2 DefaultViewNode installOrUpdateNode = new DefaultViewNode("installUpdate", loginNode); installOrUpdateNode.setVisibleInMenus(false); installOrUpdateNode.setJspUri(bundle.getJSPURI("InstallOrUpdateManager.jsp")); // update/step 3 DefaultViewNode updateNode = new DefaultViewNode("update", loginNode); updateNode.setVisibleInMenus(false); updateNode.setJspUri(bundle.getJSPURI("UpdateListManager.jsp")); // install/step 3.1 DefaultViewNode newModulesNode = new DefaultViewNode("newModule", loginNode); newModulesNode.setVisibleInMenus(false); newModulesNode.setJspUri(bundle.getJSPURI("InstallListManager.jsp")); // install/step 3.2 DefaultViewNode newModuleVersionNode = new DefaultViewNode("newModuleVersion", loginNode); newModuleVersionNode.setVisibleInMenus(false); newModuleVersionNode.setJspUri(bundle.getJSPURI("InstallNewModuleListManager.jsp")); // update and install /step 4 DefaultViewNode commitNode = new DefaultViewNode("commit", loginNode); commitNode.setVisibleInMenus(false); commitNode.setJspUri(bundle.getJSPURI("ModuleManager.jsp")); // server settings DefaultViewNode serverSettings = new DefaultViewNode("systemsettings", contentNode); serverSettings.setJspUri(bundle.getJSPURI("systemSettings.jsp")); serverSettings.setName("#{localizedStrings['com.idega.manager']['systemsettings']}"); // cache settings DefaultViewNode cacheSettings = new DefaultViewNode("cachesettings", contentNode); cacheSettings.setJspUri(bundle.getJSPURI("cacheSettings.jsp")); cacheSettings.setName("#{localizedStrings['com.idega.manager']['cachesettings']}"); } }
4,925
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
UpdateListManager.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/bean/UpdateListManager.java
/* * $Id: UpdateListManager.java,v 1.19 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 10, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.bean; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.SortedMap; import java.util.SortedSet; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.component.UISelectItems; import javax.faces.component.html.HtmlCommandButton; import javax.faces.component.html.HtmlOutputText; import javax.faces.component.html.HtmlPanelGroup; import javax.faces.component.html.HtmlSelectManyListbox; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.model.SelectItem; import javax.faces.model.SelectItemGroup; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.business.DependencyMatrix; import com.idega.manager.maven1.business.PomSorter; import com.idega.manager.maven1.business.PomValidator; import com.idega.manager.maven1.data.Module; import com.idega.manager.maven1.data.Pom; import com.idega.manager.maven1.data.ProxyPom; import com.idega.manager.maven1.data.RepositoryLogin; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.manager.maven1.util.ManagerUtils; import com.idega.manager.maven1.util.VersionComparator; import com.idega.util.datastructures.SortedByValueMap; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.19 $ */ public class UpdateListManager { protected IWResourceBundle resourceBundle; protected PomValidator pomValidator = null; protected PomSorter pomSorter = null; protected String outputText1Value; protected String outputText2Value; protected String button1Label; protected String button2Label; protected String button3Label; public UpdateListManager() { initialize(); } protected void initialize() { this.resourceBundle = ManagerUtils.getInstanceForCurrentContext().getResourceBundle(); initializePomSorter(); initializeOutputText(); initializeSubmitButtons(); } protected void initializePomSorter() { if (this.pomSorter == null) { this.pomSorter = ManagerUtils.getPomSorter(); } } protected void initializeOutputText() { this.outputText1Value = this.resourceBundle.getLocalizedString("man_manager_header", "Manager"); this.outputText2Value = this.resourceBundle.getLocalizedString("man_manager_select _updates","Select updates"); } protected void initializeSubmitButtons() { this.button1Label = this.resourceBundle.getLocalizedString("man_manager_back","Back"); this.button2Label = this.resourceBundle.getLocalizedString("man_manager_next","Next"); this.button3Label = this.resourceBundle.getLocalizedString("man_manager_cancel","Cancel"); } protected void initializeList() { this.multiSelectListbox1DefaultItems = new ArrayList(); String errorMessage = null; try { RepositoryLogin repositoryLogin = ManagerUtils.getRepositoryLogin(); this.pomSorter.initializeInstalledPomsAndAvailableUpdates(repositoryLogin); } catch (IOException ex) { errorMessage = this.resourceBundle.getLocalizedString("man_manager_no_connection", "Problems connecting to remote repository occurred"); } HtmlPanelGroup group = getGroupPanel1(); List list = group.getChildren(); list.clear(); this.button2.setDisabled(false); if (errorMessage != null) { this.button2.setDisabled(true); errorMessage = errorMessage + " <br/>"; HtmlOutputText error = new HtmlOutputText(); error.setValue(errorMessage); error.setStyle("color: red"); error.setEscape(false); list.add(error); return; } SortedMap sortedInstalledPom = this.pomSorter.getSortedInstalledPoms(); Map repositoryPom = this.pomSorter.getSortedRepositoryPomsOfAvailableUpdates(); fillList(sortedInstalledPom.keySet(), repositoryPom, sortedInstalledPom); } protected void fillList(Collection keys, Map repositoryPom, Map groupItemMap) { Map listItems = new HashMap(); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { String artifactId = (String) iterator.next(); SortedSet pomProxies = (SortedSet) repositoryPom.get(artifactId); SelectItem[] items = null; if (pomProxies != null) { Iterator pomProxiesIterator = pomProxies.iterator(); Module pom = getModuleGroupItem(groupItemMap, artifactId); items = new SelectItem[pomProxies.size()]; int i = items.length; while (pomProxiesIterator.hasNext()) { ProxyPom proxy = (ProxyPom) pomProxiesIterator.next(); // file is used as identifier String fileName = proxy.getFileName(); String label = getLabelForItem(pom, proxy); items[--i] = new SelectItem(fileName, label); } String label = getLabelForItemGroup(pom); SelectItemGroup itemGroup = new SelectItemGroup(label, null, true, items); listItems.put(itemGroup, label); } } Locale locale = this.resourceBundle.getLocale(); SortedByValueMap sortedMap = new SortedByValueMap(listItems, locale); Iterator valueIterator = sortedMap.keySet().iterator(); while (valueIterator.hasNext()) { SelectItemGroup selectItemGroup = (SelectItemGroup) valueIterator.next(); this.multiSelectListbox1DefaultItems.add(selectItemGroup); } } protected String getLabelForItemGroup(Module groupModule) { String pomName = groupModule.getNameForLabel(this.resourceBundle); String pomVersion = groupModule.getCurrentVersionForLabel(this.resourceBundle); StringBuffer buffer = new StringBuffer(); buffer.append(pomName); buffer.append(", "); buffer.append(pomVersion); return buffer.toString(); } protected String getLabelForItem(Module groupModule, Module itemModule) { String label = itemModule.getCurrentVersionForLabel(this.resourceBundle); // if the installed version is a snapshot do not recommend to install a stable version and vice versa if (groupModule.isSnapshot() ^ itemModule.isSnapshot()) { String notRecommended = this.resourceBundle.getLocalizedString("man_manager_not_recommended", "not recommended"); StringBuffer buffer = new StringBuffer(label); buffer.append(" - ").append(notRecommended); return buffer.toString(); } return label; } protected Module getModuleGroupItem(Map sortedInstalledPom, String artifactId) { return (Module) sortedInstalledPom.get(artifactId); } public void submitForm(ActionEvent event) { submitAndSetModuleManager(event, ManagerConstants.ACTION_BACK_UPDATE); } protected void submitAndSetModuleManager(ActionEvent event, String action) { UIComponent component = event.getComponent(); UIComponent parentForm = component.getParent(); HtmlSelectManyListbox selectManyList = (HtmlSelectManyListbox) parentForm.findComponent("multiSelectListbox1"); Object[] selectedValues = selectManyList.getSelectedValues(); Map repositoryPoms = this.pomSorter.getRepositoryPoms(); Map selectedPoms = new HashMap(); for (int i = 0; i < selectedValues.length; i++) { Pom pom = (Pom) repositoryPoms.get(selectedValues[i]); String artifactId = pom.getArtifactId(); selectedPoms.put(artifactId, pom); } Map installedPoms = this.pomSorter.getSortedInstalledPoms(); Collection installedModules = installedPoms.values(); Collection notInstalledModules = selectedPoms.values(); VersionComparator versionComparator = this.pomSorter.getUsedVersionComparator(); DependencyMatrix dependencyMatrix = DependencyMatrix.getInstance(notInstalledModules, installedModules, this.resourceBundle); List necessaryModules = dependencyMatrix.getListOfNecessaryModules(versionComparator); // it is important to reset the error messages - that is to set to null - if there are not any List errorMessages = dependencyMatrix.hasErrors() ? dependencyMatrix.getErrorMessages() : null; this.pomSorter.setErrorMessages(errorMessages); this.pomSorter.setNecessaryPoms(necessaryModules); ModuleManager moduleManager = ManagerUtils.getModuleManager(); if (moduleManager != null) { moduleManager.initializeDynamicContent(); moduleManager.setActionBack(action); } } public void validateSelectedModules(FacesContext context, UIComponent toValidate, Object value) { // the value of a hidden input is validated because only in this way this method is called even if nothing has been selected. // We could use the attribute "required" but this causes problems with the localization of the corresponding error message. // get the value of the component we are really interested in.... UIComponent component = context.getViewRoot().findComponent(ManagerConstants.JSF_COMPONENT_ID_MULTI_SELECT_1); Object componentValue = ((UIInput) component).getValue(); if (this.pomValidator == null) { this.pomValidator = new PomValidator(); } this.pomValidator.validateSelectedModules(context, toValidate, componentValue, this.pomSorter , this.resourceBundle); } public void initializeDynamicContent() { initializeList(); } private HtmlSelectManyListbox multiSelectListbox1 = new HtmlSelectManyListbox(); public HtmlSelectManyListbox getMultiSelectListbox1() { return this.multiSelectListbox1; } public void setMultiSelectListbox1(HtmlSelectManyListbox hsml) { this.multiSelectListbox1 = hsml; } protected List multiSelectListbox1DefaultItems = new ArrayList(); public List getMultiSelectListbox1DefaultItems() { return this.multiSelectListbox1DefaultItems; } public void setMultiSelectListbox1DefaultItems(List dsia) { this.multiSelectListbox1DefaultItems = dsia; } private UISelectItems multiSelectListbox1SelectItems = new UISelectItems(); public UISelectItems getMultiSelectListbox1SelectItems() { return this.multiSelectListbox1SelectItems; } public void setMultiSelectListbox1SelectItems(UISelectItems uisi) { this.multiSelectListbox1SelectItems = uisi; } private HtmlCommandButton button1 = new HtmlCommandButton(); public HtmlCommandButton getButton1() { return this.button1; } public void setButton1(HtmlCommandButton hcb) { this.button1 = hcb; } private HtmlCommandButton button2 = new HtmlCommandButton(); public HtmlCommandButton getButton2() { return this.button2; } public void setButton2(HtmlCommandButton hcb) { this.button2 = hcb; } private HtmlCommandButton button3 = new HtmlCommandButton(); public HtmlCommandButton getButton3() { return this.button3; } public void setButton3(HtmlCommandButton hcb) { this.button3 = hcb; } private HtmlOutputText outputText1 = new HtmlOutputText(); public HtmlOutputText getOutputText1() { return this.outputText1; } public void setOutputText1(HtmlOutputText hot) { this.outputText1 = hot; } private HtmlOutputText outputText2 = new HtmlOutputText(); public HtmlOutputText getOutputText2() { return this.outputText2; } public void setOutputText2(HtmlOutputText hot) { this.outputText2 = hot; } public String getOutputText1Value() { return this.outputText1Value; } public String getOutputText2Value() { return this.outputText2Value; } public String getButton1Label() { return this.button1Label; } public String getButton2Label() { return this.button2Label; } public String getButton3Label() { return this.button3Label; } public String button1_action() { return ManagerConstants.ACTION_BACK; } public String button2_action() { return ManagerConstants.ACTION_NEXT; } public String button3_action() { return ManagerConstants.ACTION_CANCEL; } private HtmlPanelGroup groupPanel1 = new HtmlPanelGroup(); public HtmlPanelGroup getGroupPanel1() { return this.groupPanel1; } public void setGroupPanel1(HtmlPanelGroup hpg) { this.groupPanel1 = hpg; } }
12,451
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
SystemSettings.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/bean/SystemSettings.java
/* * $Id: SystemSettings.java,v 1.5 2006/04/09 11:42:59 laddi Exp $ * Created on 29.7.2005 in project com.idega.manager * * Copyright (C) 2005 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.bean; import com.idega.core.builder.data.ICDomain; import com.idega.core.builder.data.ICDomainHome; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWMainApplication; /** * <p> * Managed bean to use to manipulate server properties * </p> * Last modified: $Date: 2006/04/09 11:42:59 $ by $Author: laddi $ * * @author <a href="mailto:tryggvil@idega.com">tryggvil</a> * @version $Revision: 1.5 $ */ public class SystemSettings { private String mainDomainName; private String mainDomainUrl; private String mainDomainServerName; private IWMainApplication iwma; /** * */ public SystemSettings() { super(); setIwma(IWMainApplication.getDefaultIWMainApplication()); loadData(); } /** * <p> * Load the data from persistence * </p> */ private void loadData() { ICDomain domain = getIwma().getIWApplicationContext().getDomain(); setMainDomainName(domain.getDomainName()); setMainDomainUrl(domain.getURL()); setMainDomainServerName(domain.getServerName()); } protected ICDomainHome getDomainHome(){ try { return (ICDomainHome) IDOLookup.getHome(ICDomain.class); } catch (IDOLookupException e) { throw new RuntimeException(e); } } /** * @return Returns the iwma. */ public IWMainApplication getIwma() { return this.iwma; } /** * @param iwma The iwma to set. */ public void setIwma(IWMainApplication iwma) { this.iwma = iwma; } /** * @return Returns the mainDomainName. */ public String getMainDomainName() { return this.mainDomainName; } /** * @param mainDomainName The mainDomainName to set. */ public void setMainDomainName(String mainDomainName) { this.mainDomainName = mainDomainName; } /** * @return Returns the mainDomainUrl. */ public String getMainDomainUrl() { return this.mainDomainUrl; } /** * @param mainDomainUrl The mainDomainUrl to set. */ public void setMainDomainUrl(String mainDomainUrl) { this.mainDomainUrl = mainDomainUrl; } public void store(){ try{ ICDomainHome domainHome = (ICDomainHome) IDOLookup.getHome(ICDomain.class); ICDomain cachedDomain = getIwma().getIWApplicationContext().getDomain(); ICDomain realDomain = domainHome.findFirstDomain(); cachedDomain.setDomainName(getMainDomainName()); realDomain.setDomainName(getMainDomainName()); //String mainDomainName = getMainDomainName(); /*String mainDomainUrl = getMainDomainUrl(); if(mainDomainUrl!=null && !mainDomainUrl.equals("")){ cachedDomain.setURL(mainDomainUrl); realDomain.setURL(mainDomainUrl); } else{ cachedDomain.setURL(null); }*/ String mainDomainServerName = getMainDomainServerName(); if(mainDomainServerName!=null && !mainDomainServerName.equals("")){ cachedDomain.setServerName(mainDomainServerName); realDomain.setServerName(mainDomainServerName); } else{ cachedDomain.setServerName(null); realDomain.setServerName(null); } realDomain.store(); } catch(Exception e){ e.printStackTrace(); } } /** * @return Returns the mainDomainServerName. */ public String getMainDomainServerName() { return this.mainDomainServerName; } /** * @param mainDomainServerName The mainDomainServerName to set. */ public void setMainDomainServerName(String mainDomainServerName) { this.mainDomainServerName = mainDomainServerName; } }
3,732
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
LoginManager.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/bean/LoginManager.java
/* * $Id: LoginManager.java,v 1.6 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 3, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.bean; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.component.UIViewRoot; import javax.faces.component.html.HtmlCommandButton; import javax.faces.component.html.HtmlInputText; import javax.faces.component.html.HtmlOutputLabel; import javax.faces.component.html.HtmlOutputText; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import org.apache.myfaces.component.html.ext.HtmlInputSecret; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.business.UserPasswordValidator; import com.idega.manager.maven1.data.RepositoryLogin; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.manager.maven1.util.ManagerUtils; /** * * Start of the install and update wizard * * 1. LoginManager * 2. InstallOrUpdateManager * * then either * * 3.1 InstallListManager * 3.2 InstallNewModuleListManager * * or * * 3.1UpdateListManager * * then * * 4. ModuleManager * * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.6 $ */ public class LoginManager { private IWResourceBundle resourceBundle = null; private String outputText1Value; private String outputText2Value; private String outputText3Value; private String outputText4Value; private String outputText5Value; private String button1Label; private String button2Label; private String button3Label; private UserPasswordValidator userPasswordValidator = null; RepositoryLogin repositoryLogin = null; public LoginManager() { initialize(); } private void initialize() { this.resourceBundle = ManagerUtils.getInstanceForCurrentContext().getResourceBundle(); this.repositoryLogin = null; initializeOutputText(); initializeInputFields(); initializeSubmitButtons(); } private void initializeOutputText() { this.outputText1Value = this.resourceBundle.getLocalizedString("man_manager_header", "Module Manager"); this.outputText2Value = this.resourceBundle.getLocalizedString("man_manager_login","Login"); this.outputText3Value = this.resourceBundle.getLocalizedString("man_repository", "Repository"); this.outputText4Value = this.resourceBundle.getLocalizedString("man_user_name", "User"); this.outputText5Value = this.resourceBundle.getLocalizedString("man_password","Password"); } private void initializeSubmitButtons() { this.button1Label = this.resourceBundle.getLocalizedString("man_manager_back","Back"); this.button2Label = this.resourceBundle.getLocalizedString("man_manager_next","Next"); this.button3Label = this.resourceBundle.getLocalizedString("man_manager_cancel","Cancel"); } private void initializeInputFields() { this.textField1.setValue(ManagerConstants.IDEGA_REPOSITORY_URL); } public RepositoryLogin getRepositoryLogin() { return this.repositoryLogin; } public void submitForm(ActionEvent event) { UIComponent component = event.getComponent(); UIComponent parentForm = component.getParent(); UIInput repositoryURLInput = (UIInput) parentForm.findComponent(ManagerConstants.JSF_COMPONENT_ID_REPOSITORY); UIInput usernameInput = (UIInput) parentForm.findComponent(ManagerConstants.JSF_COMPONENT_ID_USERNAME); UIInput passwordInput = (UIInput) parentForm.findComponent(ManagerConstants.JSF_COMPONENT_ID_PASSWORD); String repositoryURL = (String) repositoryURLInput.getValue(); String userName = (String) usernameInput.getValue(); userName = (userName == null) ? "" : userName; String password = (String) passwordInput.getValue(); password = (password == null) ? "" : password; this.repositoryLogin = RepositoryLogin.getInstanceWithAuthentication(repositoryURL, userName, password); } public void validateUserPassword(FacesContext context, UIComponent toValidate, Object value) { // the value of a hidden input is validated because only in this way this method is called even if nothing has been selected. // We could use the attribute "required" but this causes problems with the localization of the corresponding error message. // get the value of the component we are really interested in.... UIViewRoot viewRoot = context.getViewRoot(); UIComponent componentRepositoryURL = viewRoot.findComponent(ManagerConstants.JSF_COMPONENT_ID_REPOSITORY_PATH); UIComponent componentUser = viewRoot.findComponent(ManagerConstants.JSF_COMPONENT_ID_USERNAME_PATH); UIComponent componentPassword = viewRoot.findComponent(ManagerConstants.JSF_COMPONENT_ID_PASSWORD_PATH); Object componentRepositoryURLValue = ((UIInput) componentRepositoryURL).getValue(); Object componentUserValue = ((UIInput) componentUser).getValue(); Object componentPasswordValue = ((UIInput) componentPassword).getValue(); if (this.userPasswordValidator == null) { this.userPasswordValidator = new UserPasswordValidator(); } this.userPasswordValidator.validateUserPassword(context, toValidate, componentRepositoryURLValue, componentUserValue , componentPasswordValue, this.resourceBundle); } private HtmlOutputText outputText1 = new HtmlOutputText(); public HtmlOutputText getOutputText1() { return this.outputText1; } public void setOutputText1(HtmlOutputText hot) { this.outputText1 = hot; } private HtmlOutputText outputText2 = new HtmlOutputText(); public HtmlOutputText getOutputText2() { return this.outputText2; } public void setOutputText2(HtmlOutputText hot) { this.outputText2 = hot; } private HtmlOutputLabel outputText3 = new HtmlOutputLabel(); public HtmlOutputLabel getOutputText3() { return this.outputText3; } public void setOutputText3(HtmlOutputLabel hot) { this.outputText3 = hot; } private HtmlOutputLabel outputText4 = new HtmlOutputLabel(); public HtmlOutputLabel getOutputText4() { return this.outputText4; } public void setOutputText4(HtmlOutputLabel hot) { this.outputText4 = hot; } private HtmlOutputLabel outputText5 = new HtmlOutputLabel(); public HtmlOutputLabel getOutputText5() { return this.outputText5; } public void setOutputText5(HtmlOutputLabel hot) { this.outputText5 = hot; } private HtmlInputText textField1 = new HtmlInputText(); public HtmlInputText getTextField1() { return this.textField1; } public void setTextField1(HtmlInputText hit) { this.textField1 = hit; } private HtmlInputText textField2 = new HtmlInputText(); public HtmlInputText getTextField2() { return this.textField2; } public void setTextField2(HtmlInputText hit) { this.textField2 = hit; } private HtmlInputSecret secretField1 = new HtmlInputSecret(); public HtmlInputSecret getSecretField1() { return this.secretField1; } public void setSecretField1(Object secretField1) { System.out.println(secretField1); } private HtmlCommandButton button1 = new HtmlCommandButton(); public HtmlCommandButton getButton1() { return this.button1; } public void setButton1(HtmlCommandButton hcb) { this.button1 = hcb; } private HtmlCommandButton button2 = new HtmlCommandButton(); public HtmlCommandButton getButton2() { return this.button2; } public void setButton2(HtmlCommandButton hcb) { this.button2 = hcb; } private HtmlCommandButton button3 = new HtmlCommandButton(); public HtmlCommandButton getButton3() { return this.button3; } public void setButton3(HtmlCommandButton hcb) { this.button3 = hcb; } public String getOutputText1Value() { return this.outputText1Value; } public String getOutputText2Value() { return this.outputText2Value; } public String getOutputText3Value() { return this.outputText3Value; } public String getOutputText4Value() { return this.outputText4Value; } public String getOutputText5Value() { return this.outputText5Value; } public String getButton1Label() { return this.button1Label; } public String getButton2Label() { return this.button2Label; } public String getButton3Label() { return this.button3Label; } public String button2_action() { return ManagerConstants.ACTION_NEXT; } public String button3_action() { return ManagerConstants.ACTION_CANCEL; } }
8,832
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
CacheSettings.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/bean/CacheSettings.java
/* * $Id: CacheSettings.java,v 1.2 2006/04/09 11:42:59 laddi Exp $ * Created on 29.7.2005 in project com.idega.manager * * Copyright (C) 2005 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.bean; import com.idega.idegaweb.IWMainApplication; import com.idega.servlet.filter.CacheFilter; /** * <p> * Managed bean to use to manipulate server properties * </p> * Last modified: $Date: 2006/04/09 11:42:59 $ by $Author: laddi $ * * @author <a href="mailto:tryggvil@idega.com">tryggvil</a> * @version $Revision: 1.2 $ */ public class CacheSettings { private IWMainApplication iwma; private boolean cacheFilterEnabled; /** * */ public CacheSettings() { super(); setIwma(IWMainApplication.getDefaultIWMainApplication()); loadData(); } /** * <p> * TODO tryggvil describe method setIwma * </p> * @param defaultIWMainApplication */ private void setIwma(IWMainApplication defaultIWMainApplication) { this.iwma=defaultIWMainApplication; } /** * <p> * Load the data from persistence * </p> */ private void loadData() { IWMainApplication iwma = getIwma(); String propCacheFilterEnabled = iwma.getSettings().getProperty(CacheFilter.PROPERTY_CACHE_FILTER_ENABLED); boolean cacheFilterEnabled = Boolean.valueOf(propCacheFilterEnabled).booleanValue(); setCacheFilterEnabled(cacheFilterEnabled); } public void store(){ IWMainApplication iwma = getIwma(); String propCacheFilterEnabled = Boolean.toString(isCacheFilterEnabled()); iwma.getSettings().setProperty(CacheFilter.PROPERTY_CACHE_FILTER_ENABLED,propCacheFilterEnabled); CacheFilter.reload(); } /** * <p> * TODO tryggvil describe method getIwma * </p> * @return */ private IWMainApplication getIwma() { return this.iwma; } /** * @return Returns the cacheFilterEnabled. */ public boolean isCacheFilterEnabled() { return this.cacheFilterEnabled; } /** * @param cacheFilterEnabled The cacheFilterEnabled to set. */ public void setCacheFilterEnabled(boolean cacheFilterEnabled) { this.cacheFilterEnabled = cacheFilterEnabled; } }
2,211
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ModuleManager.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/bean/ModuleManager.java
/* * $Id: ModuleManager.java,v 1.21 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 10, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.bean; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.SortedMap; import javax.faces.application.Application; import javax.faces.component.UIColumn; import javax.faces.component.html.HtmlCommandButton; import javax.faces.component.html.HtmlDataTable; import javax.faces.component.html.HtmlOutputText; import javax.faces.component.html.HtmlPanelGroup; import javax.faces.el.ValueBinding; import javax.faces.event.ActionEvent; import javax.faces.model.ListDataModel; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.business.ApplicationUpdater; import com.idega.manager.maven1.business.PomSorter; import com.idega.manager.maven1.data.Module; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.manager.maven1.util.ManagerUtils; import com.idega.util.datastructures.SortedByValueMap; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.21 $ */ public class ModuleManager { private static int maxNumberOfShownErrorMessages = 5; private IWResourceBundle resourceBundle = null; private PomSorter pomSorter = null; private String outputText1Value; private String outputText2Value; private String button1Label; private String button2Label; private String button3Label; private String actionBack = ManagerConstants.ACTION_BACK_UPDATE; private String actionNext = ""; private String actionNextChangeToNewValue = null; public ModuleManager() { initialize(); } private void initialize() { this.resourceBundle = ManagerUtils.getInstanceForCurrentContext().getResourceBundle(); initializePomSorter(); initializeOutputText(); initializeSubmitButtons(); } private void initializePomSorter() { if (this.pomSorter == null) { this.pomSorter = ManagerUtils.getPomSorter(); } } private void initializeOutputText() { this.outputText1Value = this.resourceBundle.getLocalizedString("man_manager_header", "Module Manager"); this.outputText2Value = this.resourceBundle.getLocalizedString("man_manager_do_you_want_to_install_modules","Do you want to install the following modules?"); } private void initializeSubmitButtons() { this.button1Label = this.resourceBundle.getLocalizedString("man_manager_back","Back"); this.button2Label = this.resourceBundle.getLocalizedString("man_manager_next","Install"); this.button3Label = this.resourceBundle.getLocalizedString("man_manager_cancel","Cancel"); } private void initializeDataTable1() { String noPreviousVersionInstalled = this.resourceBundle.getLocalizedString("man_manager_no_previous_version_installed","No previous version installed"); List rows = new ArrayList(); SortedMap toBeInstalled = null; SortedMap sortedInstalledMap = null; if (this.pomSorter != null) { toBeInstalled = this.pomSorter.getToBeInstalledPoms(); sortedInstalledMap =this.pomSorter.getSortedInstalledPoms(); } if (toBeInstalled == null || toBeInstalled.isEmpty()) { String noModulesNeedToBeInstalled = this.resourceBundle.getLocalizedString("man_manager_no_modules_need_to_be_installed","No modules need to be installed"); String[] firstRow = { noModulesNeedToBeInstalled }; rows.add(firstRow); } else { Map tableRows = new HashMap(); Iterator iterator = toBeInstalled.values().iterator(); while (iterator.hasNext()) { Module module = (Module) iterator.next(); String name = module.getNameForLabel(this.resourceBundle); String version = module.getCurrentVersionForLabel(this.resourceBundle); String artifactId = module.getArtifactId(); Module oldPom = (Module) sortedInstalledMap.get(artifactId); String oldVersion = (oldPom == null) ? noPreviousVersionInstalled : oldPom.getCurrentVersionForLabel(this.resourceBundle); String[] row = {name, version, oldVersion}; tableRows.put(row, name); } Locale locale = this.resourceBundle.getLocale(); SortedByValueMap sortedMap = new SortedByValueMap(tableRows, locale); Iterator valueIterator = sortedMap.keySet().iterator(); while (valueIterator.hasNext()) { String[] row = (String[]) valueIterator.next(); rows.add(row); } } this.dataTable1Model = new ListDataModel(rows); // initialize columnNames String module = this.resourceBundle.getLocalizedString("man_manager_module", "Module"); String version = this.resourceBundle.getLocalizedString("man_manager_module", "New Version"); String oldVersion = this.resourceBundle.getLocalizedString("man_manager_old_version","Old version"); String[] columnNames = {module, version, oldVersion}; initializeHtmlDataTable(columnNames); } private void initializeErrorMessages() { List errorMessages = this.pomSorter.getErrorMessages(); initializeErrorMessages(errorMessages); } private void initializeErrorMessages(List errorMessages) { HtmlPanelGroup group = getGroupPanel1(); List list = group.getChildren(); list.clear(); this.button2.setDisabled(false); this.button2Label = this.resourceBundle.getLocalizedString("man_manager_next","Install"); this.outputText2Value = this.resourceBundle.getLocalizedString("man_manager_do_you_want_to_install_modules","Do you want to install the following modules?"); if (errorMessages != null) { this.outputText2Value = this.resourceBundle.getLocalizedString("man_manager_success","Problems occurred, you can not proceed"); this.button2.setDisabled(true); Iterator iterator = errorMessages.iterator(); boolean go = true; int i = 0; while (iterator.hasNext() && go) { String errorMessage = null; if (i++ == maxNumberOfShownErrorMessages) { go = false; errorMessage = this.resourceBundle.getLocalizedString("man_manager_more_problems", "more problems..."); } else { errorMessage = (String) iterator.next(); } errorMessage = errorMessage + " <br/>"; HtmlOutputText error = new HtmlOutputText(); error.setValue(errorMessage); error.setStyle("color: red"); error.setEscape(false); list.add(error); } } } public void initializeDynamicContent() { initializeDataTable1(); initializeErrorMessages(); } private HtmlDataTable dataTable1 = new HtmlDataTable(); public HtmlDataTable getDataTable1() { return this.dataTable1; } public void setDataTable1(HtmlDataTable dataTable1) { this.dataTable1 = dataTable1; } private void initializeHtmlDataTable(String[] columnNames) { Application application = ManagerUtils.getInstanceForCurrentContext().getApplication(); try { // First we remove columns from table List list = this.dataTable1.getChildren(); list.clear(); // // This is data obtained in "executeQuery" method // ResultSet resultSet = (ResultSet)data.getWrappedData(); // // columnNames = new String[colNumber]; UIColumn column; HtmlOutputText outText; HtmlOutputText headerText; // // ResultSetMetaData metaData = resultSet.getMetaData(); this.dataTable1.setVar("currentRow"); this.dataTable1.setColumnClasses("moduleManagerBigColumnClass, moduleManagerColumnClass, moduleManagerColumnClass"); // dataTable1.setHeaderClass("moduleManagerHeaderClass"); // "currentRow" must be set in the corresponding JSP page! // this variable is used above by the method call dataTable1.getVar() // In this loop we are going to add columns to table, // and to make sure that all column are populated (table.getVar is taking care of that). // As you can se we will add "headerText" and "outText" to "column", // same way we would add "<f:facet name="header">" and "<h:outputtext>" to "<h:column>" // Notice that "var" is previously set to "dbTable" and now we are using it. for (int i = 0; i < 3; i++) { // columnNames[i] = metaData.getColumnName(i + 1); // headerText = new HtmlOutputText(); headerText.setTitle(columnNames[i]); headerText.setValue(columnNames[i]); //headerText.setStyleClass("moduleManagerHeaderClass"); outText = new HtmlOutputText(); //String vblExpression = "#{" + hdt.getVar() + "." + metaData.getColumnName(i + 1) + "}"; String vblExpression = "#{" + this.dataTable1.getVar() + "[" + Integer.toString(i) + "]}"; ValueBinding vb = application.createValueBinding(vblExpression); outText.setValueBinding("value", vb); column = new UIColumn(); //map.put("width","444px"); column.getChildren().add(outText); column.setHeader(headerText); // ... we add column to list of table's components list.add(column); } } catch (Exception e) { e.printStackTrace(); } } public void submitForm(ActionEvent event) { if (this.pomSorter != null) { ApplicationUpdater updater = new ApplicationUpdater(this.pomSorter); if (! updater.installModules()) { String errorMessage = updater.getErrorMessage(); List errorMessages = new ArrayList(1); errorMessages.add(errorMessage); initializeErrorMessages(errorMessages); } else { this.outputText2Value = this.resourceBundle.getLocalizedString("man_manager_success","Modules have been successfully installed"); this.button1.setDisabled(true); this.button2.setDisabled(true); this.button3.setDisabled(true); this.pomSorter = null; // button2Label = resourceBundle.getLocalizedString("man_manager_finish","Finish"); // actionNextChangeToNewValue = ManagerConstants.ACTION_CANCEL; } } } private ListDataModel dataTable1Model = new ListDataModel(); public ListDataModel getDataTable1Model() { return this.dataTable1Model; } public void setDataTable1Model(ListDataModel dtdm) { this.dataTable1Model = dtdm; } private HtmlCommandButton button1 = new HtmlCommandButton(); public HtmlCommandButton getButton1() { return this.button1; } public void setButton1(HtmlCommandButton hcb) { this.button1 = hcb; } private HtmlCommandButton button2 = new HtmlCommandButton(); public HtmlCommandButton getButton2() { return this.button2; } public void setButton2(HtmlCommandButton hcb) { this.button2 = hcb; } private HtmlCommandButton button3 = new HtmlCommandButton(); public HtmlCommandButton getButton3() { return this.button3; } public void setButton3(HtmlCommandButton hcb) { this.button3 = hcb; } private HtmlOutputText outputText1 = new HtmlOutputText(); public HtmlOutputText getOutputText1() { return this.outputText1; } public void setOutputText1(HtmlOutputText hot) { this.outputText1 = hot; } private HtmlOutputText outputText2 = new HtmlOutputText(); public HtmlOutputText getOutputText2() { return this.outputText2; } public void setOutputText2(HtmlOutputText hot) { this.outputText2 = hot; } public String getOutputText1Value() { return this.outputText1Value; } public String getOutputText2Value() { return this.outputText2Value; } public String getButton1Label() { return this.button1Label; } public String getButton2Label() { return this.button2Label; } public String getButton3Label() { return this.button3Label; } public void setActionBack(String actionBack) { this.actionBack = actionBack; } public String button1_action() { return this.actionBack; } // first submitForm is called then this method is invoked // change the value after returning the old value! public String button2_action() { String returnValue = this.actionNext; if (this.actionNextChangeToNewValue != null) { this.actionNext = this.actionNextChangeToNewValue; this.actionNextChangeToNewValue = null; } return returnValue; } public String button3_action() { return ManagerConstants.ACTION_CANCEL; } private HtmlPanelGroup groupPanel1 = new HtmlPanelGroup(); public HtmlPanelGroup getGroupPanel1() { return this.groupPanel1; } public void setGroupPanel1(HtmlPanelGroup hpg) { this.groupPanel1 = hpg; } }
12,821
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
InstallListManager.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/bean/InstallListManager.java
/* * $Id: InstallListManager.java,v 1.8 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 10, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.bean; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.component.UISelectItems; import javax.faces.component.html.HtmlCommandButton; import javax.faces.component.html.HtmlOutputText; import javax.faces.component.html.HtmlPanelGroup; import javax.faces.component.html.HtmlSelectManyListbox; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.model.SelectItem; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.business.PomSorter; import com.idega.manager.maven1.business.PomValidator; import com.idega.manager.maven1.data.ProxyPom; import com.idega.manager.maven1.data.RepositoryLogin; import com.idega.manager.maven1.data.SimpleProxyPomList; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.manager.maven1.util.ManagerUtils; import com.idega.util.datastructures.SortedByValueMap; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.8 $ */ public class InstallListManager { private IWResourceBundle resourceBundle; private PomValidator pomValidator = null; private PomSorter pomSorter = null; private String outputText1Value; private String outputText2Value; private String button1Label; private String button2Label; private String button3Label; public InstallListManager() { initialize(); } private void initialize() { this.resourceBundle = ManagerUtils.getInstanceForCurrentContext().getResourceBundle(); initializePomSorter(); initializeOutputText(); initializeSubmitButtons(); } private void initializePomSorter() { if (this.pomSorter == null) { this.pomSorter = ManagerUtils.getPomSorter(); } } private void initializeOutputText() { this.outputText1Value = this.resourceBundle.getLocalizedString("man_manager_header", "Manager"); this.outputText2Value = this.resourceBundle.getLocalizedString("man_manager_select _new_modules","Select new modules you wish to install"); } private void initializeSubmitButtons() { this.button1Label = this.resourceBundle.getLocalizedString("man_manager_back","Back"); this.button2Label = this.resourceBundle.getLocalizedString("man_manager_next","Next"); this.button3Label = this.resourceBundle.getLocalizedString("man_manager_cancel","Cancel"); } private void initializeList() { this.multiSelectListbox1DefaultItems = new ArrayList(); String errorMessage = null; RepositoryLogin repositoryLogin = ManagerUtils.getRepositoryLogin(); try { this.pomSorter.initializeInstalledPomsAndAvailableNewModules(repositoryLogin); } catch (IOException ex) { errorMessage = this.resourceBundle.getLocalizedString("man_manager_no_connection", "Problems connecting to remote repository occurred"); } HtmlPanelGroup group = getGroupPanel1(); List list = group.getChildren(); list.clear(); this.button2.setDisabled(false); if (errorMessage != null) { this.button2.setDisabled(true); errorMessage = errorMessage + " <br/>"; HtmlOutputText error = new HtmlOutputText(); error.setValue(errorMessage); error.setStyle("color: red"); error.setEscape(false); list.add(error); return; } Map repositoryPom = this.pomSorter.getSortedSimpleProxyList(); Map listItems = new HashMap(); Iterator iterator = repositoryPom.keySet().iterator(); while (iterator.hasNext()) { String artifactId = (String) iterator.next(); SimpleProxyPomList simpleProxyPomList = (SimpleProxyPomList) repositoryPom.get(artifactId); if (! simpleProxyPomList.isEmpty()) { ProxyPom proxyPom = simpleProxyPomList.getRepresentative(); String name = proxyPom.getNameForLabel(this.resourceBundle); SelectItem item = new SelectItem(artifactId, name); listItems.put(item, name); } } Locale locale = this.resourceBundle.getLocale(); SortedByValueMap sortedMap = new SortedByValueMap(listItems, locale); Iterator valueIterator = sortedMap.keySet().iterator(); while (valueIterator.hasNext()) { SelectItem item = (SelectItem) valueIterator.next(); this.multiSelectListbox1DefaultItems.add(item); } } public void submitForm(ActionEvent event) { UIComponent component = event.getComponent(); UIComponent parentForm = component.getParent(); HtmlSelectManyListbox selectManyList = (HtmlSelectManyListbox) parentForm.findComponent("multiSelectListbox1"); Object[] selectedValues = selectManyList.getSelectedValues(); List selectedModules = Arrays.asList(selectedValues); InstallNewModuleListManager installNewModuleListManager = ManagerUtils.getInstallNewModuleListManager(); if (installNewModuleListManager != null) { installNewModuleListManager.initializeDynamicContent(selectedModules); } } public void validateSelectedModules(FacesContext context, UIComponent toValidate, Object value) { // the value of a hidden input is validated because only in this way this method is called even if nothing has been selected. // We could use the attribute "required" but this causes problems with the localization of the corresponding error message. // get the value of the component we are really interested in.... UIComponent component = context.getViewRoot().findComponent(ManagerConstants.JSF_COMPONENT_ID_MULTI_SELECT_1); Object componentValue = ((UIInput) component).getValue(); if (this.pomValidator == null) { this.pomValidator = new PomValidator(); } this.pomValidator.validateSelectedModuleNames(context, toValidate, componentValue, this.resourceBundle); } public void initializeDynamicContent() { initializeList(); } private HtmlSelectManyListbox multiSelectListbox1 = new HtmlSelectManyListbox(); public HtmlSelectManyListbox getMultiSelectListbox1() { return this.multiSelectListbox1; } public void setMultiSelectListbox1(HtmlSelectManyListbox hsml) { this.multiSelectListbox1 = hsml; } private List multiSelectListbox1DefaultItems = new ArrayList(); public List getMultiSelectListbox1DefaultItems() { return this.multiSelectListbox1DefaultItems; } public void setMultiSelectListbox1DefaultItems(List dsia) { this.multiSelectListbox1DefaultItems = dsia; } private UISelectItems multiSelectListbox1SelectItems = new UISelectItems(); public UISelectItems getMultiSelectListbox1SelectItems() { return this.multiSelectListbox1SelectItems; } public void setMultiSelectListbox1SelectItems(UISelectItems uisi) { this.multiSelectListbox1SelectItems = uisi; } private HtmlCommandButton button1 = new HtmlCommandButton(); public HtmlCommandButton getButton1() { return this.button1; } public void setButton1(HtmlCommandButton hcb) { this.button1 = hcb; } private HtmlCommandButton button2 = new HtmlCommandButton(); public HtmlCommandButton getButton2() { return this.button2; } public void setButton2(HtmlCommandButton hcb) { this.button2 = hcb; } private HtmlCommandButton button3 = new HtmlCommandButton(); public HtmlCommandButton getButton3() { return this.button3; } public void setButton3(HtmlCommandButton hcb) { this.button3 = hcb; } private HtmlOutputText outputText1 = new HtmlOutputText(); public HtmlOutputText getOutputText1() { return this.outputText1; } public void setOutputText1(HtmlOutputText hot) { this.outputText1 = hot; } private HtmlOutputText outputText2 = new HtmlOutputText(); public HtmlOutputText getOutputText2() { return this.outputText2; } public void setOutputText2(HtmlOutputText hot) { this.outputText2 = hot; } public String getOutputText1Value() { return this.outputText1Value; } public String getOutputText2Value() { return this.outputText2Value; } public String getButton1Label() { return this.button1Label; } public String getButton2Label() { return this.button2Label; } public String getButton3Label() { return this.button3Label; } public String button1_action() { return ManagerConstants.ACTION_BACK; } public String button2_action() { return ManagerConstants.ACTION_NEXT; } public String button3_action() { return ManagerConstants.ACTION_CANCEL; } private HtmlPanelGroup groupPanel1 = new HtmlPanelGroup(); public HtmlPanelGroup getGroupPanel1() { return this.groupPanel1; } public void setGroupPanel1(HtmlPanelGroup hpg) { this.groupPanel1 = hpg; } }
9,282
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
InstallNewModuleListManager.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/bean/InstallNewModuleListManager.java
/* * $Id: InstallNewModuleListManager.java,v 1.8 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 10, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.bean; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.event.ActionEvent; import com.idega.manager.maven1.data.Module; import com.idega.manager.maven1.data.SimpleProxyPomList; import com.idega.manager.maven1.util.ManagerConstants; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.8 $ */ public class InstallNewModuleListManager extends UpdateListManager { // String list of artifactIds private List selectedModules = null; public InstallNewModuleListManager() { initialize(); } public String getTitle() { return this.resourceBundle.getLocalizedString("man_manager_install_new_modules","Install new modules"); } protected void initializeList() { if (this.selectedModules == null) { // nothing to initialize return; } this.multiSelectListbox1DefaultItems = new ArrayList(); Map repositoryPom = new HashMap(); Map sortedSimpleProxyList = this.pomSorter.getSortedSimpleProxyList(); Iterator iterator = this.selectedModules.iterator(); while (iterator.hasNext()) { String artifactId = (String) iterator.next(); SimpleProxyPomList simpleProxyPomList = (SimpleProxyPomList) sortedSimpleProxyList.get(artifactId); this.pomSorter.addSimpleProxyPomList(artifactId, simpleProxyPomList, repositoryPom); } // sort Collections.sort(this.selectedModules); fillList(this.selectedModules, repositoryPom, repositoryPom); } protected Module getModuleGroupItem(Map repositoryPom, String artifactId) { Set pomSet = (Set) repositoryPom.get(artifactId); return (Module) pomSet.iterator().next(); } protected String getLabelForItemGroup(Module groupModule) { return groupModule.getNameForLabel(this.resourceBundle); } protected String getLabelForItem(Module groupModule, Module itemModule) { String label = itemModule.getCurrentVersionForLabel(this.resourceBundle); // if the suggested version is a snapshot do not recommend to install it if (itemModule.isSnapshot()) { String notRecommended = this.resourceBundle.getLocalizedString("man_manager_not_recommended", "not recommended"); StringBuffer buffer = new StringBuffer(label); buffer.append(" - ").append(notRecommended); return buffer.toString(); } return label; } public void submitForm(ActionEvent event) { submitAndSetModuleManager(event, ManagerConstants.ACTION_BACK_INSTALL); } public void initializeDynamicContent(List modules) { this.selectedModules = modules; initializeList(); } }
3,043
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
InstallOrUpdateManager.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/bean/InstallOrUpdateManager.java
/* * $Id: InstallOrUpdateManager.java,v 1.7 2008/06/11 21:10:01 tryggvil Exp $ * Created on Nov 3, 2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package com.idega.manager.bean; import java.util.ArrayList; import java.util.List; import javax.faces.component.UISelectItems; import javax.faces.component.html.HtmlCommandButton; import javax.faces.component.html.HtmlOutputText; import javax.faces.component.html.HtmlPanelGroup; import javax.faces.component.html.HtmlSelectOneRadio; import javax.faces.model.SelectItem; import com.idega.idegaweb.IWResourceBundle; import com.idega.manager.maven1.business.PomSorter; import com.idega.manager.maven1.util.ManagerConstants; import com.idega.manager.maven1.util.ManagerUtils; /** * * Last modified: $Date: 2008/06/11 21:10:01 $ by $Author: tryggvil $ * * @author <a href="mailto:thomas@idega.com">thomas</a> * @version $Revision: 1.7 $ */ public class InstallOrUpdateManager { private IWResourceBundle resourceBundle = null; private String outputText1Value; private String outputText2Value; private String button1Label; private String button2Label; private String button3Label; private PomSorter pomSorter = null; public InstallOrUpdateManager() { initialize(); } private void initialize() { this.resourceBundle = ManagerUtils.getInstanceForCurrentContext().getResourceBundle(); initializePomSorter(); initializeOutputText(); initializeSubmitButtons(); initializeRadioButtons(); } private void initializePomSorter() { this.pomSorter = new PomSorter(); } private void initializeOutputText() { this.outputText1Value = this.resourceBundle.getLocalizedString("man_manager_header", "Manager"); this.outputText2Value = this.resourceBundle.getLocalizedString("man_mamager_choose","Choose one option"); } private void initializeSubmitButtons() { this.button1Label = this.resourceBundle.getLocalizedString("man_manager_back","Back"); this.button2Label = this.resourceBundle.getLocalizedString("man_manager_next","Next"); this.button3Label = this.resourceBundle.getLocalizedString("man_manager_cancel","Cancel"); } private void initializeRadioButtons() { String installNewModules = this.resourceBundle.getLocalizedString("man_install_new_modules", "Install new modules"); String updateModules = this.resourceBundle.getLocalizedString("man_update_installed_modules","Update installed modules"); this.radioButtonList1DefaultItems = new ArrayList(2); this.radioButtonList1DefaultItems.add(new SelectItem(ManagerConstants.ACTION_INSTALL_NEW_MODULES, installNewModules)); this.radioButtonList1DefaultItems.add( new SelectItem(ManagerConstants.ACTION_UPDATE_MODULES, updateModules)); this.radioButtonList1.setValue(ManagerConstants.ACTION_INSTALL_NEW_MODULES); } public PomSorter getPomSorter() { return this.pomSorter; } private HtmlOutputText outputText1 = new HtmlOutputText(); public HtmlOutputText getOutputText1() { return this.outputText1; } public void setOutputText1(HtmlOutputText hot) { this.outputText1 = hot; } private HtmlOutputText outputText2 = new HtmlOutputText(); public HtmlOutputText getOutputText2() { return this.outputText2; } public void setOutputText2(HtmlOutputText hot) { this.outputText2 = hot; } private HtmlPanelGroup groupPanel1 = new HtmlPanelGroup(); public HtmlPanelGroup getGroupPanel1() { return this.groupPanel1; } public void setGroupPanel1(HtmlPanelGroup hpg) { this.groupPanel1 = hpg; } private HtmlSelectOneRadio radioButtonList1 = new HtmlSelectOneRadio(); public HtmlSelectOneRadio getRadioButtonList1() { return this.radioButtonList1; } public void setRadioButtonList1(HtmlSelectOneRadio hsor) { this.radioButtonList1 = hsor; } private List radioButtonList1DefaultItems = new ArrayList(); public List getRadioButtonList1DefaultItems() { return this.radioButtonList1DefaultItems; } public void setRadioButtonList1DefaultItems(List dsia) { this.radioButtonList1DefaultItems = dsia; } private UISelectItems radioButtonList1SelectItems = new UISelectItems(); public UISelectItems getRadioButtonList1SelectItems() { return this.radioButtonList1SelectItems; } public void setRadioButtonList1SelectItems(UISelectItems uisi) { this.radioButtonList1SelectItems = uisi; } private HtmlCommandButton button1 = new HtmlCommandButton(); public HtmlCommandButton getButton1() { return this.button1; } public void setButton1(HtmlCommandButton hcb) { this.button1 = hcb; } private HtmlCommandButton button2 = new HtmlCommandButton(); public HtmlCommandButton getButton2() { return this.button2; } public void setButton2(HtmlCommandButton hcb) { this.button2 = hcb; } private HtmlCommandButton button3 = new HtmlCommandButton(); public HtmlCommandButton getButton3() { return this.button3; } public void setButton3(HtmlCommandButton hcb) { this.button3 = hcb; } public String getOutputText1Value() { return this.outputText1Value; } public String getOutputText2Value() { return this.outputText2Value; } public String getButton1Label() { return this.button1Label; } public String getButton2Label() { return this.button2Label; } public String getButton3Label() { return this.button3Label; } public String button2_action() { String action = (String) this.radioButtonList1.getValue(); if (ManagerConstants.ACTION_INSTALL_NEW_MODULES.equals(action)) { InstallListManager installListManager = ManagerUtils.getInstallListManager(); if (installListManager != null) { installListManager.initializeDynamicContent(); } } else if (ManagerConstants.ACTION_UPDATE_MODULES.equals(action)) { UpdateListManager updateListManager = ManagerUtils.getUpdateListManager(); if (updateListManager != null) { updateListManager.initializeDynamicContent(); } } return action; } public String button3_action() { return ManagerConstants.ACTION_CANCEL; } }
6,447
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ModuleVersion.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven2/ModuleVersion.java
package com.idega.manager.maven2; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.maven.artifact.repository.metadata.Metadata; public class ModuleVersion { Metadata module; String version; public static String SNAPSHOT_SUFFIX="SNAPSHOT"; ModuleVersion(Metadata module,String version){ this.module=module; this.version=version; } public Metadata getModule() { return module; } public void setModule(Metadata module) { this.module = module; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public static String getMostRecentVersionAsString(Metadata module,boolean includeSnapshot){ return getMostRecentVersionAsString(module, module.getVersioning().getVersions(), includeSnapshot); } public static ModuleVersion getMostRecentVersion(Metadata module,boolean includeSnapshot){ return getMostRecentVersion(module, module.getVersioning().getVersions(), includeSnapshot); } public static String getMostRecentVersionAsString(Metadata module, List versionListString,boolean includeSnapshot){ ModuleVersion version = getMostRecentVersion(module, versionListString, includeSnapshot); return version.getVersion(); } public static ModuleVersion getMostRecentVersion(Metadata module, List versionListString,boolean includeSnapshot){ List<ModuleVersion> modules = getVersionList(module,versionListString,includeSnapshot); ModuleVersionComparator comparator = new ModuleVersionComparator(); Collections.sort(modules, comparator); return modules.get(modules.size()-1); } public static List<ModuleVersion> getVersionList(Metadata module, List versionListString,boolean includeSnapshot){ List<ModuleVersion> list = new ArrayList<ModuleVersion>(); for (Iterator iterator = versionListString.iterator(); iterator.hasNext();) { String stringVersion = (String) iterator.next(); ModuleVersion moduleVersion = new ModuleVersion(module,stringVersion); if(moduleVersion.isSnapshot()){ if(includeSnapshot){ list.add(moduleVersion); } } else{ list.add(moduleVersion); } } return list; } private boolean isSnapshot() { if(getVersion()!=null){ if(getVersion().endsWith(SNAPSHOT_SUFFIX)){ return true; } } return false; } public boolean isStable(){ return !isSnapshot(); } public String toString(){ return this.version; } }
2,494
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
ModuleVersionComparator.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven2/ModuleVersionComparator.java
package com.idega.manager.maven2; import java.util.Comparator; public class ModuleVersionComparator implements Comparator<ModuleVersion> { public int compare(ModuleVersion o1, ModuleVersion o2) { String s1 = o1.getVersion(); String s2 = o2.getVersion(); return s1.compareTo(s2); } }
313
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
RepositoryBrowserM2.java
/FileExtraction/Java_unseen/idega_com_idega_manager/src/java/com/idega/manager/maven2/RepositoryBrowserM2.java
package com.idega.manager.maven2; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.Snapshot; import org.apache.maven.artifact.repository.metadata.Versioning; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import com.idega.manager.maven1.business.RepositoryBrowser; import com.idega.manager.maven1.data.RepositoryLogin; public class RepositoryBrowserM2 extends RepositoryBrowser{ public static final String MAVEN_METADATA_FILE_NAME = "maven-metadata.xml"; public static RepositoryBrowserM2 getInstanceForIdegaRepository(RepositoryLogin repositoryLogin) { return new RepositoryBrowserM2(repositoryLogin); } public RepositoryBrowserM2(RepositoryLogin repositoryLogin) { super(repositoryLogin); } /*public List<MavenModule> getModulesInGroup(String groupId){ List<MavenModule> modules = new ArrayList<MavenModule>(); String groupUrl=getURLForGroupFolder(groupId); List<StringBuffer> artifactIds = getArtifactIdsUnder(groupUrl); for(StringBuffer bufferArtifactId: artifactIds){ String artifactId = bufferArtifactId.toString(); //String mavenMetadataUrl = getURLForMavenMetadataFile(groupId, artifactId); String artifactUrl = getURLForArtifactFolder(groupId, artifactId); MavenModule module = new MavenModule(artifactUrl); //module.setGroupId(groupId); //module.setArtifactId(artifactId); modules.add(module); } //for(MavenModule module: modules){ // System.out.println("Artifact:"+module.getArtifactId()); //} return modules; }*/ public Metadata getModuleWithGroupAndArtifactId(String groupId,String artifactId){ String artifactUrl = getURLForArtifactMetadata(groupId, artifactId); Metadata metadata=null; try { metadata = getMetadataFromUrl(artifactUrl); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } return metadata; } public List<Metadata> getModulesInGroup(String groupId){ List<Metadata> modules = new ArrayList<Metadata>(); String groupUrl=getURLForGroupFolder(groupId); List<StringBuffer> artifactIds = getArtifactIdsUnder(groupUrl); for(StringBuffer bufferArtifactId: artifactIds){ String artifactId = bufferArtifactId.toString(); //String mavenMetadataUrl = getURLForMavenMetadataFile(groupId, artifactId); String artifactUrl = getURLForArtifactMetadata(groupId, artifactId); try { Metadata metadata = getMetadataFromUrl(artifactUrl); //module.setGroupId(groupId); //module.setArtifactId(artifactId); modules.add(metadata); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //for(MavenModule module: modules){ // System.out.println("Artifact:"+module.getArtifactId()); //} return modules; } public String getArtifactUrlForMostRecent(String groupId, String artifactId){ return getArtifactUrlForMostRecent(groupId,artifactId,true); } public String getArtifactUrlForMostRecent(String groupId, String artifactId,boolean snapshot){ Metadata metadata = getModuleWithGroupAndArtifactId(groupId,artifactId); return getArtifactUrlForMostRecent(metadata,snapshot); } public String getArtifactUrlForMostRecent(Metadata metadata){ return getArtifactUrlForMostRecent(metadata,true); } public String getArtifactUrlForMostRecent(Metadata metadata,boolean snapshot){ Model pom = getModuleForMostRecent(metadata,snapshot); String artifactType = pom.getPackaging(); if(artifactType.equals("iwwar")){ artifactType="war"; } String artifactUrl = getURLForArtifactFile(metadata,snapshot,artifactType); return artifactUrl; } public Model getModuleForMostRecent(Metadata metadata){ return getModuleForMostRecent(metadata,true); } public Model getModuleForMostRecent(Metadata metadata,boolean snapshot){ //String groupId = metadata.getGroupId(); //String artifactId = metadata.getArtifactId(); //String groupUrl = getURLForGroupFolder(metadata.getGroupId()); //List<StringBuffer> artifactIds = getArtifactIdsUnder(groupUrl); //for(StringBuffer bufferArtifactId: artifactIds){ // String artifactId = bufferArtifactId.toString(); //String mavenMetadataUrl = getURLForMavenMetadataFile(groupId, artifactId); //String versionId = metadata.getVersion(); String artifactPomUrl = getURLForArtifactPom(metadata,snapshot); URL uRepositoryUrl; try { uRepositoryUrl = new URL(artifactPomUrl); URLConnection conn = uRepositoryUrl.openConnection(); Object content = conn.getContent(); InputStream input = (InputStream)content; Reader reader = new InputStreamReader(input); MavenXpp3Reader mavenReader = new MavenXpp3Reader(); Model module = mavenReader.read(reader); //module.setGroupId(groupId); //module.setArtifactId(artifactId); return module; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } //} return null; } private List<StringBuffer> getArtifactIdsUnder(String groupUrl) { // TODO Auto-generated method stub try { List<StringBuffer> folders = getFolderList(groupUrl); return folders; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public String getURLForArtifactFolder(String groupId, String artifactId) { String groupUrl = getURLForGroupFolder(groupId); String newUrl = groupUrl+artifactId+"/"; return newUrl; } public String getURLForArtifactMetadata(String groupId, String artifactId) { String folderUrl = getURLForArtifactFolder(groupId,artifactId); return folderUrl+"maven-metadata.xml"; } public String getURLForArtifactPom(Metadata metadata, boolean snapshot) { return getURLForArtifactFile(metadata,snapshot,"pom"); } public String getURLForArtifactFile(Metadata metadata, boolean snapshot, String type) { String groupId = metadata.getGroupId(); String artifactId = metadata.getArtifactId(); String folderPath = getURLForArtifactFolder(groupId,artifactId); String fileUrl = folderPath; Versioning versioning = metadata.getVersioning(); String mostRecentVersion = ModuleVersion.getMostRecentVersionAsString(metadata, versioning.getVersions(), snapshot); if(!snapshot){ //String releaseVersion = versioning.getRelease(); String releaseVersion = mostRecentVersion; fileUrl+=releaseVersion+"/"+artifactId+"-"+releaseVersion+"."+type; } else{ //String version = metadata.getVersion(); String version = mostRecentVersion; String snapshotFolderUrl = folderPath+version; String snapshotMetadataFileUrl = snapshotFolderUrl+"/maven-metadata.xml"; Metadata snapshotMetadata; try { snapshotMetadata = getMetadataFromUrl(snapshotMetadataFileUrl); Versioning snapshotVersioning = snapshotMetadata.getVersioning(); Snapshot snap = snapshotVersioning.getSnapshot(); String snapshotVersion = snapshotMetadata.getVersion(); String tstamp = snap.getTimestamp(); int buildNumber = snap.getBuildNumber(); String snapshotVersionMinusSnapshot = snapshotVersion.substring(0,snapshotVersion.indexOf("SNAPSHOT")-1); fileUrl+=snapshotVersion+"/"+artifactId+"-"+snapshotVersionMinusSnapshot+"-"+tstamp+"-"+buildNumber+"."+type; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return fileUrl; } protected Metadata getMetadataFromUrl(String artifactUrl) throws IOException, XmlPullParserException { URL uRepositoryUrl = new URL(artifactUrl); //HttpClient client = HttpClient.New(uRepositoryUrl); //client.getInputStream(); //reader = new FileReader("file://"); //Reader reader = new InputStreamReader(client.getInputStream()); URLConnection conn = uRepositoryUrl.openConnection(); Object content = conn.getContent(); InputStream input = (InputStream)content; Reader reader = new InputStreamReader(input); MetadataXpp3Reader mReader = new MetadataXpp3Reader(); Metadata metadata = mReader.read(reader); return metadata; } public static void main(String[] args){ String repositoryUrl = "http://repository.idega.com/maven2/"; RepositoryLogin login = RepositoryLogin.getInstanceWithoutAuthentication(repositoryUrl); //login.getAuthenticationInfo().setUserName("idegaweb"); //login.getAuthenticationInfo().setPassword("pl4tf0rm"); RepositoryBrowserM2 browser = new RepositoryBrowserM2(login); /*MetadataXpp3Reader mReader = new MetadataXpp3Reader(); Reader reader; MavenXpp3Reader mavenReader = new MavenXpp3Reader(); try { URL uRepositoryUrl = new URL(repositoryUrl); HttpClient client = HttpClient.New(uRepositoryUrl); //client.getInputStream(); //reader = new FileReader("file://"); reader = new InputStreamReader(client.getInputStream()); Metadata metadata = mReader.read(reader); metadata.getVersioning().getSnapshot().getBuildNumber(); Model model = mavenReader.read(reader); model.getDependencies(); model.getVersion(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ String appsGroupId = "com.idega.webapp.custom"; //String artifactId = null; String artifactId = "felixclub"; boolean includeSnapshot=true; if(artifactId==null){ List<Metadata> poms = browser.getModulesInGroup(appsGroupId); for (Iterator iterator = poms.iterator(); iterator.hasNext();) { Metadata module = (Metadata) iterator.next(); String mostRecent = ModuleVersion.getMostRecentVersionAsString(module, includeSnapshot); //System.out.println("Module found: "+module.getArtifactId()+" with version:"+module.getMostRecentVersion()+", last updated: "+module.getLastUpdated()); System.out.println("Module metadata with: "+module.getArtifactId()+" with most recent version: "+mostRecent+", lastupdated: "+module.getVersioning().getLastUpdated()); //Model model = browser.getModuleForMostRecent(module); System.out.println("Module: "+module.getArtifactId()+" has url: "+browser.getArtifactUrlForMostRecent(module,includeSnapshot)); } } else{ Metadata module = browser.getModuleWithGroupAndArtifactId(appsGroupId, artifactId); String mostRecent = ModuleVersion.getMostRecentVersionAsString(module, includeSnapshot); //System.out.println("Module found: "+module.getArtifactId()+" with version:"+module.getMostRecentVersion()+", last updated: "+module.getLastUpdated()); System.out.println("Module metadata with: "+module.getArtifactId()+" with most recent version: "+mostRecent+", lastupdated: "+module.getVersioning().getLastUpdated()); //Model model = browser.getModuleForMostRecent(module); System.out.println("Module: "+module.getArtifactId()+" has url: "+browser.getArtifactUrlForMostRecent(module,includeSnapshot)); } } }
12,200
Java
.java
idega/com.idega.manager
8
1
1
2009-06-28T15:40:16Z
2023-04-14T17:19:43Z
Persistence.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/Persistence.java
package com.gimranov.zandy.app; import android.content.Context; import android.content.SharedPreferences; import androidx.annotation.Nullable; class Persistence { private static final String FILE = "Persistence"; static void write(String key, String value) { SharedPreferences.Editor editor = Application.getInstance().getSharedPreferences(FILE, Context.MODE_PRIVATE).edit(); editor.putString(key, value); editor.apply(); } @Nullable static String read(String key) { SharedPreferences store = Application.getInstance().getSharedPreferences(FILE, Context.MODE_PRIVATE); if (!store.contains(key)) return null; return store.getString(key, null); } }
725
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
ItemDataActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/ItemDataActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.app.AlertDialog; import android.app.Dialog; import android.app.ExpandableListActivity; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.Html; import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.BaseExpandableListAdapter; import android.widget.EditText; import android.widget.ExpandableListView; import android.widget.TextView; import android.widget.TextView.BufferType; import android.widget.Toast; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.task.APIRequest; import com.gimranov.zandy.app.task.ZoteroAPITask; import java.util.ArrayList; public class ItemDataActivity extends ExpandableListActivity { private static final String TAG = ItemDataActivity.class.getSimpleName(); static final int DIALOG_SINGLE_VALUE = 0; static final int DIALOG_ITEM_TYPE = 1; static final int DIALOG_CONFIRM_NAVIGATE = 4; static final int DIALOG_CONFIRM_DELETE = 5; public Item item; private Database db; /** * For Bundle passing to Dialogs in API <= 7 */ protected Bundle b = new Bundle(); /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = new Database(this); /* Get the incoming data from the calling activity */ String itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey"); item = Item.load(itemKey, db); // When an item in the view has been updated via a sync, the temporary key may have // been swapped out, so we fall back on the DB ID if (item == null) { String itemDbId = getIntent().getStringExtra("com.gimranov.zandy.app.itemDbId"); if (itemDbId == null) { Log.d(TAG, "Failed to load item using itemKey and no dbId specified. Give up and finish activity."); finish(); return; } item = Item.loadDbId(itemDbId, db); } // Set the activity title to the current item's title, if the title works if (item.getTitle() != null && !item.getTitle().equals("")) this.setTitle(item.getTitle()); else this.setTitle(getResources().getString(R.string.item_details)); ArrayList<Bundle> rows = item.toBundleArray(db); BundleListAdapter mBundleListAdapter = new BundleListAdapter(); mBundleListAdapter.bundles = rows; setListAdapter(mBundleListAdapter); registerForContextMenu(getExpandableListView()); ExpandableListView lv = getExpandableListView(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { lv.setGroupIndicator(getResources().getDrawable(R.drawable.list_child_indicator, ItemDataActivity.this.getTheme())); } else { //noinspection deprecation lv.setGroupIndicator(getResources().getDrawable(R.drawable.list_child_indicator)); } lv.setTextFilterEnabled(true); lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { return true; } }); lv.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { // Warning here because Eclipse can't tell whether my ArrayAdapter is // being used with the correct parametrization. public boolean onGroupClick(ExpandableListView parent, View view, int position, long id) { // If we have a click on an entry, do something... BundleListAdapter adapter = (BundleListAdapter) parent.getExpandableListAdapter(); Bundle row = adapter.getGroup(position); if ("url".equals(row.getString("label"))) { row.putString("url", row.getString("content")); removeDialog(DIALOG_CONFIRM_NAVIGATE); ItemDataActivity.this.b = row; showDialog(DIALOG_CONFIRM_NAVIGATE); return true; } else if ("DOI".equals(row.getString("label"))) { String url = "https://doi.org/" + Uri.encode(row.getString("content")); row.putString("url", url); removeDialog(DIALOG_CONFIRM_NAVIGATE); ItemDataActivity.this.b = row; showDialog(DIALOG_CONFIRM_NAVIGATE); return true; } else if ("creators".equals(row.getString("label"))) { Log.d(TAG, "Trying to start creators activity"); Intent i = new Intent(getBaseContext(), CreatorActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); startActivity(i); return true; } else if ("tags".equals(row.getString("label"))) { Log.d(TAG, "Trying to start tag activity"); Intent i = new Intent(getBaseContext(), TagActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); startActivity(i); return true; } else if ("children".equals(row.getString("label"))) { Log.d(TAG, "Trying to start attachment activity"); Intent i = new Intent(getBaseContext(), AttachmentActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); startActivity(i); return true; } else if ("collections".equals(row.getString("label"))) { Log.d(TAG, "Trying to start collection membership activity"); Intent i = new Intent(getBaseContext(), CollectionMembershipActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); startActivity(i); return true; } // Suppress toast if we're going to expand the view anyway if (!"abstractNote".equals(row.getSerializable("label"))) { Toast.makeText(getApplicationContext(), row.getString("content"), Toast.LENGTH_SHORT).show(); } return false; } }); /* * On long click, we bring up an edit dialog. */ lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo; int type = ExpandableListView.getPackedPositionType(info.packedPosition); int group = ExpandableListView.getPackedPositionGroup(info.packedPosition); if (type == 0) { // If we have a long click on an entry, we'll provide a way of editing it BundleListAdapter adapter = (BundleListAdapter) ((ExpandableListView) info.targetView.getParent()).getExpandableListAdapter(); Bundle row = adapter.getGroup(group); // Show the right type of dialog for the row in question if ("itemType".equals(row.getString("label"))) { // XXX don't need i18n, since this should be overcome Toast.makeText(getApplicationContext(), "Item type cannot be changed.", Toast.LENGTH_SHORT).show(); //removeDialog(DIALOG_ITEM_TYPE); //showDialog(DIALOG_ITEM_TYPE, row); return; } else if ("children".equals(row.getString("label"))) { Log.d(TAG, "Not starting children activity on click-and-hold"); return; } else if ("creators".equals(row.getString("label"))) { Log.d(TAG, "Trying to start creators activity"); Intent i = new Intent(getBaseContext(), CreatorActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); startActivity(i); return; } else if ("tags".equals(row.getString("label"))) { Log.d(TAG, "Trying to start tag activity"); Intent i = new Intent(getBaseContext(), TagActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); startActivity(i); return; } removeDialog(DIALOG_SINGLE_VALUE); ItemDataActivity.this.b = row; showDialog(DIALOG_SINGLE_VALUE); } } }); } protected Dialog onCreateDialog(int id) { final String label = b.getString("label"); final String itemKey = b.getString("itemKey"); final String content = b.getString("content"); AlertDialog dialog; switch (id) { /* Simple editor for a single value */ case DIALOG_SINGLE_VALUE: final EditText input = new EditText(this); input.setText(content, BufferType.EDITABLE); if ("url".equals(label)) { input.setInputType(InputType.TYPE_TEXT_VARIATION_URI); } DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Item.set(itemKey, label, input.getText().toString(), db); Item item = Item.load(itemKey, db); BundleListAdapter la = (BundleListAdapter) getExpandableListAdapter(); la.bundles = item.toBundleArray(db); la.notifyDataSetChanged(); } }; dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.edit_item_field, Item.localizedStringForString(label))) .setView(input) .setPositiveButton(getResources().getString(R.string.ok), listener) .setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); //noinspection ConstantConditions dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); return dialog; /* Item type selector */ case DIALOG_ITEM_TYPE: dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.item_type_change)) // XXX i18n .setItems(Item.ITEM_TYPES_EN, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int pos) { Item.set(itemKey, label, Item.ITEM_TYPES[pos], db); Item item = Item.load(itemKey, db); BundleListAdapter la = (BundleListAdapter) getExpandableListAdapter(); la.bundles = item.toBundleArray(db); la.notifyDataSetChanged(); } }).create(); return dialog; case DIALOG_CONFIRM_NAVIGATE: dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.view_online_warning)) .setPositiveButton(getResources().getString(R.string.view), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String fixedUri = Util.INSTANCE.doiToUri(content); // The behavior for invalid URIs might be nasty, but // we'll cross that bridge if we come to it. Uri uri = Uri.parse(fixedUri); try { startActivity(new Intent(Intent.ACTION_VIEW) .setData(uri)); } catch (ActivityNotFoundException e) { //noinspection UnnecessaryReturnStatement Toast.makeText(ItemDataActivity.this, ItemDataActivity.this.getString(R.string.attachment_intent_failed_for_uri, fixedUri), Toast.LENGTH_LONG).show(); } } }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog; case DIALOG_CONFIRM_DELETE: dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.item_delete_confirm)) .setPositiveButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Item i = Item.load(itemKey, db); i.delete(db); finish(); } }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog; default: Log.e(TAG, "Invalid dialog requested"); return null; } } @Override public void onDestroy() { if (db != null) db.close(); super.onDestroy(); } @Override public void onResume() { if (db == null) db = new Database(this); super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); // Remove new item-- should be created from context of an item list menu.removeItem(R.id.do_new); // Turn on delete item MenuItem del = menu.findItem(R.id.do_delete); del.setEnabled(true); del.setVisible(true); return true; } @Override public boolean onOptionsItemSelected(MenuItem i) { // Handle item selection switch (i.getItemId()) { case R.id.do_sync: if (!ServerCredentials.check(getApplicationContext())) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return true; } Log.d(TAG, "Preparing sync requests, starting with present item"); APIRequest req = APIRequest.update(item); new ZoteroAPITask(getBaseContext()).execute(req); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started), Toast.LENGTH_SHORT).show(); return true; case R.id.do_prefs: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.do_delete: Bundle b = new Bundle(); b.putString("itemKey", item.getKey()); removeDialog(DIALOG_CONFIRM_DELETE); this.b = b; showDialog(DIALOG_CONFIRM_DELETE); return true; default: return super.onOptionsItemSelected(i); } } /** * List adapter that provides our bundles in the appropriate way */ private class BundleListAdapter extends BaseExpandableListAdapter { ArrayList<Bundle> bundles; public Bundle getChild(int groupPosition, int childPosition) { return bundles.get(groupPosition); } public long getChildId(int groupPosition, int childPosition) { return childPosition; } public int getChildrenCount(int groupPosition) { if ("abstractNote".equals(bundles.get(groupPosition).getString("label"))) { return 1; } else { return 0; } } TextView getGenericView() { // Layout parameters for the ExpandableListView AbsListView.LayoutParams lp = new AbsListView.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 64); TextView textView = new TextView(ItemDataActivity.this); textView.setLayoutParams(lp); // Center the text vertically textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.START); // Set the text starting position textView.setPadding(0, 0, 0, 0); return textView; } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { TextView textView = getGenericView(); Bundle b = getGroup(groupPosition); String label = b.getString("label"); String content = b.getString("content"); if ("title".equals(label) || "note".equals(label)) { textView.setText(Html.fromHtml(content)); } else { textView.setText(content); } return textView; } public Bundle getGroup(int groupPosition) { return bundles.get(groupPosition); } public int getGroupCount() { return bundles.size(); } public long getGroupId(int groupPosition) { return groupPosition; } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View row; Bundle b = getGroup(groupPosition); String label = b.getString("label"); String content = ""; if ("children".equals(label)) { int notes = b.getInt("noteCount", 0); int atts = b.getInt("attachmentCount", 0); if (notes == 0 && atts == 0) getResources().getString(R.string.item_attachment_info_none); else content = getResources().getString(R.string.item_attachment_info_template, notes, atts); } else if ("collections".equals((getGroup(groupPosition).getString("label")))) { int count = b.getInt("collectionCount", 0); content = getResources().getString(R.string.item_collection_count, count); } else { content = b.getString("content"); } // We are reusing views, but we need to initialize it if null if (null == convertView) { LayoutInflater inflater = getLayoutInflater(); row = inflater.inflate(R.layout.list_data, null); } else { row = convertView; } /* Our layout has just two fields */ TextView tvLabel = (TextView) row.findViewById(R.id.data_label); tvLabel.setPadding(0, 0, 0, 0); TextView tvContent = (TextView) row.findViewById(R.id.data_content); tvContent.setPadding(0, 0, 0, 0); /* Since the field names are the API / internal form, we * attempt to get a localized, human-readable version. */ tvLabel.setText(Item.localizedStringForString(label)); if ("title".equals(label) || "note".equals(label)) { tvContent.setText(Html.fromHtml(content)); } else { tvContent.setText(content); } if ("abstractNote".equals(label)) { tvLabel.setText(getResources().getString(R.string.item_more, Item.localizedStringForString("abstractNote"))); } tvContent.setMaxLines(2); tvContent.setEllipsize(TextUtils.TruncateAt.MARQUEE); return row; } public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } public boolean hasStableIds() { return true; } } }
23,590
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
SettingsActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/SettingsActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.gimranov.zandy.app.data.Database; public class SettingsActivity extends PreferenceActivity implements OnClickListener { private static final String TAG = SettingsActivity.class.getSimpleName(); static final int DIALOG_CONFIRM_DELETE = 5; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); setContentView(R.layout.preferences); Button requestButton = findViewById(R.id.requestQueue); requestButton.setOnClickListener(this); Button resetButton = findViewById(R.id.resetDatabase); resetButton.setOnClickListener(this); } public void onClick(View v) { if (v.getId() == R.id.requestQueue) { Intent i = new Intent(getApplicationContext(), RequestActivity.class); startActivity(i); } else if (v.getId() == R.id.resetDatabase) { showDialog(DIALOG_CONFIRM_DELETE); } } protected Dialog onCreateDialog(int id) { AlertDialog dialog; switch (id) { case DIALOG_CONFIRM_DELETE: dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.settings_reset_database_warning)) .setPositiveButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Database db = new Database(getBaseContext()); db.resetAllData(); finish(); } }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog; default: Log.e(TAG, "Invalid dialog requested"); return null; } } }
3,418
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
XMLResponseParser.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/XMLResponseParser.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.sax.Element; import android.sax.ElementListener; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; import android.util.Log; import android.util.Xml; import com.gimranov.zandy.app.data.Attachment; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.data.ItemCollection; import com.gimranov.zandy.app.task.APIRequest; import org.json.JSONException; import org.json.JSONObject; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; import java.io.InputStream; import java.util.ArrayList; public class XMLResponseParser extends DefaultHandler { private static final String TAG = XMLResponseParser.class.getSimpleName(); private InputStream input; private Item item; private Attachment attachment; private ItemCollection collection; private ItemCollection parent; private String updateType; private String updateKey; private boolean items = false; private APIRequest request; public static boolean followNext = true; public static ArrayList<APIRequest> queue; public static final int MODE_ITEMS = 1; public static final int MODE_ITEM = 2; public static final int MODE_ITEM_CHILDREN = 8; public static final int MODE_COLLECTIONS = 3; public static final int MODE_COLLECTION = 4; public static final int MODE_COLLECTION_ITEMS = 5; public static final int MODE_ENTRY = 6; public static final int MODE_FEED = 7; private static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"; private static final String Z_NAMESPACE = "http://zotero.org/ns/api"; public XMLResponseParser(InputStream in, APIRequest request) { followNext = true; input = in; this.request = request; // Initialize the request queue if needed if (queue == null) queue = new ArrayList<>(); } public XMLResponseParser(APIRequest request) { followNext = true; this.request = request; // Initialize the request queue if needed if (queue == null) queue = new ArrayList<>(); } public void setInputStream(InputStream in) { input = in; } public void update(String type, String key) { updateType = type; updateKey = key; } public void parse(int mode, String url, final Database db) { Element entry; RootElement root; // we have a different root for indiv. items if (mode == MODE_FEED) { root = new RootElement(ATOM_NAMESPACE, "feed"); entry = root.getChild(ATOM_NAMESPACE, "entry"); } else { // MODE_ITEM, MODE_COLLECTION Log.d(TAG, "Parsing in entry mode"); root = new RootElement(ATOM_NAMESPACE, "entry"); entry = (Element) root; } if (mode == MODE_FEED) { root.getChild(ATOM_NAMESPACE, "link").setStartElementListener(new StartElementListener() { public void start(Attributes attributes) { String rel = ""; String href = ""; int length = attributes.getLength(); // I shouldn't have to walk through, but the namespacing isn't working here for (int i = 0; i < length; i++) { if ("rel".equals(attributes.getQName(i))) rel = attributes.getValue(i); if ("href".equals(attributes.getQName(i))) href = attributes.getValue(i); } // We try to get a parent collection if necessary / possible if (rel.contains("self")) { // Try to get a parent collection int colloc = href.indexOf("/collections/"); int itemloc = href.indexOf("/items"); // Our URL looks like this: // https://api.zotero.org/users/5770/collections/2AJUSIU9/items?content=json if (colloc != -1 && itemloc != -1) { // The string "/collections/" is thirteen characters long String id = href.substring(colloc + 13, itemloc); Log.d(TAG, "Collection key: " + id); parent = ItemCollection.load(id, db); if (parent != null) parent.loadChildren(db); } else { Log.d(TAG, "Key extraction failed from root; maybe this isn't a collection listing?"); } } // If there are more items, queue them up to be handled too if (rel.contains("next")) { Log.d(TAG, "Found continuation: " + href); APIRequest req = new APIRequest(href, "get", null); req.query = href; req.disposition = "xml"; queue.add(req); } } }); } entry.setElementListener(new ElementListener() { public void start(Attributes attributes) { item = new Item(); collection = new ItemCollection(); attachment = new Attachment(); Log.d(TAG, "New entry"); } public void end() { if (items) { if (updateKey != null && updateType != null && updateType.equals("item")) { // We have an incoming new version of an item Item existing = Item.load(updateKey, db); if (existing != null) { Log.d(TAG, "Updating newly created item to replace temporary key: " + updateKey + " => " + item.getKey() + ""); existing.dirty = APIRequest.API_CLEAN; // We need to update the parent key in attachments as well, // so they aren't orphaned after we update the item key here ArrayList<Attachment> atts = Attachment.forItem(existing, db); for (Attachment a : atts) { Log.d(TAG, "Propagating item key replacement to attachment with key: " + a.key); a.parentKey = item.getKey(); a.save(db); } // We can't set the new key until after updating child attachments existing.setKey(item.getKey()); if (!existing.getType().equals("attachment")) existing.save(db); } } else if (updateKey != null && updateType != null && updateType.equals("attachment")) { // We have an incoming new version of an item Attachment existing = Attachment.load(updateKey, db); if (existing != null) { Log.d(TAG, "Updating newly created attachment to replace temporary key: " + updateKey + " => " + attachment.key + ""); existing.dirty = APIRequest.API_CLEAN; // we don't change the ZFS status... existing.key = attachment.key; existing.save(db); } } else { item.dirty = APIRequest.API_CLEAN; attachment.dirty = APIRequest.API_CLEAN; if ((attachment.url != null && !"".equals(attachment.url)) || attachment.isDownloadable()) attachment.status = Attachment.AVAILABLE; if (!item.getType().equals("attachment") && !item.getType().equals("note")) { Item oldItem = Item.load(item.getKey(), db); // Check timestamps to see if it's different; if not, we should // stop following the Atom continuation links if (oldItem != null && oldItem.getTimestamp().equals(item.getTimestamp())) { followNext = false; } item.save(db); } else { // Don't touch ZFS status here Attachment existing = Attachment.load(attachment.key, db); if (existing != null) { attachment.status = existing.status; } attachment.save(db); } } if (!item.getType().equals("attachment") && !item.getType().equals("note") && item.getChildren() != null && !item.getChildren().equals("0")) { queue.add(APIRequest.children(item)); Log.d(TAG, "Queued children request for item: " + item.getTitle() + " " + item.getKey()); Log.d(TAG, "Item has children: " + item.getChildren()); } // Add to containing collection if (!item.getType().equals("attachment") && parent != null) parent.add(item, true, db); request.getHandler().onUpdate(request); Log.d(TAG, "Done parsing item entry."); return; } if (!items) { if (updateKey != null && updateType != null && updateType.equals("collection")) { // We have an incoming new version of a collection ItemCollection existing = ItemCollection.load(updateKey, db); if (existing != null) { Log.d(TAG, "Updating newly created collection to replace temporary key: " + updateKey + " => " + collection.getKey() + ""); existing.setKey(collection.getKey()); existing.dirty = APIRequest.API_CLEAN; existing.save(db); } Log.d(TAG, "Done parsing new collection entry."); // We don't need to load again, since a new collection can't be stale return; } ItemCollection ic = ItemCollection.load(collection.getKey(), db); if (ic != null) { if (!ic.getTimestamp() .equals(collection. getTimestamp())) { // In this case, we have data, but we should refresh it collection.dirty = APIRequest.API_STALE; } else { // Collection hasn't changed! collection = ic; // We also don't need the next page, if we already saw this one followNext = false; } } else { // This means that we haven't seen the collection before, so it must be // a new one, and we don't have contents for it. collection.dirty = APIRequest.API_MISSING; } Log.d(TAG, "Status: " + collection.dirty + " for " + collection.getTitle()); collection.save(db); Log.d(TAG, "Done parsing a collection entry."); } } }); entry.getChild(ATOM_NAMESPACE, "title").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { item.setTitle(body); collection.setTitle(body); attachment.title = body; Log.d(TAG, body); } }); entry.getChild(Z_NAMESPACE, "key").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { item.setKey(body); collection.setKey(body); attachment.key = body; Log.d(TAG, body); } }); entry.getChild(ATOM_NAMESPACE, "updated").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { item.setTimestamp(body); collection.setTimestamp(body); Log.d(TAG, body); } }); entry.getChild(Z_NAMESPACE, "itemType").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { item.setType(body); items = true; Log.d(TAG, body); } }); entry.getChild(Z_NAMESPACE, "numChildren").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { item.setChildren(body); Log.d(TAG, body); } }); entry.getChild(Z_NAMESPACE, "year").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { item.setYear(body); Log.d(TAG, body); } }); entry.getChild(Z_NAMESPACE, "creatorSummary").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { item.setCreatorSummary(body); Log.d(TAG, body); } }); entry.getChild(ATOM_NAMESPACE, "id").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { item.setId(body); collection.setId(body); Log.d(TAG, body); } }); entry.getChild(ATOM_NAMESPACE, "link").setStartElementListener(new StartElementListener() { public void start(Attributes attributes) { String rel = ""; String href = ""; int length = attributes.getLength(); // I shouldn't have to walk through, but the namespacing isn't working here for (int i = 0; i < length; i++) { if ("rel".equals(attributes.getQName(i))) rel = attributes.getValue(i); if ("href".equals(attributes.getQName(i))) href = attributes.getValue(i); } if (rel != null && rel.equals("up")) { int start = href.indexOf("/items/"); // Trying to pull out the key of attachment parent attachment.parentKey = href.substring(start + 7, start + 7 + 8); Log.d(TAG, "Setting parentKey to: " + attachment.parentKey); } else if (rel != null && rel.equals("enclosure")) { attachment.url = href; attachment.status = Attachment.AVAILABLE; Log.d(TAG, "url= " + attachment.url); } else if (rel != null) Log.d(TAG, "rel=" + rel + " href=" + href); } }); entry.getChild(ATOM_NAMESPACE, "content").setStartElementListener(new StartElementListener() { public void start(Attributes attributes) { String etag = attributes.getValue(Z_NAMESPACE, "etag"); item.setEtag(etag); collection.setEtag(etag); attachment.etag = etag; Log.d(TAG, "etag: " + etag); } }); entry.getChild(ATOM_NAMESPACE, "content").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { try { JSONObject obj = new JSONObject(body); try { collection.setParent(obj.getString("parent")); } catch (JSONException e) { Log.d(TAG, "No parent found in JSON content; not a subcollection or not a collection"); } item.setContent(obj); attachment.content = obj; } catch (JSONException e) { Log.e(TAG, "JSON parse exception loading content", e); } Log.d(TAG, body); } }); try { Xml.parse(this.input, Xml.Encoding.UTF_8, root.getContentHandler()); if (parent != null) { parent.saveChildren(db); parent.markClean(); parent.save(db); } db.close(); } catch (Exception e) { Log.e(TAG, "exception loading content", e); } } }
18,234
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
MainActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/MainActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.StrictMode; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.data.ItemAdapter; import com.gimranov.zandy.app.data.ItemCollection; import com.gimranov.zandy.app.task.APIRequest; import com.gimranov.zandy.app.task.ZoteroAPITask; import com.squareup.otto.Subscribe; import java.lang.reflect.Method; import java.util.ArrayList; import oauth.signpost.OAuthProvider; import oauth.signpost.basic.DefaultOAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import oauth.signpost.http.HttpParameters; public class MainActivity extends Activity implements OnClickListener { private CommonsHttpOAuthConsumer httpOAuthConsumer; private OAuthProvider httpOAuthProvider; private static final String TAG = MainActivity.class.getSimpleName(); private static final String DEFAULT_SORT = "timestamp ASC, item_title COLLATE NOCASE"; static final int DIALOG_CHOOSE_COLLECTION = 1; private Database db; private Bundle b = new Bundle(); /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Disable death due to exposing file:// URIs if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { try { //noinspection JavaReflectionMemberAccess Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure"); m.invoke(null); } catch (Exception e) { Log.e(TAG, "Error disabling file uri exposure issue", e); } } // Let items in on the fun db = new Database(getBaseContext()); Intent intent = getIntent(); String action = intent.getAction(); if (action != null && action.equals("android.intent.action.SEND") && intent.getExtras() != null) { // Browser sends us no data, just extras Bundle extras = intent.getExtras(); for (String s : extras.keySet()) { try { Log.d("TAG", "Got extra: " + s + " => " + extras.getString(s)); } catch (ClassCastException e) { Log.e(TAG, "Not a string, it seems", e); } } Bundle b = new Bundle(); b.putString("url", extras.getString("android.intent.extra.TEXT")); b.putString("title", extras.getString("android.intent.extra.SUBJECT")); this.b = b; showDialog(DIALOG_CHOOSE_COLLECTION); } setContentView(R.layout.main); Button collectionButton = findViewById(R.id.collectionButton); collectionButton.setOnClickListener(this); Button itemButton = findViewById(R.id.itemButton); itemButton.setOnClickListener(this); Button loginButton = findViewById(R.id.loginButton); loginButton.setOnClickListener(this); if (ServerCredentials.check(getBaseContext())) { setUpLoggedInUser(); refreshList(); } } @Override public void onResume() { Application.getInstance().getBus().register(this); Button loginButton = findViewById(R.id.loginButton); if (!ServerCredentials.check(getBaseContext())) { loginButton.setText(getResources().getString(R.string.log_in)); loginButton.setClickable(true); } else { setUpLoggedInUser(); refreshList(); } super.onResume(); } @Override protected void onPause() { super.onPause(); Application.getInstance().getBus().unregister(this); } /** * Refreshes the list view, safely if possible */ private void refreshList() { ListView lv = findViewById(android.R.id.list); if (lv == null) return; ItemAdapter adapter = (ItemAdapter) lv.getAdapter(); if (adapter != null) { Cursor newCursor = getCursor(DEFAULT_SORT); adapter.changeCursor(newCursor); adapter.notifyDataSetChanged(); } } /** * Implementation of the OnClickListener interface, to handle button events. * <p> * Note: When adding a button, it needs to be added here, but the * ClickListener needs to be set in the main onCreate(..) as well. */ public void onClick(View v) { Log.d(TAG, "Click on: " + v.getId()); if (v.getId() == R.id.collectionButton) { Log.d(TAG, "Trying to start collection activity"); Intent i = new Intent(this, CollectionActivity.class); startActivity(i); } else if (v.getId() == R.id.itemButton) { Log.d(TAG, "Trying to start all-item activity"); Intent i = new Intent(this, ItemActivity.class); startActivity(i); } else if (v.getId() == R.id.loginButton) { Log.d(TAG, "Starting OAuth"); new Thread(new Runnable() { public void run() { startOAuth(); } }).start(); } else { Log.w(TAG, "Uncaught click on: " + v.getId()); } } /** * Makes the OAuth call. The response on the callback is handled by the * onNewIntent(..) method below. * <p> * This will send the user to the OAuth server to get set up. */ protected void startOAuth() { try { this.httpOAuthConsumer = new CommonsHttpOAuthConsumer( ServerCredentials.CONSUMERKEY, ServerCredentials.CONSUMERSECRET); this.httpOAuthProvider = new DefaultOAuthProvider( ServerCredentials.OAUTHREQUEST, ServerCredentials.OAUTHACCESS, ServerCredentials.OAUTHAUTHORIZE); String authUrl; authUrl = httpOAuthProvider.retrieveRequestToken(httpOAuthConsumer, ServerCredentials.CALLBACKURL); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl))); } catch (OAuthMessageSignerException e) { toastError(e.getMessage()); } catch (OAuthNotAuthorizedException e) { toastError(e.getMessage()); } catch (OAuthExpectationFailedException e) { toastError(e.getMessage()); } catch (OAuthCommunicationException e) { toastError(e.getMessage()); } } private void toastError(final String message) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show(); } }); } /** * Receives intents that the app knows how to interpret. These will probably * all be URIs with the protocol "zotero://". * <p> * This is currently only used to receive OAuth responses, but it could be * used with things like zotero://select and zotero://attachment in the * future. */ @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Log.d(TAG, "Got new intent"); if (intent == null) return; // Here's what we do if we get a share request from the browser String action = intent.getAction(); if (action != null && action.equals("android.intent.action.SEND") && intent.getExtras() != null) { // Browser sends us no data, just extras Bundle extras = intent.getExtras(); for (String s : extras.keySet()) { try { Log.d("TAG", "Got extra: " + s + " => " + extras.getString(s)); } catch (ClassCastException e) { Log.e(TAG, "Not a string, it seems", e); } } Bundle b = new Bundle(); b.putString("url", extras.getString("android.intent.extra.TEXT")); b.putString("title", extras.getString("android.intent.extra.SUBJECT")); this.b = b; showDialog(DIALOG_CHOOSE_COLLECTION); return; } /* * It's possible we've lost these to garbage collection, so we * reinstantiate them if they turn out to be null at this point. */ if (this.httpOAuthConsumer == null) this.httpOAuthConsumer = new CommonsHttpOAuthConsumer( ServerCredentials.CONSUMERKEY, ServerCredentials.CONSUMERSECRET); if (this.httpOAuthProvider == null) this.httpOAuthProvider = new DefaultOAuthProvider( ServerCredentials.OAUTHREQUEST, ServerCredentials.OAUTHACCESS, ServerCredentials.OAUTHAUTHORIZE); /* * Also double-check that intent isn't null, because something here * caused a NullPointerException for a user. */ Uri uri; uri = intent.getData(); if (uri != null) { /* * TODO The logic should have cases for the various things coming in * on this protocol. */ final String verifier = uri .getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER); new Thread(new Runnable() { public void run() { try { /* * Here, we're handling the callback from the completed OAuth. * We don't need to do anything highly visible, although it * would be nice to show a Toast or something. */ httpOAuthProvider.retrieveAccessToken( httpOAuthConsumer, verifier); HttpParameters params = httpOAuthProvider .getResponseParameters(); final String userID = params.getFirst("userID"); Log.d(TAG, "uid: " + userID); final String userKey = httpOAuthConsumer.getToken(); Log.d(TAG, "ukey: " + userKey); final String userSecret = httpOAuthConsumer.getTokenSecret(); Log.d(TAG, "usecret: " + userSecret); runOnUiThread(new Runnable() { public void run() { /* * These settings live in the Zotero preferences tree. */ SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); SharedPreferences.Editor editor = settings.edit(); // For Zotero, the key and secret are identical, it seems editor.putString("user_key", userKey); editor.putString("user_secret", userSecret); editor.putString("user_id", userID); editor.apply(); setUpLoggedInUser(); doSync(); } }); } catch (OAuthMessageSignerException | OAuthNotAuthorizedException | OAuthExpectationFailedException e) { toastError(e.getMessage()); } catch (OAuthCommunicationException e) { toastError("Error communicating with server. Check your time settings, network connectivity, and try again. OAuth error: " + e.getMessage()); } } }).start(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); // button doesn't make sense here. menu.removeItem(R.id.do_new); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.do_sync: return doSync(); case R.id.do_prefs: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.do_search: onSearchRequested(); return true; default: return super.onOptionsItemSelected(item); } } private boolean doSync() { if (!ServerCredentials.check(getApplicationContext())) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return true; } Log.d(TAG, "Making sync request for all collections"); ServerCredentials cred = new ServerCredentials(getBaseContext()); APIRequest req = APIRequest.fetchCollections(cred); new ZoteroAPITask(getBaseContext()).execute(req); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started), Toast.LENGTH_SHORT).show(); return true; } private void setUpLoggedInUser() { Button loginButton = findViewById(R.id.loginButton); loginButton.setVisibility(View.GONE); ItemAdapter adapter = new ItemAdapter(this, getCursor(DEFAULT_SORT)); ListView lv = findViewById(android.R.id.list); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // If we have a click on an item, do something... ItemAdapter adapter = (ItemAdapter) parent.getAdapter(); Cursor cur = adapter.getCursor(); // Place the cursor at the selected item if (cur.moveToPosition(position)) { // and load an activity for the item Item item = Item.load(cur); Log.d(TAG, "Loading item data with key: " + item.getKey()); // We create and issue a specified intent with the necessary data Intent i = new Intent(getBaseContext(), ItemDataActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); i.putExtra("com.gimranov.zandy.app.itemDbId", item.dbId); startActivity(i); } else { // failed to move cursor-- show a toast TextView tvTitle = view.findViewById(R.id.item_title); Toast.makeText(getApplicationContext(), getResources().getString(R.string.cant_open_item, tvTitle.getText()), Toast.LENGTH_SHORT).show(); } } }); } public Cursor getCursor(String sortBy) { Cursor cursor = db.query("items", Database.ITEMCOLS, null, null, null, null, sortBy, null); if (cursor == null) { Log.e(TAG, "cursor is null"); } return cursor; } @Override protected Dialog onCreateDialog(int id) { final String url = b.getString("url"); final String title = b.getString("title"); AlertDialog dialog; switch (id) { case DIALOG_CHOOSE_COLLECTION: AlertDialog.Builder builder = new AlertDialog.Builder(this); // Now we're dealing with share link, it seems. // For now, just add it to the main library-- we'd like to let the person choose a library, // but not yet. final ArrayList<ItemCollection> collections = ItemCollection.getCollections(db); int size = collections.size(); String[] collectionNames = new String[size]; for (int i = 0; i < size; i++) { collectionNames[i] = collections.get(i).getTitle(); } builder.setTitle(getResources().getString(R.string.choose_parent_collection)) .setItems(collectionNames, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int pos) { Item item = new Item(getBaseContext(), "webpage"); item.save(db); Log.d(TAG, "New item has key: " + item.getKey() + ", dbId: " + item.dbId); Item.set(item.getKey(), "url", url, db); Item.set(item.getKey(), "title", title, db); Item.setTag(item.getKey(), null, "#added-by-zandy", 1, db); collections.get(pos).add(item); collections.get(pos).saveChildren(db); Log.d(TAG, "Loading item data with key: " + item.getKey()); // We create and issue a specified intent with the necessary data Intent i = new Intent(getBaseContext(), ItemDataActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); i.putExtra("com.gimranov.zandy.app.itemDbId", item.dbId); startActivity(i); } }); dialog = builder.create(); return dialog; default: Log.e(TAG, "Invalid dialog requested"); return null; } } @Subscribe public void syncComplete(SyncEvent event) { refreshList(); } }
19,946
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
NoteActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/NoteActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.Html; import android.text.Spanned; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.BufferType; import android.widget.Toast; import com.gimranov.zandy.app.data.Attachment; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.task.APIRequest; /** * This Activity handles displaying and editing of notes. * * @author mlt */ public class NoteActivity extends Activity { private static final String TAG = NoteActivity.class.getSimpleName(); static final int DIALOG_NOTE = 3; public Attachment att; private Database db; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note); db = new Database(this); /* Get the incoming data from the calling activity */ final String attKey = getIntent().getStringExtra("com.gimranov.zandy.app.attKey"); final Attachment att = Attachment.load(attKey, db); if (att == null) { Log.e(TAG, "NoteActivity started without attKey; finishing."); finish(); return; } Item item = Item.load(att.parentKey, db); this.att = att; setTitle(getResources().getString(R.string.note_for_item, item.getTitle())); TextView text = findViewById(R.id.noteText); TextView title = findViewById(R.id.noteTitle); title.setText(att.title); Spanned spanned; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { spanned = Html.fromHtml(att.content.optString("note", ""), Html.FROM_HTML_MODE_COMPACT); } else { //noinspection deprecation spanned = Html.fromHtml(att.content.optString("note", "")); } text.setText(spanned); Button editButton = findViewById(R.id.editNote); editButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { showDialog(DIALOG_NOTE); } }); /* Warn that this won't propagate for attachment notes */ if (!"note".equals(att.getType())) { Toast.makeText(this, R.string.attachment_note_warning, Toast.LENGTH_LONG).show(); } } protected Dialog onCreateDialog(int id) { AlertDialog dialog; switch (id) { case DIALOG_NOTE: final EditText input = new EditText(this); input.setText(att.content.optString("note", ""), BufferType.EDITABLE); AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.note)) .setView(input) .setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Editable value = input.getText(); String fixed = value.toString().replaceAll("\n\n", "\n<br>"); att.setNoteText(fixed); att.dirty = APIRequest.API_DIRTY; att.save(db); TextView text = findViewById(R.id.noteText); TextView title = findViewById(R.id.noteTitle); title.setText(att.title); text.setText(Html.fromHtml(att.content.optString("note", ""))); } }).setNeutralButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }); dialog = builder.create(); return dialog; default: Log.e(TAG, "Invalid dialog requested"); return null; } } }
5,574
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
Application.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/Application.java
package com.gimranov.zandy.app; import com.squareup.otto.Bus; public class Application extends android.app.Application { private static final String TAG = Application.class.getSimpleName(); private static Application instance; private Bus bus; @Override public void onCreate() { super.onCreate(); bus = new Bus(); instance = this; } public Bus getBus() { return bus; } public static Application getInstance() { return instance; } }
521
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
Query.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/Query.java
package com.gimranov.zandy.app; import java.util.ArrayList; import android.database.Cursor; import android.os.Bundle; import com.gimranov.zandy.app.data.Database; /** * This class is intended to provide ways of handling queries to the database. * <p> * TODO * Needed functions: * - specify sets of fields and terms for those fields * * related need for mapping of fields-- i.e., publicationTitle = journalTitle * - provide reasonable efficiency through use of indexes; in SQLite or in Java * - return data in efficient fashion, preferably by exposing a Cursor or * some other paged access method. * - normalize queries and data to let * - allow saving of queries * <p> * Some of this will mean changes to other parts of Zandy's data storage model; * specifically, the raw JSON we're using now won't get us much further. We * could in theory maintain an index with tokens drawn from the JSON that * we populate on original save... Not sure about this. * * @author ajlyon */ public class Query { private ArrayList<Bundle> parameters; private String sortBy; public Query() { parameters = new ArrayList<>(); } public void set(String field, String value) { Bundle b = new Bundle(); b.putString("field", field); b.putString("value", value); parameters.add(b); } public void sortBy(String term) { sortBy = term; } public Cursor query(Database db) { StringBuilder sb = new StringBuilder(); String[] args = new String[parameters.size()]; int i = 0; for (Bundle b : parameters) { if ("tag".equals(b.getString("field"))) { sb.append("item_content LIKE ?"); args[i] = "%" + b.getString("value") + "%"; } else { sb.append(b.getString("field")).append("=?"); args[i] = b.getString("value"); } i++; if (i < parameters.size()) sb.append(","); } return db.query("items", Database.ITEMCOLS, sb.toString(), args, null, null, this.sortBy, null); } }
2,119
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
CollectionMembershipActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/CollectionMembershipActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import java.util.ArrayList; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.data.ItemCollection; import com.gimranov.zandy.app.task.APIRequest; import com.gimranov.zandy.app.task.ZoteroAPITask; /** * This Activity handles displaying and editing collection memberships for a * given item. * * @author ajlyon */ public class CollectionMembershipActivity extends ListActivity { private static final String TAG = CollectionMembershipActivity.class.getSimpleName(); static final int DIALOG_CONFIRM_NAVIGATE = 4; static final int DIALOG_COLLECTION_LIST = 1; private String itemKey; private String itemTitle; private Database db; /** * For API <= 7, where we can't pass Bundles to dialogs */ private Bundle b = new Bundle(); /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = new Database(this); /* Get the incoming data from the calling activity */ itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey"); Item item = Item.load(itemKey, db); if (item == null) { Log.e(TAG, "Null item for key: " + itemKey); finish(); } itemTitle = item.getTitle(); this.setTitle(getResources().getString(R.string.collections_for_item, itemTitle)); ArrayList<ItemCollection> rows = ItemCollection.getCollections(item, db); setListAdapter(new ArrayAdapter<ItemCollection>(this, R.layout.list_data, rows) { @Override public View getView(int position, View convertView, ViewGroup parent) { View row; // We are reusing views, but we need to initialize it if null if (null == convertView) { LayoutInflater inflater = getLayoutInflater(); row = inflater.inflate(R.layout.list_data, null); } else { row = convertView; } /* Our layout has just two fields */ TextView tvLabel = (TextView) row.findViewById(R.id.data_label); tvLabel.setText(""); TextView tvContent = (TextView) row.findViewById(R.id.data_content); tvContent.setText(getItem(position).getTitle()); return row; } }); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { // Warning here because Eclipse can't tell whether my ArrayAdapter is // being used with the correct parametrization. @SuppressWarnings("unchecked") public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // If we have a click on an entry, prompt to view that tag's items. ArrayAdapter<ItemCollection> adapter = (ArrayAdapter<ItemCollection>) parent.getAdapter(); ItemCollection row = adapter.getItem(position); Bundle b = new Bundle(); b.putString("itemKey", itemKey); b.putString("collectionKey", row.getKey()); CollectionMembershipActivity.this.b = b; removeDialog(DIALOG_CONFIRM_NAVIGATE); showDialog(DIALOG_CONFIRM_NAVIGATE); } }); } @Override public void onDestroy() { if (db != null) db.close(); super.onDestroy(); } @Override public void onResume() { if (db == null) db = new Database(this); super.onResume(); } protected Dialog onCreateDialog(int id) { final String collectionKey = b.getString("collectionKey"); final String itemKey = b.getString("itemKey"); AlertDialog dialog; switch (id) { case DIALOG_COLLECTION_LIST: AlertDialog.Builder builder = new AlertDialog.Builder(this); final ArrayList<ItemCollection> collections = ItemCollection.getCollections(db); int size = collections.size(); String[] collectionNames = new String[size]; for (int i = 0; i < size; i++) { collectionNames[i] = collections.get(i).getTitle(); } builder.setTitle(getResources().getString(R.string.choose_parent_collection)) .setItems(collectionNames, new DialogInterface.OnClickListener() { @SuppressWarnings("unchecked") public void onClick(DialogInterface dialog, int pos) { Item item = Item.load(itemKey, db); collections.get(pos).add(item, false, db); collections.get(pos).saveChildren(db); ArrayAdapter<ItemCollection> la = (ArrayAdapter<ItemCollection>) getListAdapter(); la.clear(); for (ItemCollection b : ItemCollection.getCollections(item, db)) { la.add(b); } la.notifyDataSetChanged(); } }); dialog = builder.create(); return dialog; case DIALOG_CONFIRM_NAVIGATE: dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.collection_membership_detail)) .setPositiveButton(getResources().getString(R.string.tag_view), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent i = new Intent(getBaseContext(), ItemActivity.class); i.putExtra("com.gimranov.zandy.app.collectionKey", collectionKey); startActivity(i); } }).setNeutralButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).setNegativeButton(getResources().getString(R.string.collection_remove_item), new DialogInterface.OnClickListener() { @SuppressWarnings("unchecked") public void onClick(DialogInterface dialog, int whichButton) { Item item = Item.load(itemKey, db); ItemCollection coll = ItemCollection.load(collectionKey, db); coll.remove(item, false, db); ArrayAdapter<ItemCollection> la = (ArrayAdapter<ItemCollection>) getListAdapter(); la.clear(); for (ItemCollection b : ItemCollection.getCollections(item, db)) { la.add(b); } la.notifyDataSetChanged(); } }).create(); return dialog; default: Log.e(TAG, "Invalid dialog requested"); return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.do_sync: if (!ServerCredentials.check(getApplicationContext())) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return true; } Log.d(TAG, "Preparing sync requests"); new ZoteroAPITask(getBaseContext()).execute(APIRequest.update(Item.load(itemKey, db))); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started), Toast.LENGTH_SHORT).show(); return true; case R.id.do_new: Bundle b = new Bundle(); b.putString("itemKey", itemKey); removeDialog(DIALOG_COLLECTION_LIST); this.b = b; showDialog(DIALOG_COLLECTION_LIST); return true; case R.id.do_prefs: startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } }
10,676
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
TagActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/TagActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import java.util.ArrayList; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import android.text.Editable; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.BufferType; import android.widget.Toast; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.task.APIRequest; import com.gimranov.zandy.app.task.ZoteroAPITask; /** * This Activity handles displaying and editing tags. It works almost the same as * ItemDataActivity, using a simple ArrayAdapter on Bundles with the tag info. * * @author ajlyon */ public class TagActivity extends ListActivity { private static final String TAG = TagActivity.class.getSimpleName(); static final int DIALOG_TAG = 3; static final int DIALOG_CONFIRM_NAVIGATE = 4; private Item item; private Database db; protected Bundle b = new Bundle(); /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = new Database(this); /* Get the incoming data from the calling activity */ String itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey"); Item item = Item.load(itemKey, db); this.item = item; this.setTitle(getResources().getString(R.string.tags_for_item, item.getTitle())); ArrayList<Bundle> rows = item.tagsToBundleArray(); /* * We use the standard ArrayAdapter, passing in our data as a Bundle. * Since it's no longer a simple TextView, we need to override getView, but * we can do that anonymously. */ setListAdapter(new ArrayAdapter<Bundle>(this, R.layout.list_data, rows) { @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { View row; // We are reusing views, but we need to initialize it if null if (null == convertView) { LayoutInflater inflater = getLayoutInflater(); row = inflater.inflate(R.layout.list_data, null); } else { row = convertView; } /* Our layout has just two fields */ TextView tvLabel = row.findViewById(R.id.data_label); TextView tvContent = row.findViewById(R.id.data_content); if (getItem(position).getInt("type") == 1) tvLabel.setText(getResources().getString(R.string.tag_auto)); else tvLabel.setText(getResources().getString(R.string.tag_user)); tvContent.setText(getItem(position).getString("tag")); return row; } }); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { // Warning here because Eclipse can't tell whether my ArrayAdapter is // being used with the correct parametrization. @SuppressWarnings("unchecked") public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // If we have a click on an entry, prompt to view that tag's items. ArrayAdapter<Bundle> adapter = (ArrayAdapter<Bundle>) parent.getAdapter(); Bundle row = adapter.getItem(position); removeDialog(DIALOG_CONFIRM_NAVIGATE); TagActivity.this.b = row; showDialog(DIALOG_CONFIRM_NAVIGATE); } }); /* * On long click, we bring up an edit dialog. */ lv.setOnItemLongClickListener(new OnItemLongClickListener() { /* * Same annotation as in onItemClick(..), above. */ @SuppressWarnings("unchecked") public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // If we have a long click on an entry, show an editor ArrayAdapter<Bundle> adapter = (ArrayAdapter<Bundle>) parent.getAdapter(); Bundle row = adapter.getItem(position); removeDialog(DIALOG_TAG); TagActivity.this.b = row; showDialog(DIALOG_TAG); return true; } }); } @Override public void onDestroy() { if (db != null) db.close(); super.onDestroy(); } @Override public void onResume() { if (db == null) db = new Database(this); super.onResume(); } protected Dialog onCreateDialog(int id) { @SuppressWarnings("unused") final int type = b.getInt("type"); final String tag = b.getString("tag"); final String itemKey = b.getString("itemKey"); AlertDialog dialog; switch (id) { /* Simple editor for a single tag */ case DIALOG_TAG: final EditText input = new EditText(this); input.setText(tag, BufferType.EDITABLE); dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.tag_edit)) .setView(input) .setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @SuppressWarnings("unchecked") public void onClick(DialogInterface dialog, int whichButton) { Editable value = input.getText(); Log.d(TAG, "Got tag: " + value.toString()); Item.setTag(itemKey, tag, value.toString(), 0, db); Item item = Item.load(itemKey, db); Log.d(TAG, "Have JSON: " + item.getContent().toString()); ArrayAdapter<Bundle> la = (ArrayAdapter<Bundle>) getListAdapter(); la.clear(); for (Bundle b : item.tagsToBundleArray()) { la.add(b); } la.notifyDataSetChanged(); } }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog; case DIALOG_CONFIRM_NAVIGATE: dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.tag_view_confirm)) .setPositiveButton(getResources().getString(R.string.tag_view), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent i = new Intent(getBaseContext(), ItemActivity.class); i.putExtra("com.gimranov.zandy.app.tag", tag); startActivity(i); } }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog; default: Log.e(TAG, "Invalid dialog requested"); return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.do_sync: if (!ServerCredentials.check(getApplicationContext())) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return true; } Log.d(TAG, "Preparing sync requests"); new ZoteroAPITask(getBaseContext()).execute(APIRequest.update(this.item)); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started), Toast.LENGTH_SHORT).show(); return true; case R.id.do_new: Bundle row = new Bundle(); row.putString("tag", ""); row.putString("itemKey", this.item.getKey()); row.putInt("type", 0); removeDialog(DIALOG_TAG); this.b = row; showDialog(DIALOG_TAG); return true; case R.id.do_prefs: startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } }
11,025
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
SyncEvent.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/SyncEvent.java
package com.gimranov.zandy.app; class SyncEvent { private static final String TAG = SyncEvent.class.getCanonicalName(); static final int COMPLETE_CODE = 1; static final SyncEvent COMPLETE = new SyncEvent(COMPLETE_CODE); private int status; private SyncEvent(int status) { this.status = status; } public int getStatus() { return status; } }
394
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
RequestActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/RequestActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.app.ListActivity; import android.content.Context; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.text.Html; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import android.widget.Toast; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.task.APIRequest; /** * This activity exists only for debugging, at least at this point * <p> * Potentially, this could let users cancel pending requests and do things * like resolve sync conflicts. * * @author ajlyon */ public class RequestActivity extends ListActivity { @SuppressWarnings("unused") private static final String TAG = RequestActivity.class.getSimpleName(); private Database db; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = new Database(this); setContentView(R.layout.requests); this.setTitle(getResources().getString(R.string.sync_pending_requests)); setListAdapter(new ResourceCursorAdapter(this, android.R.layout.simple_list_item_2, create()) { @Override public void bindView(View view, Context c, Cursor cur) { APIRequest req = new APIRequest(cur); TextView tvTitle = view.findViewById(android.R.id.text1); TextView tvInfo = view.findViewById(android.R.id.text2); tvTitle.setText(req.query); // Set to an html-formatted representation of the request if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { tvInfo.setText(Html.fromHtml(req.toHtmlString(), Html.FROM_HTML_MODE_COMPACT)); } else { //noinspection deprecation tvInfo.setText(Html.fromHtml(req.toHtmlString())); } } }); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ResourceCursorAdapter adapter = (ResourceCursorAdapter) parent.getAdapter(); Cursor cur = adapter.getCursor(); // Place the cursor at the selected item if (cur.moveToPosition(position)) { // and replace the cursor with one for the selected collection APIRequest req = new APIRequest(cur); // toast for now-- later do something Toast.makeText(getApplicationContext(), req.query, Toast.LENGTH_SHORT).show(); } else { // failed to move cursor; should do something } } }); } public Cursor create() { String[] cols = Database.REQUESTCOLS; String[] args = {}; return db.query("apirequests", cols, "", args, null, null, null, null); } }
4,160
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
ServerCredentials.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/ServerCredentials.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import java.io.File; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.gimranov.zandy.app.storage.StorageManager; import com.gimranov.zandy.app.task.APIRequest; public class ServerCredentials { /** * Application key -- available from Zotero */ static final String CONSUMERKEY = "93a5aac13612aed2a236"; static final String CONSUMERSECRET = "196d86bd1298cb78511c"; /** * This is the zotero:// protocol we intercept * It probably shouldn't be changed. */ static final String CALLBACKURL = "zotero://"; /** * This is the Zotero API server. Those who set up independent * Zotero installations will need to change this. */ public static final String APIBASE = "https://api.zotero.org"; /** * These are the API GET-only methods */ public static final String ITEMFIELDS = "/itemFields"; public static final String ITEMTYPES = "/itemTypes"; public static final String ITEMTYPECREATORTYPES = "/itemTypeCreatorTypes"; public static final String CREATORFIELDS = "/creatorFields"; public static final String ITEMNEW = "/items/new"; /* These are the manipulation methods */ // /users/1/items GET, POST, PUT, DELETE public static final String ITEMS = "/users/USERID/items"; public static final String COLLECTIONS = "/users/USERID/collections"; public static final String TAGS = "/tags"; public static final String GROUPS = "/groups"; /** * And these are the OAuth endpoints we talk to. * <p> * We embed the requested permissions in the endpoint URLs; see * http://www.zotero.org/support/dev/server_api/oauth#requesting_specific_permissions * for more details. */ static final String OAUTHREQUEST = "https://www.zotero.org/oauth/request?" + "library_access=1&" + "notes_access=1&" + "write_access=1&" + "all_groups=write"; static final String OAUTHACCESS = "https://www.zotero.org/oauth/access?" + "library_access=1&" + "notes_access=1&" + "write_access=1&" + "all_groups=write"; static final String OAUTHAUTHORIZE = "https://www.zotero.org/oauth/authorize?" + "library_access=1&" + "notes_access=1&" + "write_access=1&" + "all_groups=write"; private String userID; private String userKey; public ServerCredentials(Context c) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); userID = settings.getString("user_id", null); userKey = settings.getString("user_key", null); } public String prep(String in) { if (userID == null) { Log.d(ServerCredentials.class.getCanonicalName(), "UserID was null"); return in; } return in.replace("USERID", userID); } /** * Replaces USERID with appropriate ID if needed, and sets key if missing * * @param req * @return */ public APIRequest prep(APIRequest req) { req.query = prep(req.query); if (req.key == null) req.key = userKey; return req; } public String getKey() { return userKey; } public static boolean check(Context c) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c); return settings.getString("user_id", null) != null && settings.getString("user_key", null) != null && !"".equals(settings.getString("user_id", null)) && !"".equals(settings.getString("user_key", null)); } }
4,630
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
AmazonZxingGlue.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/AmazonZxingGlue.java
package com.gimranov.zandy.app; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.util.Log; import com.google.zxing.integration.android.IntentIntegrator; public class AmazonZxingGlue { private static final String TAG = AmazonZxingGlue.class.getSimpleName(); public static AlertDialog showDownloadDialog(final Context activity) { AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity); downloadDialog.setTitle(IntentIntegrator.DEFAULT_TITLE); downloadDialog.setMessage(IntentIntegrator.DEFAULT_MESSAGE); downloadDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Uri uri = Uri.parse("amzn://apps/android?asin=B004R1FCII"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { activity.startActivity(intent); } catch (ActivityNotFoundException anfe) { // Hmm, market is not installed Log.w(TAG, "Amazon is not installed; cannot install"); } } }); downloadDialog.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) {} }); return downloadDialog.show(); } }
1,634
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
ItemActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/ItemActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.DatabaseAccess; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.data.ItemAdapter; import com.gimranov.zandy.app.data.ItemCollection; import com.gimranov.zandy.app.task.APIEvent; import com.gimranov.zandy.app.task.APIRequest; import com.gimranov.zandy.app.task.ZoteroAPITask; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.squareup.otto.Subscribe; import org.apache.http.util.ByteArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; public class ItemActivity extends ListActivity { private static final String TAG = ItemActivity.class.getSimpleName(); static final int DIALOG_VIEW = 0; static final int DIALOG_NEW = 1; static final int DIALOG_SORT = 2; static final int DIALOG_IDENTIFIER = 3; static final int DIALOG_PROGRESS = 6; /** * Allowed sort orderings */ static final String[] SORTS = { "item_year, item_title COLLATE NOCASE", "item_creator COLLATE NOCASE, item_year", "item_title COLLATE NOCASE, item_year", "timestamp ASC, item_title COLLATE NOCASE" }; /** * Strings providing the names of each ordering, respectively */ static final int[] SORT_NAMES = { R.string.sort_year_title, R.string.sort_creator_year, R.string.sort_title_year, R.string.sort_modified_title }; private static final String SORT_CHOICE = "sort_choice"; private String collectionKey; private String query; private Database db; private ProgressDialog mProgressDialog; private ProgressThread progressThread; public String sortBy = "item_year, item_title"; final Handler syncHandler = new Handler() { public void handleMessage(Message msg) { Log.d(TAG, "received message: " + msg.arg1); refreshView(); if (msg.arg1 == APIRequest.UPDATED_DATA) { refreshView(); return; } if (msg.arg1 == APIRequest.QUEUED_MORE) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_queued_more, msg.arg2), Toast.LENGTH_SHORT).show(); return; } if (msg.arg1 == APIRequest.BATCH_DONE) { Application.getInstance().getBus().post(SyncEvent.COMPLETE); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_complete), Toast.LENGTH_SHORT).show(); return; } if (msg.arg1 == APIRequest.ERROR_UNKNOWN) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_error), Toast.LENGTH_SHORT).show(); } } }; private APIEvent mEvent = new APIEvent() { private int updates = 0; @Override public void onComplete(APIRequest request) { Message msg = syncHandler.obtainMessage(); msg.arg1 = APIRequest.BATCH_DONE; syncHandler.sendMessage(msg); Log.d(TAG, "fired oncomplete"); } @Override public void onUpdate(APIRequest request) { updates++; if (updates % 10 == 0) { Message msg = syncHandler.obtainMessage(); msg.arg1 = APIRequest.UPDATED_DATA; syncHandler.sendMessage(msg); } else { // do nothing } } @Override public void onError(APIRequest request, Exception exception) { Log.e(TAG, "APIException caught", exception); Message msg = syncHandler.obtainMessage(); msg.arg1 = APIRequest.ERROR_UNKNOWN; syncHandler.sendMessage(msg); } @Override public void onError(APIRequest request, int error) { Log.e(TAG, "API error caught"); Message msg = syncHandler.obtainMessage(); msg.arg1 = APIRequest.ERROR_UNKNOWN; syncHandler.sendMessage(msg); } }; protected Bundle b = new Bundle(); /** * Refreshes the current list adapter */ private void refreshView() { ItemAdapter adapter = (ItemAdapter) getListAdapter(); if (adapter == null) return; Cursor newCursor = prepareCursor(); adapter.changeCursor(newCursor); adapter.notifyDataSetChanged(); Log.d(TAG, "refreshing view on request"); } /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String persistedSort = Persistence.read(SORT_CHOICE); if (persistedSort != null) sortBy = persistedSort; db = new Database(this); setContentView(R.layout.items); Intent intent = getIntent(); collectionKey = intent.getStringExtra("com.gimranov.zandy.app.collectionKey"); ItemCollection coll = ItemCollection.load(collectionKey, db); APIRequest req; if (coll != null) { req = APIRequest.fetchItems(coll, false, new ServerCredentials(this)); } else { req = APIRequest.fetchItems(false, new ServerCredentials(this)); } prepareAdapter(); ItemAdapter adapter = (ItemAdapter) getListAdapter(); Cursor cur = adapter.getCursor(); if (intent.getBooleanExtra("com.gimranov.zandy.app.rerequest", false) || cur == null || cur.getCount() == 0) { if (!ServerCredentials.check(getBaseContext())) { Toast.makeText(getBaseContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return; } Toast.makeText(this, getResources().getString(R.string.collection_empty), Toast.LENGTH_SHORT).show(); Log.d(TAG, "Running a request to populate missing items"); ZoteroAPITask task = new ZoteroAPITask(this); req.setHandler(mEvent); task.execute(req); } ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // If we have a click on an item, do something... ItemAdapter adapter = (ItemAdapter) parent.getAdapter(); Cursor cur = adapter.getCursor(); // Place the cursor at the selected item if (cur.moveToPosition(position)) { // and load an activity for the item Item item = Item.load(cur); Log.d(TAG, "Loading item data with key: " + item.getKey()); // We create and issue a specified intent with the necessary data Intent i = new Intent(getBaseContext(), ItemDataActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); i.putExtra("com.gimranov.zandy.app.itemDbId", item.dbId); startActivity(i); } else { // failed to move cursor-- show a toast TextView tvTitle = (TextView) view.findViewById(R.id.item_title); Toast.makeText(getApplicationContext(), getResources().getString(R.string.cant_open_item, tvTitle.getText()), Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onResume() { super.onResume(); Application.getInstance().getBus().register(this); refreshView(); } @Override public void onDestroy() { ItemAdapter adapter = (ItemAdapter) getListAdapter(); Cursor cur = adapter.getCursor(); if (cur != null) cur.close(); if (db != null) db.close(); super.onDestroy(); handler.removeCallbacksAndMessages(null); syncHandler.removeCallbacksAndMessages(null); } @Override protected void onPause() { super.onPause(); Application.getInstance().getBus().unregister(this); } private void prepareAdapter() { ItemAdapter adapter = new ItemAdapter(this, prepareCursor()); setListAdapter(adapter); } private Cursor prepareCursor() { Cursor cursor; // Be ready for a search Intent intent = getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { query = intent.getStringExtra(SearchManager.QUERY); cursor = getCursor(query); this.setTitle(getResources().getString(R.string.search_results, query)); } else if (query != null) { cursor = getCursor(query); this.setTitle(getResources().getString(R.string.search_results, query)); } else if (intent.getStringExtra("com.gimranov.zandy.app.tag") != null) { String tag = intent.getStringExtra("com.gimranov.zandy.app.tag"); Query q = new Query(); q.set("tag", tag); cursor = getCursor(q); this.setTitle(getResources().getString(R.string.tag_viewing_items, tag)); } else { collectionKey = intent.getStringExtra("com.gimranov.zandy.app.collectionKey"); ItemCollection coll; if (collectionKey != null && (coll = ItemCollection.load(collectionKey, db)) != null) { cursor = getCursor(coll); this.setTitle(coll.getTitle()); } else { cursor = getCursor(); this.setTitle(getResources().getString(R.string.all_items)); } } return cursor; } protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_NEW: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.item_type)) // XXX i18n .setItems(Item.ITEM_TYPES_EN, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int pos) { Item item = new Item(getBaseContext(), Item.ITEM_TYPES[pos]); item.dirty = APIRequest.API_DIRTY; item.save(db); if (collectionKey != null) { ItemCollection coll = ItemCollection.load(collectionKey, db); if (coll != null) { coll.loadChildren(db); coll.add(item); coll.saveChildren(db); } } Log.d(TAG, "Loading item data with key: " + item.getKey()); // We create and issue a specified intent with the necessary data Intent i = new Intent(getBaseContext(), ItemDataActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); startActivity(i); } }); AlertDialog dialog = builder.create(); return dialog; case DIALOG_SORT: // We generate the sort name list for our current locale String[] sorts = new String[SORT_NAMES.length]; for (int j = 0; j < SORT_NAMES.length; j++) { sorts[j] = getResources().getString(SORT_NAMES[j]); } AlertDialog.Builder builder2 = new AlertDialog.Builder(this); builder2.setTitle(getResources().getString(R.string.set_sort_order)) .setItems(sorts, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int pos) { Cursor cursor; setSortBy(SORTS[pos]); ItemCollection collection; if (collectionKey != null && (collection = ItemCollection.load(collectionKey, db)) != null) { cursor = getCursor(collection); } else { if (query != null) { cursor = getCursor(query); } else { cursor = getCursor(); } } ItemAdapter adapter = (ItemAdapter) getListAdapter(); adapter.changeCursor(cursor); Log.d(TAG, "Re-sorting by: " + SORTS[pos]); Persistence.write(SORT_CHOICE, SORTS[pos]); } }); return builder2.create(); case DIALOG_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setIndeterminate(true); mProgressDialog.setMessage(getResources().getString(R.string.identifier_looking_up)); return mProgressDialog; case DIALOG_IDENTIFIER: final EditText input = new EditText(this); input.setHint(getResources().getString(R.string.identifier_hint)); final ItemActivity current = this; dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.identifier_message)) .setView(input) .setPositiveButton(getResources().getString(R.string.menu_search), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Editable value = input.getText(); // run search Bundle c = new Bundle(); c.putString("mode", "isbn"); c.putString("identifier", value.toString()); removeDialog(DIALOG_PROGRESS); ItemActivity.this.b = c; showDialog(DIALOG_PROGRESS); } }).setNeutralButton(getResources().getString(R.string.scan), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // If we're about to download from Google play, cancel that dialog // and prompt from Amazon if we're on an Amazon device IntentIntegrator integrator = new IntentIntegrator(current); AlertDialog producedDialog = integrator.initiateScan(); if (producedDialog != null && "amazon".equals(BuildConfig.FLAVOR)) { producedDialog.dismiss(); AmazonZxingGlue.showDownloadDialog(current); } } }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog; default: return null; } } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_PROGRESS: } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); // Turn on sort item MenuItem sort = menu.findItem(R.id.do_sort); sort.setEnabled(true); sort.setVisible(true); // Turn on search item MenuItem search = menu.findItem(R.id.do_search); search.setEnabled(true); search.setVisible(true); // Turn on identifier item MenuItem identifier = menu.findItem(R.id.do_identifier); identifier.setEnabled(true); identifier.setVisible(true); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.do_sync: if (!ServerCredentials.check(getBaseContext())) { Toast.makeText(getBaseContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return true; } // Get credentials ServerCredentials cred = new ServerCredentials(getBaseContext()); // Make this a collection-specific sync, preceding by de-dirtying Item.queue(db); ArrayList<APIRequest> list = new ArrayList<APIRequest>(); APIRequest[] templ = {}; for (Item i : Item.queue) { Log.d(TAG, "Adding dirty item to sync: " + i.getTitle()); list.add(cred.prep(APIRequest.update(i))); } if (collectionKey == null) { Log.d(TAG, "Adding sync request for all items"); APIRequest req = APIRequest.fetchItems(false, cred); req.setHandler(mEvent); list.add(req); } else { Log.d(TAG, "Adding sync request for collection: " + collectionKey); APIRequest req = APIRequest.fetchItems(collectionKey, true, cred); req.setHandler(mEvent); list.add(req); } APIRequest[] reqs = list.toArray(templ); ZoteroAPITask task = new ZoteroAPITask(getBaseContext()); task.setHandler(syncHandler); task.execute(reqs); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started), Toast.LENGTH_SHORT).show(); return true; case R.id.do_new: removeDialog(DIALOG_NEW); showDialog(DIALOG_NEW); return true; case R.id.do_identifier: removeDialog(DIALOG_IDENTIFIER); showDialog(DIALOG_IDENTIFIER); return true; case R.id.do_search: onSearchRequested(); return true; case R.id.do_prefs: Intent i = new Intent(getBaseContext(), SettingsActivity.class); startActivity(i); return true; case R.id.do_sort: removeDialog(DIALOG_SORT); showDialog(DIALOG_SORT); return true; default: return super.onOptionsItemSelected(item); } } /* Sorting */ public void setSortBy(String sort) { this.sortBy = sort; } /* Handling the ListView and keeping it up to date */ public Cursor getCursor() { return DatabaseAccess.INSTANCE.items(db, (ItemCollection) null, sortBy); } public Cursor getCursor(ItemCollection parent) { return DatabaseAccess.INSTANCE.items(db, parent, sortBy); } public Cursor getCursor(String query) { return DatabaseAccess.INSTANCE.items(db, query, sortBy); } public Cursor getCursor(Query query) { return query.query(db); } @Subscribe public void syncComplete(SyncEvent event) { if (event.getStatus() == SyncEvent.COMPLETE_CODE) refreshView(); } /* Thread and helper to run lookups */ @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { Log.d(TAG, "_____________________on_activity_result"); IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { // handle scan result Bundle b = new Bundle(); b.putString("mode", "isbn"); b.putString("identifier", scanResult.getContents()); if (scanResult != null && scanResult.getContents() != null) { Log.d(TAG, b.getString("identifier")); progressThread = new ProgressThread(handler, b); progressThread.start(); this.b = b; removeDialog(DIALOG_PROGRESS); showDialog(DIALOG_PROGRESS); } else { Toast.makeText(getApplicationContext(), getResources().getString(R.string.identifier_scan_failed), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), getResources().getString(R.string.identifier_scan_failed), Toast.LENGTH_SHORT).show(); } } final Handler handler = new Handler() { public void handleMessage(Message msg) { Log.d(TAG, "______________________handle_message"); if (ProgressThread.STATE_DONE == msg.arg2) { Bundle data = msg.getData(); String itemKey = data.getString("itemKey"); if (itemKey != null) { if (collectionKey != null) { Item item = Item.load(itemKey, db); ItemCollection coll = ItemCollection.load(collectionKey, db); coll.add(item); coll.saveChildren(db); } mProgressDialog.dismiss(); mProgressDialog = null; Log.d(TAG, "Loading new item data with key: " + itemKey); // We create and issue a specified intent with the necessary data Intent i = new Intent(getBaseContext(), ItemDataActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", itemKey); startActivity(i); } return; } if (ProgressThread.STATE_PARSING == msg.arg2) { mProgressDialog.setMessage(getResources().getString(R.string.identifier_processing)); return; } if (ProgressThread.STATE_ERROR == msg.arg2) { dismissDialog(DIALOG_PROGRESS); Toast.makeText(getApplicationContext(), getResources().getString(R.string.identifier_lookup_failed), Toast.LENGTH_SHORT).show(); progressThread.setState(ProgressThread.STATE_DONE); } } }; private class ProgressThread extends Thread { Handler mHandler; Bundle arguments; final static int STATE_DONE = 5; final static int STATE_FETCHING = 1; final static int STATE_PARSING = 6; final static int STATE_ERROR = 7; int mState; ProgressThread(Handler h, Bundle b) { mHandler = h; arguments = b; Log.d(TAG, "_____________________thread_constructor"); } public void run() { Log.d(TAG, "_____________________thread_run"); mState = STATE_FETCHING; // Setup String identifier = arguments.getString("identifier"); String mode = arguments.getString("mode"); URL url; String urlstring; String response = ""; if ("isbn".equals(mode)) { urlstring = "http://xisbn.worldcat.org/webservices/xid/isbn/" + identifier + "?method=getMetadata&fl=*&format=json&count=1"; } else { urlstring = ""; } try { Log.d(TAG, "Fetching from: " + urlstring); url = new URL(urlstring); /* Open a connection to that URL. */ URLConnection ucon = url.openConnection(); /* * Define InputStreams to read from the URLConnection. */ InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is, 16000); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; /* * Read bytes to the Buffer until there is nothing more to read(-1). */ while (mState == STATE_FETCHING && (current = bis.read()) != -1) { baf.append((byte) current); } response = new String(baf.toByteArray()); Log.d(TAG, response); } catch (IOException e) { Log.e(TAG, "Error: ", e); } Message msg = mHandler.obtainMessage(); msg.arg2 = STATE_PARSING; mHandler.sendMessage(msg); /* * { "stat":"ok", "list":[{ "url":["http://www.worldcat.org/oclc/177669176?referer=xid"], "publisher":"O'Reilly", "form":["BA"], "lccn":["2004273129"], "lang":"eng", "city":"Sebastopol, CA", "author":"by Mark Lutz and David Ascher.", "ed":"2nd ed.", "year":"2003", "isbn":["0596002815"], "title":"Learning Python", "oclcnum":["177669176", .. "748093898"]}]} */ // This is OCLC-specific logic try { JSONObject result = new JSONObject(response); if (!result.getString("stat").equals("ok")) { Log.e(TAG, "Error response received"); msg = mHandler.obtainMessage(); msg.arg2 = STATE_ERROR; mHandler.sendMessage(msg); return; } result = result.getJSONArray("list").getJSONObject(0); String form = result.getJSONArray("form").getString(0); String type; if ("AA".equals(form)) type = "audioRecording"; else if ("VA".equals(form)) type = "videoRecording"; else if ("FA".equals(form)) type = "film"; else type = "book"; // TODO Fix this type = "book"; Item item = new Item(getBaseContext(), type); JSONObject content = item.getContent(); if (result.has("lccn")) { String lccn = "LCCN: " + result.getJSONArray("lccn").getString(0); content.put("extra", lccn); } if (result.has("isbn")) { content.put("ISBN", result.getJSONArray("isbn").getString(0)); } content.put("title", result.optString("title", "")); content.put("place", result.optString("city", "")); content.put("edition", result.optString("ed", "")); content.put("language", result.optString("lang", "")); content.put("publisher", result.optString("publisher", "")); content.put("date", result.optString("year", "")); item.setTitle(result.optString("title", "")); item.setYear(result.optString("year", "")); String author = result.optString("author", ""); item.setCreatorSummary(author); JSONArray array = new JSONArray(); JSONObject member = new JSONObject(); member.accumulate("creatorType", "author"); member.accumulate("name", author); array.put(member); content.put("creators", array); item.setContent(content); item.save(db); msg = mHandler.obtainMessage(); Bundle data = new Bundle(); data.putString("itemKey", item.getKey()); msg.setData(data); msg.arg2 = STATE_DONE; mHandler.sendMessage(msg); } catch (JSONException e) { Log.e(TAG, "exception parsing response", e); msg = mHandler.obtainMessage(); msg.arg2 = STATE_ERROR; mHandler.sendMessage(msg); } } public void setState(int state) { mState = state; } } }
31,616
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
AttachmentActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/AttachmentActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import android.text.Editable; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.BufferType; import android.widget.Toast; import com.gimranov.zandy.app.data.Attachment; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.storage.StorageManager; import com.gimranov.zandy.app.task.APIRequest; import com.gimranov.zandy.app.task.ZoteroAPITask; import com.gimranov.zandy.app.webdav.WebDavTrust; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.CountingOutputStream; import org.json.JSONException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Authenticator; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Enumeration; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * This Activity handles displaying and editing attachments. It works almost the same as * ItemDataActivity and TagActivity, using a simple ArrayAdapter on Bundles with the creator info. * <p> * This currently operates by showing the attachments for a given item * * @author ajlyon */ public class AttachmentActivity extends ListActivity { private static final String TAG = AttachmentActivity.class.getSimpleName(); static final int DIALOG_CONFIRM_NAVIGATE = 4; static final int DIALOG_FILE_PROGRESS = 6; static final int DIALOG_CONFIRM_DELETE = 5; static final int DIALOG_NOTE = 3; static final int DIALOG_NEW = 1; public Item item; private ProgressDialog mProgressDialog; private ProgressThread progressThread; private Database db; /** * For <= Android 2.1 (API 7), we can't pass bundles to showDialog(), so set this instead */ private Bundle b = new Bundle(); private ArrayList<File> tmpFiles; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tmpFiles = new ArrayList<File>(); db = new Database(this); /* Get the incoming data from the calling activity */ final String itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey"); Item item = Item.load(itemKey, db); this.item = item; if (item == null) { Log.e(TAG, "AttachmentActivity started without itemKey; finishing."); finish(); return; } this.setTitle(getResources().getString(R.string.attachments_for_item, item.getTitle())); ArrayList<Attachment> rows = Attachment.forItem(item, db); /* * We use the standard ArrayAdapter, passing in our data as a Attachment. * Since it's no longer a simple TextView, we need to override getView, but * we can do that anonymously. */ setListAdapter(new ArrayAdapter<Attachment>(this, R.layout.list_attach, rows) { @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { View row; // We are reusing views, but we need to initialize it if null if (null == convertView) { LayoutInflater inflater = getLayoutInflater(); row = inflater.inflate(R.layout.list_attach, null); } else { row = convertView; } ImageView tvType = row.findViewById(R.id.attachment_type); TextView tvSummary = row.findViewById(R.id.attachment_summary); Attachment att = getItem(position); Log.d(TAG, "Have an attachment: " + att.title + " fn:" + att.filename + " status:" + att.status); tvType.setImageResource(Item.resourceForType(att.getType())); try { Log.d(TAG, att.content.toString(4)); } catch (JSONException e) { Log.e(TAG, "JSON parse exception when reading attachment content", e); } if (att.getType().equals("note")) { String note = att.content.optString("note", ""); if (note.length() > 40) { note = note.substring(0, 40); } tvSummary.setText(note); } else { StringBuilder status = new StringBuilder(getResources().getString(R.string.status)); if (att.status == Attachment.AVAILABLE) status.append(getResources().getString(R.string.attachment_zfs_available)); else if (att.status == Attachment.LOCAL) status.append(getResources().getString(R.string.attachment_zfs_local)); else status.append(getResources().getString(R.string.attachment_unknown)); tvSummary.setText(att.title + " " + status.toString()); } return row; } }); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemLongClickListener(new OnItemLongClickListener() { // Warning here because Eclipse can't tell whether my ArrayAdapter is // being used with the correct parametrization. @SuppressWarnings("unchecked") public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // If we have a click on an entry, show its note ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter(); Attachment row = adapter.getItem(position); if (row.content.has("note")) { Log.d(TAG, "Trying to start note view activity for: " + row.key); Intent i = new Intent(getBaseContext(), NoteActivity.class); i.putExtra("com.gimranov.zandy.app.attKey", row.key);//row.content.optString("note", "")); startActivity(i); } return true; } }); lv.setOnItemClickListener(new OnItemClickListener() { // Warning here because Eclipse can't tell whether my ArrayAdapter is // being used with the correct parametrization. @SuppressWarnings("unchecked") public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // If we have a long click on an entry, do something... ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter(); Attachment row = adapter.getItem(position); String url = (row.url != null && !row.url.equals("")) ? row.url : row.content.optString("url"); if (!row.getType().equals("note")) { Bundle b = new Bundle(); b.putString("title", row.title); b.putString("attachmentKey", row.key); b.putString("content", url); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); if (settings.getBoolean("webdav_enabled", false)) b.putString("mode", "webdav"); else b.putString("mode", "zfs"); if (row.isDownloadable()) { loadFileAttachment(b); } else { AttachmentActivity.this.b = b; showDialog(DIALOG_CONFIRM_NAVIGATE); } } if (row.getType().equals("note")) { Bundle b = new Bundle(); b.putString("attachmentKey", row.key); b.putString("itemKey", itemKey); b.putString("content", row.content.optString("note", "")); removeDialog(DIALOG_NOTE); AttachmentActivity.this.b = b; showDialog(DIALOG_NOTE); } } }); } @Override public void onDestroy() { if (db != null) db.close(); if (tmpFiles != null) { for (File f : tmpFiles) { if (!f.delete()) { Log.e(TAG, "Failed to delete temporary file on activity close."); } } tmpFiles.clear(); } super.onDestroy(); handler.removeCallbacksAndMessages(null); } @Override public void onResume() { if (db == null) db = new Database(this); super.onResume(); } @Override protected Dialog onCreateDialog(int id) { final String attachmentKey = b.getString("attachmentKey"); final String itemKey = b.getString("itemKey"); final String content = b.getString("content"); final String mode = b.getString("mode"); AlertDialog dialog; switch (id) { case DIALOG_CONFIRM_NAVIGATE: dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.view_online_warning)) .setPositiveButton(getResources().getString(R.string.view), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // The behavior for invalid URIs might be nasty, but // we'll cross that bridge if we come to it. try { Uri uri = Uri.parse(content); startActivity(new Intent(Intent.ACTION_VIEW) .setData(uri)); } catch (ActivityNotFoundException e) { // There can be exceptions here; not sure what would prompt us to have // URIs that the browser can't load, but it apparently happens. Toast.makeText(getApplicationContext(), getResources().getString(R.string.attachment_intent_failed_for_uri, content), Toast.LENGTH_SHORT).show(); } } }).setNeutralButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog; case DIALOG_CONFIRM_DELETE: dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.attachment_delete_confirm)) .setPositiveButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() { @SuppressWarnings("unchecked") public void onClick(DialogInterface dialog, int whichButton) { Attachment a = Attachment.load(attachmentKey, db); a.delete(db); ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter(); la.clear(); for (Attachment at : Attachment.forItem(Item.load(itemKey, db), db)) { la.add(at); } } }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog; case DIALOG_NOTE: final EditText input = new EditText(this); input.setText(content, BufferType.EDITABLE); AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.note)) .setView(input) .setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @SuppressWarnings("unchecked") public void onClick(DialogInterface dialog, int whichButton) { Editable value = input.getText(); String fixed = value.toString().replaceAll("\n\n", "\n<br>"); if (mode != null && mode.equals("new")) { Log.d(TAG, "Attachment created with parent key: " + itemKey); Attachment att = new Attachment("note", itemKey); att.setNoteText(fixed); att.dirty = APIRequest.API_NEW; att.save(db); } else { Attachment att = Attachment.load(attachmentKey, db); att.setNoteText(fixed); att.dirty = APIRequest.API_DIRTY; att.save(db); } ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter(); la.clear(); for (Attachment a : Attachment.forItem(Item.load(itemKey, db), db)) { la.add(a); } la.notifyDataSetChanged(); } }).setNeutralButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }); // We only want the delete option when this isn't a new note if (mode == null || !"new".equals(mode)) { builder = builder.setNegativeButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Bundle b = new Bundle(); b.putString("attachmentKey", attachmentKey); b.putString("itemKey", itemKey); removeDialog(DIALOG_CONFIRM_DELETE); AttachmentActivity.this.b = b; showDialog(DIALOG_CONFIRM_DELETE); } }); } dialog = builder.create(); //noinspection ConstantConditions dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); return dialog; case DIALOG_FILE_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title"))); mProgressDialog.setIndeterminate(true); return mProgressDialog; default: Log.e(TAG, "Invalid dialog requested"); return null; } } protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_FILE_PROGRESS: mProgressDialog.setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title"))); progressThread = new ProgressThread(handler, b); progressThread.start(); } } private void showAttachment(Attachment att) { if (att.status == Attachment.LOCAL) { Log.d(TAG, "Starting to display local attachment " + att.title); Uri uri = Uri.fromFile(new File(att.filename)); String contentType = att.getContentType(); try { startActivity(new Intent(Intent.ACTION_VIEW) .setDataAndType(uri, contentType)); } catch (ActivityNotFoundException e) { Log.e(TAG, "No activity for intent", e); Toast.makeText(getApplicationContext(), getResources().getString(R.string.attachment_intent_failed, contentType), Toast.LENGTH_SHORT).show(); } } } /** * This mainly is to move the logic out of the onClick callback above * Decides whether to download or view, and launches the appropriate action * * @param b */ private void loadFileAttachment(Bundle b) { Attachment att = Attachment.load(b.getString("attachmentKey"), db); File attFile = new File(att.filename); if (att.status == Attachment.AVAILABLE || attFile.length() == 0) { Log.d(TAG, "Starting to try and download attachment (status: " + att.status + ", fn: " + att.filename + ")"); this.b = b; showDialog(DIALOG_FILE_PROGRESS); } else showAttachment(att); } /** * Refreshes the current list adapter */ @SuppressWarnings("unchecked") private void refreshView() { ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter(); la.clear(); for (Attachment at : Attachment.forItem(item, db)) { la.add(at); } } final Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.arg2) { case ProgressThread.STATE_DONE: if (mProgressDialog.isShowing()) dismissDialog(DIALOG_FILE_PROGRESS); refreshView(); if (null != msg.obj) showAttachment((Attachment) msg.obj); break; case ProgressThread.STATE_FAILED: // Notify that we failed to get anything Toast.makeText(getApplicationContext(), getResources().getString(R.string.attachment_no_download_url), Toast.LENGTH_SHORT).show(); if (mProgressDialog.isShowing()) dismissDialog(DIALOG_FILE_PROGRESS); // Let's try to fall back on an online version AttachmentActivity.this.b = msg.getData(); showDialog(DIALOG_CONFIRM_NAVIGATE); refreshView(); break; case ProgressThread.STATE_UNZIPPING: mProgressDialog.setMax(msg.arg1); mProgressDialog.setProgress(0); mProgressDialog.setMessage(getResources().getString(R.string.attachment_unzipping)); break; case ProgressThread.STATE_RUNNING: mProgressDialog.setMax(msg.arg1); mProgressDialog.setProgress(0); mProgressDialog.setIndeterminate(false); break; default: mProgressDialog.setProgress(msg.arg1); break; } } }; private class ProgressThread extends Thread { Handler mHandler; Bundle arguments; final static int STATE_DONE = 5; final static int STATE_FAILED = 3; final static int STATE_RUNNING = 1; final static int STATE_UNZIPPING = 6; ProgressThread(Handler h, Bundle b) { mHandler = h; arguments = b; } @SuppressWarnings("unchecked") public void run() { // Setup final String attachmentKey = arguments.getString("attachmentKey"); // Can't fetch if we have nothing to fetch if (attachmentKey == null) return; final String mode = arguments.getString("mode"); URL url; File file; String urlstring; Attachment att = Attachment.load(attachmentKey, db); String sanitized = att.getCanonicalStorageName(); file = new File(StorageManager.getDocumentsDirectory(AttachmentActivity.this), sanitized); final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); if ("webdav".equals(mode)) { urlstring = att.getDownloadUrlWebDav(settings); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(settings.getString("webdav_username", ""), settings.getString("webdav_password", "").toCharArray()); } }); if (settings.getBoolean("webdav_ssl_override", false)) { WebDavTrust.installAllTrustingCertificate(); } } else { urlstring = att.getDownloadUrlZfs(settings); } try { try { url = new URL(urlstring); } catch (MalformedURLException e) { // Alert that we don't have a valid download URL and return Message msg = mHandler.obtainMessage(); msg.arg2 = STATE_FAILED; msg.setData(arguments); mHandler.sendMessage(msg); Log.e(TAG, "Download URL not valid: " + urlstring, e); return; } //this is the downloader method long startTime = System.currentTimeMillis(); Log.d(TAG, "download beginning"); Log.d(TAG, "download url:" + url.toString()); Log.d(TAG, "downloaded file name:" + file.getPath()); /* Open a connection to that URL. */ URLConnection ucon = url.openConnection(); ucon.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); ucon.setRequestProperty("Accept", "*/*"); Message msg = mHandler.obtainMessage(); msg.arg1 = ucon.getContentLength(); msg.arg2 = STATE_RUNNING; mHandler.sendMessage(msg); /* * Define InputStreams to read from the URLConnection. */ InputStream is = null; FileOutputStream fos = null; try { fos = new FileOutputStream(file); final AtomicInteger counter = new AtomicInteger(); OutputStream outputStream = new CountingOutputStream(fos) { @Override protected void afterWrite(int n) throws IOException { super.afterWrite(n); if (n > 0) { int completed = counter.addAndGet(n); Message message = mHandler.obtainMessage(); message.arg1 = completed; mHandler.sendMessage(message); } } }; is = ucon.getInputStream(); IOUtils.copy(is, outputStream); } finally { if (is != null) { is.close(); } if (fos != null) { fos.close(); } } /* Save to temporary directory for WebDAV */ if ("webdav".equals(mode)) { File tmpFile = File.createTempFile("zandy", ".zip", StorageManager.getCacheDirectory(AttachmentActivity.this)); FileUtils.copyFile(file, tmpFile); //noinspection ResultOfMethodCallIgnored file.delete(); // Keep track of temp files that we've created. if (tmpFiles == null) tmpFiles = new ArrayList<>(); tmpFiles.add(tmpFile); ZipFile zf = new ZipFile(tmpFile); Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zf.entries(); do { ZipEntry entry = entries.nextElement(); // Change the message to reflect that we're unzipping now msg = mHandler.obtainMessage(); msg.arg1 = (int) entry.getSize(); msg.arg2 = STATE_UNZIPPING; mHandler.sendMessage(msg); String name64 = entry.getName(); try { byte[] byteName = Base64.decode(name64.getBytes(), 0, name64.length() - 5, Base64.DEFAULT); String name = new String(byteName); Log.d(TAG, "Found file " + name + " from encoded " + name64); // If the linkMode is not an imported URL (snapshot) and the MIME type isn't text/html, // then we unzip it and we're happy. If either of the preceding is true, we skip the file // unless the filename includes .htm (covering .html automatically) if ((!att.getType().equals("text/html")) || name.contains(".htm")) { FileOutputStream fos2 = new FileOutputStream(file); InputStream entryStream = zf.getInputStream(entry); final AtomicInteger counter = new AtomicInteger(); OutputStream outputStream = new CountingOutputStream(fos2) { @Override protected void afterWrite(int n) throws IOException { super.afterWrite(n); if (n > 0) { int completed = counter.addAndGet(n); Message message = mHandler.obtainMessage(); message.arg1 = completed; mHandler.sendMessage(message); } } }; IOUtils.copy(entryStream, outputStream); fos2.close(); entryStream.close(); Log.d(TAG, "Finished reading file"); } else { Log.d(TAG, "Skipping file: " + name); } } catch (IllegalArgumentException | NegativeArraySizeException e) { Log.e(TAG, "b64 " + name64, e); } } while (entries.hasMoreElements()); zf.close(); // We remove the file from the ArrayList if deletion succeeded; // otherwise deletion is put off until the activity exits. if (tmpFile.delete()) { tmpFiles.remove(tmpFile); } } Log.d(TAG, "download ready in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec"); } catch (IOException e) { Log.e(TAG, "Error: ", e); toastError(R.string.attachment_download_failed, e.getMessage()); } att.filename = file.getPath(); File newFile = new File(att.filename); Message msg = mHandler.obtainMessage(); if (newFile.length() > 0) { att.status = Attachment.LOCAL; Log.d(TAG, "File downloaded: " + att.filename); msg.obj = att; } else { Log.d(TAG, "File not downloaded: " + att.filename); att.status = Attachment.AVAILABLE; msg.obj = null; } att.save(db); msg.arg2 = STATE_DONE; mHandler.sendMessage(msg); } } private void toastError(final int resource, final String detail) { AttachmentActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(AttachmentActivity.this, AttachmentActivity.this.getString(resource) + "\n " + detail, Toast.LENGTH_LONG ).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Bundle b = new Bundle(); // Handle item selection switch (item.getItemId()) { case R.id.do_sync: if (!ServerCredentials.check(getApplicationContext())) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return true; } Log.d(TAG, "Preparing sync requests, starting with present item"); new ZoteroAPITask(getBaseContext()).execute(APIRequest.update(this.item)); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started), Toast.LENGTH_SHORT).show(); return true; case R.id.do_new: b.putString("itemKey", this.item.getKey()); b.putString("mode", "new"); AttachmentActivity.this.b = b; removeDialog(DIALOG_NOTE); showDialog(DIALOG_NOTE); return true; case R.id.do_prefs: startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } }
33,655
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
LookupActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/LookupActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.apache.http.util.ByteArrayBuffer; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.gimranov.zandy.app.data.Database; /** * Runs lookup routines to create new items * * @author ajlyon */ public class LookupActivity extends Activity implements OnClickListener { private static final String TAG = LookupActivity.class.getSimpleName(); static final int DIALOG_PROGRESS = 6; private ProgressDialog mProgressDialog; private ProgressThread progressThread; private Database db; private Bundle b = new Bundle(); /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = new Database(this); /* Get the incoming data from the calling activity */ final String identifier = getIntent().getStringExtra("com.gimranov.zandy.app.identifier"); final String mode = getIntent().getStringExtra("com.gimranov.zandy.app.mode"); setContentView(R.layout.lookup); Button lookupButton = (Button) findViewById(R.id.lookupButton); lookupButton.setOnClickListener(this); } /** * Implementation of the OnClickListener interface, to handle button events. * <p> * Note: When adding a button, it needs to be added here, but the * ClickListener needs to be set in the main onCreate(..) as well. */ public void onClick(View v) { Log.d(TAG, "Click on: " + v.getId()); if (v.getId() == R.id.lookupButton) { Log.d(TAG, "Trying to start search activity"); TextView field = (TextView) findViewById(R.id.identifier); Editable fieldContents = (Editable) field.getText(); Bundle b = new Bundle(); b.putString("mode", "isbn"); b.putString("identifier", fieldContents.toString()); this.b = b; showDialog(DIALOG_PROGRESS); } else { Log.w(TAG, "Uncaught click on: " + v.getId()); } } @Override public void onDestroy() { super.onDestroy(); handler.removeCallbacksAndMessages(null); } @Override public void onResume() { if (db == null) db = new Database(this); super.onResume(); } protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIndeterminate(true); mProgressDialog.setMax(100); return mProgressDialog; default: Log.e(TAG, "Invalid dialog requested"); return null; } } protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_PROGRESS: mProgressDialog.setProgress(0); mProgressDialog.setMessage("Looking up item..."); progressThread = new ProgressThread(handler, b); progressThread.start(); } } final Handler handler = new Handler() { public void handleMessage(Message msg) { if (ProgressThread.STATE_DONE == msg.arg2) { if (mProgressDialog.isShowing()) dismissDialog(DIALOG_PROGRESS); // do something-- we're done. return; } if (ProgressThread.STATE_PARSING == msg.arg2) { mProgressDialog.setMessage("Parsing item data..."); return; } int total = msg.arg1; mProgressDialog.setProgress(total); if (total >= 100) { dismissDialog(DIALOG_PROGRESS); progressThread.setState(ProgressThread.STATE_DONE); } } }; private class ProgressThread extends Thread { Handler mHandler; Bundle arguments; final static int STATE_DONE = 5; final static int STATE_FETCHING = 1; final static int STATE_PARSING = 6; int mState; ProgressThread(Handler h, Bundle b) { mHandler = h; arguments = b; } public void run() { mState = STATE_FETCHING; // Setup String identifier = arguments.getString("identifier"); String mode = arguments.getString("mode"); URL url; String urlstring; if ("isbn".equals(mode)) { if (identifier == null || identifier.equals("")) identifier = "0674081250"; urlstring = "http://xisbn.worldcat.org/webservices/xid/isbn/" + identifier + "?method=getMetadata&fl=*&format=json&count=1"; } else { urlstring = ""; } try { Log.d(TAG, "Fetching from: " + urlstring); url = new URL(urlstring); /* Open a connection to that URL. */ URLConnection ucon = url.openConnection(); /* * Define InputStreams to read from the URLConnection. */ InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is, 16000); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; /* * Read bytes to the Buffer until there is nothing more to read(-1). */ while (mState == STATE_FETCHING && (current = bis.read()) != -1) { baf.append((byte) current); if (baf.length() % 2048 == 0) { Message msg = mHandler.obtainMessage(); // XXX do real length later Log.d(TAG, baf.length() + " downloaded so far"); msg.arg1 = baf.length() % 100; mHandler.sendMessage(msg); } } String content = new String(baf.toByteArray()); Log.d(TAG, content); } catch (IOException e) { Log.e(TAG, "Error: ", e); } Message msg = mHandler.obtainMessage(); msg.arg2 = STATE_DONE; mHandler.sendMessage(msg); } void setState(int state) { mState = state; } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.do_prefs: startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } }
8,704
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
CreatorActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/CreatorActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import java.util.ArrayList; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.gimranov.zandy.app.data.Creator; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.task.APIRequest; import com.gimranov.zandy.app.task.ZoteroAPITask; /** * This Activity handles displaying and editing creators. It works almost the same as * ItemDataActivity and TagActivity, using a simple ArrayAdapter on Bundles with the creator info. * * This currently operates by showing the creators for a given item; it could be * modified some day to show all creators in the database (when they come to be saved * that way). * * @author ajlyon * */ public class CreatorActivity extends ListActivity { private static final String TAG = CreatorActivity.class.getSimpleName(); static final int DIALOG_CREATOR = 3; static final int DIALOG_CONFIRM_NAVIGATE = 4; static final int DIALOG_CONFIRM_DELETE = 5; public Item item; private Database db; /** * For API <= 7, to pass bundles to activities */ private Bundle b = new Bundle(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = new Database(this); /* Get the incoming data from the calling activity */ String itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey"); Item item = Item.load(itemKey, db); this.item = item; this.setTitle("Creators for "+item.getTitle()); ArrayList<Bundle> rows = item.creatorsToBundleArray(); /* * We use the standard ArrayAdapter, passing in our data as a Bundle. * Since it's no longer a simple TextView, we need to override getView, but * we can do that anonymously. */ setListAdapter(new ArrayAdapter<Bundle>(this, R.layout.list_data, rows) { @Override public View getView(int position, View convertView, ViewGroup parent) { View row; // We are reusing views, but we need to initialize it if null if (null == convertView) { LayoutInflater inflater = getLayoutInflater(); row = inflater.inflate(R.layout.list_data, null); } else { row = convertView; } /* Our layout has just two fields */ TextView tvLabel = (TextView) row.findViewById(R.id.data_label); TextView tvContent = (TextView) row.findViewById(R.id.data_content); tvLabel.setText(Item.localizedStringForString( getItem(position).getString("creatorType"))); tvContent.setText(getItem(position).getString("name")); return row; } }); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { // Warning here because Eclipse can't tell whether my ArrayAdapter is // being used with the correct parametrization. @SuppressWarnings("unchecked") public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // If we have a click on an entry, do something... ArrayAdapter<Bundle> adapter = (ArrayAdapter<Bundle>) parent.getAdapter(); Bundle row = adapter.getItem(position); /* TODO Rework this logic to open an ItemActivity showing items with this creator if (row.getString("label").equals("url")) { row.putString("url", row.getString("content")); removeDialog(DIALOG_CONFIRM_NAVIGATE); showDialog(DIALOG_CONFIRM_NAVIGATE, row); return; } if (row.getString("label").equals("DOI")) { String url = "https://doi.org/"+Uri.encode(row.getString("content")); row.putString("url", url); removeDialog(DIALOG_CONFIRM_NAVIGATE); showDialog(DIALOG_CONFIRM_NAVIGATE, row); return; } */ Toast.makeText(getApplicationContext(), row.getString("name"), Toast.LENGTH_SHORT).show(); } }); /* * On long click, we bring up an edit dialog. */ lv.setOnItemLongClickListener(new OnItemLongClickListener() { /* * Same annotation as in onItemClick(..), above. */ @SuppressWarnings("unchecked") public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // If we have a long click on an entry, show an editor ArrayAdapter<Bundle> adapter = (ArrayAdapter<Bundle>) parent.getAdapter(); Bundle row = adapter.getItem(position); CreatorActivity.this.b = row; removeDialog(DIALOG_CREATOR); showDialog(DIALOG_CREATOR); return true; } }); } @Override public void onDestroy() { if (db != null) db.close(); super.onDestroy(); } @Override public void onResume() { if (db == null) db = new Database(this); super.onResume(); } protected Dialog onCreateDialog(int id) { final String creatorType = b.getString("creatorType"); final int creatorPosition = b.getInt("position"); String name = b.getString("name"); String firstName = b.getString("firstName"); String lastName = b.getString("lastName"); switch (id) { /* Editor for a creator */ case DIALOG_CREATOR: AlertDialog.Builder builder; AlertDialog dialog; LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.creator_dialog, (ViewGroup) findViewById(R.id.layout_root)); TextView textName = (TextView) layout.findViewById(R.id.creator_name); textName.setText(name); TextView textFN = (TextView) layout.findViewById(R.id.creator_firstName); textFN.setText(firstName); TextView textLN = (TextView) layout.findViewById(R.id.creator_lastName); textLN.setText(lastName); CheckBox mode = (CheckBox) layout.findViewById(R.id.creator_mode); mode.setChecked((firstName == null || firstName.equals("")) && (lastName == null || lastName.equals("")) && (lastName != null && !name.equals(""))); // Set up the adapter to get creator types String[] types = Item.localizedCreatorTypesForItemType(item.getType()); // what position are we? int arrPosition = 0; String localType = ""; if (creatorType != null) { localType = Item.localizedStringForString(creatorType); } else { // We default to the first possibility when none specified localType = Item.localizedStringForString( Item.creatorTypesForItemType(item.getType())[0]); } for (int i = 0; i < types.length; i++) { if (types[i].equals(localType)) { arrPosition = i; break; } } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner spinner = (Spinner) layout.findViewById(R.id.creator_type); spinner.setAdapter(adapter); spinner.setSelection(arrPosition); builder = new AlertDialog.Builder(this); builder.setView(layout); builder.setPositiveButton(getResources().getString(R.string.ok), new OnClickListener(){ @SuppressWarnings("unchecked") public void onClick(DialogInterface dialog, int whichButton) { Creator c; TextView textName = (TextView) layout.findViewById(R.id.creator_name); TextView textFN = (TextView) layout.findViewById(R.id.creator_firstName); TextView textLN = (TextView) layout.findViewById(R.id.creator_lastName); Spinner spinner = (Spinner) layout.findViewById(R.id.creator_type); CheckBox mode = (CheckBox) layout.findViewById(R.id.creator_mode); String selected = (String) spinner.getSelectedItem(); // Set up the adapter to get creator types String[] types = Item.localizedCreatorTypesForItemType(item.getType()); // what position are we? int typePos = 0; for (int i = 0; i < types.length; i++) { if (types[i].equals(selected)) { typePos = i; break; } } String realType = Item.creatorTypesForItemType(item.getType())[typePos]; if (mode.isChecked()) c = new Creator(realType, textName.getText().toString(), true); else c = new Creator(realType, textFN.getText().toString(), textLN.getText().toString()); Item.setCreator(item.getKey(), c, creatorPosition, db); item = Item.load(item.getKey(), db); ArrayAdapter<Bundle> la = (ArrayAdapter<Bundle>) getListAdapter(); la.clear(); for (Bundle b : item.creatorsToBundleArray()) { la.add(b); } la.notifyDataSetChanged(); } }); builder.setNeutralButton(getResources().getString(R.string.cancel), new OnClickListener(){ public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }); builder.setNegativeButton(getResources().getString(R.string.menu_delete), new OnClickListener(){ @SuppressWarnings("unchecked") public void onClick(DialogInterface dialog, int whichButton) { Item.setCreator(item.getKey(), null, creatorPosition, db); item = Item.load(item.getKey(), db); ArrayAdapter<Bundle> la = (ArrayAdapter<Bundle>) getListAdapter(); la.clear(); for (Bundle b : item.creatorsToBundleArray()) { la.add(b); } la.notifyDataSetChanged(); } }); dialog = builder.create(); return dialog; case DIALOG_CONFIRM_NAVIGATE: /* dialog = new AlertDialog.Builder(this) .setTitle("View this online?") .setPositiveButton("View", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // The behavior for invalid URIs might be nasty, but // we'll cross that bridge if we come to it. Uri uri = Uri.parse(content); startActivity(new Intent(Intent.ACTION_VIEW) .setData(uri)); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); return dialog;*/ return null; default: Log.e(TAG, "Invalid dialog requested"); return null; } } /* * I've been just copying-and-pasting the options menu code from activity to activity. * It needs to be reworked for some of these activities. */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.do_sync: if (!ServerCredentials.check(getApplicationContext())) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return true; } Log.d(TAG, "Preparing sync requests, starting with present item"); new ZoteroAPITask(getBaseContext()).execute(APIRequest.update(this.item)); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started), Toast.LENGTH_SHORT).show(); return true; case R.id.do_new: Bundle row = new Bundle(); row.putInt("position", -1); row.putString("itemKey", this.item.getKey()); removeDialog(DIALOG_CREATOR); this.b = row; showDialog(DIALOG_CREATOR); return true; case R.id.do_prefs: startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } }
14,295
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
CollectionActivity.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/CollectionActivity.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.gimranov.zandy.app.data.CollectionAdapter; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.DatabaseAccess; import com.gimranov.zandy.app.data.ItemCollection; import com.gimranov.zandy.app.task.APIEvent; import com.gimranov.zandy.app.task.APIRequest; import com.gimranov.zandy.app.task.ZoteroAPITask; public class CollectionActivity extends ListActivity { private static final String TAG = CollectionActivity.class.getSimpleName(); private ItemCollection collection; private Database db; final Handler handler = new Handler() { public void handleMessage(Message msg) { Log.d(TAG, "received message: " + msg.arg1); refreshView(); if (msg.arg1 == APIRequest.UPDATED_DATA) { //refreshView(); return; } if (msg.arg1 == APIRequest.QUEUED_MORE) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_queued_more, msg.arg2), Toast.LENGTH_SHORT).show(); return; } if (msg.arg1 == APIRequest.BATCH_DONE) { Application.getInstance().getBus().post(SyncEvent.COMPLETE); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_complete), Toast.LENGTH_SHORT).show(); return; } if (msg.arg1 == APIRequest.ERROR_UNKNOWN) { String desc = (msg.arg2 == 0) ? "" : " (" + msg.arg2 + ")"; Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_error) + desc, Toast.LENGTH_SHORT).show(); } } }; /** * Refreshes the current list adapter */ private void refreshView() { CollectionAdapter adapter = (CollectionAdapter) getListAdapter(); Cursor newCursor = (collection == null) ? create() : create(collection); adapter.changeCursor(newCursor); adapter.notifyDataSetChanged(); Log.d(TAG, "refreshing view on request"); } /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); db = new Database(this); setContentView(R.layout.collections); CollectionAdapter collectionAdapter; String collectionKey = getIntent().getStringExtra("com.gimranov.zandy.app.collectionKey"); if (collectionKey != null) { ItemCollection coll = ItemCollection.load(collectionKey, db); // We set the title to the current collection this.collection = coll; this.setTitle(coll.getTitle()); collectionAdapter = new CollectionAdapter(this, create(coll)); } else { this.setTitle(getResources().getString(R.string.collections)); collectionAdapter = new CollectionAdapter(this, create()); } setListAdapter(collectionAdapter); ListView lv = getListView(); lv.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { CollectionAdapter adapter = (CollectionAdapter) parent.getAdapter(); Cursor cur = adapter.getCursor(); // Place the cursor at the selected item if (cur.moveToPosition(position)) { // and open activity for the selected collection ItemCollection coll = ItemCollection.load(cur); if (coll != null && coll.getKey() != null && coll.getSubcollections(db).size() > 0) { Log.d(TAG, "Loading child collection with key: " + coll.getKey()); // We create and issue a specified intent with the necessary data Intent i = new Intent(getBaseContext(), CollectionActivity.class); i.putExtra("com.gimranov.zandy.app.collectionKey", coll.getKey()); startActivity(i); } else { Log.d(TAG, "Failed loading child collections for collection"); Toast.makeText(getApplicationContext(), getResources().getString(R.string.collection_no_subcollections), Toast.LENGTH_SHORT).show(); } } else { // failed to move cursor-- show a toast TextView tvTitle = (TextView) view.findViewById(R.id.collection_title); Toast.makeText(getApplicationContext(), getResources().getString(R.string.collection_cant_open, tvTitle.getText()), Toast.LENGTH_SHORT).show(); } return true; } }); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CollectionAdapter adapter = (CollectionAdapter) parent.getAdapter(); Cursor cur = adapter.getCursor(); // Place the cursor at the selected item if (cur.moveToPosition(position)) { // and replace the cursor with one for the selected collection ItemCollection coll = ItemCollection.load(cur); if (coll != null && coll.getKey() != null) { Intent i = new Intent(getBaseContext(), ItemActivity.class); if (coll.getSize() == 0) { // Send a message that we need to refresh the collection i.putExtra("com.gimranov.zandy.app.rerequest", true); } i.putExtra("com.gimranov.zandy.app.collectionKey", coll.getKey()); startActivity(i); } else { // collection loaded was null. why? Log.d(TAG, "Failed loading items for collection at position: " + position); return; } } else { // failed to move cursor-- show a toast TextView tvTitle = (TextView) view.findViewById(R.id.collection_title); Toast.makeText(getApplicationContext(), getResources().getString(R.string.collection_cant_open, tvTitle.getText()), Toast.LENGTH_SHORT).show(); return; } } }); } protected void onResume() { CollectionAdapter adapter = (CollectionAdapter) getListAdapter(); // XXX This may be too agressive-- fix if causes issues Cursor newCursor = (collection == null) ? create() : create(collection); adapter.changeCursor(newCursor); adapter.notifyDataSetChanged(); if (db == null) db = new Database(this); super.onResume(); } public void onDestroy() { CollectionAdapter adapter = (CollectionAdapter) getListAdapter(); Cursor cur = adapter.getCursor(); if (cur != null) cur.close(); if (db != null) db.close(); super.onDestroy(); handler.removeCallbacksAndMessages(null); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.zotero_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.do_sync: if (!ServerCredentials.check(getApplicationContext())) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return true; } APIRequest req = APIRequest.fetchCollections(new ServerCredentials(getApplicationContext())); req.setHandler(new APIEvent() { private int updates = 0; @Override public void onComplete(APIRequest request) { Message msg = handler.obtainMessage(); msg.arg1 = APIRequest.BATCH_DONE; handler.sendMessage(msg); Log.d(TAG, "fired oncomplete"); } @Override public void onUpdate(APIRequest request) { updates++; Message msg = handler.obtainMessage(); msg.arg1 = APIRequest.UPDATED_DATA; handler.sendMessage(msg); } @Override public void onError(APIRequest request, Exception exception) { Log.e(TAG, "APIException caught", exception); Message msg = handler.obtainMessage(); msg.arg1 = APIRequest.ERROR_UNKNOWN; handler.sendMessage(msg); } @Override public void onError(APIRequest request, int error) { Log.e(TAG, "API error caught"); Message msg = handler.obtainMessage(); msg.arg1 = APIRequest.ERROR_UNKNOWN; msg.arg2 = request.status; handler.sendMessage(msg); } }); ZoteroAPITask task = new ZoteroAPITask(getBaseContext()); task.setHandler(handler); task.execute(req); Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_collection), Toast.LENGTH_SHORT).show(); return true; case R.id.do_new: Log.d(TAG, "Can't yet make new collections"); // XXX no i18n for temporary string Toast.makeText(getApplicationContext(), "Sorry, new collection creation is not yet possible. Soon!", Toast.LENGTH_SHORT).show(); return true; case R.id.do_prefs: startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } /** * Gives a cursor for top-level collections */ public Cursor create() { return DatabaseAccess.INSTANCE.collections(db); } /** * Gives a cursor for child collections of a given parent */ public Cursor create(ItemCollection parent) { return DatabaseAccess.INSTANCE.collectionsForParent(db, parent); } }
12,674
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
Item.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/data/Item.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app.data; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.UUID; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import com.gimranov.zandy.app.ItemDisplayUtil; import com.gimranov.zandy.app.R; import com.gimranov.zandy.app.task.APIRequest; public class Item { private String id; private String title; private String type; private String owner; private String key; private String etag; private String year; private String children; private String creatorSummary; private JSONObject content; public String dbId; /** * Timestamp of last update from server */ private String timestamp; /** * Queue of dirty items to be sent to the server */ public static ArrayList<Item> queue = new ArrayList<Item>(); private static final String TAG = Item.class.getSimpleName(); /** * The next two types are arrays of information on items that we need * elsewhere */ public static final String[] ITEM_TYPES_EN = {"Artwork", "Audio Recording", "Bill", "Blog Post", "Book", "Book Section", "Case", "Computer Program", "Conference Paper", "Dictionary Entry", "Document", "E-mail", "Encyclopedia Article", "Film", "Forum Post", "Hearing", "Instant Message", "Interview", "Journal Article", "Letter", "Magazine Article", "Manuscript", "Map", "Newspaper Article", "Note", "Patent", "Podcast", "Presentation", "Radio Broadcast", "Report", "Statute", "TV Broadcast", "Thesis", "Video Recording", "Web Page"}; public static final String[] ITEM_TYPES = {"artwork", "audioRecording", "bill", "blogPost", "book", "bookSection", "case", "computerProgram", "conferencePaper", "dictionaryEntry", "document", "email", "encyclopediaArticle", "film", "forumPost", "hearing", "instantMessage", "interview", "journalArticle", "letter", "magazineArticle", "manuscript", "map", "newspaperArticle", "note", "patent", "podcast", "presentation", "radioBroadcast", "report", "statute", "tvBroadcast", "thesis", "videoRecording", "webpage"}; /** * Represents whether the item has been dirtied Dirty items have changes * that haven't been applied to the API */ public String dirty; public Item() { content = new JSONObject(); year = ""; creatorSummary = ""; key = ""; owner = ""; type = ""; title = ""; id = ""; etag = ""; timestamp = ""; children = ""; dirty = APIRequest.API_CLEAN; } public Item(Context c, String type) { this(); content = fieldsForItemType(c, type); key = "zandy:" + UUID.randomUUID().toString(); dirty = APIRequest.API_NEW; this.type = type; } public boolean equals(Item b) { if (b == null) return false; Log.d(TAG, "Comparing myself (" + key + ") to " + b.key); if (b.key == null || key == null) return false; if (b.key.equals(key)) return true; return false; } public String getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { if (title == null) title = ""; if (!this.title.equals(title)) { this.content.remove("title"); try { this.content.put("title", title); this.title = title; if (!APIRequest.API_CLEAN.equals(this.dirty)) this.dirty = APIRequest.API_DIRTY; } catch (JSONException e) { Log.e(TAG, "Exception setting title", e); } } } /* * These can't be propagated, so they only make sense before the item has * been saved to the API. */ public void setId(String id) { if (this.id != id) { this.id = id; } } public void setOwner(String owner) { if (this.owner != owner) { this.owner = owner; } } public void setKey(String key) { if (this.key != key) { this.key = key; } } public void setEtag(String etag) { if (this.etag != etag) { this.etag = etag; } } public String getOwner() { return owner; } public String getKey() { return key; } public JSONObject getContent() { return content; } public void setContent(JSONObject content) { if (!this.content.toString().equals(content.toString())) { if (!APIRequest.API_CLEAN.equals(this.dirty)) this.dirty = APIRequest.API_DIRTY; this.content = content; } } public void setContent(String content) throws JSONException { JSONObject con = new JSONObject(content); if (this.content != con) { if (!APIRequest.API_CLEAN.equals(this.dirty)) this.dirty = APIRequest.API_DIRTY; this.content = con; } } public void setType(String type) { this.type = type; } public void setChildren(String children) { this.children = children; } public String getChildren() { return children; } public String getType() { return type; } public String getEtag() { return etag; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getCreatorSummary() { return creatorSummary; } public void setCreatorSummary(String creatorSummary) { this.creatorSummary = creatorSummary; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } /** * Makes ArrayList<Bundle> from the present item. This was moved from * ItemDataActivity, but it's most likely to be used by such display * activities */ public ArrayList<Bundle> toBundleArray(Database db) { JSONObject itemContent = this.content; /* * Here we walk through the data and make Bundles to send to the * ArrayAdapter. There should be no real risk of JSON exceptions, since * the JSON was checked when initialized in the Item object. * * Each Bundle has two keys: "label" and "content" */ JSONArray fields = itemContent.names(); ArrayList<Bundle> rows = new ArrayList<Bundle>(); Bundle b; try { JSONArray values = itemContent.toJSONArray(fields); for (int i = 0; i < itemContent.length(); i++) { b = new Bundle(); /* Special handling for some types */ if (fields.getString(i).equals("tags")) { // We display the tags semicolon-delimited StringBuilder sb = new StringBuilder(); try { JSONArray tagArray = values.getJSONArray(i); for (int j = 0; j < tagArray.length(); j++) { sb.append(tagArray.getJSONObject(j) .getString("tag")); if (j < tagArray.length() - 1) sb.append("; "); } b.putString("content", sb.toString()); } catch (JSONException e) { // Fall back to empty Log.e(TAG, "Exception parsing tags, with input: " + values.getString(i), e); b.putString("content", ""); } } else if (fields.getString(i).equals("notes")) { // TODO handle notes continue; } else if (fields.getString(i).equals("creators")) { b.putString("content", String.valueOf(ItemDisplayUtil.INSTANCE.formatCreatorList(values.getJSONArray(i)))); } else if (fields.getString(i).equals("itemType")) { // We want to show the localized or human-readable type b.putString("content", Item.localizedStringForString(values .getString(i))); } else { // All other data is treated as just text b.putString("content", values.getString(i)); } b.putString("label", fields.getString(i)); b.putString("itemKey", getKey()); rows.add(b); } b = new Bundle(); int notes = 0; int atts = 0; ArrayList<Attachment> attachments = Attachment.forItem(this, db); for (Attachment a : attachments) { if ("note".equals(a.getType())) notes++; else atts++; } b.putInt("noteCount", notes); b.putInt("attachmentCount", atts); b.putString("content", "not-empty-so-sorting-works"); b.putString("label", "children"); b.putString("itemKey", getKey()); rows.add(b); b = new Bundle(); int collectionCount = ItemCollection.getCollectionCount(this, db); b.putInt("collectionCount", collectionCount); b.putString("content", "not-empty-so-sorting-works"); b.putString("label", "collections"); b.putString("itemKey", getKey()); rows.add(b); } catch (JSONException e) { /* * We could die here, but I'd rather not, since this shouldn't be * possible. */ Log.e(TAG, "JSON parse exception making bundles!", e); } /* We'd like to put these in a certain order, so let's try! */ Collections.sort(rows, new Comparator<Bundle>() { @Override public int compare(Bundle b1, Bundle b2) { boolean mt1 = (b1.containsKey("content") && b1.getString("content").equals("")); boolean mt2 = (b2.containsKey("content") && b2.getString("content").equals("")); /* Put the empty fields at the bottom, same order */ return ( Item.sortValueForLabel(b1.getString("label")) - Item.sortValueForLabel(b2.getString("label")) - (mt2 ? 300 : 0) + (mt1 ? 300 : 0)); } }); return rows; } /** * Makes ArrayList<Bundle> from the present item's tags Primarily for use * with TagActivity, but who knows? */ public ArrayList<Bundle> tagsToBundleArray() { JSONObject itemContent = this.content; /* * Here we walk through the data and make Bundles to send to the * ArrayAdapter. There should be no real risk of JSON exceptions, since * the JSON was checked when initialized in the Item object. * * Each Bundle has three keys: "itemKey", "tag", and "type" */ ArrayList<Bundle> rows = new ArrayList<Bundle>(); Bundle b = new Bundle(); if (!itemContent.has("tags")) { return rows; } try { JSONArray tags = itemContent.getJSONArray("tags"); Log.d(TAG, tags.toString()); for (int i = 0; i < tags.length(); i++) { b = new Bundle(); // Type is not always specified, but we try to get it // and fall back to 0 when missing. Log.d(TAG, tags.getJSONObject(i).toString()); if (tags.getJSONObject(i).has("type")) b.putInt("type", tags.getJSONObject(i).optInt("type", 0)); b.putString("tag", tags.getJSONObject(i).optString("tag")); b.putString("itemKey", this.key); rows.add(b); } } catch (JSONException e) { Log.e(TAG, "JSON exception caught in tag bundler: ", e); } return rows; } /** * Makes ArrayList<Bundle> from the present item's creators. Primarily for * use with CreatorActivity, but who knows? */ public ArrayList<Bundle> creatorsToBundleArray() { JSONObject itemContent = this.content; /* * Here we walk through the data and make Bundles to send to the * ArrayAdapter. There should be no real risk of JSON exceptions, since * the JSON was checked when initialized in the Item object. * * Each Bundle has six keys: "itemKey", "name", "firstName", "lastName", * "creatorType", "position" * * Field mode is encoded implicitly -- if either of "firstName" and * "lastName" is non-empty ("") or non-null, we treat this as a * two-field name. key The field "name" is the one-field name if the * others are empty, otherwise it's a display version of the two-field * name. */ ArrayList<Bundle> rows = new ArrayList<Bundle>(); Bundle b = new Bundle(); if (!itemContent.has("creators")) { return rows; } try { JSONArray creators = itemContent.getJSONArray("creators"); Log.d(TAG, creators.toString()); for (int i = 0; i < creators.length(); i++) { b = new Bundle(); Log.d(TAG, creators.getJSONObject(i).toString()); b.putString("creatorType", creators.getJSONObject(i).getString( "creatorType")); b.putString("firstName", creators.getJSONObject(i).optString( "firstName")); b.putString("lastName", creators.getJSONObject(i).optString( "lastName")); b.putString("name", creators.getJSONObject(i).optString( "name")); // If name is empty, fill with the others if (b.getString("name").equals("")) b.putString("name", b.getString("firstName") + " " + b.getString("lastName")); b.putString("itemKey", this.key); b.putInt("position", i); rows.add(b); } } catch (JSONException e) { Log.e(TAG, "JSON exception caught in creator bundler: ", e); } return rows; } /** * Saves the item's current state. Marking dirty should happen before this */ public void save(Database db) { Item existing = load(key, db); if (dbId == null && existing == null) { String[] args = {title, key, type, year, creatorSummary, content.toString(), etag, dirty, timestamp, children}; Cursor cur = db .rawQuery( "insert into items (item_title, item_key, item_type, item_year, item_creator, item_content, etag, dirty, timestamp, item_children) " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", args); if (cur != null) cur.close(); Item fromDB = load(key, db); dbId = fromDB.dbId; } else { if (dbId == null) dbId = existing.dbId; String[] args = {title, type, year, creatorSummary, content.toString(), etag, dirty, timestamp, key, children, dbId}; Log.i(TAG, "Updating existing item"); Cursor cur = db .rawQuery( "update items set item_title=?, item_type=?, item_year=?," + " item_creator=?, item_content=?, etag=?, dirty=?," + " timestamp=?, item_key=?, item_children=? " + " where _id=?", args); if (cur != null) cur.close(); } } /** * Deletes an item from the database, keeping a record of it in the deleteditems table * We will then send out delete requests via the API to propagate the deletion */ public void delete(Database db) { String[] args = {dbId}; db.rawQuery("delete from items where _id=?", args); db.rawQuery("delete from itemtocreators where item_id=?", args); db.rawQuery("delete from itemtocollections where item_id=?", args); ArrayList<Attachment> atts = Attachment.forItem(this, db); for (Attachment a : atts) { a.delete(db); } // Don't prepare deletion requests for unsynced new items if (!APIRequest.API_NEW.equals(dirty)) { String[] args2 = {key, etag}; db.rawQuery("insert into deleteditems (item_key, etag) values (?, ?)", args2); } } /** * Loads and returns an Item for the specified item key Returns null when no * match is found for the specified itemKey * * @param itemKey * @return */ public static Item load(String itemKey, Database db) { String[] cols = Database.ITEMCOLS; String[] args = {itemKey}; Cursor cur = db.query("items", cols, "item_key=?", args, null, null, null, null); Item item = load(cur); if (cur != null) cur.close(); return item; } /** * Loads and returns an Item for the specified item DB ID * Returns null when no match is found for the specified DB ID * * @param itemDbId * @return */ public static Item loadDbId(String itemDbId, Database db) { String[] cols = Database.ITEMCOLS; String[] args = {itemDbId}; Cursor cur = db.query("items", cols, "_id=?", args, null, null, null, null); Item item = load(cur); if (cur != null) cur.close(); return item; } /** * Loads an item from the specified Cursor, where the cursor was created * using the recommended query in Database.ITEMCOLS * <p> * Does not close the cursor! * * @param cur * @return An Item object for the current row of the Cursor */ public static Item load(Cursor cur) { Item item = new Item(); if (cur == null) { Log.e(TAG, "Didn't find an item for update"); return null; } // {"item_title", "item_type", "item_content", "etag", "dirty", "_id", // "item_key", "item_year", "item_creator", "timestamp", "item_children"}; item.setTitle(cur.getString(0)); item.setType(cur.getString(1)); try { item.setContent(cur.getString(2)); } catch (JSONException e) { Log.e(TAG, "JSON error loading item", e); } item.setEtag(cur.getString(3)); item.dirty = cur.getString(4); item.dbId = cur.getString(5); item.setKey(cur.getString(6)); item.setYear(cur.getString(7)); item.setCreatorSummary(cur.getString(8)); item.setTimestamp(cur.getString(9)); item.children = cur.getString(10); if (item.children == null) item.children = ""; return item; } /** * Static method for modification of items in the database */ public static void set(String itemKey, String label, String content, Database db) { // Load the item Item item = load(itemKey, db); // Don't set anything to null if (content == null) content = ""; switch (label) { case "title": item.title = content; break; case "itemType": item.type = content; break; case "children": item.children = content; break; case "date": item.year = content.replaceAll("^.*?(\\d{4}).*$", "$1"); break; } try { item.content.put(label, content); } catch (JSONException e) { Log .e(TAG, "Caught JSON exception when we tried to modify the JSON content"); } item.dirty = APIRequest.API_DIRTY; item.save(db); item = load(itemKey, db); } /** * Static method for setting tags Add a tag, change a tag, or replace an * existing tag. If newTag is empty ("") or null, the old tag is simply * deleted. * <p> * If oldTag is empty or null, the new tag is appended. * <p> * We make it into a user tag, which the desktop client does as well. */ public static void setTag(String itemKey, String oldTag, String newTag, int type, Database db) { // Load the item Item item = load(itemKey, db); try { JSONArray tags = item.content.getJSONArray("tags"); JSONArray newTags = new JSONArray(); Log.d(TAG, "Old: " + tags.toString()); // Allow adding a new tag if (oldTag == null || oldTag.equals("")) { Log.d(TAG, "Adding new tag: " + newTag); newTags = tags.put(new JSONObject().put("tag", newTag).put( "type", type)); } else { // In other cases, we're removing or replacing a tag for (int i = 0; i < tags.length(); i++) { if (tags.getJSONObject(i).getString("tag").equals(oldTag)) { if (newTag != null && !newTag.equals("")) newTags.put(new JSONObject().put("tag", newTag) .put("type", type)); else Log.d(TAG, "Tag removed: " + oldTag); } else { newTags.put(tags.getJSONObject(i)); } } } item.content.put("tags", newTags); } catch (JSONException e) { Log.e(TAG, "Caught JSON exception when we tried to modify the JSON content", e); } item.dirty = APIRequest.API_DIRTY; item.save(db); } /** * Static method for setting creators * <p> * Add, change, or replace a creator. If creator is null, the old creator is * simply deleted. * <p> * If position is -1, the new creator is appended. */ public static void setCreator(String itemKey, Creator c, int position, Database db) { // Load the item Item item = load(itemKey, db); try { JSONArray creators = item.content.getJSONArray("creators"); JSONArray newCreators = new JSONArray(); Log.d(TAG, "Old: " + creators.toString()); // Allow adding a new tag if (position < 0) { newCreators = creators.put(c.toJSON()); } else { if (c == null) { // we have a deletion for (int i = 0; i < creators.length(); i++) { if (i == position) continue; // skip the deleted one newCreators.put(creators.get(i)); } } else { newCreators = creators.put(position, c.toJSON()); } } StringBuilder sb = new StringBuilder(); for (int j = 0; j < creators.length(); j++) { if (j > 0) sb.append(", "); sb.append(((JSONObject) creators.get(j)).optString("lastName", "")); } item.creatorSummary = sb.toString(); item.content.put("creators", newCreators); Log.d(TAG, "New: " + newCreators.toString()); } catch (JSONException e) { Log.e(TAG, "Caught JSON exception when we tried to modify the JSON content"); } item.dirty = APIRequest.API_DIRTY; item.save(db); } /** * Identifies dirty items in the database and queues them for syncing */ public static void queue(Database db) { Log.d(TAG, "Clearing item dirty queue before repopulation"); queue.clear(); Item item; String[] cols = Database.ITEMCOLS; String[] args = {APIRequest.API_CLEAN}; Cursor cur = db.query("items", cols, "dirty!=?", args, null, null, null, null); if (cur == null) { Log.d(TAG, "No dirty items found in database"); queue.clear(); return; } do { Log.d(TAG, "Adding item to dirty queue"); item = load(cur); queue.add(item); } while (cur.moveToNext()); cur.close(); } /** * Maps types to the resources providing images for them. * * @param type * @return A resource representing an image for the item or other type */ public static int resourceForType(String type) { if (type == null || type.equals("")) return R.drawable.page_white; // TODO Complete this list switch (type) { case "artwork": return R.drawable.picture; // if (type.equals("audioRecording")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("bill")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("blogPost")) return // R.drawable.ic_menu_close_clear_cancel; case "book": return R.drawable.book; case "bookSection": return R.drawable.book_open; // if (type.equals("case")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("computerProgram")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("conferencePaper")) return // R.drawable.ic_menu_close_clear_cancel; case "dictionaryEntry": return R.drawable.page_white_width; case "document": return R.drawable.page_white; // if (type.equals("email")) return // R.drawable.ic_menu_close_clear_cancel; case "encyclopediaArticle": return R.drawable.page_white_text_width; case "film": return R.drawable.film; // if (type.equals("forumPost")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("hearing")) return // R.drawable.ic_menu_close_clear_cancel; case "instantMessage": return R.drawable.comment; // if (type.equals("interview")) return // R.drawable.ic_menu_close_clear_cancel; case "journalArticle": return R.drawable.page_white_text; case "letter": return R.drawable.email; case "magazineArticle": return R.drawable.layout; case "manuscript": return R.drawable.script; case "map": return R.drawable.map; case "newspaperArticle": return R.drawable.newspaper; // if (type.equals("patent")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("podcast")) return // R.drawable.ic_menu_close_clear_cancel; case "presentation": return R.drawable.page_white_powerpoint; // if (type.equals("radioBroadcast")) return // R.drawable.ic_menu_close_clear_cancel; case "report": return R.drawable.report; // if (type.equals("statute")) return // R.drawable.ic_menu_close_clear_cancel; case "thesis": return R.drawable.report_user; case "tvBroadcast": return R.drawable.television; case "videoRecording": return R.drawable.film; case "webpage": return R.drawable.page; // Not item types, but still something case "collection": return R.drawable.folder; case "application/pdf": return R.drawable.page_white_acrobat; case "note": return R.drawable.note; // if (type.equals("snapshot")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("link")) return // R.drawable.ic_menu_close_clear_cancel; // Return something generic if all else fails default: return R.drawable.page_white; } } /** * Provides the human-readable equivalent for strings * <p> * TODO This should pull the data from the API as a fallback, but we will * hard-code the list for now * * @param s * @return */ // XXX i18n public static String localizedStringForString(String s) { if (s == null) { Log.e(TAG, "Received null string in localizedStringForString"); return ""; } // Item fields from the API switch (s) { case "numPages": return "# of Pages"; case "numberOfVolumes": return "# of Volumes"; case "abstractNote": return "Abstract"; case "accessDate": return "Accessed"; case "applicationNumber": return "Application Number"; case "archive": return "Archive"; case "artworkSize": return "Artwork Size"; case "assignee": return "Assignee"; case "billNumber": return "Bill Number"; case "blogTitle": return "Blog Title"; case "bookTitle": return "Book Title"; case "callNumber": return "Call Number"; case "caseName": return "Case Name"; case "code": return "Code"; case "codeNumber": return "Code Number"; case "codePages": return "Code Pages"; case "codeVolume": return "Code Volume"; case "committee": return "Committee"; case "company": return "Company"; case "conferenceName": return "Conference Name"; case "country": return "Country"; case "court": return "Court"; case "DOI": return "DOI"; case "date": return "Date"; case "dateDecided": return "Date Decided"; case "dateEnacted": return "Date Enacted"; case "dictionaryTitle": return "Dictionary Title"; case "distributor": return "Distributor"; case "docketNumber": return "Docket Number"; case "documentNumber": return "Document Number"; case "edition": return "Edition"; case "encyclopediaTitle": return "Encyclopedia Title"; case "episodeNumber": return "Episode Number"; case "extra": return "Extra"; case "audioFileType": return "File Type"; case "filingDate": return "Filing Date"; case "firstPage": return "First Page"; case "audioRecordingFormat": return "Format"; case "videoRecordingFormat": return "Format"; case "forumTitle": return "Forum/Listserv Title"; case "genre": return "Genre"; case "history": return "History"; case "ISBN": return "ISBN"; case "ISSN": return "ISSN"; case "institution": return "Institution"; case "issue": return "Issue"; case "issueDate": return "Issue Date"; case "issuingAuthority": return "Issuing Authority"; case "journalAbbreviation": return "Journal Abbr"; case "label": return "Label"; case "language": return "Language"; case "programmingLanguage": return "Language"; case "legalStatus": return "Legal Status"; case "legislativeBody": return "Legislative Body"; case "libraryCatalog": return "Library Catalog"; case "archiveLocation": return "Loc. in Archive"; case "interviewMedium": return "Medium"; case "artworkMedium": return "Medium"; case "meetingName": return "Meeting Name"; case "nameOfAct": return "Name of Act"; case "network": return "Network"; case "pages": return "Pages"; case "patentNumber": return "Patent Number"; case "place": return "Place"; case "postType": return "Post Type"; case "priorityNumbers": return "Priority Numbers"; case "proceedingsTitle": return "Proceedings Title"; case "programTitle": return "Program Title"; case "publicLawNumber": return "Public Law Number"; case "publicationTitle": return "Publication"; case "publisher": return "Publisher"; case "references": return "References"; case "reportNumber": return "Report Number"; case "reportType": return "Report Type"; case "reporter": return "Reporter"; case "reporterVolume": return "Reporter Volume"; case "rights": return "Rights"; case "runningTime": return "Running Time"; case "scale": return "Scale"; case "section": return "Section"; case "series": return "Series"; case "seriesNumber": return "Series Number"; case "seriesText": return "Series Text"; case "seriesTitle": return "Series Title"; case "session": return "Session"; case "shortTitle": return "Short Title"; case "studio": return "Studio"; case "subject": return "Subject"; case "system": return "System"; case "title": return "Title"; case "thesisType": return "Type"; case "mapType": return "Type"; case "manuscriptType": return "Type"; case "letterType": return "Type"; case "presentationType": return "Type"; case "url": return "URL"; case "university": return "University"; case "version": return "Version"; case "volume": return "Volume"; case "websiteTitle": return "Website Title"; case "websiteType": return "Website Type"; // Item fields not in the API case "creators": return "Creators"; case "tags": return "Tags"; case "itemType": return "Item Type"; case "children": return "Attachments"; case "collections": return "Collections"; // And item types case "artwork": return "Artwork"; case "audioRecording": return "Audio Recording"; case "bill": return "Bill"; case "blogPost": return "Blog Post"; case "book": return "Book"; case "bookSection": return "Book Section"; case "case": return "Case"; case "computerProgram": return "Computer Program"; case "conferencePaper": return "Conference Paper"; case "dictionaryEntry": return "Dictionary Entry"; case "document": return "Document"; case "email": return "E-mail"; case "encyclopediaArticle": return "Encyclopedia Article"; case "film": return "Film"; case "forumPost": return "Forum Post"; case "hearing": return "Hearing"; case "instantMessage": return "Instant Message"; case "interview": return "Interview"; case "journalArticle": return "Journal Article"; case "letter": return "Letter"; case "magazineArticle": return "Magazine Article"; case "manuscript": return "Manuscript"; case "map": return "Map"; case "newspaperArticle": return "Newspaper Article"; case "note": return "Note"; case "patent": return "Patent"; case "podcast": return "Podcast"; case "presentation": return "Presentation"; case "radioBroadcast": return "Radio Broadcast"; case "report": return "Report"; case "statute": return "Statute"; case "tvBroadcast": return "TV Broadcast"; case "thesis": return "Thesis"; case "videoRecording": return "Video Recording"; case "webpage": return "Web Page"; // Creator types case "artist": return "Artist"; case "attorneyAgent": return "Attorney/Agent"; case "author": return "Author"; case "bookAuthor": return "Book Author"; case "cartographer": return "Cartographer"; case "castMember": return "Cast Member"; case "commenter": return "Commenter"; case "composer": return "Composer"; case "contributor": return "Contributor"; case "cosponsor": return "Cosponsor"; case "counsel": return "Counsel"; case "director": return "Director"; case "editor": return "Editor"; case "guest": return "Guest"; case "interviewee": return "Interview With"; case "interviewer": return "Interviewer"; case "inventor": return "Inventor"; case "performer": return "Performer"; case "podcaster": return "Podcaster"; case "presenter": return "Presenter"; case "producer": return "Producer"; case "programmer": return "Programmer"; case "recipient": return "Recipient"; case "reviewedAuthor": return "Reviewed Author"; case "scriptwriter": return "Scriptwriter"; case "seriesEditor": return "Series Editor"; case "sponsor": return "Sponsor"; case "translator": return "Translator"; case "wordsBy": return "Words By"; // Or just leave it the way it is default: return s; } } /** * Gets creator types, localized, for specified item type. * * @param s * @return */ public static String[] localizedCreatorTypesForItemType(String s) { String[] types = creatorTypesForItemType(s); String[] local = new String[types.length]; for (int i = 0; i < types.length; i++) { local[i] = localizedStringForString(types[i]); } return local; } /** * Gets valid creator types for the specified item type. Would be good to * have this draw from the API, but probably easier to hard-code the whole * mess. * <p> * Remapping of creator types on item type conversion is a separate issue. * * @param s itemType to provide creatorTypes for * @return */ public static String[] creatorTypesForItemType(String s) { Log.d(TAG, "Getting creator types for item type: " + s); switch (s) { case "artwork": return new String[]{"artist", "contributor"}; case "audioRecording": return new String[]{"performer", "composer", "contributor", "wordsBy"}; case "bill": return new String[]{"sponsor", "contributor", "cosponsor"}; case "blogPost": return new String[]{"author", "commenter", "contributor"}; case "book": return new String[]{"author", "contributor", "editor", "seriesEditor", "translator"}; case "bookSection": return new String[]{"author", "bookAuthor", "contributor", "editor", "seriesEditor", "translator"}; case "case": return new String[]{"author", "contributor", "counsel"}; case "computerProgram": return new String[]{"programmer", "contributor"}; case "conferencePaper": return new String[]{"author", "contributor", "editor", "seriesEditor", "translator"}; case "dictionaryEntry": return new String[]{"author", "contributor", "editor", "seriesEditor", "translator"}; case "document": return new String[]{"author", "contributor", "editor", "reviewedAuthor", "translator"}; case "email": return new String[]{"author", "contributor", "recipient"}; case "encyclopediaArticle": return new String[]{"author", "contributor", "editor", "seriesEditor", "translator"}; case "film": return new String[]{"director", "contributor", "producer", "scriptwriter"}; case "forumPost": return new String[]{"author", "contributor"}; case "hearing": return new String[]{"contributor"}; case "instantMessage": return new String[]{"author", "contributor", "recipient"}; case "interview": return new String[]{"interviewee", "contributor", "interviewer", "translator"}; case "journalArticle": return new String[]{"author", "contributor", "editor", "reviewedAuthor", "translator"}; case "letter": return new String[]{"author", "contributor", "recipient"}; case "magazineArticle": return new String[]{"author", "contributor", "reviewedAuthor", "translator"}; case "manuscript": return new String[]{"author", "contributor", "translator"}; case "map": return new String[]{"cartographer", "contributor", "seriesEditor"}; case "newspaperArticle": return new String[]{"author", "contributor", "reviewedAuthor", "translator"}; case "patent": return new String[]{"inventor", "attorneyAgent", "contributor"}; case "podcast": return new String[]{"podcaster", "contributor", "guest"}; case "presentation": return new String[]{"presenter", "contributor"}; case "radioBroadcast": return new String[]{"director", "castMember", "contributor", "guest", "producer", "scriptwriter"}; case "report": return new String[]{"author", "contributor", "seriesEditor", "translator"}; case "statute": return new String[]{"author", "contributor"}; case "tvBroadcast": return new String[]{"director", "castMember", "contributor", "guest", "producer", "scriptwriter"}; case "thesis": return new String[]{"author", "contributor"}; case "videoRecording": return new String[]{"director", "castMember", "contributor", "producer", "scriptwriter"}; case "webpage": return new String[]{"author", "contributor", "translator"}; default: return null; } } /** * Gets JSON template for the specified item type. * <p> * Remapping of fields on item type conversion is a separate issue. * * @param c Current context, needed to fetch string resources with * templates * @param s itemType to provide fields for * @return */ private static JSONObject fieldsForItemType(Context c, String s) { JSONObject template = new JSONObject(); String json = ""; try { // And item types switch (s) { case "artwork": json = c.getString(R.string.template_artwork); break; case "audioRecording": json = c.getString(R.string.template_audioRecording); break; case "bill": json = c.getString(R.string.template_bill); break; case "blogPost": json = c.getString(R.string.template_blogPost); break; case "book": json = c.getString(R.string.template_book); break; case "bookSection": json = c.getString(R.string.template_bookSection); break; case "case": json = c.getString(R.string.template_case); break; case "computerProgram": json = c.getString(R.string.template_computerProgram); break; case "conferencePaper": json = c.getString(R.string.template_conferencePaper); break; case "dictionaryEntry": json = c.getString(R.string.template_dictionaryEntry); break; case "document": json = c.getString(R.string.template_document); break; case "email": json = c.getString(R.string.template_email); break; case "encyclopediaArticle": json = c.getString(R.string.template_encyclopediaArticle); break; case "film": json = c.getString(R.string.template_film); break; case "forumPost": json = c.getString(R.string.template_forumPost); break; case "hearing": json = c.getString(R.string.template_hearing); break; case "instantMessage": json = c.getString(R.string.template_instantMessage); break; case "interview": json = c.getString(R.string.template_interview); break; case "journalArticle": json = c.getString(R.string.template_journalArticle); break; case "letter": json = c.getString(R.string.template_letter); break; case "magazineArticle": json = c.getString(R.string.template_magazineArticle); break; case "manuscript": json = c.getString(R.string.template_manuscript); break; case "map": json = c.getString(R.string.template_map); break; case "newspaperArticle": json = c.getString(R.string.template_newspaperArticle); break; case "note": json = c.getString(R.string.template_note); break; case "patent": json = c.getString(R.string.template_patent); break; case "podcast": json = c.getString(R.string.template_podcast); break; case "presentation": json = c.getString(R.string.template_presentation); break; case "radioBroadcast": json = c.getString(R.string.template_radioBroadcast); break; case "report": json = c.getString(R.string.template_report); break; case "statute": json = c.getString(R.string.template_statute); break; case "tvBroadcast": json = c.getString(R.string.template_tvBroadcast); break; case "thesis": json = c.getString(R.string.template_thesis); break; case "videoRecording": json = c.getString(R.string.template_videoRecording); break; case "webpage": json = c.getString(R.string.template_webpage); break; } template = new JSONObject(json); JSONArray names = template.names(); for (int i = 0; i < names.length(); i++) { if (names.getString(i).equals("itemType")) continue; if (names.getString(i).equals("tags")) continue; if (names.getString(i).equals("notes")) continue; if (names.getString(i).equals("creators")) { JSONArray roles = template.getJSONArray("creators"); for (int j = 0; j < roles.length(); j++) { roles.put(j, roles.getJSONObject(j).put("firstName", "").put("lastName", "")); } template.put("creators", roles); continue; } template.put(names.getString(i), ""); } Log.d(TAG, "Got JSON template: " + template.toString(4)); } catch (JSONException e) { Log.e(TAG, "JSON exception parsing item template", e); } return template; } public static int sortValueForLabel(String s) { // First type, and the bare minimum... switch (s) { case "itemType": return 0; case "title": return 1; case "creators": return 2; case "date": return 3; // Then container titles, with one value case "publicationTitle": return 5; case "blogTitle": return 5; case "bookTitle": return 5; case "dictionaryTitle": return 5; case "encyclopediaTitle": return 5; case "forumTitle": return 5; case "proceedingsTitle": return 5; case "programTitle": return 5; case "websiteTitle": return 5; case "meetingName": return 5; // Abstracts case "abstractNote": return 10; // Publishing data case "publisher": return 12; case "place": return 13; // Series, publication numbers case "pages": return 14; case "numPages": return 16; case "series": return 16; case "seriesTitle": return 17; case "seriesText": return 18; case "volume": return 19; case "numberOfVolumes": return 20; case "issue": return 20; case "section": return 21; case "publicationNumber": return 22; case "edition": return 23; // Locators case "DOI": return 50; case "archive": return 51; case "archiveLocation": return 52; case "ISBN": return 53; case "ISSN": return 54; case "libraryCatalog": return 55; case "callNumber": return 56; // Housekeeping and navigation, at the very end case "attachments": return 250; case "tags": return 251; case "related": return 252; default: return 200; } } }
56,282
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
Attachment.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/data/Attachment.java
package com.gimranov.zandy.app.data; import java.util.ArrayList; import java.util.Locale; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import android.content.SharedPreferences; import android.database.Cursor; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.util.Log; import android.webkit.MimeTypeMap; import com.gimranov.zandy.app.task.APIRequest; public class Attachment { public String key; public String parentKey; public String etag; public int status; public String dbId; public String title; public String filename; public String url; /* { "itemType": "attachment", "linkMode": "imported_url", "title": "S00193ED1V01Y200905CAC006.pdf", "accessDate": "2017-10-10 04:36:27", "url": "http:\/\/www.morganclaypool.com\/doi\/pdf\/10.2200\/S00193ED1V01Y200905CAC006", "note": "", "contentType": "application\/pdf", "charset": "", "filename": "S00193ED1V01Y200905CAC006.pdf", "md5": null, "mtime": null, "tags": [] } */ /** * Queue of attachments that need to be synced, because they're dirty */ public static ArrayList<Attachment> queue; /** * APIRequest.API_DIRTY means that we'll try to push this version up to the server */ public String dirty; /** * Zotero's JSON format for attachment / child information * <p> * linkMode: O = file attachment, in ZFS? * 1 = link attachment? */ public JSONObject content; private static final String TAG = Attachment.class.getSimpleName(); public static final int AVAILABLE = 1; public static final int LOCAL = 2; public static final int UNKNOWN = 3; public static final String MODE_LINKED_URL = "linked_url"; public static final String MODE_LINKED_FILE = "linked_file"; public static final String MODE_IMPORTED_URL = "imported_url"; public static final String MODE_IMPORTED_FILE = "imported_file"; public Attachment() { if (queue == null) queue = new ArrayList<>(); parentKey = title = filename = url = etag = dirty = ""; status = UNKNOWN; content = new JSONObject(); } public Attachment(String type, String parentKey) { this(); content = new JSONObject(); try { content.put("itemType", type); } catch (JSONException e) { Log.d(TAG, "JSON exception caught setting itemType in Attachment constructor", e); } key = UUID.randomUUID().toString(); this.parentKey = parentKey; dirty = APIRequest.API_NEW; } public String getType() { String type = ""; try { type = content.getString("itemType"); if (type.equals("attachment")) { if (content.has("mimeType")) { type = content.getString("mimeType"); } else if (content.has("contentType")) { type = content.getString("contentType"); } } if (type.equals("note")) type = "note"; } catch (JSONException e) { Log.e(TAG, "JSON exception parsing attachment content: " + content.toString(), e); } return type; } @Nullable public String getOriginalFilename() { return content.optString("filename"); } public String getCanonicalStorageName() { String originalFilename = getOriginalFilename(); String sanitized = (originalFilename == null ? title : originalFilename).replace(' ', '_'); // If no 1-6-character extension, try to add one using MIME type if (!sanitized.matches(".*\\.[a-zA-Z0-9]{1,6}$")) { String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(getType()); if (extension != null) sanitized = sanitized + "." + extension; } return sanitized.replaceFirst("^(.*?)(\\.[^.]*)?$", "$1" + "_" + key + "$2"); } @NonNull public String getContentType() { String mimeType = content.optString("mimeType"); if (mimeType != null && !mimeType.isEmpty()) { return mimeType; } String contentType = content.optString("contentType"); if (contentType != null && !contentType.isEmpty()) { return contentType; } Log.w(TAG, "Could not determine content type for " + title + ", assumed PDF"); return "application/pdf"; } public boolean isDownloadable() { String linkMode = content.optString("linkMode"); return (MODE_IMPORTED_FILE.equals(linkMode)) || (MODE_IMPORTED_URL.equals(linkMode)); } public String getDownloadUrlWebDav(SharedPreferences settings) { //urlstring = "https://dfs.humnet.ucla.edu/home/ajlyon/zotero/223RMC7C.zip"; //urlstring = "http://www.gimranov.com/research/zotero/223RMC7C.zip"; return settings.getString("webdav_path", "") + "/" + key + ".zip"; } public String getDownloadUrlZfs(SharedPreferences settings) { if (url == null || url.isEmpty()) { return String.format(Locale.US, "https://api.zotero.org/users/%s/items/%s/file?key=%s", settings.getString("user_id", ""), key, settings.getString("user_key", "")); } else { return url + "?key=" + settings.getString("user_key", ""); } } public void setNoteText(String text) { try { content.put("note", text); } catch (JSONException e) { Log.e(TAG, "JSON exception setting note text", e); } } public void save(Database db) { Attachment existing = load(key, db); if (dbId == null && existing == null) { Log.d(TAG, "Saving new, with status: " + status); String[] args = {key, parentKey, title, filename, url, Integer.toString(status), etag, dirty, content.toString()}; Cursor cur = db .rawQuery( "insert into attachments (attachment_key, item_key, title, filename, url, status, etag, dirty, content) " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?)", args); if (cur != null) cur.close(); Attachment fromDB = load(key, db); dbId = fromDB.dbId; } else { Log.d(TAG, "Updating attachment, with status: " + status + " and fn: " + filename); if (dbId == null) dbId = existing.dbId; String[] args = {key, parentKey, title, filename, url, Integer.toString(status), etag, dirty, content.toString(), dbId}; Cursor cur = db .rawQuery( "update attachments set attachment_key=?, item_key=?, title=?," + " filename=?, url=?, status=?, etag=?, dirty=?, " + " content=? " + " where _id=?", args); if (cur != null) cur.close(); } db.close(); } /** * Deletes an attachment from the database, keeping a record of it in the deleteditems table * We will then send out delete requests via the API to propagate the deletion */ public void delete(Database db) { String[] args = {dbId}; db.rawQuery("delete from attachments where _id=?", args); // Don't prepare deletion requests for unsynced new attachments if (!APIRequest.API_NEW.equals(dirty)) { String[] args2 = {key, etag}; db.rawQuery("insert into deleteditems (item_key, etag) values (?, ?)", args2); } } /** * Identifies dirty items in the database and queues them for syncing */ public static void queue(Database db) { if (queue == null) { // Initialize the queue if necessary queue = new ArrayList<>(); } Log.d(TAG, "Clearing attachment dirty queue before repopulation"); queue.clear(); Attachment attachment; String[] cols = Database.ATTCOLS; String[] args = {APIRequest.API_CLEAN}; Cursor cur = db.query("attachments", cols, "dirty != ?", args, null, null, null, null); if (cur == null) { Log.d(TAG, "No dirty attachments found in database"); queue.clear(); return; } do { Log.d(TAG, "Adding attachment to dirty queue"); attachment = load(cur); queue.add(attachment); } while (cur.moveToNext()); cur.close(); } /** * Get an Attachment from the current cursor position. * <p> * Does not close cursor. */ public static Attachment load(Cursor cur) { if (cur == null) return null; Attachment a = new Attachment(); a.dbId = cur.getString(0); a.key = cur.getString(1); a.parentKey = cur.getString(2); a.title = cur.getString(3); a.filename = cur.getString(4); a.url = cur.getString(5); try { a.status = cur.getInt(6); } catch (Exception e) { a.status = UNKNOWN; } a.etag = cur.getString(7); a.dirty = cur.getString(8); try { a.content = new JSONObject(cur.getString(9)); } catch (JSONException e) { Log.e(TAG, "Caught JSON exception loading attachment from db", e); } return a; } public static Attachment load(String key, Database db) { String[] cols = Database.ATTCOLS; String[] args = {key}; Cursor cur = db.query("attachments", cols, "attachment_key=?", args, null, null, null, null); Attachment a = load(cur); if (cur != null) cur.close(); return a; } /** * Provides ArrayList of Attachments for a given Item * Useful for powering UI * <p> * We can also use this to trigger background syncs */ public static ArrayList<Attachment> forItem(Item item, Database db) { ArrayList<Attachment> list = new ArrayList<Attachment>(); if (item.dbId == null) item.save(db); Log.d(TAG, "Looking for the kids of an item with key: " + item.getKey()); String[] cols = {"_id", "attachment_key", "item_key", "title", "filename", "url", "status", "etag", "dirty", "content"}; String[] args = {item.getKey()}; Cursor cursor = db.query("attachments", cols, "item_key=?", args, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { Attachment a = Attachment.load(cursor); list.add(a); cursor.moveToNext(); } cursor.close(); } else { Log.d(TAG, "Cursor was null, so we still didn't get attachments for the item!"); } return list; } }
11,113
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
Database.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/data/Database.java
package com.gimranov.zandy.app.data; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.util.Log; public class Database { public static final String TAG = Database.class.getSimpleName(); public static final String[] ITEMCOLS = {"item_title", "item_type", "item_content", "etag", "dirty", "_id", "item_key", "item_year", "item_creator", "timestamp", "item_children"}; public static final String[] COLLCOLS = {"collection_name", "collection_parent", "etag", "dirty", "_id", "collection_key", "collection_size", "timestamp"}; static final String[] ATTCOLS = {"_id", "attachment_key", "item_key", "title", "filename", "url", "status", "etag", "dirty", "content"}; public static final String[] REQUESTCOLS = {"_id", "uuid", "type", "query", "key", "method", "disposition", "if_match", "update_key", "update_type", "created", "last_attempt", "status", "body"}; // the database version; increment to call update private static final int DATABASE_VERSION = 20; private static final String DATABASE_NAME = "Zotero"; private final DatabaseOpenHelper mDatabaseOpenHelper; public Database(Context context) { mDatabaseOpenHelper = DatabaseOpenHelper.getHelper(context); } /** * Deletes the entire contents of the database by dropping the tables and re-adding them */ public void resetAllData() { Log.d(TAG, "Dropping tables to reset database"); String[] tables = {"collections", "items", "creators", "children", "itemtocreators", "itemtocollections", "deleteditems", "attachments", "apirequests", "notes"}; String[] args = {}; for (String table : tables) { rawQuery("DROP TABLE IF EXISTS " + table, args); } Log.d(TAG, "Recreating database tables"); SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase(); mDatabaseOpenHelper.onCreate(db); } public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase(); Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); if (cursor == null) { return null; } else if (!cursor.moveToFirst()) { cursor.close(); return null; } return cursor; } public Cursor rawQuery(String selection, String[] args) { Log.d(TAG, "Query: " + selection); SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase(); Cursor cursor = db.rawQuery(selection, args); if (cursor == null) { return null; } else if (!cursor.moveToFirst()) { cursor.close(); return null; } return cursor; } void beginTransaction() { SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase(); db.beginTransaction(); } void endTransaction() { SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase(); db.endTransaction(); } void setTransactionSuccessful() { SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase(); db.setTransactionSuccessful(); } /** * No-op. */ public void close() { } public SQLiteStatement compileStatement(String sql) throws SQLiteException { SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase(); return db.compileStatement(sql); } private static class DatabaseOpenHelper extends SQLiteOpenHelper { @SuppressWarnings("unused") private final Context mHelperContext; @SuppressWarnings("unused") private SQLiteDatabase mDatabase; private static DatabaseOpenHelper instance; // table creation statements // for temp table creation to work, must have (_id as first field private static final String COLLECTIONS_CREATE = "create table collections" + " (_id integer primary key autoincrement, " + "collection_name text not null, " + "collection_key string unique, " + "collection_parent string, " + "collection_type text, " + "collection_size int, " + "etag string, " + "dirty string, " + "timestamp string);"; private static final String ITEMS_CREATE = "create table items" + " (_id integer primary key autoincrement, " + "item_key string unique, " + "item_title string not null, " + "etag string, " + "item_type string not null, " + "item_content string," + "item_year string," + "item_creator string," + "item_children string," + "dirty string, " + "timestamp string);"; private static final String CREATORS_CREATE = "create table creators" + " (_id integer primary key autoincrement, " + "name string, " + "firstName string, " + "lastName string, " + "creatorType string );"; private static final String ITEM_TO_CREATORS_CREATE = "create table itemtocreators" + " (_id integer primary key autoincrement, " + "creator_id int not null, item_id int not null);"; private static final String ITEM_TO_COLLECTIONS_CREATE = "create table itemtocollections" + " (_id integer primary key autoincrement, " + "collection_id int not null, item_id int not null);"; private static final String DELETED_ITEMS_CREATE = "create table deleteditems" + " (_id integer primary key autoincrement, " + "item_key string not null, etag string not null);"; private static final String ATTACHMENTS_CREATE = "create table attachments" + " (_id integer primary key autoincrement, " + "item_key string not null, " + "attachment_key string not null, " + "title string, " + "filename string, " + "url string, " + "status string, " + "content string, " + "etag string, " + "dirty string);"; private static final String APIREQUESTS_CREATE = "create table apirequests" + " (_id integer primary key autoincrement, " + "uuid string unique, " + "type string, " + "query string, " + "key string, " + "method string, " + "disposition string, " + "if_match string, " + "update_key string, " + "update_type string, " + "created string, " + "last_attempt string, " + "status integer," + "body string);"; /* We don't use this table right now */ private static final String NOTES_CREATE = "create table notes" + " (_id integer primary key autoincrement, " + "item_key string, " + "note_key string not null, " + "title string, " + "filename string, " + "url string, " + "status string, " + "content string, " + "etag string);"; DatabaseOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mHelperContext = context; } static synchronized DatabaseOpenHelper getHelper(Context context) { if (instance == null) instance = new DatabaseOpenHelper(context); return instance; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(COLLECTIONS_CREATE); db.execSQL(ITEMS_CREATE); db.execSQL(CREATORS_CREATE); db.execSQL(ITEM_TO_CREATORS_CREATE); db.execSQL(ITEM_TO_COLLECTIONS_CREATE); db.execSQL(DELETED_ITEMS_CREATE); db.execSQL(ATTACHMENTS_CREATE); db.execSQL(NOTES_CREATE); db.execSQL(APIREQUESTS_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 14) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data."); db.execSQL("DROP TABLE IF EXISTS collections"); db.execSQL("DROP TABLE IF EXISTS items"); db.execSQL("DROP TABLE IF EXISTS creators"); db.execSQL("DROP TABLE IF EXISTS children"); db.execSQL("DROP TABLE IF EXISTS itemtocreators"); db.execSQL("DROP TABLE IF EXISTS itemtocollections"); onCreate(db); } else { if (oldVersion == 14 && newVersion == 15) { // here, we just added a table db.execSQL(DELETED_ITEMS_CREATE); } if (oldVersion == 15 && newVersion > 15) { // here, we just added a table db.execSQL("create table if not exists deleteditems" + " (_id integer primary key autoincrement, " + "item_key int not null, etag int not null);"); } if (oldVersion < 17 && newVersion == 17) { db.execSQL(ATTACHMENTS_CREATE); db.execSQL(NOTES_CREATE); db.execSQL("alter table items " + " add column item_children string;"); } if (oldVersion == 17 && newVersion == 18) { db.execSQL("alter table attachments " + " add column etag string;"); db.execSQL("alter table attachments " + " add column content string;"); db.execSQL("alter table notes " + " add column etag string;"); db.execSQL("alter table notes " + " add column content string;"); } if (oldVersion == 18 && newVersion == 19) { db.execSQL("alter table attachments " + " add column dirty string;"); } if (oldVersion == 19 && newVersion == 20) { db.execSQL(APIREQUESTS_CREATE); } } } } }
11,991
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
ItemCollection.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/data/ItemCollection.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app.data; import java.util.ArrayList; import java.util.HashSet; import java.util.Objects; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.util.Log; import com.gimranov.zandy.app.task.APIRequest; import org.jetbrains.annotations.NotNull; /** * Represents a Zotero collection of Item objects. Collections can * be iterated over, but it's quite likely that iteration will prove unstable * if you make changes to them while iterating. * <p> * To put items in collections, add them using the add(..) methods, and save the * collection. * * @author ajlyon */ public class ItemCollection extends HashSet<Item> { /** * What is this for? */ private static final long serialVersionUID = -4673800475017605707L; public static final String TAG = ItemCollection.class.getSimpleName(); private String id; private String title; private String key; private String etag; /** * Subcollections of this collection. This is accessed through * a lazy getter, which caches the value. This may at times be * incorrect, since we don't repopulate this to reflect changes * after first populating it. */ private ArrayList<ItemCollection> subcollections; /** * This is an approximate size that we have from the database-- it may be outdated * at times, but it's often better than wading through the database and figuring out * the size that way. * <p> * This size is updated only when loading children; */ private int size; private ItemCollection parent; private String parentKey; public String dbId; public String dirty; /** * Timestamp of last update from server; this is an Atom-formatted * timestamp */ private String timestamp; public ItemCollection(String title) { setTitle(title); dirty = APIRequest.API_DIRTY; } public ItemCollection() { } /** * We call void remove(Item) to allow for queueing * the action for application on the server, via the API. * <p> * When fromAPI is not true, queues a collection membership * request for the server as well. * * @param item * @param fromAPI False for collection memberships we receive from the server * @param db */ public void remove(Item item, boolean fromAPI, Database db) { String[] args = {dbId, item.dbId}; db.rawQuery("delete from itemtocollections where collection_id=? and item_id=?", args); if (!fromAPI) { APIRequest req = APIRequest.remove(item, this); req.status = APIRequest.REQ_NEW; req.save(db); } super.remove(item); } /* Getters and setters */ public String getId() { return id; } public String getEtag() { return etag; } public void setEtag(String etag) { this.etag = etag; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getTitle() { return title; } public void setTitle(String title) { if (!title.equals(this.title)) { this.title = title; this.dirty = APIRequest.API_DIRTY; } } /* I'm not sure how easy this is to propagate to the API */ public ItemCollection getParent(Database db) { if (parent != null) return parent; if (Objects.equals(parentKey, "false")) return null; if (parentKey != null) { parent = load(parentKey, db); } return parent; } public void setParent(ItemCollection parent) { this.parentKey = parent.getKey(); this.parent = parent; } public void setParent(String parentKey) { this.parentKey = parentKey; } /* These can't be propagated, so it only makes sense before the collection * has been saved to the API. */ public void setId(String id) { this.id = id; } public void setKey(String key) { this.key = key; } public String getKey() { return key; } /** * Returns the size, not as measured, but as listed in DB * * @return */ public int getSize() { return size; } /** * Marks the collection as clean and clears the pending additions and * removals. * <p> * Note that dirty markings don't matter until saved to the DB, so * this should be followed by a save. */ public void markClean() { dirty = APIRequest.API_CLEAN; } public boolean add(Item item, Database db) { return add(item, false, db); } /** * Adds the specified item to this collection. * <p> * When fromAPI is not true, queues a collection membership * request for the server as well. * * @param item * @param fromAPI False for collection memberships we receive from the server * @param db * @return Whether this is a new item for the collection */ public boolean add(Item item, boolean fromAPI, Database db) { for (Item i : this) { if (i.equals(item)) { Log.d(TAG, "Item already in collection"); return false; } } super.add(item); Log.d(TAG, "Item added to collection"); if (!fromAPI) { Log.d(TAG, "Saving new collection membership request to database"); APIRequest req = APIRequest.add(item, this); req.status = APIRequest.REQ_NEW; req.save(db); } return true; } /** * Returns ArrayList of Item objects not in the specified ArrayList of item keys. Used for determining * when items have been deleted from a collection. */ public ArrayList<Item> notInKeys(ArrayList<String> keys) { ArrayList<Item> notThere = new ArrayList<Item>(); for (Item i : this) { if (!keys.contains(i.getKey())) notThere.add(i); } return notThere; } /** * Saves the collection metadata to the database. * <p> * Does nothing with the collection children. */ public void save(Database db) { ItemCollection existing = load(key, db); if (existing == null) { try { SQLiteStatement insert = db.compileStatement("insert or replace into collections " + "(collection_name, collection_key, collection_parent, etag, dirty, collection_size, timestamp)" + " values (?, ?, ?, ?, ?, ?, ?)"); // Why, oh why does bind* use 1-based indexing? And cur.get* uses 0-based! insert.bindString(1, title); if (key == null) insert.bindNull(2); else insert.bindString(2, key); if (parentKey == null) insert.bindNull(3); else insert.bindString(3, parentKey); if (etag == null) insert.bindNull(4); else insert.bindString(4, etag); if (dirty == null) insert.bindNull(5); else insert.bindString(5, dirty); insert.bindLong(6, size); if (timestamp == null) insert.bindNull(7); else insert.bindString(7, timestamp); insert.executeInsert(); insert.clearBindings(); insert.close(); Log.d(TAG, "Saved collection with key: " + key); } catch (SQLiteException e) { Log.e(TAG, "Exception compiling or running insert statement", e); throw e; } // XXX we need a way to handle locally-created collections ItemCollection loaded = load(key, db); if (loaded == null) { Log.e(TAG, "Item didn't stick-- still nothing for key: " + key); } else { dbId = loaded.dbId; } } else { dbId = existing.dbId; try { SQLiteStatement update = db.compileStatement("update collections set " + "collection_name=?, etag=?, dirty=?, collection_size=?, timestamp=?" + " where _id=?"); update.bindString(1, title); if (etag == null) update.bindNull(2); else update.bindString(2, etag); if (dirty == null) update.bindNull(3); else update.bindString(3, dirty); update.bindLong(4, size); if (timestamp == null) update.bindNull(5); else update.bindString(5, timestamp); update.bindString(6, dbId); update.executeInsert(); update.clearBindings(); update.close(); Log.i(TAG, "Updating existing collection."); } catch (SQLiteException e) { Log.e(TAG, "Exception compiling or running update statement", e); } } db.close(); } /** * Saves the item-collection relationship. This saves the collection * itself as well. * * @throws Exception If we can't save the collection or children */ public void saveChildren(Database db) { /* The size is about to be the size of the internal ArrayList, so * set it now so it'll be propagated to the database if the collection * is new. * * Save it now-- to fix the size, and to make sure we have a database ID. */ loadChildren(db); Log.d(TAG, "Collection has dbid: " + dbId); /* The saving is implemented by removing all the records for this collection * and saving them anew. This is a risky way to do things. One approach is to * wrap the operation in a transaction, or we could try to keep track of changes. */ HashSet<String> keys = new HashSet<>(); for (Item i : this) { if (i.dbId == null) i.save(db); keys.add(i.dbId); } db.beginTransaction(); try { String[] cid = {this.dbId}; db.rawQuery("delete from itemtocollections where collection_id=?", cid); for (String i : keys) { String[] args = {this.dbId, i}; db.rawQuery( "insert into itemtocollections (collection_id, item_id) values (?, ?)", args); } db.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, "Exception caught on saving collection children", e); } finally { db.endTransaction(); } // We can now get a proper and total count String[] args = {this.dbId}; Cursor cur = db.rawQuery( "select count(distinct item_id) from itemtocollections where collection_id=?", args); cur.moveToFirst(); if (!cur.isAfterLast()) this.size = cur.getInt(0); cur.close(); save(db); } /** * Loads the Item members of the collection into the ArrayList<> */ public void loadChildren(Database db) { if (dbId == null) save(db); Log.d(TAG, "Looking for the kids of a collection with id: " + dbId); String[] args = {dbId}; Cursor cursor = db.rawQuery("SELECT item_title, item_type, item_content, etag, dirty, items._id, item_key, item_year, item_creator, items.timestamp, item_children" + " FROM items, itemtocollections WHERE items._id = item_id AND collection_id=? ORDER BY item_title", args); if (cursor != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { Item i = Item.load(cursor); Log.d(TAG, "Adding an item to the collection: " + (i != null ? i.getTitle() : null)); size = this.size(); super.add(i); cursor.moveToNext(); } cursor.close(); } else { Log.d(TAG, "Cursor was null, so we still didn't get kids for the collection!"); } } /** * Gets the subcollections of the current collection. * <p> * This is a lazy getter and won't check again after the first time. * * @return */ public ArrayList<ItemCollection> getSubcollections(Database db) { if (this.subcollections != null) return this.subcollections; this.subcollections = new ArrayList<ItemCollection>(); String[] args = {this.key}; Cursor cur = db.query("collections", Database.COLLCOLS, "collection_parent=?", args, null, null, null, null); if (cur == null) { Log.d(TAG, "No subcollections found for collection: " + this.title); return this.subcollections; } do { ItemCollection collection = load(cur); if (collection == null) { Log.e(TAG, "Got a null collection when loading from cursor, in getSubcollections"); continue; } Log.d(TAG, "Found subcollection: " + collection.title); this.subcollections.add(collection); } while (cur.moveToNext()); cur.close(); return this.subcollections; } /** * Loads and returns an ItemCollection for the specified collection key * Returns null when no match is found for the specified collKey * * @param collKey * @return */ public static ItemCollection load(String collKey, Database db) { if (collKey == null) return null; String[] cols = Database.COLLCOLS; String[] args = {collKey}; Log.i(TAG, "Loading collection with key: " + collKey); Cursor cur = db.query("collections", cols, "collection_key=?", args, null, null, null, null); ItemCollection coll = load(cur); if (coll == null) Log.i(TAG, "Null collection loaded!"); if (cur != null) cur.close(); return coll; } /** * Loads a collection from the specified Cursor, where the cursor was created using * the recommended query in Database.COLLCOLS * <p> * Returns null when the specified cursor is null. * <p> * Does not close the cursor! * * @param cur * @return An ItemCollection object for the current row of the Cursor */ public static ItemCollection load(Cursor cur) { ItemCollection coll = new ItemCollection(); if (cur == null) { return null; } coll.setTitle(cur.getString(0)); coll.setParent(cur.getString(1)); coll.etag = cur.getString(2); coll.dirty = cur.getString(3); coll.dbId = cur.getString(4); coll.setKey(cur.getString(5)); coll.size = cur.getInt(6); coll.timestamp = cur.getString(7); return coll; } /** * Gives us ItemCollection objects to feed into something like UI */ public static ArrayList<ItemCollection> getCollections(Database db) { ArrayList<ItemCollection> collections = new ArrayList<ItemCollection>(); ItemCollection coll; String[] cols = Database.COLLCOLS; Cursor cur = db.query("collections", cols, "", null, null, null, "collection_name", null); if (cur == null) { Log.d(TAG, "No collections found in database"); return collections; } return getItemCollections(collections, cur); } /** * Gives us ItemCollection objects containing given item * to feed into something like UI */ public static ArrayList<ItemCollection> getCollections(Item i, Database db) { ArrayList<ItemCollection> collections = new ArrayList<ItemCollection>(); String[] args = {i.dbId}; Cursor cursor = db.rawQuery("SELECT collection_name, collection_parent," + " etag, dirty, collections._id, collection_key, collection_size," + " timestamp FROM collections, itemtocollections" + " WHERE collections._id = collection_id AND item_id=?" + " ORDER BY collection_name", args); if (cursor == null) { Log.d(TAG, "No collections found for item"); return collections; } return getItemCollections(collections, cursor); } @NotNull private static ArrayList<ItemCollection> getItemCollections(ArrayList<ItemCollection> collections, Cursor cursor) { ItemCollection coll; do { Log.d(TAG, "Adding collection to collection list"); coll = load(cursor); collections.add(coll); } while (cursor.moveToNext()); cursor.close(); return collections; } /** * Gives us count of ItemCollection objects containing given item * to feed into something like UI */ static int getCollectionCount(Item i, Database db) { String[] args = {i.dbId}; Cursor cursor = db.rawQuery("SELECT COUNT(*) " + " FROM collections, itemtocollections" + " WHERE collections._id = collection_id AND item_id=?", args); if (cursor == null) { Log.d(TAG, "No collections found for item"); return 0; } int count = cursor.getInt(0); cursor.close(); return count; } }
18,555
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
CollectionAdapter.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/data/CollectionAdapter.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app.data; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import com.gimranov.zandy.app.R; import com.gimranov.zandy.app.task.APIRequest; /** * Exposes collection to be displayed by a ListView * @author ajlyon * */ public class CollectionAdapter extends ResourceCursorAdapter { public static final String TAG = CollectionAdapter.class.getSimpleName(); public Context context; public CollectionAdapter(Context context, Cursor cursor) { super(context, R.layout.list_collection, cursor, false); this.context = context; } public View newView(Context context, Cursor cur, ViewGroup parent) { LayoutInflater li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return li.inflate(R.layout.list_collection, parent, false); } /** * Call this when the data has been updated-- it refreshes the cursor and notifies of the change */ public void notifyDataSetChanged() { super.notifyDataSetChanged(); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView tvTitle = (TextView)view.findViewById(R.id.collection_title); TextView tvInfo = (TextView)view.findViewById(R.id.collection_info); Database db = new Database(context); ItemCollection collection = ItemCollection.load(cursor); tvTitle.setText(collection.getTitle()); StringBuilder sb = new StringBuilder(); sb.append(collection.getSize()).append(" items"); sb.append("; ").append(collection.getSubcollections(db).size()).append(" subcollections"); if(!collection.dirty.equals(APIRequest.API_CLEAN)) sb.append("; ").append(collection.dirty); tvInfo.setText(sb.toString()); db.close(); } }
2,757
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
ItemAdapter.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/data/ItemAdapter.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app.data; import android.content.Context; import android.database.Cursor; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import com.gimranov.zandy.app.R; /** * Exposes items to be displayed by a ListView * * @author ajlyon */ public class ItemAdapter extends ResourceCursorAdapter { public static final String TAG = ItemAdapter.class.getSimpleName(); public ItemAdapter(Context context, Cursor cursor) { super(context, R.layout.list_item, cursor, false); } public View newView(Context context, Cursor cur, ViewGroup parent) { LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return li.inflate(R.layout.list_item, parent, false); } /** * Call this when the data has been updated */ public void notifyDataSetChanged() { super.notifyDataSetChanged(); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView tvTitle = view.findViewById(R.id.item_title); ImageView tvType = view.findViewById(R.id.item_type); TextView tvSummary = view.findViewById(R.id.item_summary); if (cursor == null) { Log.e(TAG, "cursor is null in bindView"); } Item item = Item.load(cursor); if (item == null) { Log.e(TAG, "item is null in bindView"); } if (tvTitle == null) { Log.e(TAG, "tvTitle is null in bindView"); } Log.d(TAG, "setting image for item (" + item.getKey() + ") of type: " + item.getType()); tvType.setImageResource(Item.resourceForType(item.getType())); tvSummary.setText(item.getCreatorSummary() + " (" + item.getYear() + ")"); if (tvSummary.getText().equals(" ()")) tvSummary.setVisibility(View.GONE); tvTitle.setText(item.getTitle()); } }
2,917
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
Creator.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/data/Creator.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app.data; import org.json.JSONException; import org.json.JSONObject; /** * Need to work out DB saving and loading soon * * @author ajlyon */ public class Creator { private String lastName; private String firstName; private String name; private String creatorType; private boolean singleField; private int dbId; public static final String TAG = "com.gimranov.zandy.app.data.Creator"; /** * A Creator, given type, a single string, and a boolean mode. * * @param mCreatorType A valid creator type * @param mName Name. If not in single-field-mode, last word will be lastName * @param mSingleField If true, name won't be parsed into first and last */ public Creator(String mCreatorType, String mName, boolean mSingleField) { creatorType = mCreatorType; singleField = mSingleField; name = mName; if (singleField) return; String[] pieces = name.split(" "); if (pieces.length > 1) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < pieces.length - 1; i++) { sb.append(pieces[i]); } firstName = sb.toString(); lastName = pieces[pieces.length - 1]; } } /** * A creator given two name parts. They'll be joined for the name field. * * @param type * @param first * @param last */ public Creator(String type, String first, String last) { creatorType = type; firstName = first; lastName = last; singleField = false; name = first + " " + last; } public String getCreatorType() { return creatorType; } public void setCreatorType(String creatorType) { this.creatorType = creatorType; } public int getDbId() { return dbId; } public void setDbId(int dbId) { this.dbId = dbId; } public String getLastName() { return lastName; } public String getFirstName() { return firstName; } public String getName() { return name; } public boolean isSingleField() { return singleField; } public JSONObject toJSON() throws JSONException { if (singleField) return new JSONObject().accumulate("name", name) .accumulate("creatorType", creatorType); return new JSONObject().accumulate("firstName", firstName) .accumulate("lastName", lastName) .accumulate("creatorType", creatorType); } }
3,457
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
StorageManager.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/storage/StorageManager.java
package com.gimranov.zandy.app.storage; import android.content.Context; import android.os.Environment; import java.io.File; public class StorageManager { public static File getDocumentsDirectory(Context context) { File documents = new File(context.getExternalFilesDir(null), "documents"); //noinspection ResultOfMethodCallIgnored documents.mkdirs(); return documents; } public static File getCacheDirectory(Context context) { File cache = new File(context.getExternalFilesDir(null), "cache"); //noinspection ResultOfMethodCallIgnored cache.mkdirs(); return cache; } }
652
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
ZoteroAPITask.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/task/ZoteroAPITask.java
/* * Zandy * Based in part on Mendroid, Copyright 2011 Martin Paul Eve <martin@martineve.com> * * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. * */ package com.gimranov.zandy.app.task; import java.util.ArrayList; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.util.Log; import com.gimranov.zandy.app.ServerCredentials; import com.gimranov.zandy.app.XMLResponseParser; import com.gimranov.zandy.app.data.Attachment; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; /** * Executes one or more API requests asynchronously. * <p> * Steps in migration: * 1. Move the logic on what kind of request is handled how into the APIRequest itself * 2. Throw exceptions when we have errors * 3. Call the handlers when provided * 4. Move aggressive syncing logic out of ZoteroAPITask itself; it should be elsewhere. * * @author ajlyon */ public class ZoteroAPITask extends AsyncTask<APIRequest, Message, Message> { private static final String TAG = ZoteroAPITask.class.getSimpleName(); public ArrayList<APIRequest> deletions; public ArrayList<APIRequest> queue; public int syncMode = -1; public static final int AUTO_SYNC_STALE_COLLECTIONS = 1; public boolean autoMode = false; private Database db; private ServerCredentials cred; private Handler handler; public ZoteroAPITask(Context c) { queue = new ArrayList<APIRequest>(); cred = new ServerCredentials(c); /* TODO reenable in a working way if (settings.getBoolean("sync_aggressively", false)) syncMode = AUTO_SYNC_STALE_COLLECTIONS; */ deletions = APIRequest.delete(c); db = new Database(c); } public void setHandler(Handler h) { handler = h; } private Handler getHandler() { if (handler == null) { handler = new Handler() { }; } return handler; } @Override protected Message doInBackground(APIRequest... params) { return doFetch(params); } @SuppressWarnings("unused") public Message doFetch(APIRequest... reqs) { int count = reqs.length; for (int i = 0; i < count; i++) { if (reqs[i] == null) { Log.d(TAG, "Skipping null request"); continue; } // Just in case we missed something, we fix the user ID right here too, // and we set the key as well. reqs[i] = cred.prep(reqs[i]); try { Log.i(TAG, "Executing API call: " + reqs[i].query); reqs[i].issue(db, cred); Log.i(TAG, "Successfully retrieved API call: " + reqs[i].query); reqs[i].succeeded(db); } catch (APIException e) { Log.e(TAG, "Failed to execute API call: " + e.request.query, e); e.request.status = APIRequest.REQ_FAILING + e.request.getHttpStatus(); e.request.save(db); Message msg = Message.obtain(); msg.arg1 = APIRequest.ERROR_UNKNOWN + e.request.getHttpStatus(); return msg; } // The XML parser's queue is simply from following continuations in the paged // feed. We shouldn't split out its requests... if (XMLResponseParser.queue != null && !XMLResponseParser.queue.isEmpty()) { Log.i(TAG, "Finished call, but adding " + XMLResponseParser.queue.size() + " items to queue."); queue.addAll(XMLResponseParser.queue); XMLResponseParser.queue.clear(); } else { Log.i(TAG, "Finished call, and parser's request queue is empty"); } } // if (queue.size() > 0) { // If the last batch saw unchanged items, don't follow the Atom // continuations; just run the child requests // XXX This is disabled for now if (false && !XMLResponseParser.followNext) { ArrayList<APIRequest> toRemove = new ArrayList<APIRequest>(); for (APIRequest r : queue) { if (r.type != APIRequest.ITEMS_CHILDREN) { Log.d(TAG, "Removing request from queue since last page had old items: " + r.query); toRemove.add(r); } } queue.removeAll(toRemove); } Log.i(TAG, "Starting queued requests: " + queue.size() + " requests"); APIRequest[] templ = {}; APIRequest[] requests = queue.toArray(templ); queue.clear(); Log.i(TAG, "Queue size now: " + queue.size()); // XXX I suspect that this calling of doFetch from doFetch might be the cause of our // out-of-memory situations. We may be able to accomplish the same thing by expecting // the code listening to our handler to fetch again if QUEUED_MORE is received. In that // case, we could just save our queue here and really return. // XXX Test: Here, we try to use doInBackground instead doInBackground(requests); // Return a message with the number of requests added to the queue Message msg = Message.obtain(); msg.arg1 = APIRequest.QUEUED_MORE; msg.arg2 = requests.length; return msg; } // Here's where we tie in to periodic housekeeping syncs // If we're already in auto mode (that is, here), just move on if (autoMode) { Message msg = Message.obtain(); msg.arg1 = APIRequest.UPDATED_DATA; return msg; } Log.d(TAG, "Sending local changes"); Item.queue(db); Attachment.queue(db); APIRequest[] templ = {}; ArrayList<APIRequest> list = new ArrayList<APIRequest>(); for (Item i : Item.queue) { list.add(cred.prep(APIRequest.update(i))); } for (Attachment a : Attachment.queue) { list.add(cred.prep(APIRequest.update(a, db))); } // This queue has deletions, collection memberships, and failing requests // We may want to filter it in the future list.addAll(APIRequest.queue(db)); // We're in auto mode... autoMode = true; doInBackground(list.toArray(templ)); // Return a message noting that we've queued more requests Message msg = Message.obtain(); msg.arg1 = APIRequest.QUEUED_MORE; msg.arg2 = list.size(); return msg; } @Override protected void onPostExecute(Message result) { getHandler().sendMessage(result); } }
7,513
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
APIRequest.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/task/APIRequest.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app.task; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.os.Handler; import android.util.Log; import com.gimranov.zandy.app.ServerCredentials; import com.gimranov.zandy.app.XMLResponseParser; import com.gimranov.zandy.app.data.Attachment; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.data.ItemCollection; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.UUID; /** * Represents a request to the Zotero API. These can be consumed by * other things like ZoteroAPITask. These should be queued up for many purposes. * <p> * The APIRequest should include the HttpPost / HttpGet / etc. that it needs * to be executed, and optionally a callback to be called when it completes. * <p> * See http://www.zotero.org/support/dev/server_api for information. * * @author ajlyon */ @SuppressWarnings("DanglingJavadoc") public class APIRequest { private static final String TAG = APIRequest.class.getSimpleName(); /** * Statuses used for items and collections. They are currently strings, but * they should change to integers. These statuses may be stored in the database. */ // XXX i18n public static final String API_DIRTY = "Unsynced change"; public static final String API_NEW = "New item / collection"; public static final String API_MISSING = "Partial data"; public static final String API_STALE = "Stale data"; public static final String API_WIP = "Sync attempted"; public static final String API_CLEAN = "No unsynced change"; /* * These are constants represented by integers. * * The above should be moving down here some time. */ /** * HTTP response codes that we are used to */ private static final int HTTP_ERROR_CONFLICT = 412; private static final int HTTP_ERROR_UNSPECIFIED = 400; /* * The following are used when passing things back to the UI * from the API request service / thread. */ /** * Used to indicate database data has changed. */ public static final int UPDATED_DATA = 1000; /** * Current set of requests completed. */ public static final int BATCH_DONE = 2000; /** * Used to indicate an error with no more details. */ public static final int ERROR_UNKNOWN = 4000; /** * Queued more requests */ public static final int QUEUED_MORE = 3000; /** * Request types */ private static final int ITEMS_ALL = 10000; private static final int ITEMS_FOR_COLLECTION = 10001; static final int ITEMS_CHILDREN = 10002; private static final int COLLECTIONS_ALL = 10003; private static final int ITEM_BY_KEY = 10004; // Requests that require write access private static final int ITEM_NEW = 20000; public static final int ITEM_UPDATE = 20001; public static final int ITEM_DELETE = 20002; public static final int ITEM_MEMBERSHIP_ADD = 20003; public static final int ITEM_MEMBERSHIP_REMOVE = 20004; private static final int ITEM_ATTACHMENT_NEW = 20005; public static final int ITEM_ATTACHMENT_UPDATE = 20006; public static final int ITEM_ATTACHMENT_DELETE = 20007; public static final int ITEM_FIELDS = 30000; public static final int CREATOR_TYPES = 30001; public static final int ITEM_FIELDS_L10N = 30002; public static final int CREATOR_TYPES_L10N = 30003; /** * Request status for use within the database */ public static final int REQ_NEW = 40000; static final int REQ_FAILING = 41000; /** * We'll request the whole collection or library rather than * individual feeds when we have less than this proportion of * the items. Used when pre-fetching keys. */ private static double REREQUEST_CUTOFF = 0.7; /** * Type of request we're sending. This should be one of * the request types listed above. */ public int type; /** * Callback handler */ private APIEvent handler; /** * Base query to send. */ public String query; /** * API key used to make request. Can be omitted for requests that don't need one. */ public String key; /** * One of get, put, post, delete. * Lower-case preferred, but we coerce them anyway. */ public String method; /** * Response disposition: xml or raw. JSON also planned */ public String disposition; /** * Used when sending JSON in POST and PUT requests. */ public String contentType = "application/json"; /** * Optional token to avoid accidentally sending one request twice. The * server will decline to carry out a second request with the same writeToken * for a single API key in a several-hour period. */ public String writeToken; /** * The eTag received from the server when requesting an item. We can make changes * (delete, update) to an item only while the tag is valid; if the item changes * server-side, our request will be declined until we request the item anew and get * a new valid eTag. */ public String ifMatch; /** * Request body, generally JSON. */ public String body; /** * The temporary key (UUID) that the request is based on. */ public String updateKey; /** * Type of object we expect to get. This and the updateKey are used to update * the UUIDs / local keys of locally-created items. I know, it's a hack. */ public String updateType; /** * Status code for the request. Codes should be constants defined in APIRequest; * take the REQ_* code and add the response code if applicable. */ public int status; /** * UUID for this request. We use this for DB lookups and as the write token when * appropriate. Every request should have one. */ private String uuid; /** * Timestamp when this request was first created. */ private Date created; /** * Timestamp when this request was last attempted to be run. */ private Date lastAttempt; /** * Creates a basic APIRequest item. Augment the item using instance methods for more complex * requests, or pass it to ZoteroAPITask for simpler ones. The request can be run by * simply calling the instance method `issue(..)`, but not from the UI thread. * <p> * The constructor is not to be used directly; use the static methods in this class, or create from * a cursor. The one exception is the Atom feed continuations produced by XMLResponseParser, but that * should be moved into this class as well. * * @param query Fragment being requested, like /items * @param method GET, POST, PUT, or DELETE (except that lowercase is preferred) * @param key Can be null, if you're planning on making requests that don't need a key. */ public APIRequest(String query, String method, String key) { this.query = query; this.method = method; this.key = key; // default to XML processing this.disposition = "xml"; // If this is processing-intensive, we can probably move it to the save method this.uuid = UUID.randomUUID().toString(); created = new Date(); } /** * Load an APIRequest from its serialized form in the database * public static final String[] REQUESTCOLS = {"_id", "uuid", "type", * "query", "key", "method", "disposition", "if_match", "update_key", * "update_type", "created", "last_attempt", "status"}; * * @param cur */ public APIRequest(Cursor cur) { // N.B.: getString and such use 0-based indexing this.uuid = cur.getString(1); this.type = cur.getInt(2); this.query = cur.getString(3); this.key = cur.getString(4); this.method = cur.getString(5); this.disposition = cur.getString(6); this.ifMatch = cur.getString(7); this.updateKey = cur.getString(8); this.updateType = cur.getString(9); this.created = new Date(); this.created.setTime(cur.getLong(10)); this.lastAttempt = new Date(); this.lastAttempt.setTime(cur.getLong(11)); this.status = cur.getInt(12); this.body = cur.getString(13); } /** * Saves the APIRequest's basic info to the database. Does not maintain handler information. * * @param db */ public void save(Database db) { try { Log.d(TAG, "Saving APIRequest to database: " + uuid + " " + query); SQLiteStatement insert = db.compileStatement("insert or replace into apirequests " + "(uuid, type, query, key, method, disposition, if_match, update_key, update_type, " + "created, last_attempt, status, body)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)"); // Why, oh why does bind* use 1-based indexing? And cur.get* uses 0-based! insert.bindString(1, uuid); insert.bindLong(2, (long) type); String createdUnix = Long.toString(created.getTime()); String lastAttemptUnix; if (lastAttempt == null) lastAttemptUnix = null; else lastAttemptUnix = Long.toString(lastAttempt.getTime()); String status = Integer.toString(this.status); // Iterate through null-allowed strings and bind them String[] strings = {query, key, method, disposition, ifMatch, updateKey, updateType, createdUnix, lastAttemptUnix, status, body}; for (int i = 0; i < strings.length; i++) { Log.d(TAG, (3 + i) + ":" + strings[i]); if (strings[i] == null) insert.bindNull(3 + i); else insert.bindString(3 + i, strings[i]); } insert.executeInsert(); insert.clearBindings(); insert.close(); } catch (SQLiteException e) { Log.e(TAG, "Exception compiling or running insert statement", e); throw e; } } /** * Getter for the request's implementation of the APIEvent interface, * used for call-backs, usually tying into the UI. * <p> * Returns a no-op, logging handler if none specified * * @return */ public APIEvent getHandler() { if (handler == null) { /* * We have to fall back on a no-op event handler to prevent null exceptions */ return new APIEvent() { @Override public void onComplete(APIRequest request) { Log.d(TAG, "onComplete called but no handler"); } @Override public void onUpdate(APIRequest request) { Log.d(TAG, "onUpdate called but no handler"); } @Override public void onError(APIRequest request, Exception exception) { Log.d(TAG, "onError called but no handler"); } @Override public void onError(APIRequest request, int error) { Log.d(TAG, "onError called but no handler"); } }; } return handler; } public void setHandler(APIEvent handler) { if (this.handler == null) { this.handler = handler; return; } Log.e(TAG, "APIEvent handler for request cannot be replaced"); } /** * Set an Android standard handler to be used for the APIEvents * * @param handler */ public void setHandler(Handler handler) { final Handler mHandler = handler; if (this.handler == null) { this.handler = new APIEvent() { @Override public void onComplete(APIRequest request) { mHandler.sendEmptyMessage(BATCH_DONE); } @Override public void onUpdate(APIRequest request) { mHandler.sendEmptyMessage(UPDATED_DATA); } @Override public void onError(APIRequest request, Exception exception) { mHandler.sendEmptyMessage(ERROR_UNKNOWN); } @Override public void onError(APIRequest request, int error) { mHandler.sendEmptyMessage(ERROR_UNKNOWN); } }; return; } Log.e(TAG, "APIEvent handler for request cannot be replaced"); } /** * Populates the body with a JSON representation of * the specified item. * <p> * Use this for updating items, i.e.: * PUT /users/1/items/ABCD2345 * * @param item Item to put in the body. */ public void setBody(Item item) { try { body = item.getContent().toString(4); } catch (JSONException e) { Log.e(TAG, "Error setting body for item", e); } } /** * Populates the body with a JSON representation of the specified * items. * <p> * Use this for creating new items, i.e.: * POST /users/1/items * * @param items */ public void setBody(ArrayList<Item> items) { try { JSONArray array = new JSONArray(); for (Item i : items) { JSONObject jItem = i.getContent(); array.put(jItem); } JSONObject obj = new JSONObject(); obj.put("items", array); body = obj.toString(4); } catch (JSONException e) { Log.e(TAG, "Error setting body for items", e); } } /** * Populates the body with a JSON representation of specified * attachments; note that this is will not work with non-note * attachments until the server API supports them. * * @param attachments */ public void setBodyWithNotes(ArrayList<Attachment> attachments) { try { JSONArray array = new JSONArray(); for (Attachment a : attachments) { JSONObject jAtt = a.content; array.put(jAtt); } JSONObject obj = new JSONObject(); obj.put("items", array); body = obj.toString(4); } catch (JSONException e) { Log.e(TAG, "Error setting body for attachments", e); } } /** * Getter for the request's UUID * * @return */ public String getUuid() { return uuid; } /** * Sets the HTTP response code portion of the request's status * * @param code * @return The new status */ public int setHttpStatus(int code) { status = (status - status % 1000) + code; return status; } /** * Gets the HTTP response code portion of the request's status; * returns 0 if there was no code set. */ public int getHttpStatus() { return status % 1000; } /** * Record a failed attempt to run the request. * <p> * Saves the APIRequest in its current state. * * @param db Database object * @return Date object with new lastAttempt value */ public Date recordAttempt(Database db) { lastAttempt = new Date(); save(db); return lastAttempt; } /** * To be called when the request succeeds. Currently just * deletes the corresponding row from the database. * * @param db Database object */ public void succeeded(Database db) { getHandler().onComplete(this); String[] args = {uuid}; db.rawQuery("delete from apirequests where uuid=?", args); } /** * Returns HTML-formatted string of the request * <p> * XXX i18n, once we settle on a format * * @return */ public String toHtmlString() { StringBuilder sb = new StringBuilder(); sb.append("<h1>"); sb.append(status); sb.append("</h1>"); sb.append("<p><i>"); sb.append(method).append("</i> ").append(query); sb.append("</p>"); sb.append("<p>Body: "); sb.append(body); sb.append("</p>"); sb.append("<p>Created: "); sb.append(created.toString()); sb.append("</p>"); sb.append("<p>Attempted: "); if (lastAttempt.getTime() == 0) sb.append("Never"); else sb.append(lastAttempt.toString()); sb.append("</p>"); return sb.toString(); } /** * Issues the specified request, calling its specified handler as appropriate * <p> * This should not be run from a UI thread * * @return * @throws APIException */ public void issue(Database db, ServerCredentials cred) throws APIException { URI uri; // Add the API key, if missing and we have it if (!query.contains("key=") && key != null) { String suffix = (query.contains("?")) ? "&key=" + key : "?key=" + key; query = query + suffix; } // Force lower-case method = method.toLowerCase(); Log.i(TAG, "Request " + method + ": " + query); try { uri = new URI(query); } catch (URISyntaxException e1) { throw new APIException(APIException.INVALID_URI, "Invalid URI: " + query, this); } HttpClient client = new DefaultHttpClient(); // The default implementation includes an Expect: header, which // confuses the Zotero servers. client.getParams().setParameter("http.protocol.expect-continue", false); // We also need to send our data nice and raw. client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpGet get = new HttpGet(uri); HttpPost post = new HttpPost(uri); HttpPut put = new HttpPut(uri); HttpDelete delete = new HttpDelete(uri); for (HttpRequest request : Arrays.asList(get, post, put, delete)) { request.setHeader("Zotero-API-Version", "1"); } // There are several shared initialization routines for POST and PUT if ("post".equals(method) || "put".equals(method)) { if (ifMatch != null) { post.setHeader("If-Match", ifMatch); put.setHeader("If-Match", ifMatch); } if (contentType != null) { post.setHeader("Content-Type", contentType); put.setHeader("Content-Type", contentType); } if (body != null) { Log.d(TAG, "Request body: " + body); // Force the encoding to UTF-8 StringEntity entity; try { entity = new StringEntity(body, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new APIException(APIException.INVALID_UUID, "UnsupportedEncodingException. This shouldn't " + "be possible-- UTF-8 is certainly supported", this); } post.setEntity(entity); put.setEntity(entity); } } if ("get".equals(method)) { if (contentType != null) { get.setHeader("Content-Type", contentType); } } /* For requests that return Atom feeds or entries (XML): * ITEMS_ALL ] * ITEMS_FOR_COLLECTION ]- Except format=keys * ITEMS_CHILDREN ] * * ITEM_BY_KEY * COLLECTIONS_ALL * ITEM_NEW * ITEM_UPDATE * ITEM_ATTACHMENT_NEW * ITEM_ATTACHMENT_UPDATE */ if ("xml".equals(disposition)) { XMLResponseParser parse = new XMLResponseParser(this); // These types will always have a temporary key that we've // been using locally, and which should be replaced by the // incoming item key. if (type == ITEM_NEW || type == ITEM_ATTACHMENT_NEW) { parse.update(updateType, updateKey); } try { HttpResponse hr; if ("post".equals(method)) { hr = client.execute(post); } else if ("put".equals(method)) { hr = client.execute(put); } else { // We fall back on GET here, but there really // shouldn't be anything else, so we throw in that case // for good measure if (!"get".equals(method)) { throw new APIException(APIException.INVALID_METHOD, "Unexpected method: " + method, this); } hr = client.execute(get); } // Record the response code status = hr.getStatusLine().getStatusCode(); Log.d(TAG, status + " : " + hr.getStatusLine().getReasonPhrase()); if (status < 400) { HttpEntity he = hr.getEntity(); InputStream in = he.getContent(); parse.setInputStream(in); // Entry mode if the request is an update (PUT) or if it is a request // for a single item by key (ITEM_BY_KEY) int mode = ("put".equals(method) || type == APIRequest.ITEM_BY_KEY) ? XMLResponseParser.MODE_ENTRY : XMLResponseParser.MODE_FEED; try { parse.parse(mode, uri.toString(), db); } catch (RuntimeException e) { throw new RuntimeException("Parser threw exception on request: " + method + " " + query, e); } } else { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); hr.getEntity().writeTo(ostream); Log.e(TAG, "Error Body: " + ostream.toString()); Log.e(TAG, "Request Body:" + body); if (status == 412) { // This is: "Precondition Failed", meaning that we provided // the wrong etag to update the item. That should mean that // there is a conflict between what we're sending (PUT) and // the server. We mark that ourselves and save the request // to the database, and also notify our handler. getHandler().onError(this, APIRequest.HTTP_ERROR_CONFLICT); } else { Log.e(TAG, "Response status " + status + " : " + ostream.toString()); getHandler().onError(this, APIRequest.HTTP_ERROR_UNSPECIFIED); } status = getHttpStatus() + REQ_FAILING; recordAttempt(db); // I'm not sure whether we should throw here throw new APIException(APIException.HTTP_ERROR, ostream.toString(), this); } } catch (Exception e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement el : e.getStackTrace()) { sb.append(el.toString()).append("\n"); } recordAttempt(db); throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(), this, e); } } // end if ("xml".equals(disposition)) {..} /* For requests that return non-XML data: * ITEMS_ALL ] * ITEMS_FOR_COLLECTION ]- For format=keys * ITEMS_CHILDREN ] * * No server response: * ITEM_DELETE * ITEM_MEMBERSHIP_ADD * ITEM_MEMBERSHIP_REMOVE * ITEM_ATTACHMENT_DELETE * * Currently not supported; return JSON: * ITEM_FIELDS * CREATOR_TYPES * ITEM_FIELDS_L10N * CREATOR_TYPES_L10N * * These ones use BasicResponseHandler, which gives us * the response as a basic string. This is only appropriate * for smaller responses, since it means we have to wait until * the entire response is received before parsing it, so we * don't use it for the XML responses. * * The disposition here is "none" or "raw". * * The JSON-returning requests, such as ITEM_FIELDS, are not currently * supported; they should have a disposition of their own. */ else { BasicResponseHandler brh = new BasicResponseHandler(); String resp; try { if ("post".equals(method)) { resp = client.execute(post, brh); } else if ("put".equals(method)) { resp = client.execute(put, brh); } else if ("delete".equals(method)) { resp = client.execute(delete, brh); } else { // We fall back on GET here, but there really // shouldn't be anything else, so we throw in that case // for good measure if (!"get".equals(method)) { throw new APIException(APIException.INVALID_METHOD, "Unexpected method: " + method, this); } resp = client.execute(get, brh); } } catch (IOException e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement el : e.getStackTrace()) { sb.append(el.toString()).append("\n"); } recordAttempt(db); throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(), this); } if ("raw".equals(disposition)) { /* * The output should be a newline-delimited set of alphanumeric * keys. */ String[] keys = resp.split("\n"); ArrayList<String> missing = new ArrayList<String>(); if (type == ITEMS_ALL || type == ITEMS_FOR_COLLECTION) { // Try to get a parent collection // Our query looks like this: // /users/5770/collections/2AJUSIU9/items int colloc = query.indexOf("/collections/"); int itemloc = query.indexOf("/items"); // The string "/collections/" is thirteen characters long ItemCollection coll = ItemCollection.load( query.substring(colloc + 13, itemloc), db); if (coll != null) { coll.loadChildren(db); // If this is a collection's key listing, we first look // for any synced keys we have that aren't in the list ArrayList<String> keyAL = new ArrayList<String>(Arrays.asList(keys)); ArrayList<Item> notThere = coll.notInKeys(keyAL); // We should then remove those memberships for (Item i : notThere) { coll.remove(i, true, db); } } ArrayList<Item> recd = new ArrayList<Item>(); for (String key1 : keys) { Item got = Item.load(key1, db); if (got == null) { missing.add(key1); } else { // We can update the collection membership immediately if (coll != null) coll.add(got, true, db); recd.add(got); } } if (coll != null) { coll.saveChildren(db); coll.save(db); } Log.d(TAG, "Received " + keys.length + " keys, " + missing.size() + " missing ones"); Log.d(TAG, "Have " + (double) recd.size() / keys.length + " of list"); if (recd.size() == keys.length) { Log.d(TAG, "No new items"); succeeded(db); } else if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) { Log.d(TAG, "Requesting full list"); APIRequest mReq; if (type == ITEMS_FOR_COLLECTION) { mReq = fetchItems(coll, false, cred); } else { mReq = fetchItems(false, cred); } mReq.status = REQ_NEW; mReq.save(db); } else { Log.d(TAG, "Requesting " + missing.size() + " items one by one"); APIRequest mReq; for (String key : missing) { // Queue request for the missing key mReq = fetchItem(key, cred); mReq.status = REQ_NEW; mReq.save(db); } // Queue request for the collection again, by key // XXX This is not the best way to make sure these // items are put in the correct collection. if (type == ITEMS_FOR_COLLECTION) { fetchItems(coll, true, cred).save(db); } } } else if (type == ITEMS_CHILDREN) { // Try to get a parent item // Our query looks like this: // /users/5770/items/2AJUSIU9/children int itemloc = query.indexOf("/items/"); int childloc = query.indexOf("/children"); // The string "/items/" is seven characters long Item item = Item.load( query.substring(itemloc + 7, childloc), db); ArrayList<Attachment> recd = new ArrayList<Attachment>(); for (String key1 : keys) { Attachment got = Attachment.load(key1, db); if (got == null) missing.add(key1); else recd.add(got); } if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) { APIRequest mReq; mReq = cred.prep(children(item)); mReq.status = REQ_NEW; mReq.save(db); } else { APIRequest mReq; for (String key : missing) { // Queue request for the missing key mReq = fetchItem(key, cred); mReq.status = REQ_NEW; mReq.save(db); } } } } else if ("json".equals(disposition)) { // TODO } else { /* Here, disposition should be "none" */ // Nothing to be done. } getHandler().onComplete(this); } } /** NEXT SECTION: Static methods for generating APIRequests */ /** * Produces an API request for the specified item key * * @param key Item key * @param cred Credentials */ public static APIRequest fetchItem(String key, ServerCredentials cred) { APIRequest req = new APIRequest(ServerCredentials.APIBASE + cred.prep(ServerCredentials.ITEMS) + "/" + key, "get", null); req.query = req.query + "?content=json"; req.disposition = "xml"; req.type = ITEM_BY_KEY; req.key = cred.getKey(); return req; } /** * Produces an API request for the items in a specified collection. * * @param collection The collection to fetch * @param keysOnly Use format=keys rather than format=atom/content=json * @param cred Credentials */ public static APIRequest fetchItems(ItemCollection collection, boolean keysOnly, ServerCredentials cred) { return fetchItems(collection.getKey(), keysOnly, cred); } /** * Produces an API request for the items in a specified collection. * * @param collectionKey The collection to fetch * @param keysOnly Use format=keys rather than format=atom/content=json * @param cred Credentials */ public static APIRequest fetchItems(String collectionKey, boolean keysOnly, ServerCredentials cred) { APIRequest req = new APIRequest(ServerCredentials.APIBASE + cred.prep(ServerCredentials.COLLECTIONS) + "/" + collectionKey + "/items", "get", null); if (keysOnly) { req.query = req.query + "?format=keys"; req.disposition = "raw"; } else { req.query = req.query + "?content=json"; req.disposition = "xml"; } req.type = APIRequest.ITEMS_FOR_COLLECTION; req.key = cred.getKey(); return req; } /** * Produces an API request for all items * * @param keysOnly Use format=keys rather than format=atom/content=json * @param cred Credentials */ public static APIRequest fetchItems(boolean keysOnly, ServerCredentials cred) { APIRequest req = new APIRequest(ServerCredentials.APIBASE + cred.prep(ServerCredentials.ITEMS) + "/top", "get", null); if (keysOnly) { req.query = req.query + "?format=keys"; req.disposition = "raw"; } else { req.query = req.query + "?content=json"; req.disposition = "xml"; } req.type = APIRequest.ITEMS_ALL; req.key = cred.getKey(); return req; } /** * Produces an API request for all collections */ public static APIRequest fetchCollections(ServerCredentials cred) { APIRequest req = new APIRequest(ServerCredentials.APIBASE + cred.prep(ServerCredentials.COLLECTIONS) + "?content=json", "get", null); req.disposition = "xml"; req.type = APIRequest.COLLECTIONS_ALL; req.key = cred.getKey(); return req; } /** * Produces an API request to remove the specified item from the collection. * This request always needs a key, but it isn't set automatically and should * be set by whatever consumes this request. * <p> * From the API docs: * DELETE /users/1/collections/QRST9876/items/ABCD2345 * * @param item * @param collection * @return */ public static APIRequest remove(Item item, ItemCollection collection) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.COLLECTIONS + "/" + collection.getKey() + "/items/" + item.getKey(), "DELETE", null); templ.disposition = "none"; return templ; } /** * Produces an API request to add the specified items to the collection. * This request always needs a key, but it isn't set automatically and should * be set by whatever consumes this request. * <p> * From the API docs: * POST /users/1/collections/QRST9876/items * <p> * ABCD2345 FBCD2335 * * @param items * @param collection * @return */ public static APIRequest add(ArrayList<Item> items, ItemCollection collection) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.COLLECTIONS + "/" + collection.getKey() + "/items", "POST", null); StringBuilder sb = new StringBuilder(); for (Item i : items) { sb.append(i.getKey()).append(" "); } templ.body = sb.toString(); templ.disposition = "none"; return templ; } /** * Craft a request to add a single item to the server * * @param item * @param collection * @return */ public static APIRequest add(Item item, ItemCollection collection) { ArrayList<Item> items = new ArrayList<Item>(); items.add(item); return add(items, collection); } /** * Craft a request to add items to the server * This does not attempt to update them, just add them. * * @param items * @return */ public static APIRequest add(ArrayList<Item> items) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "?content=json", "POST", null); templ.setBody(items); templ.disposition = "xml"; templ.updateType = "item"; // TODO this needs to be reworked to send all the keys. Or the whole system // needs to be reworked. Log.d(TAG, "Using the templ key of the first new item for now..."); templ.updateKey = items.get(0).getKey(); return templ; } /** * Craft a request to add child items (notes, attachments) to the server * This does not attempt to update them, just add them. * * @param item The parent item of the attachments * @param attachments * @return */ public static APIRequest add(Item item, ArrayList<Attachment> attachments) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "/" + item.getKey() + "/children?content=json", "POST", null); templ.setBodyWithNotes(attachments); templ.disposition = "xml"; templ.updateType = "attachment"; // TODO this needs to be reworked to send all the keys. Or the whole system // needs to be reworked. Log.d(TAG, "Using the templ key of the first new attachment for now..."); templ.updateKey = attachments.get(0).key; return templ; } /** * Craft a request for the children of the specified item * * @param item * @return */ public static APIRequest children(Item item) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "/" + item.getKey() + "/children?content=json", "GET", null); templ.disposition = "xml"; templ.type = ITEMS_CHILDREN; return templ; } /** * Craft a request to update an attachment on the server * Does not refresh eTag * * @param attachment * @return */ public static APIRequest update(Attachment attachment, Database db) { Log.d(TAG, "Attachment key pre-update: " + attachment.key); // If we have an attachment marked as new, update it if (attachment.key.length() > 10) { Item item = Item.load(attachment.parentKey, db); ArrayList<Attachment> aL = new ArrayList<Attachment>(); aL.add(attachment); if (item == null) { Log.e(TAG, "Orphaned attachment with key: " + attachment.key); attachment.delete(db); // send something, so we don't get errors elsewhere return new APIRequest(ServerCredentials.APIBASE, "GET", null); } return add(item, aL); } APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "/" + attachment.key, "PUT", null); try { templ.body = attachment.content.toString(4); } catch (JSONException e) { Log.e(TAG, "JSON exception setting body for attachment update: " + attachment.key, e); } templ.ifMatch = '"' + attachment.etag + '"'; templ.disposition = "xml"; return templ; } /** * Craft a request to update an attachment on the server * Does not refresh eTag * * @param item * @return */ public static APIRequest update(Item item) { // If we have an item with our temporary ID, upload it if (item.getKey().startsWith("zandy:")) { ArrayList<Item> mAL = new ArrayList<>(); mAL.add(item); return add(mAL); } APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "/" + item.getKey(), "PUT", null); templ.setBody(item); templ.ifMatch = '"' + item.getEtag() + '"'; Log.d(TAG, "etag: " + item.getEtag()); templ.disposition = "xml"; return templ; } /** * Produces API requests to delete queued items from the server. * This request always needs a key. * <p> * From the API docs: * DELETE /users/1/items/ABCD2345 * If-Match: "8e984e9b2a8fb560b0085b40f6c2c2b7" * * @param c * @return */ public static ArrayList<APIRequest> delete(Context c) { ArrayList<APIRequest> list = new ArrayList<>(); Database db = new Database(c); String[] args = {}; Cursor cur = db.rawQuery("select item_key, etag from deleteditems", args); if (cur == null) { db.close(); Log.d(TAG, "No deleted items found in database"); return list; } do { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "/" + cur.getString(0), "DELETE", null); templ.disposition = "none"; templ.ifMatch = cur.getString(1); Log.d(TAG, "Adding deleted item: " + cur.getString(0) + " : " + templ.ifMatch); // Save the request to the database to be dispatched later templ.save(db); list.add(templ); } while (cur.moveToNext()); cur.close(); db.rawQuery("delete from deleteditems", args); db.close(); return list; } /** * Returns APIRequest objects from the database * * @return */ static ArrayList<APIRequest> queue(Database db) { ArrayList<APIRequest> list = new ArrayList<>(); String[] cols = Database.REQUESTCOLS; String[] args = {}; Cursor cur = db.query("apirequests", cols, "", args, null, null, null, null); if (cur == null) return list; do { APIRequest req = new APIRequest(cur); list.add(req); Log.d(TAG, "Queueing request: " + req.query); } while (cur.moveToNext()); cur.close(); return list; } }
45,341
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
APIException.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/task/APIException.java
/******************************************************************************* * This file is part of Zandy. * * Zandy 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. * * Zandy 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 Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app.task; public class APIException extends Exception { /** * Don't know what this is for. */ private static final long serialVersionUID = 1L; /** * Exception types */ static final int INVALID_METHOD = 10; static final int INVALID_UUID = 11; static final int INVALID_URI = 12; static final int HTTP_ERROR = 13; public APIRequest request; public int type; APIException(int type, String message, APIRequest request) { super(message); this.request = request; } APIException(int type, String message, APIRequest request, Throwable cause) { super(message, cause); this.request = request; } }
1,567
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
APIEvent.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/task/APIEvent.java
package com.gimranov.zandy.app.task; public interface APIEvent { void onComplete(APIRequest request); void onUpdate(APIRequest request); void onError(APIRequest request, Exception exception); void onError(APIRequest request, int error); }
259
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
WebDavTrust.java
/FileExtraction/Java_unseen/avram_zandy/src/main/java/com/gimranov/zandy/app/webdav/WebDavTrust.java
package com.gimranov.zandy.app.webdav; import android.annotation.SuppressLint; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.SecureRandom; import java.security.cert.X509Certificate; public class WebDavTrust { private static final String TAG = WebDavTrust.class.getSimpleName(); // Kudos and blame to http://stackoverflow.com/a/1201102/950790 public static void installAllTrustingCertificate() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } @SuppressLint("TrustAllX509TrustManager") public void checkClientTrusted(X509Certificate[] certs, String authType) { } @SuppressLint("TrustAllX509TrustManager") public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception ignored) { } } }
1,551
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
MainActivityLoggedOutTest.java
/FileExtraction/Java_unseen/avram_zandy/src/androidTest/java/com/gimranov/zandy/app/MainActivityLoggedOutTest.java
package com.gimranov.zandy.app; import android.content.Intent; import android.net.Uri; import androidx.test.espresso.intent.rule.IntentsTestRule; import androidx.test.filters.LargeTest; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.intent.Intents.intended; import static androidx.test.espresso.intent.matcher.ComponentNameMatchers.hasClassName; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasData; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static com.schibsted.spain.barista.assertion.BaristaVisibilityAssertions.assertDisplayed; import static org.hamcrest.Matchers.allOf; @RunWith(AndroidJUnit4.class) @LargeTest public class MainActivityLoggedOutTest { @Rule public IntentsTestRule<MainActivity> activityTestRule = new IntentsTestRule<>(MainActivity.class); @Test public void loginButtonShowsOnLaunch() { assertDisplayed(R.id.loginButton); } @Test public void loginButtonLaunchesOauth() throws Exception { onView(withId(R.id.loginButton)).perform(click()); Thread.sleep(1000); intended(allOf(hasAction(Intent.ACTION_VIEW), hasData(new BaseMatcher<Uri>() { @Override public boolean matches(Object item) { return ((Uri) item).getHost().contains("zotero.org"); } @Override public void describeTo(Description description) { description.appendText("should have host zotero.org"); } }))); } @Test public void viewCollectionsLaunchesActivity() throws Exception { onView(withId(R.id.collectionButton)).perform(click()); intended(hasComponent(hasClassName(CollectionActivity.class.getName()))); } }
2,235
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
ApiTest.java
/FileExtraction/Java_unseen/avram_zandy/src/androidTest/java/com/gimranov/zandy/app/ApiTest.java
package com.gimranov.zandy.app; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import androidx.test.filters.SmallTest; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.task.APIException; import com.gimranov.zandy.app.task.APIRequest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static androidx.test.core.app.ApplicationProvider.getApplicationContext; import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.fail; @RunWith(AndroidJUnit4.class) @SmallTest public class ApiTest { private Context mContext; private Database mDb; private ServerCredentials mCred; /** * Access information for the Zandy test user on Zotero.org */ private static final String TEST_UID = BuildConfig.TEST_USER_ID; private static final String TEST_KEY = BuildConfig.TEST_USER_KEY_READONLY; private static final String TEST_COLLECTION = "U8GNSSF3"; // unlikely to exist private static final String TEST_MISSING_ITEM = "ZZZZZZZZ"; @Before public void setUp() { mContext = getApplicationContext(); mDb = new Database(mContext); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); SharedPreferences.Editor editor = settings.edit(); // For Zotero, the key and secret are identical, it seems editor.putString("user_key", TEST_KEY); editor.putString("user_secret", TEST_KEY); editor.putString("user_id", TEST_UID); editor.commit(); mCred = new ServerCredentials(mContext); } @Test public void testPreConditions() { // Make sure we do indeed have the key set up assertTrue(ServerCredentials.check(mContext)); } @Test public void testItemsRequest() throws APIException { APIRequest items = APIRequest.fetchItems(false, mCred); items.issue(mDb, mCred); } @Test public void testCollectionsRequest() throws APIException { APIRequest collections = APIRequest.fetchCollections(mCred); collections.issue(mDb, mCred); } @Test public void testItemsForCollection() throws APIException { APIRequest collection = APIRequest.fetchItems(TEST_COLLECTION, false, mCred); collection.issue(mDb, mCred); } // verify that we fail on this item, which should be missing public void testMissingItem() throws APIException { APIRequest missingItem = APIRequest.fetchItem(TEST_MISSING_ITEM, mCred); try { missingItem.issue(mDb, mCred); // We shouldn't get here fail(); } catch (APIException e) { // We expect only one specific exception message if (!"Item does not exist".equals(e.getCause().getMessage())) throw e; } } }
2,744
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
SyncTest.java
/FileExtraction/Java_unseen/avram_zandy/src/androidTest/java/com/gimranov/zandy/app/SyncTest.java
package com.gimranov.zandy.app; import android.content.SharedPreferences; import android.preference.PreferenceManager; import androidx.test.espresso.ViewInteraction; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import com.gimranov.zandy.app.data.Database; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static androidx.test.core.app.ApplicationProvider.getApplicationContext; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.RootMatchers.withDecorView; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withClassName; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; @LargeTest @RunWith(AndroidJUnit4.class) public class SyncTest { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Before public void setUpCredentials() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); preferences.edit() .putString("user_id", BuildConfig.TEST_USER_ID) .putString("user_key", BuildConfig.TEST_USER_KEY_READONLY) .commit(); } @After public void clearCredentials() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); preferences.edit().clear().commit(); } @Before @After public void clearDatabase() { Database database = new Database(getApplicationContext()); database.resetAllData(); } @Test public void syncTest() { openActionBarOverflowOrOptionsMenu(getApplicationContext()); ViewInteraction textView = onView( allOf(withId(android.R.id.title), withText(R.string.menu_sync), childAtPosition( childAtPosition( withClassName(is("com.android.internal.view.menu.ListMenuItemView")), 0), 0), isDisplayed())); textView.perform(click()); onView(withText(R.string.sync_started)) .inRoot(withDecorView(not(is(mActivityTestRule.getActivity().getWindow().getDecorView())))) .check(matches(isDisplayed())); ViewInteraction button2 = onView( allOf(withId(R.id.itemButton), withText(R.string.view_items), childAtPosition( allOf(withId(R.id.main), childAtPosition( withId(android.R.id.content), 0)), 1), isDisplayed())); button2.perform(click()); } private static Matcher<View> childAtPosition( final Matcher<View> parentMatcher, final int position) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("Child at position " + position + " in parent "); parentMatcher.describeTo(description); } @Override public boolean matchesSafely(View view) { ViewParent parent = view.getParent(); return parent instanceof ViewGroup && parentMatcher.matches(parent) && view.equals(((ViewGroup) parent).getChildAt(position)); } }; } }
4,470
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
MainActivityLoggedInTest.java
/FileExtraction/Java_unseen/avram_zandy/src/androidTest/java/com/gimranov/zandy/app/MainActivityLoggedInTest.java
package com.gimranov.zandy.app; import android.content.SharedPreferences; import android.preference.PreferenceManager; import androidx.test.espresso.intent.rule.IntentsTestRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import com.gimranov.zandy.app.data.Database; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static androidx.test.core.app.ApplicationProvider.getApplicationContext; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static org.hamcrest.Matchers.not; @RunWith(AndroidJUnit4.class) @LargeTest public class MainActivityLoggedInTest { @Rule public IntentsTestRule<MainActivity> activityTestRule = new IntentsTestRule<MainActivity>(MainActivity.class){ @Override protected void beforeActivityLaunched() { super.beforeActivityLaunched(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); preferences.edit() .putString("user_id", BuildConfig.TEST_USER_ID) .putString("user_key", BuildConfig.TEST_USER_KEY_READONLY) .commit(); } }; @Before public void setUpCredentials() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); preferences.edit() .putString("user_id", BuildConfig.TEST_USER_ID) .putString("user_key", BuildConfig.TEST_USER_KEY_READONLY) .commit(); } @After public void clearCredentials() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); preferences.edit().clear().commit(); } @Before @After public void clearDatabase() { Database database = new Database(getApplicationContext()); database.resetAllData(); } @Test public void loginButtonDoesNotShow() { onView(withId(R.id.loginButton)).check(matches(not(isDisplayed()))); } }
2,461
Java
.java
avram/zandy
144
28
31
2011-08-09T10:18:49Z
2023-08-22T04:06:10Z
TCPClient.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/TCPClient.java
package com.ecos.train; import com.ecos.train.activity.MainActivity; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; public class TCPClient extends Thread { private String serverMessage; private boolean mRun = false; Socket socket; public PrintWriter out; BufferedReader in; public TCPClient() { this.start(); } public void stopClient(){ mRun = false; try { socket.close(); } catch (Exception e) { } } public void run() { mRun = true; try { InetAddress serverAddr = InetAddress.getByName(Settings.consoleIp); socket = new Socket(serverAddr, Settings.consolePort); try { //send the message to the server out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); //pass the out poitner to writer thread MainActivity.mTcpWrite.setOut(out); //receive the message which the server sends back in = new BufferedReader(new InputStreamReader(socket.getInputStream())); StringBuilder sb = new StringBuilder(); MainActivity.getMessage("READY"); //in this while the client listens for the messages sent by the server while (mRun) { serverMessage = in.readLine(); if (serverMessage.startsWith("<REPLY") || serverMessage.startsWith("<EVENT")) { sb = new StringBuilder(); sb.append(serverMessage).append("\n"); } else if (serverMessage.startsWith("<END")) { sb.append(serverMessage).append("\n"); if (serverMessage != null) { //call the method messageReceived from MyActivity class MainActivity.getMessage(sb.toString().trim()); } serverMessage = null; } else { sb.append(serverMessage).append("\n"); } } } catch (Exception e) { MainActivity.getMessage("DISCONNECT"); } finally { //the socket must be closed. It is not possible to reconnect to this socket // after it is closed, which means a new socket instance has to be created. socket.close(); } } catch (Exception e) { MainActivity.getMessage("DISCONNECT"); } } }
2,252
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z
TCPWrite.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/TCPWrite.java
package com.ecos.train; import android.util.Log; import com.ecos.train.activity.MainActivity; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedDeque; public class TCPWrite extends Thread { private boolean mRun = false; private Queue lstMessage; PrintWriter out; public TCPWrite() { lstMessage = new ConcurrentLinkedDeque(); } public void setOut(PrintWriter pw) { out = pw; this.start(); } /** * Sends the message entered by client to the server * @param message text entered by client */ public void sendMessage(String message) { lstMessage.offer(message); } public void sendTCP(String message){ if (out != null && !out.checkError()) { Log.d("SEND", message); out.println(message); out.flush(); } } public void stopClient(){ mRun = false; } public void run() { mRun = true; String m; while (mRun) { synchronized(lstMessage) { while(!lstMessage.isEmpty()) { m = (String) lstMessage.poll(); if (m != null) { sendTCP(m); } } } } } /**************************************************************************/ /** Command Console **/ /**************************************************************************/ public void getConsoleState() { sendMessage("get(1, status, info)"); } public void emergencyStop(boolean state) { if(state) { sendMessage("set(1, stop)"); } else { sendMessage("set(1, go)"); } } public void viewConsole() { sendMessage("request(1, view)"); } /**************************************************************************/ /** Command Train Manager **/ /**************************************************************************/ public void getAllTrains() { sendMessage("queryObjects(10, name, addr)"); } /**************************************************************************/ /** Command Train **/ /**************************************************************************/ public void getTrainMainState(int id) { sendMessage("get("+id+",name,speed,dir,speedindicator)"); } public void getTrainSymbol(int id) { sendMessage("get("+id+",locodesc)"); } public void getTrainButtonState(int id) { sendMessage("get("+id+",func[0],func[1],func[2],func[3]," + "func[4],func[5],func[6],func[7])"); } public void getTrainButtonStateF8F15(int id) { sendMessage("get("+id+",func[8],func[9],func[10],func[11]," + "func[12],func[13],func[14],func[15])"); } public void getTrainButtonStateF16F23(int id) { sendMessage("get("+id+",func[16],func[17],func[18],func[19]," + "func[20],func[21],func[22],func[23])"); } public void getTrainButtonStateF24F27(int id) { sendMessage("get("+id+",func[24],func[25],func[26],func[27])"); } public void setButton(int id, int i, boolean enabled) { int value = (enabled) ? 1 : 0; sendMessage("set("+id+", func["+i+", "+value+"])"); } public void setSpeed(int id,int speed) { sendMessage("set("+id+", speed["+speed+"])"); } public void setDir(int id,int dir) { sendMessage("set("+id+", dir["+dir+"])"); } public void takeControl(int id) { sendMessage("request("+id+", control, force)"); } public void releaseControl(int id) { sendMessage("release("+id+", control)"); } public void takeViewTrain(int id) { sendMessage("request("+id+", view)"); } public void releaseViewTrain(int id) { sendMessage("release("+id+", view)"); } public void setName(int id, String name) { sendMessage("set("+id+", name[\""+name+"\"])"); } public void getButtonName(int id) { sendMessage("get("+id+", funcexists[0], " + "funcexists[1], funcexists[2], funcexists[3], funcexists[4], funcexists[5], funcexists[6], funcexists[7])"); } public void getButtonNameF8F15(int id) { sendMessage("get("+id+", funcexists[8], " + "funcexists[9], funcexists[10], funcexists[11], funcexists[12], funcexists[13], funcexists[14], funcexists[15])"); } public void getButtonNameF16F23(int id) { sendMessage("get("+id+", funcexists[16], " + "funcexists[17], funcexists[18], funcexists[19], funcexists[20], funcexists[21], funcexists[22], funcexists[23])"); } public void getButtonNameF24F27(int id) { sendMessage("get("+id+", funcexists[24], " + "funcexists[25], funcexists[26], funcexists[27])"); } public void delete(int id) { sendMessage("delete("+id+")"); } /**************************************************************************/ /** Command Switching Objects **/ /**************************************************************************/ public void getAllObject() { sendMessage("queryObjects(11, name1, name2, addrext)"); } public void takeViewObject() { sendMessage("request(11, view)"); } public void releaseViewObject() { sendMessage("release(11, view)"); } public void getState(int id) { sendMessage("request("+id+",view)"); sendMessage("get("+id+", state, symbol)"); } public void changeState(int id, int val) { sendMessage("request("+id+",control)"); sendMessage("set("+id+", state["+val+"])"); sendMessage("release("+id+",control)"); } }
5,381
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z
Settings.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/Settings.java
package com.ecos.train; import java.util.ArrayList; import java.util.List; import com.ecos.train.object.Train; public class Settings { public static final int CONSOLE_PORT = 15471; public static String consoleIp = ""; public static int consolePort = CONSOLE_PORT; public static List<Train> allTrains = new ArrayList<Train>(); public static int currentTrainIndex = -1; public static boolean fullVersion = false; public static final int SPEED_MIN = 0; public static final int SPEED_MAX = 127; public static final int SPEED_STEP = 10; public static final int FUNCTION_BUTTONS = 28; public static boolean sortById = false; public static String protocolVersion = "0.2"; public static Train getCurrentTrain() { if(currentTrainIndex != -1) { return allTrains.get(currentTrainIndex); } else { return new Train(-1, "", ""); } } }
859
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z
PreferencesActivity.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/activity/PreferencesActivity.java
/******************************************************************************* * Copyright (c) 2011 LSIIT - Université de Strasbourg * Copyright (c) 2011 Erkan VALENTIN <erkan.valentin[at]unistra.fr> * http://www.senslab.info/ * * 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 com.ecos.train.activity; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import com.ecos.train.R; public class PreferencesActivity extends PreferenceActivity implements OnPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); bindPreferenceSummaryToValue(findPreference("ip")); bindPreferenceSummaryToValue(findPreference("port")); bindPreferenceSummaryToValue(findPreference("pref_speed")); } /** * Attaches a listener so the summary is always updated with the preference value. * Also fires the listener once, to initialize the summary (so it shows up before the value * is changed.) */ private void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(this); // Trigger the listener immediately with the preference's // current value. onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list (since they have separate labels/values). ListPreference listPreference = (ListPreference) preference; int prefIndex = listPreference.findIndexOfValue(stringValue); if (prefIndex >= 0) { preference.setSummary(listPreference.getEntries()[prefIndex]); } } else { // For other preferences, set the summary to the value's simple string representation. preference.setSummary(stringValue); } return true; } }
3,033
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z
MainActivity.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/activity/MainActivity.java
/******************************************************************************* * Copyright (c) 2011 LSIIT - Université de Strasbourg * Copyright (c) 2011 Erkan VALENTIN <erkan.valentin[at]unistra.fr> * http://www.senslab.info/ * * 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 com.ecos.train.activity; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.ecos.train.R; import com.ecos.train.Settings; import com.ecos.train.TCPClient; import com.ecos.train.TCPWrite; import com.ecos.train.object.FunctionSymbol; import com.ecos.train.object.SwitchSymbol; import com.ecos.train.object.Train; import com.ecos.train.ui.TrainSpinAdapter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity implements OnClickListener, OnSeekBarChangeListener, OnItemSelectedListener, OnTouchListener { public static final String LITE_PACKAGE = "com.ecos.train"; public static final String FULL_PACKAGE = "com.ecos.train.unlock"; SharedPreferences pref = null; public static TCPClient mTcpClient = null; public static TCPWrite mTcpWrite = null; private static Handler mainHandler; private static Runnable mainUpdate; private static Queue lstMessage = new ConcurrentLinkedDeque(); ToggleButton btnConnect = null; ToggleButton cbReverse = null; Spinner sTrainId = null; ToggleButton btnControl = null; ToggleButton btnEmergency = null; SeekBar sbSpeed = null; TextView tvSpeed = null; LinearLayout llSwitch = null; LinearLayout llTrain = null; TrainSpinAdapter dataAdapter; private MenuItem editItem = null; Dialog infoDialog = null; TextView protocolVersion = null; TextView applicationVersion = null; TextView hardwareVersion = null; TextView ecosVersion = null; List<ToggleButton> listSwitch = new ArrayList<ToggleButton>(); List<SeekBar> listSwitchMulti = new ArrayList<SeekBar>(); List<TextView> listSwitchMultiValue = new ArrayList<TextView>(); List<TextView> listSwitchMultiLabel = new ArrayList<TextView>(); List<ToggleButton> listButtons = new ArrayList<ToggleButton>(); private static final int SETTINGS = 0; private int speedStep = Settings.SPEED_STEP; private boolean connected = false; private boolean symbolLoaded = false; private boolean switchLoaded = false; private boolean volumeDownPressed = false; public static Activity activity; /**************************************************************************/ /** Listeners **/ /**************************************************************************/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); //StrictMode.setThreadPolicy(policy); //get elements setContentView(R.layout.main); btnConnect = (ToggleButton) findViewById(R.id.btnConnect); cbReverse = (ToggleButton) findViewById(R.id.cbReverse); sbSpeed = (SeekBar) findViewById(R.id.sbSpeed); sTrainId = (Spinner) findViewById(R.id.sTrainId); btnControl = (ToggleButton) findViewById(R.id.tbControl); btnEmergency = (ToggleButton) findViewById(R.id.btnEmergency); tvSpeed = (TextView) findViewById(R.id.tvSpeed); //add listeners btnConnect.setOnClickListener(this); cbReverse.setOnClickListener(this); sbSpeed.setOnSeekBarChangeListener(this); sTrainId.setOnItemSelectedListener(this); btnControl.setOnClickListener(this); //get the function buttons Resources res = getResources(); for(int i=0; i<Settings.FUNCTION_BUTTONS; i++) { int resourceId = res.getIdentifier("btnF"+i, "id", getPackageName()); listButtons.add(((ToggleButton) findViewById(resourceId))); } initFunctionButtons(); //init buttons setStateButtons(false); setStateEmergency(false); setStateList(false); setStateControl(false); ((ToggleButton) findViewById(R.id.btnEmergency)).setOnClickListener(this); ((TextView) findViewById(R.id.tvF8_F15)).setOnClickListener(this); ((TextView) findViewById(R.id.tvF16_F23)).setOnClickListener(this); ((TextView) findViewById(R.id.tvF24_F27)).setOnClickListener(this); pref = PreferenceManager.getDefaultSharedPreferences(this); Settings.fullVersion = true; //checkSig(this); //get speed step in save preference speedStep = Integer.parseInt(pref.getString("pref_speed", Settings.SPEED_STEP+"")); //info dialog infoDialog = new Dialog(this); LayoutInflater inflater = getLayoutInflater(); final View infoView = inflater.inflate(R.layout.info_dialog, null); infoDialog.setContentView(infoView); infoDialog.setTitle(getString(R.string.app_name)); protocolVersion = ((TextView) infoView.findViewById(R.id.tvProtocolVersion)); applicationVersion = ((TextView) infoView.findViewById(R.id.tvApplicationVersion)); hardwareVersion = ((TextView) infoView.findViewById(R.id.tvHardwareVersion)); ecosVersion = ((TextView) infoView.findViewById(R.id.tvEcosVersion)); llSwitch = ((LinearLayout) findViewById(R.id.llSwitch)); llSwitch.setVisibility(LinearLayout.GONE); llTrain = ((LinearLayout) findViewById(R.id.llTrain)); llTrain.setVisibility(LinearLayout.VISIBLE); boolean lockRotation = pref.getBoolean("pref_lockrotation", false); if(lockRotation) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } displayArrow(R.id.tvF8_F15, "down"); displayArrow(R.id.tvF16_F23, "down"); displayArrow(R.id.tvF24_F27, "down"); activity = this; mainHandler = new Handler(); mainUpdate = new Runnable() { public void run() { readSocket(); } }; } public void onRadioButtonClicked(View view) { boolean checked = ((RadioButton) view).isChecked(); switch(view.getId()) { case R.id.rTrain: if (checked) { llTrain.setVisibility(LinearLayout.VISIBLE); llSwitch.setVisibility(LinearLayout.GONE); } break; case R.id.rSwitch: if (checked) { llSwitch.setVisibility(LinearLayout.VISIBLE); llTrain.setVisibility(LinearLayout.GONE); if(Settings.fullVersion && connected) { if(!switchLoaded) { mTcpWrite.getAllObject(); switchLoaded = true; } } } break; } } @Override public void onClick(View v) { //click on a function buttons if(v.getTag(R.string.btn_name) != null) { if(v.getTag(R.string.btn_name).toString().startsWith("btn")) { String token[] = v.getTag(R.string.btn_name).toString().split(";"); mTcpWrite.setButton(Settings.getCurrentTrain().getId(), Integer.parseInt( token[1]), ((ToggleButton) v).isChecked()); return; } } //click on emergency button if(v.getId() == R.id.btnEmergency) { mTcpWrite.emergencyStop(((ToggleButton) v).isChecked()); } //click on connect button else if(v.getId() == R.id.btnConnect) { symbolLoaded = false; switchLoaded = false; connectToStation(((ToggleButton) v).isChecked()); } //click on control button else if(v.getId() == R.id.tbControl) { if(((ToggleButton) v).isChecked()) { mTcpWrite.takeControl(Settings.getCurrentTrain().getId()); mTcpWrite.takeViewTrain(Settings.getCurrentTrain().getId()); setStateButtons(true); } else { mTcpWrite.releaseControl(Settings.getCurrentTrain().getId()); setStateButtons(false); } } //click on F8-F15 banner else if(v.getId() == R.id.tvF8_F15) { LinearLayout l = (LinearLayout) findViewById(R.id.llF8_F15); if(l.getVisibility() == LinearLayout.VISIBLE) { l.setVisibility(LinearLayout.GONE); displayArrow(R.id.tvF8_F15, "down"); } else { if(!connected) { return; } l.setVisibility(LinearLayout.VISIBLE); displayArrow(R.id.tvF8_F15, "up"); mTcpWrite.getTrainButtonStateF8F15(Settings.getCurrentTrain().getId()); } } //click on F16-F23 banner else if(v.getId() == R.id.tvF16_F23) { LinearLayout l = (LinearLayout) findViewById(R.id.llF16_F23); if(l.getVisibility() == LinearLayout.VISIBLE) { l.setVisibility(LinearLayout.GONE); displayArrow(R.id.tvF16_F23, "down"); } else { if(!connected) { return; } l.setVisibility(LinearLayout.VISIBLE); displayArrow(R.id.tvF16_F23, "up"); mTcpWrite.getTrainButtonStateF16F23(Settings.getCurrentTrain().getId()); } } //click on F24-F27 banner else if(v.getId() == R.id.tvF24_F27) { LinearLayout l = (LinearLayout) findViewById(R.id.llF24_F27); if(l.getVisibility() == LinearLayout.VISIBLE) { l.setVisibility(LinearLayout.GONE); displayArrow(R.id.tvF24_F27, "down"); } else { if(!connected) { return; } l.setVisibility(LinearLayout.VISIBLE); displayArrow(R.id.tvF24_F27, "up"); mTcpWrite.getTrainButtonStateF24F27(Settings.getCurrentTrain().getId()); } } //click on reverse button else if(v.getId() == R.id.cbReverse) { mTcpWrite.setDir(Settings.getCurrentTrain().getId(),((ToggleButton) v).isChecked()?1:0); } //click on switching objects button else { mTcpWrite.changeState(Integer.parseInt(v.getTag().toString()), ((ToggleButton) v).isChecked()?1 :0); } } public void displayArrow(int label, String state) { TextView t = (TextView) findViewById(label); Resources res = getResources(); int resourceId = res.getIdentifier(state, "drawable", getPackageName()); Drawable img = res.getDrawable(resourceId); t.setCompoundDrawablesWithIntrinsicBounds(img, null , null, null); } @Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { } @Override public void onStartTrackingTouch(SeekBar arg0) { } @Override public void onStopTrackingTouch(SeekBar sb) { //speed seekbar if(sb.getId() == R.id.sbSpeed) { mTcpWrite.setSpeed(Settings.getCurrentTrain().getId(), sb.getProgress()); displaySpeed(sb.getProgress()); } //switching object seekbar else { try { int id = Integer.parseInt(sb.getTag().toString()); mTcpWrite.changeState(id, sb.getProgress()); for(TextView t: listSwitchMultiValue) { if(Integer.parseInt(t.getTag().toString()) == id) { t.setText(sb.getProgress()+""); } } } catch(Exception e) {} } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); editItem = menu.getItem(1); return true; } @Override public boolean onPrepareOptionsMenu (Menu menu) { if(Settings.currentTrainIndex == -1) { menu.getItem(1).setEnabled(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.iSettings: Intent i = new Intent(this, PreferencesActivity.class); startActivityForResult(i, MainActivity.SETTINGS); return true; case R.id.iEdit: //show alert dialog to edit train name AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.edit_form, null); final EditText edName = ((EditText)dialogView.findViewById(R.id.edName)); final TextView edId = ((TextView)dialogView.findViewById(R.id.tv_id)); final TextView edAddress = ((TextView)dialogView.findViewById(R.id.tv_address)); edName.setText(Settings.getCurrentTrain().getName()); edId.setText(Settings.getCurrentTrain().getId()+""); edAddress.setText(Settings.getCurrentTrain().getAddress()); builder.setView( dialogView); builder.setTitle(getString(R.string.btn_edit)) .setPositiveButton(R.string.tv_save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String name = edName.getText().toString(); mTcpWrite.setName(Settings.getCurrentTrain().getId(), name); for (Train t : Settings.allTrains) { if(t.getId() == Settings.getCurrentTrain().getId()) { t.setName(name); } } dataAdapter.notifyDataSetChanged(); } }) .setNegativeButton(R.string.tv_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); return true; case R.id.iInfo: //show alert dialog to display console info infoDialog.show(); try { PackageInfo manager = getPackageManager().getPackageInfo(getPackageName(), 0); ecosVersion.setText(manager.versionName + " - build " + manager.versionCode); } catch (Exception e) { } return true; default: return super.onOptionsItemSelected(item); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == MainActivity.SETTINGS) { //get speed step speedStep = Integer.parseInt(pref.getString("pref_speed", Settings.SPEED_STEP+"")); //check if something change on ip address if(!Settings.consoleIp.equals(pref.getString("ip", ""))){ disconnect(); return; } //check if something change on sorting preference if(Settings.sortById != pref.getBoolean("pref_sort", false)) { Settings.sortById = pref.getBoolean("pref_sort", false); if(connected) { sortTrainsList(Settings.sortById); dataAdapter.notifyDataSetChanged(); //restore the latest selection for(int i=0; i<Settings.allTrains.size(); i++) { if(Settings.allTrains.get(i).getId() == Settings.getCurrentTrain().getId()) { sTrainId.setSelection(i); break; } } } } //check if locodesc enable boolean locodesc = pref.getBoolean("pref_locodesc", false); if(locodesc) { if(mTcpClient != null) { getTrainsSymbol(); } } //check if lock screen rotation enable boolean lockRotation = pref.getBoolean("pref_lockrotation", false); if(lockRotation) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } } } @Override public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) { setStateButtons(false); hideExtraFunctionButtons(); //release old train if(Settings.currentTrainIndex != -1) { mTcpWrite.releaseViewTrain(Settings.getCurrentTrain().getId()); mTcpWrite.releaseControl(Settings.getCurrentTrain().getId()); } //get train and take control Settings.currentTrainIndex = pos; mTcpWrite.takeControl(Settings.getCurrentTrain().getId()); btnControl.setChecked(true); mTcpWrite.takeViewTrain(Settings.getCurrentTrain().getId()); mTcpWrite.getTrainMainState(Settings.getCurrentTrain().getId()); displayArrow(R.id.tvF8_F15, "down"); displayArrow(R.id.tvF16_F23, "down"); } @Override public void onNothingSelected(AdapterView<?> arg0) { } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onStop(); try { mTcpClient.stopClient(); } catch (Exception e) { } } /**************************************************************************/ /** Buttons management **/ /**************************************************************************/ public void setFnButtons(boolean isEnabled) { for(ToggleButton t: listButtons) { t.setEnabled(isEnabled); } if(!Settings.fullVersion) { for(int i=8; i<listButtons.size(); i++) { listButtons.get(i).setEnabled(false); } } } public void setStateButtons(boolean state) { sbSpeed.setEnabled(state); cbReverse.setEnabled(state); sbSpeed.setEnabled(state); if(editItem != null) { editItem.setEnabled(state); if(!Settings.fullVersion) { editItem.setEnabled(false); } } setFnButtons(state); } public void hideExtraFunctionButtons() { ((LinearLayout) findViewById(R.id.llF8_F15)).setVisibility(LinearLayout.GONE); ((LinearLayout) findViewById(R.id.llF16_F23)).setVisibility(LinearLayout.GONE); } public void setStateControl(boolean state) { btnControl.setEnabled(state); } public void setStateEmergency(boolean state) { btnEmergency.setEnabled(state); } public void setStateList(boolean state) { sTrainId.setEnabled(state); } public void readSocket() { String m; synchronized (lstMessage) { while (!lstMessage.isEmpty()) { m = (String) lstMessage.poll(); if (m != null) { readMessage(m); } } } } public void readMessage(String mMessage) { //Check last line Log.d("RECEIVED", mMessage + ""); String respLine[] = mMessage.split("\n"); //check command result before String cmd_result = respLine[respLine.length-1]; if(cmd_result.equals("DISCONNECT")) { disconnect(); } else if(cmd_result.equals("READY")) { } else { //just check the return code if(!cmd_result.startsWith("<END 0 ")) { Toast.makeText(getApplicationContext(), cmd_result, Toast.LENGTH_SHORT).show(); return; } } //if not connected, set connection! if(!connected) { //check if connection ok if(mMessage.equals("READY")) { connected = true; setStateList(true); setStateEmergency(true); mTcpWrite.viewConsole(); btnConnect.setChecked(true); mTcpWrite.getConsoleState(); } else { connected = false; btnConnect.setChecked(false); } } //emergency state response if(respLine[0].equals("<REPLY get(1, status, info)>")) { parseEmergency(respLine); parseConsoleVersion(respLine); mTcpWrite.getAllTrains(); } //train list response else if(respLine[0].equals("<REPLY queryObjects(10, name, addr)>")) { Settings.allTrains = parseTrainsList(mMessage); Settings.sortById = pref.getBoolean("pref_sort", false); sortTrainsList(Settings.sortById); dataAdapter = new TrainSpinAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, Settings.allTrains); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sTrainId.setAdapter(dataAdapter); } //train state response else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+",name,speed,dir,speedindicator)>")) { parseTrainState(respLine); initFunctionButtons(); mTcpWrite.getTrainButtonState(Settings.getCurrentTrain().getId()); } //train buttons state response else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+",func[0],func[1],func[2],func[3]," + "func[4],func[5],func[6],func[7])>")) { parseButtons(respLine); setStateButtons(true); hideExtraFunctionButtons(); setStateList(true); setStateControl(true); if(!Settings.protocolVersion.equals("0.1")) { mTcpWrite.getButtonName(Settings.getCurrentTrain().getId()); } } //manage event else if(respLine[0].startsWith("<EVENT")) { parseEvent(respLine); } //console info response else if(respLine[0].equals("<REPLY get(1, info)>")) { parseConsoleVersion(respLine); } //switching objects list response else if(respLine[0].equals("<REPLY queryObjects(11, name1, name2, addrext)>")) { parseSwitchList(respLine); } //train buttons name response 0-7 else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+", funcexists[0], " + "funcexists[1], funcexists[2], funcexists[3], funcexists[4], funcexists[5], funcexists[6], funcexists[7])>")){ parseButtonSymbol(respLine); boolean locodesc = pref.getBoolean("pref_locodesc", false); if(locodesc) { if(!symbolLoaded) { symbolLoaded = true; getTrainsSymbol(); } } } //train buttons name response 8-15 else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+", funcexists[8], " + "funcexists[9], funcexists[10], funcexists[11], funcexists[12], funcexists[13], funcexists[14], funcexists[15])>")){ parseButtonSymbol(respLine); } //train buttons name response 16-23 else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+", funcexists[16], " + "funcexists[17], funcexists[18], funcexists[19], funcexists[20], funcexists[21], funcexists[22], funcexists[23])>")){ parseButtonSymbol(respLine); } //train buttons name response 24-27 else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+", funcexists[24], " + "funcexists[25], funcexists[26], funcexists[27])>")){ parseButtonSymbol(respLine); } //train buttons response 8-15 else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+",func[8],func[9],func[10],func[11]," + "func[12],func[13],func[14],func[15])>")) { parseButtons(respLine); if(!Settings.protocolVersion.equals("0.1")) { mTcpWrite.getButtonNameF8F15(Settings.getCurrentTrain().getId()); } } //train buttons response 16-23 else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+",func[16],func[17],func[18],func[19]," + "func[20],func[21],func[22],func[23])>")) { parseButtons(respLine); if(!Settings.protocolVersion.equals("0.1")) { mTcpWrite.getButtonNameF16F23(Settings.getCurrentTrain().getId()); } } //train buttons response 24-27 else if(respLine[0].equals("<REPLY get("+Settings.getCurrentTrain().getId()+",func[24],func[25],func[26],func[27])>")) { parseButtons(respLine); if(!Settings.protocolVersion.equals("0.1")) { mTcpWrite.getButtonNameF24F27(Settings.getCurrentTrain().getId()); } } //a switching object response else { parseTrainsSymbol(respLine); parseSwitch(respLine); parseSwitchSymbol(respLine); } } public static void getMessage(String message) { lstMessage.offer(message); Log.d("RECEIVED", message+""); if(mainHandler != null) mainHandler.post(mainUpdate); } /**************************************************************************/ /** Connect/Disconnect to console **/ /**************************************************************************/ public void connectToStation(boolean state) { //connect if(state) { Settings.consoleIp = pref.getString("ip", ""); try{ Settings.consolePort = Integer.parseInt( pref.getString("port", Settings.CONSOLE_PORT+"")); } catch(Exception e) { Settings.consolePort = Settings.CONSOLE_PORT; } //new connectTask().execute(""); mTcpClient = new TCPClient(); mTcpWrite = new TCPWrite(); } else { disconnect(); } } public void disconnect() { if(mTcpClient != null) { mTcpClient.stopClient(); mTcpWrite.stopClient(); } connected = false; setStateButtons(false); hideExtraFunctionButtons(); setStateControl(false); setStateEmergency(false); setStateList(false); llSwitch.removeAllViews(); llSwitch.setVisibility(LinearLayout.GONE); displayArrow(R.id.tvF8_F15, "down"); displayArrow(R.id.tvF16_F23, "down"); } /**************************************************************************/ /** Parse output **/ /**************************************************************************/ public List<Train> parseTrainsList(String result) { List<Train> listTrain = new ArrayList<Train>(); String list[] = result.split("\n"); Pattern p = Pattern.compile("(.*) name\\[\"(.*)\"\\] addr\\[(.*)\\]"); String id = ""; String addr = ""; String name = ""; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); while (m.find() == true) { id = m.group(1).trim(); name = m.group(2).trim(); addr = m.group(3).trim(); } int idd = -1; try { idd = Integer.parseInt(id); } catch(Exception e) { } listTrain.add(new Train(idd, name, addr)); } return listTrain; } public void parseTrainState(String[] result) { parseSpeed(result); parseDir(result); } public boolean parseSpeed(String[] list) { if(volumeDownPressed) { return true; } String id = ""; int iid = 0; boolean match = false; Pattern p = Pattern.compile("(.*) speedindicator\\[(.*)\\]"); for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); while (m.find() == true) { match = true; id = m.group(1).trim(); try { iid = Integer.parseInt(id); Settings.getCurrentTrain().setSpeedIndicator(Integer.parseInt(m.group(2).trim())); } catch(Exception e) { } } } p = Pattern.compile("(.*) speed\\[(.*)\\]"); int speed = 0; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); while (m.find() == true) { match = true; id = m.group(1).trim(); try { iid = Integer.parseInt(id); speed = Integer.parseInt(m.group(2).trim()); } catch(Exception e) { } if(iid == Settings.getCurrentTrain().getId()) { sbSpeed.setProgress(speed); displaySpeed(speed); } } } return match; } public boolean parseDir(String[] list) { Pattern p = Pattern.compile("(.*) dir\\[(.*)\\]"); String id = ""; int iid = 0; String dir = ""; boolean idir = true; boolean match = false; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); while (m.find() == true) { match = true; id = m.group(1).trim(); try { iid = Integer.parseInt(id); } catch(Exception e) { } dir = m.group(2).trim(); if(iid == Settings.getCurrentTrain().getId()) { try { idir = Integer.parseInt(dir) == 0 ? true : false; } catch(Exception s) { } cbReverse.setChecked(!idir); } } } return match; } public boolean parseButtons(String[] list) { Pattern p = Pattern.compile("(.*) func\\[(.*),(.*)\\]"); String id = ""; int iid = 0; String btn = ""; int ibtn = -1; String state = ""; boolean istate = false; boolean match = false; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); while (m.find() == true) { match = true; id = m.group(1).trim(); btn = m.group(2).trim(); state = m.group(3).trim(); try { iid = Integer.parseInt(id); } catch(Exception e) { } if(iid == Settings.getCurrentTrain().getId()) { ibtn = -1; try { ibtn = Integer.parseInt(btn); } catch(Exception e) { } istate = false; if(state.equals("1")) { istate = true; } if(ibtn < listButtons.size()) { listButtons.get(ibtn).setChecked(istate); } } } } return match; } public void parseButtonSymbol(String[] result) { Pattern p = Pattern.compile("(.*) funcexists\\[(.*)\\]"); for(int i=1; i<result.length-1; i++) { Matcher m = p.matcher(result[i]); int fctNum = -1; int fctSymbol = -1; while (m.find() == true) { String[] f = m.group(2).split(","); if(f.length >= 2) { fctNum = Integer.parseInt(f[0].trim()); fctSymbol = Integer.parseInt(f[1].trim()); if(fctSymbol == -1) { listButtons.get(fctNum).setEnabled(false); } else if(!FunctionSymbol.getInstance().getSymbols().get(fctSymbol,"").equals("")) { Resources res = getResources(); int resourceId = res.getIdentifier("f"+fctSymbol, "drawable", getPackageName()); Drawable img = res.getDrawable( resourceId ); listButtons.get(fctNum).setCompoundDrawablesWithIntrinsicBounds(img, null , null, null); //check if moment function if(f.length == 3) { listButtons.get(fctNum).setTag(R.string.btn_type,"moment"); listButtons.get(fctNum).setText(getString(R.string.btn_f) + fctNum + "*"); listButtons.get(fctNum).setTextOn(getString(R.string.btn_f) + fctNum + "*"); listButtons.get(fctNum).setTextOff(getString(R.string.btn_f) + fctNum + "*"); } else { listButtons.get(fctNum).setTag(R.string.btn_type,"permanent"); } } } } } } public void parseConsoleVersion(String[] result) { //read Protocol Version Pattern p = Pattern.compile("(.*) ProtocolVersion\\[(.*)\\]"); for(int i=1; i<result.length-1; i++) { Matcher m = p.matcher(result[i]); while (m.find() == true) { Settings.protocolVersion = m.group(2).trim(); protocolVersion.setText(Settings.protocolVersion); } } //read Application Version p = Pattern.compile("(.*) ApplicationVersion\\[(.*)\\]"); for(int i=1; i<result.length-1; i++) { Matcher m = p.matcher(result[i]); while (m.find() == true) { String applicationVersionNumber = m.group(2).trim(); applicationVersion.setText(applicationVersionNumber); } } //read Hardware Version p = Pattern.compile("(.*) HardwareVersion\\[(.*)\\]"); for(int i=1; i<result.length-1; i++) { Matcher m = p.matcher(result[i]); while (m.find() == true) { String hardwareVersionNumber = m.group(2).trim(); hardwareVersion.setText(hardwareVersionNumber); } } } public void parseEvent(String[] result) { Pattern p = Pattern.compile("<EVENT (.*)>"); Matcher m = p.matcher(result[0]); while (m.find() == true) { try { int eventId = Integer.parseInt(m.group(1).trim()); if(eventId == 1) { parseEmergency(result); } else if(eventId == Settings.getCurrentTrain().getId()) { parseSpeed(result); parseButtons(result); parseDir(result); parseLostControl(result); } else { parseSwitch(result); } } catch(Exception e) { return; } } } public boolean parseTrainsSymbol(String[] list) { //1000 symbol[LOCO_TYPE_DIESEL, IMAGE_TYPE_INT, 8] Pattern p = Pattern.compile("(.*) symbol\\[(.*), (.*), (.*)]"); boolean match = false; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); int id = 0; String type = ""; String category = ""; int index = 0; while (m.find() == true) { match = true; try { id = Integer.parseInt(m.group(1).trim()); category = m.group(2).trim(); type = m.group(3).trim(); index = Integer.parseInt(m.group(4).trim()); if(type.equals("IMAGE_TYPE_INT")) { for (Train t : Settings.allTrains) { if(t.getId() == id) { t.setSymbol(index); dataAdapter.notifyDataSetChanged(); } } } else if(type.equals("IMAGE_TYPE_USER")) { if(category.equals("LOCO_TYPE_DIESEL")) index = 1; if(category.equals("LOCO_TYPE_STEAM")) index = 0; if(category.equals("LOCO_TYPE_MISC")) index = 3; if(category.equals("LOCO_TYPE_E")) index = 2; for (Train t : Settings.allTrains) { if(t.getId() == id) { t.setSymbol(index); dataAdapter.notifyDataSetChanged(); } } } } catch(Exception e) { } } } return match; } public boolean parseSwitch(String[] list) { Pattern p = Pattern.compile("(.*) state\\[(.*)\\]"); boolean match = false; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); int id = 0; int state = 0; while (m.find() == true) { match = true; try { id = Integer.parseInt(m.group(1).trim()); state = Integer.parseInt(m.group(2).trim()); for(ToggleButton t : listSwitch) { if(Integer.parseInt(t.getTag().toString()) == id) { if(state == 1) { t.setChecked(true); } else { t.setChecked(false); } } } for(SeekBar t : listSwitchMulti) { if(Integer.parseInt(t.getTag().toString()) == id) { t.setProgress(state); for(TextView v: listSwitchMultiValue) { if(Integer.parseInt(v.getTag().toString()) == id) { v.setText(t.getProgress()+""); } } } } } catch(Exception e) { } } } return match; } public boolean parseSwitchSymbol(String[] list) { Pattern p = Pattern.compile("(.*) symbol\\[(.*)\\]"); boolean match = false; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); int id = 0; int symbol = 0; while (m.find() == true) { match = true; try { id = Integer.parseInt(m.group(1).trim()); symbol = Integer.parseInt(m.group(2).trim()); for(ToggleButton t : listSwitch) { if(Integer.parseInt(t.getTag().toString()) == id) { if(!SwitchSymbol.getInstance().getSymbols().get(symbol,"").equals("")) { Resources res = getResources(); int resourceId = res.getIdentifier("s"+symbol, "drawable", getPackageName()); Drawable img = res.getDrawable(resourceId); t.setCompoundDrawablesWithIntrinsicBounds(img, null , null, null); } } } for(TextView v: listSwitchMultiLabel) { if(Integer.parseInt(v.getTag().toString()) == id) { if(!SwitchSymbol.getInstance().getSymbols().get(symbol,"").equals("")) { Resources res = getResources(); int resourceId = res.getIdentifier("s"+symbol, "drawable", getPackageName()); Drawable img = res.getDrawable(resourceId); v.setCompoundDrawablesWithIntrinsicBounds(img, null , null, null); } } } } catch(Exception e) { } } } return match; } public void parseSwitchList(String[] result) { ((LinearLayout) findViewById(R.id.llSwitch)).removeAllViews(); Pattern p = Pattern.compile("(.*) name1\\[\"(.*)\"\\] name2\\[\"(.*)\"\\] addrext\\[(.*)\\]"); listSwitch = new ArrayList<ToggleButton>(); listSwitchMulti = new ArrayList<SeekBar>(); listSwitchMultiValue = new ArrayList<TextView>(); listSwitchMultiLabel = new ArrayList<TextView>(); String id = ""; String name1 = ""; String name2 = ""; String addrext = ""; for(int i=1; i<result.length-1; i++) { Matcher m = p.matcher(result[i]); while (m.find() == true) { id = m.group(1).trim(); name1 = m.group(2).trim(); name2 = m.group(3).trim(); addrext = m.group(4).trim(); String[] addr = addrext.split(","); //for 2 states create ToggleButton if(addr.length == 2) { ToggleButton tg = createButton(id, name1 + " " + name2); listSwitch.add(tg); ((LinearLayout) findViewById(R.id.llSwitch)).addView(tg); } else { //for multi states create SeekBar SeekBar sb = createSeekBar(id, addr.length - 1); listSwitchMulti.add(sb); TextView name = new TextView(this); name.setText(name1 + " " + name2); name.setTag(id); listSwitchMultiLabel.add(name); TextView value = new TextView(this); value.setText(sb.getProgress()+""); value.setTag(id); value.setGravity(Gravity.CENTER); listSwitchMultiValue.add(value); ((LinearLayout) findViewById(R.id.llSwitch)).addView(name); ((LinearLayout) findViewById(R.id.llSwitch)).addView(sb); ((LinearLayout) findViewById(R.id.llSwitch)).addView(value); } } } //get initial state for (ToggleButton t : listSwitch) { mTcpWrite.getState(Integer.parseInt(t.getTag().toString())); } for (SeekBar s : listSwitchMulti) { mTcpWrite.getState(Integer.parseInt(s.getTag().toString())); } } public boolean parseEmergency(String[] list) { Pattern p = Pattern.compile("(.*) status\\[(.*)\\]"); String state = ""; boolean match = false; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); while (m.find() == true) { match = true; state = m.group(2).trim(); if(state.equals("GO")) { btnEmergency.setChecked(false); } else { btnEmergency.setChecked(true); } } } return match; } public boolean parseLostControl(String[] list) { Pattern p = Pattern.compile("(.*) msg\\[(.*)\\]"); String event = ""; boolean match = false; for(int i=1; i<list.length-1; i++) { Matcher m = p.matcher(list[i]); while (m.find() == true) { match = true; event = m.group(2).trim(); if(event.equals("CONTROL_LOST")) { btnControl.setChecked(false); setStateButtons(false); } } } return match; } /**************************************************************************/ /** Utils **/ /**************************************************************************/ public void sortTrainsList(boolean sortById) { if(sortById) { Collections.sort(Settings.allTrains, Train.TrainIdComparator); } else { Collections.sort(Settings.allTrains, Train.TrainNameComparator); } } public static boolean checkSig(Context context) { boolean match = false; if (context.getPackageManager().checkSignatures( LITE_PACKAGE, FULL_PACKAGE) == PackageManager.SIGNATURE_MATCH) match = true; return match; } public ToggleButton createButton(String id, String name) { ToggleButton tg = new ToggleButton(this); tg.setText(name); tg.setTextOn(name); tg.setTextOff(name); tg.setTag(id); tg.setOnClickListener(this); return tg; } public void initFunctionButtons() { for(int i=0; i<listButtons.size(); i++) { listButtons.get(i).setOnClickListener(this); listButtons.get(i).setOnTouchListener(this); listButtons.get(i).setTag(R.string.btn_name,"btn;"+i); listButtons.get(i).setText(getString(R.string.btn_f) + i); listButtons.get(i).setTextOn(getString(R.string.btn_f) + i); listButtons.get(i).setTextOff(getString(R.string.btn_f) + i); listButtons.get(i).setCompoundDrawablesWithIntrinsicBounds(null,null,null,null); } } public SeekBar createSeekBar(String id, int max) { SeekBar sb = new SeekBar(this); sb.setMax(max); sb.setProgress(0); sb.setTag(id); sb.setOnSeekBarChangeListener(this); return sb; } public void displaySpeed(int speed) { int speedIndicator = Settings.getCurrentTrain().getSpeedIndicator(); if(speedIndicator == 0) { tvSpeed.setText(getApplicationContext().getString( R.string.tv_speed) + " " + speed + "/" + Settings.SPEED_MAX); } else { tvSpeed.setText(getApplicationContext().getString( R.string.tv_speed) + " " + speed + "/" + Settings.SPEED_MAX + " (" + ((int)speedIndicator*speed/Settings.SPEED_MAX) + "/" + speedIndicator + "km/h)"); } } public void displayError(String error) { Toast.makeText(this, error , Toast.LENGTH_SHORT).show(); } /**************************************************************************/ /** Change speed with volume button **/ /**************************************************************************/ @Override public boolean dispatchKeyEvent(KeyEvent event) { int action = event.getAction(); int keyCode = event.getKeyCode(); switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: if (action == KeyEvent.ACTION_UP) { changeSpeed(true); } return true; case KeyEvent.KEYCODE_VOLUME_DOWN: if (action == KeyEvent.ACTION_DOWN) { volumeDownPressed = true; changeSpeed(false); } return true; default: return super.dispatchKeyEvent(event); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { volumeDownPressed = false; return super.onKeyUp(keyCode, event); } public void changeSpeed(boolean increase) { if(!Settings.fullVersion) { return; } if(sbSpeed.isEnabled()) { int current_value = sbSpeed.getProgress(); int new_value = current_value; if(increase) { new_value = current_value + speedStep; if(new_value > Settings.SPEED_MAX) { new_value = Settings.SPEED_MAX; } sbSpeed.setProgress(new_value); } else { new_value = current_value - speedStep; if(new_value < Settings.SPEED_MIN) { new_value = Settings.SPEED_MIN; } sbSpeed.setProgress(new_value); } mTcpWrite.setSpeed(Settings.getCurrentTrain().getId(), sbSpeed.getProgress()); displaySpeed(sbSpeed.getProgress()); } } @Override public boolean onTouch(View v, MotionEvent me) { if(v.getTag(R.string.btn_type) != null) { if(v.getTag(R.string.btn_type).toString().equals("moment")) { String token[] = v.getTag(R.string.btn_name).toString().split(";"); if (me.getAction() == MotionEvent.ACTION_DOWN) { mTcpWrite.setButton(Settings.getCurrentTrain().getId(), Integer.parseInt(token[1]), true); ((ToggleButton) v).setChecked(true); return true; } else if (me.getAction() == MotionEvent.ACTION_UP) { mTcpWrite.setButton(Settings.getCurrentTrain().getId(), Integer.parseInt(token[1]), false); ((ToggleButton) v).setChecked(false); return true; } } } return false; } private void getTrainsSymbol() { List<Train> list = Settings.allTrains; for (Train train : list) { mTcpWrite.getTrainSymbol(train.getId()); } } }
42,331
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z
TrainSpinAdapter.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/ui/TrainSpinAdapter.java
package com.ecos.train.ui; import java.util.List; import android.content.Context; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ecos.train.R; import com.ecos.train.object.Train; public class TrainSpinAdapter extends ArrayAdapter<Train>{ private Context context; private List<Train> values; public TrainSpinAdapter(Context context, int textViewResourceId, List<Train> values) { super(context, textViewResourceId, values); this.context = context; this.values = values; } public int getCount(){ return values.size(); } public Train getItem(int position){ return values.get(position); } public long getItemId(int position){ return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { return display(position, convertView, parent); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return display(position, convertView, parent); } public View display(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View spinnerEntry = inflater.inflate(R.layout.spinner_entry_with_icon, null); TextView name = (TextView) spinnerEntry.findViewById(R.id.spinnerName); name.setText(values.get(position).toString()); ImageView icon = (ImageView) spinnerEntry.findViewById(R.id.spinnerLogo); int symbol = values.get(position).getSymbol(); Resources res = getContext().getResources(); int resourceId = res.getIdentifier("loco"+symbol, "drawable", getContext().getPackageName()); icon.setImageResource(resourceId); return spinnerEntry; } }
1,873
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z
Train.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/object/Train.java
package com.ecos.train.object; import java.util.Comparator; public class Train implements Comparable<Train> { private int id; private String name; private String address; private int speedIndicator = 0; private int symbol = 0; public Train(int id, String name, String address){ this.id = id; this.name = name; this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getSpeedIndicator() { return speedIndicator; } public void setSpeedIndicator(int speedIndicator) { this.speedIndicator = speedIndicator; } public int getSymbol() { return symbol; } public void setSymbol(int symbol) { this.symbol = symbol; } public String toString() { return name + " (" + id + ")"; } @Override public int compareTo(Train t) { return name.compareTo(t.getName()); } public static Comparator<Train> TrainNameComparator = new Comparator<Train>() { public int compare(Train train1, Train train2) { String trainName1 = train1.getName().toUpperCase(); String trainName2 = train2.getName().toUpperCase(); return trainName1.compareTo(trainName2); } }; public static Comparator<Train> TrainIdComparator = new Comparator<Train>() { public int compare(Train train1, Train train2) { int trainId1 = train1.getId(); int trainId2 = train2.getId(); return trainId1 - trainId2; } }; }
1,636
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z
SwitchSymbol.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/object/SwitchSymbol.java
package com.ecos.train.object; import android.util.SparseArray; public class SwitchSymbol { private static SwitchSymbol INSTANCE = null; private SparseArray<String> symbols; private SwitchSymbol(){ symbols = new SparseArray<String>(); symbols.put(0, "Turnout left"); symbols.put(1, "Turnout right"); symbols.put(2, "Turnout 3-way"); symbols.put(3, "Double slip tournout 2-way"); symbols.put(4, "Double slip turnout 4-way"); symbols.put(5, "Semaphore hp01"); symbols.put(6, "Semaphore hp02"); symbols.put(7, "Semaphore hp012"); symbols.put(8, "Switch signal"); symbols.put(9, "Light signal"); symbols.put(10, "Light signal"); symbols.put(11, "Light signal"); symbols.put(12, "Light signal"); symbols.put(13, "Switch signal"); symbols.put(14, "Lattice mast lightning"); symbols.put(15, "Streetlight"); symbols.put(16, "Lightning"); symbols.put(17, "Decoupling track"); symbols.put(18, "General Function"); symbols.put(19, "Curved turnout left"); symbols.put(20, "Curved turnout right"); symbols.put(21, "Signal SNCB 2 states"); symbols.put(22, "Signal SNCB 4 states"); symbols.put(23, "Signal NS 2 states"); symbols.put(24, "Signal NS 3 states"); symbols.put(25, "Signal CFL 3 states"); symbols.put(26, "Signal SNCF 3 states"); symbols.put(27, "Boom"); symbols.put(28, "Engine Shed"); symbols.put(29, "Distant signal"); symbols.put(30, "Distant signal"); symbols.put(31, "Distant signal"); symbols.put(32, "Distant signal"); symbols.put(33, "Double crossower turnout 2-way"); symbols.put(34, "Double crossower turnout 4-way left"); symbols.put(35, "Double crossower turnout 4-way right"); symbols.put(36, "Function with track"); symbols.put(37, "Start goal unidirectional"); symbols.put(38, "Dummy 2-states"); symbols.put(39, "Dummy 3-states"); symbols.put(40, "Dummy 4-states"); symbols.put(41, "Start goal bidirectional"); symbols.put(42, "Route"); } public static synchronized SwitchSymbol getInstance(){ if (INSTANCE == null){ INSTANCE = new SwitchSymbol(); } return INSTANCE; } public SparseArray<String> getSymbols() { return symbols; } }
2,163
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z