Skip to content

Commit b5e675b

Browse files
committed
refactor: general code maintenance
1 parent 707713f commit b5e675b

File tree

9 files changed

+179
-159
lines changed

9 files changed

+179
-159
lines changed

src/main/java/com/conaxgames/poll/Settings.java

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,17 +26,11 @@ public void reload() {
2626

2727
try {
2828
settings.syncWithConfig(file, PollPlugin.getInstance().getResource("settings.yml"));
29-
} catch (Exception exception) {
30-
Bukkit.getLogger().info("Unable to load settings.yml");
29+
} catch (Exception e) {
30+
Bukkit.getLogger().warning("Unable to sync settings.yml: " + e.getMessage());
3131
}
3232

33-
// SQLite database file
3433
sqliteFile = settings.getString("sqlite_file", "polls.db");
35-
36-
// Poll settings
37-
// No restrictions
38-
39-
// GUI settings
4034
useFillerglass = settings.getBoolean("gui.use_fillerglass", true);
4135
autoUpdate = settings.getBoolean("gui.auto_update", true);
4236
updateInterval = settings.getInt("gui.update_interval", 20);

src/main/java/com/conaxgames/poll/commands/impl/PollCommands.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ public class PollCommands extends BaseCommand {
1818

1919
public PollCommands(PollPlugin plugin) {
2020
this.plugin = plugin;
21-
plugin.getLibraryPlugin().getPaperCommandManager().registerCommand(this);
2221
}
2322

2423
@Default

src/main/java/com/conaxgames/poll/data/Poll.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import lombok.Data;
44
import lombok.NoArgsConstructor;
5-
import lombok.AllArgsConstructor;
65

76
import java.time.LocalDateTime;
87
import java.util.HashMap;
@@ -12,7 +11,6 @@
1211

1312
@Data
1413
@NoArgsConstructor
15-
@AllArgsConstructor
1614
public class Poll {
1715

1816
private String id;

src/main/java/com/conaxgames/poll/data/PollDataManager.java

Lines changed: 81 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -111,90 +111,75 @@ private Poll loadPollFromResultSet(ResultSet rs) throws SQLException {
111111
}
112112

113113
private void loadVotesForPoll(Poll poll) {
114-
try (PreparedStatement stmt = connection.prepareStatement(
115-
"SELECT * FROM votes WHERE poll_id = ?")) {
116-
stmt.setString(1, poll.getId());
117-
118-
try (ResultSet rs = stmt.executeQuery()) {
114+
executeQuery("SELECT * FROM votes WHERE poll_id = ?",
115+
stmt -> stmt.setString(1, poll.getId()),
116+
rs -> {
119117
while (rs.next()) {
120118
String playerUuid = rs.getString("player_uuid");
121119
String option = rs.getString("option");
122120

123121
poll.getPlayerVotes().put(UUID.fromString(playerUuid), option);
124122
poll.getVotes().put(option, poll.getVotes().getOrDefault(option, 0) + 1);
125123
}
126-
}
127-
} catch (SQLException e) {
128-
plugin.getLogger().severe("Failed to load votes for poll " + poll.getId() + ": " + e.getMessage());
129-
}
124+
},
125+
"Failed to load votes for poll " + poll.getId()
126+
);
130127
}
131128

132129
public void savePoll(Poll poll) {
133-
try (PreparedStatement stmt = connection.prepareStatement(
134-
"INSERT INTO polls (id, question, options, created_at, expires_at, created_by, active) VALUES (?, ?, ?, ?, ?, ?, ?)")) {
135-
stmt.setInt(1, Integer.parseInt(poll.getId()));
136-
stmt.setString(2, poll.getQuestion());
137-
stmt.setString(3, String.join("|", poll.getOptions()));
138-
stmt.setString(4, poll.getCreatedAt().format(DATE_FORMATTER));
139-
stmt.setString(5, poll.getExpiresAt().format(DATE_FORMATTER));
140-
stmt.setString(6, poll.getCreatedBy());
141-
stmt.setInt(7, poll.isActive() ? 1 : 0);
142-
143-
stmt.executeUpdate();
144-
activePolls.put(poll.getId(), poll);
145-
} catch (SQLException e) {
146-
plugin.getLogger().severe("Failed to save poll: " + e.getMessage());
147-
}
130+
executeUpdate("INSERT INTO polls (id, question, options, created_at, expires_at, created_by, active) VALUES (?, ?, ?, ?, ?, ?, ?)",
131+
stmt -> {
132+
stmt.setInt(1, Integer.parseInt(poll.getId()));
133+
stmt.setString(2, poll.getQuestion());
134+
stmt.setString(3, String.join("|", poll.getOptions()));
135+
stmt.setString(4, poll.getCreatedAt().format(DATE_FORMATTER));
136+
stmt.setString(5, poll.getExpiresAt().format(DATE_FORMATTER));
137+
stmt.setString(6, poll.getCreatedBy());
138+
stmt.setInt(7, poll.isActive() ? 1 : 0);
139+
},
140+
"Failed to save poll"
141+
);
142+
activePolls.put(poll.getId(), poll);
148143
}
149144

150145
public void saveVote(String pollId, UUID playerId, String option) {
151-
try (PreparedStatement stmt = connection.prepareStatement(
152-
"INSERT INTO votes (poll_id, player_uuid, option, voted_at) VALUES (?, ?, ?, ?)")) {
153-
stmt.setInt(1, Integer.parseInt(pollId));
154-
stmt.setString(2, playerId.toString());
155-
stmt.setString(3, option);
156-
stmt.setString(4, LocalDateTime.now().format(DATE_FORMATTER));
157-
158-
stmt.executeUpdate();
159-
} catch (SQLException e) {
160-
plugin.getLogger().severe("Failed to save vote: " + e.getMessage());
161-
}
146+
executeUpdate("INSERT INTO votes (poll_id, player_uuid, option, voted_at) VALUES (?, ?, ?, ?)",
147+
stmt -> {
148+
stmt.setInt(1, Integer.parseInt(pollId));
149+
stmt.setString(2, playerId.toString());
150+
stmt.setString(3, option);
151+
stmt.setString(4, LocalDateTime.now().format(DATE_FORMATTER));
152+
},
153+
"Failed to save vote"
154+
);
162155
}
163156

164157
public void updatePollStatus(String pollId, boolean active) {
165-
try (PreparedStatement stmt = connection.prepareStatement(
166-
"UPDATE polls SET active = ? WHERE id = ?")) {
167-
stmt.setInt(1, active ? 1 : 0);
168-
stmt.setInt(2, Integer.parseInt(pollId));
169-
170-
stmt.executeUpdate();
171-
172-
if (!active) {
173-
activePolls.remove(pollId);
174-
}
175-
} catch (SQLException e) {
176-
plugin.getLogger().severe("Failed to update poll status: " + e.getMessage());
158+
executeUpdate("UPDATE polls SET active = ? WHERE id = ?",
159+
stmt -> {
160+
stmt.setInt(1, active ? 1 : 0);
161+
stmt.setInt(2, Integer.parseInt(pollId));
162+
},
163+
"Failed to update poll status"
164+
);
165+
166+
if (!active) {
167+
activePolls.remove(pollId);
177168
}
178169
}
179170

180171
public void deletePoll(String pollId) {
181-
try {
182-
try (PreparedStatement stmt = connection.prepareStatement(
183-
"DELETE FROM votes WHERE poll_id = ?")) {
184-
stmt.setInt(1, Integer.parseInt(pollId));
185-
stmt.executeUpdate();
186-
}
187-
188-
try (PreparedStatement stmt = connection.prepareStatement(
189-
"DELETE FROM polls WHERE id = ?")) {
190-
stmt.setInt(1, Integer.parseInt(pollId));
191-
stmt.executeUpdate();
192-
}
193-
194-
activePolls.remove(pollId);
195-
} catch (SQLException e) {
196-
plugin.getLogger().severe("Failed to delete poll: " + e.getMessage());
197-
}
172+
executeUpdate("DELETE FROM votes WHERE poll_id = ?",
173+
stmt -> stmt.setInt(1, Integer.parseInt(pollId)),
174+
"Failed to delete votes for poll"
175+
);
176+
177+
executeUpdate("DELETE FROM polls WHERE id = ?",
178+
stmt -> stmt.setInt(1, Integer.parseInt(pollId)),
179+
"Failed to delete poll"
180+
);
181+
182+
activePolls.remove(pollId);
198183
}
199184

200185
public Collection<Poll> getActivePolls() {
@@ -206,20 +191,17 @@ public Poll getPoll(String pollId) {
206191
}
207192

208193
public void cleanupExpiredPolls() {
209-
try (PreparedStatement stmt = connection.prepareStatement(
210-
"SELECT id FROM polls WHERE active = 1 AND expires_at <= ?")) {
211-
stmt.setString(1, LocalDateTime.now().format(DATE_FORMATTER));
212-
213-
try (ResultSet rs = stmt.executeQuery()) {
194+
executeQuery("SELECT id FROM polls WHERE active = 1 AND expires_at <= ?",
195+
stmt -> stmt.setString(1, LocalDateTime.now().format(DATE_FORMATTER)),
196+
rs -> {
214197
while (rs.next()) {
215198
String pollId = String.valueOf(rs.getInt("id"));
216199
plugin.getLogger().info("Cleaning up expired poll " + pollId);
217200
updatePollStatus(pollId, false);
218201
}
219-
}
220-
} catch (SQLException e) {
221-
plugin.getLogger().severe("Failed to cleanup expired polls: " + e.getMessage());
222-
}
202+
},
203+
"Failed to cleanup expired polls"
204+
);
223205
}
224206

225207
public String getNextPollId() {
@@ -235,4 +217,30 @@ public void shutdown() {
235217
}
236218
}
237219
}
220+
221+
private void executeQuery(String sql, SQLConsumer<PreparedStatement> parameterSetter,
222+
SQLConsumer<ResultSet> resultProcessor, String errorMessage) {
223+
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
224+
parameterSetter.accept(stmt);
225+
try (ResultSet rs = stmt.executeQuery()) {
226+
resultProcessor.accept(rs);
227+
}
228+
} catch (SQLException e) {
229+
plugin.getLogger().severe(errorMessage + ": " + e.getMessage());
230+
}
231+
}
232+
233+
private void executeUpdate(String sql, SQLConsumer<PreparedStatement> parameterSetter, String errorMessage) {
234+
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
235+
parameterSetter.accept(stmt);
236+
stmt.executeUpdate();
237+
} catch (SQLException e) {
238+
plugin.getLogger().severe(errorMessage + ": " + e.getMessage());
239+
}
240+
}
241+
242+
@FunctionalInterface
243+
private interface SQLConsumer<T> {
244+
void accept(T t) throws SQLException;
245+
}
238246
}

src/main/java/com/conaxgames/poll/listeners/PollListener.java

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ private void startCleanupTask() {
3232
public void run() {
3333
plugin.getDataManager().cleanupExpiredPolls();
3434
}
35-
}.runTaskTimer(plugin, 20L * 60 * 5, 20L * 60 * 5); // Every 5 minutes
35+
}.runTaskTimer(plugin, 20L * 60 * 5, 20L * 60 * 5);
3636
}
3737

3838
@EventHandler
@@ -62,28 +62,7 @@ public void onInventoryClick(InventoryClickEvent event) {
6262

6363
if (cleanOption != null) {
6464
event.setCancelled(true);
65-
66-
UUID playerId = player.getUniqueId();
67-
68-
if (poll.isExpired()) {
69-
player.sendMessage(CC.RED + "This poll has expired!");
70-
player.closeInventory();
71-
return;
72-
}
73-
74-
if (poll.hasVoted(playerId)) {
75-
player.sendMessage(CC.RED + "You have already voted on this poll!");
76-
return;
77-
}
78-
79-
if (poll.vote(playerId, cleanOption)) {
80-
plugin.getDataManager().saveVote(poll.getId(), playerId, cleanOption);
81-
82-
player.sendMessage(CC.GREEN + "Your vote has been recorded!");
83-
player.closeInventory();
84-
} else {
85-
player.sendMessage(CC.RED + "Failed to record your vote. Please try again.");
86-
}
65+
handleVote(player, poll, cleanOption);
8766
}
8867
}
8968
}
@@ -128,6 +107,29 @@ public void run() {
128107
}
129108
}
130109

110+
private void handleVote(Player player, Poll poll, String option) {
111+
UUID playerId = player.getUniqueId();
112+
113+
if (poll.isExpired()) {
114+
player.sendMessage(CC.RED + "This poll has expired!");
115+
player.closeInventory();
116+
return;
117+
}
118+
119+
if (poll.hasVoted(playerId)) {
120+
player.sendMessage(CC.RED + "You have already voted on this poll!");
121+
return;
122+
}
123+
124+
if (poll.vote(playerId, option)) {
125+
plugin.getDataManager().saveVote(poll.getId(), playerId, option);
126+
player.sendMessage(CC.GREEN + "Your vote has been recorded!");
127+
player.closeInventory();
128+
} else {
129+
player.sendMessage(CC.RED + "Failed to record your vote. Please try again.");
130+
}
131+
}
132+
131133
public void registerOptionInput(Player player, PollCreationMenu menu) {
132134
playersAddingOptions.put(player.getUniqueId(), menu);
133135
player.closeInventory();
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.conaxgames.poll.menus;
2+
3+
import com.conaxgames.libraries.menu.Button;
4+
import com.conaxgames.libraries.menu.Menu;
5+
import com.conaxgames.libraries.message.FormatUtil;
6+
import com.conaxgames.libraries.util.CC;
7+
import com.conaxgames.libraries.xseries.XMaterial;
8+
import com.conaxgames.poll.PollPlugin;
9+
import com.conaxgames.poll.data.Poll;
10+
import com.conaxgames.poll.util.TimeUtil;
11+
import org.bukkit.Material;
12+
import org.bukkit.entity.Player;
13+
14+
import java.util.ArrayList;
15+
import java.util.List;
16+
17+
public abstract class BasePollMenu extends Menu {
18+
19+
protected final PollPlugin plugin;
20+
21+
protected BasePollMenu(PollPlugin plugin) {
22+
this.plugin = plugin;
23+
this.setPlaceholder(plugin.getSettings().useFillerglass);
24+
}
25+
26+
protected Button createPollInfoButton(Poll poll, Player player) {
27+
return new Button() {
28+
@Override
29+
public String getName(Player player) {
30+
return CC.YELLOW + "Poll #" + poll.getId();
31+
}
32+
33+
@Override
34+
public List<String> getDescription(Player player) {
35+
List<String> lore = new ArrayList<>();
36+
37+
List<String> wrappedQuestion = FormatUtil.wordWrap(CC.YELLOW + poll.getQuestion(), 40);
38+
lore.addAll(wrappedQuestion);
39+
lore.add("");
40+
41+
lore.add(CC.GRAY + "Created by: " + CC.WHITE + poll.getCreatedBy());
42+
lore.add(CC.GRAY + "Expires: " + CC.WHITE + TimeUtil.formatDateTime(poll.getExpiresAt()));
43+
lore.add(CC.GRAY + "Time remaining: " + CC.WHITE + TimeUtil.getTimeRemaining(poll.getExpiresAt()));
44+
lore.add(CC.GRAY + "Total votes: " + CC.WHITE + poll.getTotalVotes());
45+
lore.add("");
46+
47+
if (poll.hasVoted(player.getUniqueId())) {
48+
String votedOption = poll.getPlayerVote(player.getUniqueId());
49+
lore.add(CC.GREEN + "✓ You voted for: " + CC.WHITE + votedOption);
50+
} else {
51+
lore.add(CC.GRAY + "Click an option below to vote!");
52+
}
53+
54+
return lore;
55+
}
56+
57+
@Override
58+
public Material getMaterial(Player player) {
59+
return XMaterial.BOOK.get();
60+
}
61+
};
62+
}
63+
}

src/main/java/com/conaxgames/poll/menus/PollListMenu.java

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.conaxgames.poll.menus;
22

33
import com.conaxgames.libraries.menu.Button;
4-
import com.conaxgames.libraries.menu.Menu;
54
import com.conaxgames.libraries.message.FormatUtil;
65
import com.conaxgames.libraries.util.CC;
76
import com.conaxgames.libraries.xseries.XMaterial;
@@ -17,13 +16,10 @@
1716
import java.util.List;
1817
import java.util.Map;
1918

20-
public class PollListMenu extends Menu {
21-
22-
private final PollPlugin plugin;
19+
public class PollListMenu extends BasePollMenu {
2320

2421
public PollListMenu(PollPlugin plugin) {
25-
this.plugin = plugin;
26-
this.setPlaceholder(plugin.getSettings().useFillerglass);
22+
super(plugin);
2723
this.setAutoUpdate(plugin.getSettings().autoUpdate);
2824
}
2925

0 commit comments

Comments
 (0)