Add NoteDao, used by NoteActionHandler to delete note when read

This commit is contained in:
P0nk
2022-12-26 15:55:28 +01:00
parent 188eb74a70
commit 605f2e212e
6 changed files with 147 additions and 26 deletions

View File

@@ -22,19 +22,23 @@
package net.server.channel.handlers;
import client.Client;
import database.DaoException;
import database.NoteDao;
import model.Note;
import net.AbstractPacketHandler;
import net.packet.InPacket;
import tools.DatabaseConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tools.PacketCreator;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
public final class NoteActionHandler extends AbstractPacketHandler {
private static final Logger log = LoggerFactory.getLogger(NoteActionHandler.class);
@Override
public final void handlePacket(InPacket p, Client c) {
public void handlePacket(InPacket p, Client c) {
int action = p.readByte();
if (action == 0 && c.getPlayer().getCashShop().getAvailableNotes() > 0) {
String charname = p.readString();
@@ -58,24 +62,20 @@ public final class NoteActionHandler extends AbstractPacketHandler {
int id = p.readInt();
p.readByte(); //Fame, but we read it from the database :)
try (Connection con = DatabaseConnection.getConnection()) {
try (PreparedStatement ps = con.prepareStatement("SELECT `fame` FROM notes WHERE id=? AND deleted=0")) {
ps.setInt(1, id);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
fame += rs.getInt("fame");
}
}
}
try (PreparedStatement ps = con.prepareStatement("UPDATE notes SET `deleted` = 1 WHERE id = ?")) {
ps.setInt(1, id);
ps.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
final Optional<Note> note;
try {
note = NoteDao.delete(id);
} catch (DaoException e) {
log.error("Failed to delete note {}", id, e);
continue;
}
if (note.isEmpty()) {
log.warn("Note with id {} not able to be deleted. Already deleted?", id);
continue;
}
fame += note.get().fame();
}
if (fame > 0) {
c.getPlayer().gainFame(fame);