working on tag module

This commit is contained in:
2025-07-27 22:56:27 +02:00
parent acf2e6cc3a
commit 4f54276e8f
27 changed files with 1426 additions and 19 deletions

6
tags/build.gradle.kts Normal file
View File

@@ -0,0 +1,6 @@
description = "Umbrella : Tags"
dependencies{
implementation(project(":core"))
}

View File

@@ -0,0 +1,12 @@
/* © SRSoftware 2025 */
package de.srsoftware.umbrella.tags;
public class Constants {
private Constants(){}
public static final String CONFIG_DATABASE = "umbrella.modules.tags.database";
public static final String DB_VERSION = "project_db_version";
public static final String MODULE = "module";
public static final String TABLE_TAGS = "tags";
public static final String TAG = "tag";
}

View File

@@ -0,0 +1,129 @@
/* © SRSoftware 2025 */
package de.srsoftware.umbrella.tags;
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.core.Constants.ERROR_FAILED_CREATE_TABLE;
import static de.srsoftware.umbrella.core.Constants.USER_ID;
import static de.srsoftware.umbrella.tags.Constants.*;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
import static java.text.MessageFormat.format;
import de.srsoftware.tools.jdbc.Query;
import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class SqliteDb implements TagDB{
private static final int INITIAL_DB_VERSION = 1;
private static final System.Logger LOG = System.getLogger("TagDB");
private final Connection db;
public SqliteDb(Connection conn) {
this.db = conn;
init();
}
private int createTables() {
createTagTables();
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 createTagTables() {
var createTable = """
CREATE TABLE IF NOT EXISTS "{0}" (
{1} VARCHAR(255) NOT NULL,
{2} VARCHAR(20) NOT NULL,
{3} INTEGER NOT NULL,
{4} INTEGER NOT NULL,
PRIMARY KEY ({1}, {2}, {3}, {4})
)""";
try {
var stmt = db.prepareStatement(format(createTable,TABLE_TAGS, TAG, MODULE, ID, USER_ID));
stmt.execute();
stmt.close();
} catch (SQLException e) {
LOG.log(ERROR,ERROR_FAILED_CREATE_TABLE,TABLE_TAGS,e);
throw new RuntimeException(e);
}
}
@Override
public String delete(long userId, String module, long entityId, String tag) {
try {
Query.delete().from(TABLE_TAGS)
.where(TAG,equal(tag)).where(MODULE,equal(module)).where(ID,equal(entityId)).where(USER_ID,equal(userId))
.execute(db);
return tag;
} catch (SQLException e){
throw new UmbrellaException("Failed to save tag {0}",tag);
}
}
private void init(){
var version = createTables();
LOG.log(INFO,"Updated task db to version {0}",version);
}
@Override
public Set<String> list(long userId, String module, long entityId) {
try {
var tags = new HashSet<String>();
var rs = select(TAG).from(TABLE_TAGS).where(MODULE,equal(module)).where(ID,equal(entityId)).where(USER_ID,equal(userId)).exec(db);
while (rs.next()) tags.add(rs.getString(1));
rs.close();
return tags;
} catch (SQLException e) {
throw new UmbrellaException("Failed to load tags");
}
}
@Override
public String save(Collection<Long> userIds, String module, long entityId, String tag) {
try {
var query = replaceInto(TABLE_TAGS,USER_ID,MODULE,ID,TAG);
for (var userId : userIds) query.values(userId,module,entityId,tag);
query.execute(db).close();
return tag;
} catch (SQLException e){
throw new UmbrellaException("Failed to save tag {0}",tag);
}
}
}

View File

@@ -0,0 +1,13 @@
/* © SRSoftware 2025 */
package de.srsoftware.umbrella.tags;
import java.util.Collection;
import java.util.Set;
public interface TagDB {
Object delete(long userId, String module, long entityId, String tag);
Set<String> list(long id, String module, long entityId);
String save(Collection<Long> userIds, String module, long entityId, String tag);
}

View File

@@ -0,0 +1,112 @@
/* © SRSoftware 2025 */
package de.srsoftware.umbrella.tags;
import static de.srsoftware.umbrella.core.ConnectionProvider.connect;
import static de.srsoftware.umbrella.core.Constants.*;
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.tags.Constants.CONFIG_DATABASE;
import static de.srsoftware.umbrella.tags.Constants.TAG;
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.TagService;
import de.srsoftware.umbrella.core.api.UserService;
import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import de.srsoftware.umbrella.core.model.Token;
import org.json.JSONArray;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class TagModule extends BaseHandler implements TagService {
private final SqliteDb tagDb;
private final UserService users;
public TagModule(Configuration config, UserService userService) {
var dbFile = config.get(CONFIG_DATABASE).orElseThrow(() -> missingFieldException(CONFIG_DATABASE));
tagDb = new SqliteDb(connect(dbFile));
users = userService;
}
@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 entityId = Long.parseLong(head);
var tag = tagDb.delete(user.get().id(),module,entityId,body(ex));
return sendContent(ex, tag);
} 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 {
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 tags = tagDb.list(user.get().id(),module,entityId);
return sendContent(ex, tags);
} 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(TAG) && json.get(TAG) instanceof String tag)) throw missingFieldException(TAG);
List<Long> userList = json.has(USER_LIST) && json.get(USER_LIST) instanceof JSONArray arr ?
arr.toList().stream().filter(elem -> elem instanceof Number).map(elem -> (Number) elem).map(Number::longValue).toList()
: List.of(user.get().id());
if (userList.isEmpty()) throw missingFieldException(USER_LIST);
tag = tagDb.save(userList, module, entityId, tag);
return sendContent(ex, tag);
} catch (NumberFormatException e) {
return sendContent(ex, HTTP_UNPROCESSABLE, "Entity id missing in path.");
} catch (UmbrellaException e) {
return send(ex, e);
}
}
}