preparing notes module (backend)

Signed-off-by: Stephan Richter <s.richter@srsoftware.de>
This commit is contained in:
2025-07-28 18:22:13 +02:00
parent 378ef640d9
commit 6600b6fd27
13 changed files with 386 additions and 14 deletions

View File

@@ -0,0 +1,11 @@
/* © SRSoftware 2025 */
package de.srsoftware.umbrella.notes;
public class Constants {
private Constants(){}
public static final String CONFIG_DATABASE = "umbrella.modules.notes.database";
public static final String DB_VERSION = "notes_db_version";
public static final String TABLE_NOTES = "notes";
public static final String NOTE = "note";
}

View File

@@ -0,0 +1,135 @@
/* © SRSoftware 2025 */
package de.srsoftware.umbrella.notes;
import static de.srsoftware.umbrella.core.ConnectionProvider.connect;
import static de.srsoftware.umbrella.core.Constants.USER_LIST;
import static de.srsoftware.umbrella.core.ResponseCode.HTTP_UNPROCESSABLE;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.missingFieldException;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.unprocessable;
import static de.srsoftware.umbrella.notes.Constants.CONFIG_DATABASE;
import static de.srsoftware.umbrella.notes.Constants.NOTE;
import static java.net.HttpURLConnection.HTTP_OK;
import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.configuration.Configuration;
import de.srsoftware.tools.Path;
import de.srsoftware.tools.SessionToken;
import de.srsoftware.umbrella.core.BaseHandler;
import de.srsoftware.umbrella.core.api.NoteService;
import de.srsoftware.umbrella.core.api.TagService;
import de.srsoftware.umbrella.core.api.UserService;
import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import de.srsoftware.umbrella.core.model.Note;
import de.srsoftware.umbrella.core.model.Token;
import de.srsoftware.umbrella.core.model.UmbrellaUser;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.json.JSONArray;
public class NoteModule extends BaseHandler implements NoteService {
private final NotesDb notesDb;
private final UserService users;
public NoteModule(Configuration config, UserService userService) {
var dbFile = config.get(CONFIG_DATABASE).orElseThrow(() -> missingFieldException(CONFIG_DATABASE));
notesDb = new SqliteDb(connect(dbFile));
users = userService;
}
@Override
public void deleteEntity(String module, long entityId) {
notesDb.deleteEntity(module,entityId);
}
@Override
public boolean doDelete(Path path, HttpExchange ex) throws IOException {
addCors(ex);
try {
Optional<Token> token = SessionToken.from(ex).map(Token::of);
var user = users.loadUser(token);
if (user.isEmpty()) return unauthorized(ex);
var module = path.pop();
if (module == null) throw unprocessable("Module missing in path.");
var head = path.pop();
long noteId = Long.parseLong(head);
noteId = notesDb.delete(noteId,user.get().id());
return sendContent(ex, noteId);
} catch (NumberFormatException e){
return sendContent(ex,HTTP_UNPROCESSABLE,"Entity id missing in path.");
} catch (UmbrellaException e){
return send(ex,e);
}
}
@Override
public boolean doGet(Path path, HttpExchange ex) throws IOException {
addCors(ex);
try {
var user = users.refreshSession(ex);
if (user.isEmpty()) return unauthorized(ex);
var module = path.pop();
if (module == null) throw unprocessable("Module missing in path.");
var head = path.pop();
long entityId = Long.parseLong(head);
return sendContent(ex, getNotes(module,entityId));
} catch (NumberFormatException e){
return sendContent(ex,HTTP_UNPROCESSABLE,"Entity id missing in path.");
} catch (UmbrellaException e){
return send(ex,e);
}
}
@Override
public boolean doOptions(Path path, HttpExchange ex) throws IOException {
addCors(ex);
return sendEmptyResponse(HTTP_OK,ex);
}
@Override
public boolean doPost(Path path, HttpExchange ex) throws IOException {
addCors(ex);
try {
Optional<Token> token = SessionToken.from(ex).map(Token::of);
var user = users.loadUser(token);
if (user.isEmpty()) return unauthorized(ex);
var module = path.pop();
if (module == null) throw unprocessable("Module missing in path.");
var head = path.pop();
long entityId = Long.parseLong(head);
var json = json(ex);
if (!(json.has(NOTE) && json.get(NOTE) instanceof String text)) throw missingFieldException(NOTE);
List<Long> userList = null;
if (!json.has(USER_LIST)) throw missingFieldException(USER_LIST);
var ul = json.isNull(USER_LIST) ? null : json.get(USER_LIST);
if (ul instanceof JSONArray arr){
userList = arr.toList().stream()
.filter(elem -> elem instanceof Number)
.map(Number.class::cast)
.map(Number::longValue)
.toList();
} else if (ul != null) throw unprocessable("User list must be NULL or array of user ids!");
// userList == null → tag is shared with all users
if (userList != null && userList.isEmpty()) throw unprocessable("User list must not be an empty list!");
var note = new Note(0,module,entityId,user.get().id(),text, LocalDateTime.now());
note = save(note);
return sendContent(ex, note);
} catch (NumberFormatException e) {
return sendContent(ex, HTTP_UNPROCESSABLE, "Entity id missing in path.");
} catch (UmbrellaException e) {
return send(ex, e);
}
}
public Collection<Note> getNotes(String module, long entityId) throws UmbrellaException{
return notesDb.list(module,entityId);
}
@Override
public Note save(Note note) {
return notesDb.save(note);
}
}

View File

@@ -0,0 +1,17 @@
/* © SRSoftware 2025 */
package de.srsoftware.umbrella.notes;
import de.srsoftware.umbrella.core.model.Note;
import java.util.Collection;
import java.util.Set;
public interface NotesDb {
long delete(long noteId, long userId);
void deleteEntity(String module, long entityId);
Set<Note> list(String module, long entityId);
Note save(Note note);
}

View File

@@ -0,0 +1,139 @@
/* © SRSoftware 2025 */
package de.srsoftware.umbrella.notes;
import static de.srsoftware.tools.jdbc.Condition.equal;
import static de.srsoftware.tools.jdbc.Query.*;
import static de.srsoftware.tools.jdbc.Query.SelectQuery.ALL;
import static de.srsoftware.umbrella.core.Constants.*;
import static de.srsoftware.umbrella.notes.Constants.*;
import static java.lang.System.Logger.Level.*;
import static java.text.MessageFormat.format;
import de.srsoftware.tools.jdbc.Query;
import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import de.srsoftware.umbrella.core.model.Note;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class SqliteDb implements NotesDb {
private static final int INITIAL_DB_VERSION = 1;
private static final System.Logger LOG = System.getLogger("NotesDB");
private final Connection db;
public SqliteDb(Connection conn) {
this.db = conn;
init();
}
private int createTables() {
createNotesTables();
return createSettingsTable();
}
private int createSettingsTable() {
var createTable = """
CREATE TABLE IF NOT EXISTS {0} ( {1} VARCHAR(255) PRIMARY KEY, {2} VARCHAR(255) NOT NULL);
""";
try {
var stmt = db.prepareStatement(format(createTable,TABLE_SETTINGS, KEY, VALUE));
stmt.execute();
stmt.close();
} catch (SQLException e) {
LOG.log(ERROR,ERROR_FAILED_CREATE_TABLE,TABLE_SETTINGS,e);
throw new RuntimeException(e);
}
Integer version = null;
try {
var rs = select(VALUE).from(TABLE_SETTINGS).where(KEY, equal(DB_VERSION)).exec(db);
if (rs.next()) version = rs.getInt(VALUE);
rs.close();
if (version == null) {
version = INITIAL_DB_VERSION;
insertInto(TABLE_SETTINGS, KEY, VALUE).values(DB_VERSION,version).execute(db).close();
}
return version;
} catch (SQLException e) {
LOG.log(ERROR,ERROR_READ_TABLE,DB_VERSION,TABLE_SETTINGS,e);
throw new RuntimeException(e);
}
}
private void createNotesTables() {
var createTable = """
CREATE TABLE IF NOT EXISTS "{0}" (
{1} INTEGER NOT NULL PRIMARY KEY,
{2} TEXT NOT NULL,
{3} VARCHAR(20) NOT NULL,
{4} INTEGER NOT NULL,
{5} INTEGER NOT NULL,
{6} DATETIME NOT NULL
)""";
try {
var stmt = db.prepareStatement(format(createTable,TABLE_NOTES, ID, NOTE, MODULE, ENTITY_ID, USER_ID, TIMESTAMP));
stmt.execute();
stmt.close();
} catch (SQLException e) {
LOG.log(ERROR,ERROR_FAILED_CREATE_TABLE,TABLE_NOTES,e);
throw new RuntimeException(e);
}
}
@Override
public long delete(long noteId, long userId) {
LOG.log(WARNING,"Not checking whether deleted not belongs to user!");
try {
Query.delete().from(TABLE_NOTES)
.where(ID,equal(noteId))
.execute(db);
return noteId;
} catch (SQLException e){
throw new UmbrellaException("Failed to delete note {0}",noteId);
}
}
@Override
public void deleteEntity(String module, long entityId) {
try {
Query.delete().from(TABLE_NOTES)
.where(MODULE,equal(module)).where(ENTITY_ID,equal(entityId))
.execute(db);
} catch (SQLException e){
throw new UmbrellaException("Failed to delete notes of ({0} {1})",module,entityId);
}
}
private void init(){
var version = createTables();
LOG.log(INFO,"Updated task db to version {0}",version);
}
@Override
public Set<Note> list(String module, long entityId) {
try {
var tags = new HashSet<Note>();
var rs = select(ALL).from(TABLE_NOTES).where(MODULE,equal(module)).where(ENTITY_ID,equal(entityId)).exec(db);
while (rs.next()) tags.add(Note.of(rs));
rs.close();
return tags;
} catch (SQLException e) {
throw new UmbrellaException("Failed to load tags");
}
}
@Override
public Note save(Note note) {
try {
replaceInto(TABLE_NOTES,USER_ID,MODULE,ENTITY_ID,NOTE,TIMESTAMP)
.values(note.authorId(),note.module(),note.entityId(),note.text(),note.timestamp())
.execute(db).close();
return note;
} catch (SQLException e){
throw new UmbrellaException("Failed to save note: {0}",note.text());
}
}
}