[DEV] backend might be finished and ready but not tested

This commit is contained in:
Edouard DUPIN 2022-06-27 00:02:56 +02:00
parent b10fe0bddc
commit 9f262679b9
22 changed files with 1225 additions and 1977 deletions

View File

@ -2,7 +2,8 @@ package org.kar.karusic;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.sql.*;
@ -11,22 +12,35 @@ import org.kar.karusic.annotation.SQLComment;
import org.kar.karusic.annotation.SQLIfNotExists;
import org.kar.karusic.annotation.SQLLimitSize;
import org.kar.karusic.annotation.SQLNotNull;
import org.kar.karusic.annotation.SQLNotRead;
import org.kar.karusic.annotation.SQLPrimaryKey;
import org.kar.karusic.annotation.SQLTableLinkGeneric;
import org.kar.karusic.annotation.SQLTableName;
import org.kar.karusic.annotation.SQLUpdateTime;
import org.kar.karusic.db.DBEntry;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.kar.karusic.annotation.SQLCreateTime;
import org.kar.karusic.annotation.SQLDefault;
public class SqlWrapper {
public static class ExceptionDBInterface extends Exception {
public int errorID;
ExceptionDBInterface(int errorId, String message) {
super(message);
this.errorID = errorId;
}
}
public SqlWrapper() {
}
public String convertTypeInSQL(Class<?> type) throws Exception {
public static String convertTypeInSQL(Class<?> type) throws Exception {
if (type == Long.class || type == long.class ) {
return "bigint";
}
@ -54,7 +68,171 @@ public class SqlWrapper {
throw new Exception("Imcompatible type of element in object for: " + type.getCanonicalName());
}
public <T> T insert(T data) throws Exception {
protected static <T> void setValuedb(Class<?> type, T data, int index, Field field, PreparedStatement ps) throws IllegalArgumentException, IllegalAccessException, SQLException {
if (type == Long.class) {
Object tmp = field.get(data);
if (tmp == null) {
ps.setNull(index++, Types.BIGINT);
} else {
ps.setLong(index++, (Long)tmp);
}
} else if (type == long.class ) {
ps.setLong(index++, field.getLong(data));
} else if (type == Integer.class) {
Object tmp = field.get(data);
if (tmp == null) {
ps.setNull(index++, Types.INTEGER);
} else {
ps.setInt(index++, (Integer)tmp);
}
} else if (type == int.class ) {
ps.setInt(index++, field.getInt(data));
} else if (type == Float.class) {
Object tmp = field.get(data);
if (tmp == null) {
ps.setNull(index++, Types.FLOAT);
} else {
ps.setFloat(index++, (Float)tmp);
}
} else if (type == float.class) {
ps.setFloat(index++, field.getFloat(data));
} else if (type == Double.class) {
Object tmp = field.get(data);
if (tmp == null) {
ps.setNull(index++, Types.DOUBLE);
} else {
ps.setDouble(index++, (Double)tmp);
}
} else if (type == Double.class) {
ps.setDouble(index++, field.getDouble(data));
} else if (type == Boolean.class) {
Object tmp = field.get(data);
if (tmp == null) {
ps.setNull(index++, Types.INTEGER);
} else {
ps.setBoolean(index++, (Boolean)tmp);
}
} else if (type == boolean.class) {
ps.setBoolean(index++, field.getBoolean(data));
} else if (type == Timestamp.class) {
Object tmp = field.get(data);
if (tmp == null) {
ps.setNull(index++, Types.INTEGER);
} else {
ps.setTimestamp(index++, (Timestamp)tmp);
}
} else if (type == Date.class) {
Object tmp = field.get(data);
if (tmp == null) {
ps.setNull(index++, Types.INTEGER);
} else {
ps.setDate(index++, (Date)tmp);
}
} else if (type == String.class) {
Object tmp = field.get(data);
if (tmp == null) {
ps.setNull(index++, Types.VARCHAR);
} else {
ps.setString(index++, (String)tmp);
}
}
}
protected static <T> void setValueFromDb(Class<?> type, T data, int index, Field field, ResultSet rs) throws IllegalArgumentException, IllegalAccessException, SQLException {
if (type == Long.class) {
Long tmp = rs.getLong(index);
if (rs.wasNull()) {
field.set(data, null);
} else {
field.set(data, tmp);
}
} else if (type == long.class ) {
Long tmp = rs.getLong(index);
if (rs.wasNull()) {
//field.set(data, null);
} else {
field.setLong(data, tmp);
}
} else if (type == Integer.class) {
Integer tmp = rs.getInt(index);
if (rs.wasNull()) {
field.set(data, null);
} else {
field.set(data, tmp);
}
} else if (type == int.class ) {
Integer tmp = rs.getInt(index);
if (rs.wasNull()) {
//field.set(data, null);
} else {
field.setInt(data, tmp);
}
} else if (type == Float.class) {
Float tmp = rs.getFloat(index);
if (rs.wasNull()) {
field.set(data, null);
} else {
field.set(data, tmp);
}
} else if (type == float.class) {
Float tmp = rs.getFloat(index);
if (rs.wasNull()) {
//field.set(data, null);
} else {
field.setFloat(data, tmp);
}
} else if (type == Double.class) {
Double tmp = rs.getDouble(index);
if (rs.wasNull()) {
field.set(data, null);
} else {
field.set(data, tmp);
}
} else if (type == double.class) {
Double tmp = rs.getDouble(index);
if (rs.wasNull()) {
//field.set(data, null);
} else {
field.setDouble(data, tmp);
}
} else if (type == Boolean.class) {
Boolean tmp = rs.getBoolean(index);
if (rs.wasNull()) {
field.set(data, null);
} else {
field.set(data, tmp);
}
} else if (type == boolean.class) {
Boolean tmp = rs.getBoolean(index);
if (rs.wasNull()) {
//field.set(data, null);
} else {
field.setBoolean(data, tmp);
}
} else if (type == Timestamp.class) {
Timestamp tmp = rs.getTimestamp(index);
if (rs.wasNull()) {
field.set(data, null);
} else {
field.set(data, tmp);
}
} else if (type == Date.class) {
Date tmp = rs.getDate(index);
if (rs.wasNull()) {
field.set(data, null);
} else {
field.set(data, tmp);
}
} else if (type == String.class) {
String tmp = rs.getString(index);
if (rs.wasNull()) {
field.set(data, null);
} else {
field.set(data, tmp);
}
}
}
public static <T> T insert(T data) throws Exception {
Class<?> clazz = data.getClass();
//public static NodeSmall createNode(String typeInNode, String name, String descrition, Long parentId) {
@ -146,73 +324,7 @@ public class SqlWrapper {
}
}
count++;
if (type == Long.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, (Long)tmp);
}
} else if (type == long.class ) {
ps.setLong(iii++, elem.getLong(data));
} else if (type == Integer.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setInt(iii++, (Integer)tmp);
}
} else if (type == int.class ) {
ps.setInt(iii++, elem.getInt(data));
} else if (type == Float.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.FLOAT);
} else {
ps.setFloat(iii++, (Float)tmp);
}
} else if (type == float.class) {
ps.setFloat(iii++, elem.getFloat(data));
} else if (type == Double.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.DOUBLE);
} else {
ps.setDouble(iii++, (Double)tmp);
}
} else if (type == float.class) {
ps.setDouble(iii++, elem.getDouble(data));
} else if (type == Boolean.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setBoolean(iii++, (Boolean)tmp);
}
} else if (type == boolean.class) {
ps.setBoolean(iii++, elem.getBoolean(data));
} else if (type == Timestamp.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setTimestamp(iii++, (Timestamp)tmp);
}
} else if (type == Date.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setDate(iii++, (Date)tmp);
}
} else if (type == String.class) {
Object tmp = elem.get(data);
if (tmp == null) {
ps.setNull(iii++, Types.VARCHAR);
} else {
ps.setString(iii++, (String)tmp);
}
}
setValuedb(type, data, iii++, elem, ps);
}
// execute the request
int affectedRows = ps.executeUpdate();
@ -248,24 +360,459 @@ public class SqlWrapper {
return data;
}
public static <T> T insertWithJson(Class<T> clazz, String jsonData) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// parse the object to be sure the data are valid:
T data = mapper.readValue(jsonData, clazz);
return insert(data);
}
public void update(Class<?> clazz, long id, String jsonData) throws Exception {
}
public Object get(Class<?> clazz, long id) throws Exception {
return null;
}
public List<Object> gets(Class<?> clazz) throws Exception {
return null;
}
public void delete(Class<?> clazz, long id) throws Exception {
}
public void setDelete(Class<?> clazz, long id) throws Exception {
public static <T> void update(Class<T> clazz, long id, String jsonData) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// parse the object to be sure the data are valid:
T data = mapper.readValue(jsonData, clazz);
// Read the tree to filter injection of data:
JsonNode root = mapper.readTree(jsonData);
List<String> keys = new ArrayList<>();
Iterator<String> iterator = root.fieldNames();
iterator.forEachRemaining(e -> keys.add(e));
update(data, id, keys);
}
public String createTable(Class<?> clazz) throws Exception {
public static <T> void update(T data, long id, List<String> filterValue) throws Exception {
Class<?> clazz = data.getClass();
//public static NodeSmall createNode(String typeInNode, String name, String description, Long parentId) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
// real add in the BDD:
try {
String tableName = getTableName(clazz);
boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
StringBuilder query = new StringBuilder();
query.append("UPDATE ");
query.append(tableName);
query.append(" SET ");
boolean firstField = true;
Field primaryKeyField = null;
int count = 0;
for (Field elem : clazz.getFields()) {
boolean primaryKey = elem.getDeclaredAnnotationsByType(SQLPrimaryKey.class).length != 0;
if (primaryKey) {
primaryKeyField = elem;
continue;
}
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
if (linkGeneric) {
continue;
}
boolean createTime = elem.getDeclaredAnnotationsByType(SQLCreateTime.class).length != 0;
if (createTime) {
continue;
}
String name = elem.getName();
boolean updateTime = elem.getDeclaredAnnotationsByType(SQLUpdateTime.class).length != 0;
if (! updateTime && !filterValue.contains(name)) {
continue;
}
if (!elem.getClass().isPrimitive()) {
Object tmp = elem.get(data);
if(tmp == null && elem.getDeclaredAnnotationsByType(SQLDefault.class).length != 0) {
continue;
}
}
count++;
if (firstField) {
firstField = false;
} else {
query.append(",");
}
query.append(" `");
query.append(name);
query.append("` = ");
if (updateTime) {
query.append(" now(3) ");
} else {
query.append("? ");
}
}
query.append(" WHERE `");
query.append(primaryKeyField.getName());
query.append("` = ?");
firstField = true;
System.out.println("generate the querry: '" + query.toString() + "'");
// prepare the request:
PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);
int iii = 1;
for (Field elem : clazz.getFields()) {
boolean primaryKey = elem.getDeclaredAnnotationsByType(SQLPrimaryKey.class).length != 0;
if (primaryKey) {
continue;
}
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
if (linkGeneric) {
continue;
}
boolean createTime = elem.getDeclaredAnnotationsByType(SQLCreateTime.class).length != 0;
if (createTime) {
continue;
}
String name = elem.getName();
boolean updateTime = elem.getDeclaredAnnotationsByType(SQLUpdateTime.class).length != 0;
if (updateTime || !filterValue.contains(name)) {
continue;
}
Class<?> type = elem.getType();
if (!type.isPrimitive()) {
Object tmp = elem.get(data);
if(tmp == null && elem.getDeclaredAnnotationsByType(SQLDefault.class).length != 0) {
continue;
}
}
count++;
setValuedb(type, data, iii++, elem, ps);
}
ps.setLong(iii++, id);
// execute the request
int affectedRows = ps.executeUpdate();
// todo manage the list of element is valid ...
//ps.execute();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public static <T> T get(Class<T> clazz, long id) throws Exception {
//public static NodeSmall createNode(String typeInNode, String name, String description, Long parentId) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
T out = null;
// real add in the BDD:
try {
String tableName = getTableName(clazz);
boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
StringBuilder query = new StringBuilder();
query.append("SELECT ");
//query.append(tableName);
//query.append(" SET ");
boolean firstField = true;
Field primaryKeyField = null;
int count = 0;
for (Field elem : clazz.getFields()) {
boolean primaryKey = elem.getDeclaredAnnotationsByType(SQLPrimaryKey.class).length != 0;
if (primaryKey) {
primaryKeyField = elem;
}
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
if (linkGeneric) {
continue;
}
boolean createTime = elem.getDeclaredAnnotationsByType(SQLCreateTime.class).length != 0;
if (createTime) {
continue;
}
String name = elem.getName();
boolean updateTime = elem.getDeclaredAnnotationsByType(SQLUpdateTime.class).length != 0;
if (updateTime) {
continue;
}
count++;
if (firstField) {
firstField = false;
} else {
query.append(",");
}
query.append(" ");
query.append(tableName);
query.append(".");
query.append(name);
}
query.append(" FROM `");
query.append(tableName);
query.append("` ");
query.append(" WHERE ");
query.append(tableName);
query.append(".");
query.append(primaryKeyField.getName());
query.append(" = ?");
/*
query.append(" AND ");
query.append(tableName);
query.append(".deleted = false ");
*/
firstField = true;
System.out.println("generate the querry: '" + query.toString() + "'");
// prepare the request:
PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);
int iii = 1;
ps.setLong(iii++, id);
// execute the request
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Object data = clazz.getConstructors()[0].newInstance();
count = 1;
for (Field elem : clazz.getFields()) {
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
if (linkGeneric) {
continue;
}
boolean createTime = elem.getDeclaredAnnotationsByType(SQLCreateTime.class).length != 0;
if (createTime) {
continue;
}
String name = elem.getName();
boolean updateTime = elem.getDeclaredAnnotationsByType(SQLUpdateTime.class).length != 0;
if (updateTime) {
continue;
}
//this.name = rs.getString(iii++);
//this.description = rs.getString(iii++);
//this.covers = getListOfIds(rs, iii++);
setValueFromDb(elem.getType(), data, count, elem, rs);
count++;
}
out = (T)data;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
entry.disconnect();
entry = null;
return out;
}
public static <T> List<T> gets(Class<T> clazz, boolean fool) throws Exception {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
List<T> out = new ArrayList<>();
// real add in the BDD:
try {
String tableName = getTableName(clazz);
boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
StringBuilder query = new StringBuilder();
query.append("SELECT ");
//query.append(tableName);
//query.append(" SET ");
boolean firstField = true;
int count = 0;
for (Field elem : clazz.getFields()) {
boolean notRead = elem.getDeclaredAnnotationsByType(SQLNotRead.class).length != 0;
if (!fool && notRead) {
continue;
}
String name = elem.getName();
count++;
if (firstField) {
firstField = false;
} else {
query.append(",");
}
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
if (linkGeneric) {
String localName = name;
if (name.endsWith("s")) {
localName = name.substring(0, name.length()-1);
}
String tmpVariable = "tmp_" + Integer.toString(count);
query.append(" (SELECT GROUP_CONCAT(");
query.append(tmpVariable);
query.append(".");
query.append(localName);
query.append("_id SEPARATOR '-') FROM ");
query.append(tableName);
query.append("_link_");
query.append(localName);
query.append(" ");
query.append(tmpVariable);
query.append(" WHERE ");
query.append(tmpVariable);
query.append(".deleted = false AND ");
query.append(localName);
query.append(".id = ");
query.append(tmpVariable);
query.append(".");
query.append(localName);
query.append("_id GROUP BY ");
query.append(tmpVariable);
query.append(".");
query.append(localName);
query.append("_id ) AS ");
query.append(name);
query.append(" ");
/*
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM cover_link_node tmp" +
" WHERE tmp.deleted = false" +
" AND node.id = tmp.node_id" +
" GROUP BY tmp.node_id) AS covers" +
*/
} else {
query.append(" ");
query.append(tableName);
query.append(".");
query.append(name);
}
}
query.append(" FROM `");
query.append(tableName);
query.append("` ");
query.append(" WHERE ");
//query.append(tableName);
//query.append(".");
//query.append(primaryKeyField.getName());
//query.append(" = ?");
//query.append(" AND ");
query.append(tableName);
query.append(".deleted = false ");
firstField = true;
System.out.println("generate the querry: '" + query.toString() + "'");
// prepare the request:
PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);
// execute the request
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Object data = clazz.getConstructors()[0].newInstance();
count = 1;
for (Field elem : clazz.getFields()) {
boolean notRead = elem.getDeclaredAnnotationsByType(SQLNotRead.class).length != 0;
if (!fool && notRead) {
continue;
}
String name = elem.getName();
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
if (linkGeneric) {
List<Long> idList = getListOfIds(rs, count);
elem.set(data, idList);
/*String query = "SELECT node.id," +
" node.name," +
" node.description," +
" node.parent_id," +
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM cover_link_node tmp" +
" WHERE tmp.deleted = false" +
" AND node.id = tmp.node_id" +
" GROUP BY tmp.node_id) AS covers" +
" FROM node" +
" WHERE node.deleted = false " +
" AND node.type = ?" +
" AND node.id = ?" +
" ORDER BY node.name";
*/
continue;
} else {
setValueFromDb(elem.getType(), data, count, elem, rs);
}
count++;
}
out.add((T)data);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
entry.disconnect();
entry = null;
return out;
}
public static void addLink(Class<?> clazz, long localKey, String table, long remoteKey) throws Exception {
String tableName = getTableName(clazz);
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
long uniqueSQLID = -1;
// real add in the BDD:
try {
// prepare the request:
String query = "INSERT INTO " + tableName + "_link_" + table + " (create_date, modify_date, " + tableName + "_id, " + table + "_id)" +
" VALUES (now(3), now(3), ?, ?)";
PreparedStatement ps = entry.connection.prepareStatement(query,
Statement.RETURN_GENERATED_KEYS);
int iii = 1;
ps.setLong(iii++, localKey);
ps.setLong(iii++, remoteKey);
// execute the request
int affectedRows = ps.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating data failed, no rows affected.");
}
// retreive uid inserted
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
uniqueSQLID = generatedKeys.getLong(1);
} else {
throw new SQLException("Creating user failed, no ID obtained (1).");
}
} catch (Exception ex) {
System.out.println("Can not get the UID key inserted ... ");
ex.printStackTrace();
throw new SQLException("Creating user failed, no ID obtained (2).");
}
} catch (SQLException ex) {
ex.printStackTrace();
throw new ExceptionDBInterface(500, "SQL error: " + ex.getMessage());
} finally {
entry.disconnect();
}
}
public static void removeLink(Class<?> clazz, long localKey, String table, long remoteKey) throws Exception {
String tableName = getTableName(clazz);
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "UPDATE `" + tableName + "_link_" + table + "` SET `modify_date`=now(3), `deleted`=true WHERE `" + tableName + "_id` = ? AND `" + table + "_id` = ?";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setLong(iii++, localKey);
ps.setLong(iii++, remoteKey);
ps.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
throw new ExceptionDBInterface(500, "SQL error: " + ex.getMessage());
} finally {
entry.disconnect();
}
}
protected static List<Long> getListOfIds(ResultSet rs, int iii) throws SQLException {
String trackString = rs.getString(iii);
if (rs.wasNull()) {
return null;
}
List<Long> out = new ArrayList<>();
String[] elements = trackString.split("-");
for (String elem : elements) {
Long tmp = Long.parseLong(elem);
out.add(tmp);
}
return out;
}
public static void delete(Class<?> clazz, long id) throws Exception {
}
public static void setDelete(Class<?> clazz, long id) throws Exception {
String tableName = getTableName(clazz);
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "UPDATE `" + tableName + "` SET `modify_date`=now(3), `deleted`=true WHERE `id` = ?";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setLong(iii++, id);
ps.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
throw new ExceptionDBInterface(500, "SQL error: " + ex.getMessage());
} finally {
entry.disconnect();
}
}
public static String createTable(Class<?> clazz) throws Exception {
String tableName = getTableName(clazz);
boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
StringBuilder out = new StringBuilder();
@ -399,7 +946,7 @@ public class SqlWrapper {
}
public String getTableName(final Class<?> element) throws Exception {
public static String getTableName(final Class<?> element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(SQLTableName.class);
if (annotation.length == 0) {
return null;
@ -413,7 +960,7 @@ public class SqlWrapper {
}
return tmp;
}
public String getComment(final Field element) throws Exception {
public static String getComment(final Field element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(SQLComment.class);
if (annotation.length == 0) {
return null;
@ -427,7 +974,7 @@ public class SqlWrapper {
}
return tmp;
}
public String getDefault(final Field element) throws Exception {
public static String getDefault(final Field element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(SQLDefault.class);
if (annotation.length == 0) {
return null;
@ -441,7 +988,7 @@ public class SqlWrapper {
}
return tmp;
}
public Integer getLimitSize(final Field element) throws Exception {
public static Integer getLimitSize(final Field element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(SQLLimitSize.class);
if (annotation.length == 0) {
return null;

View File

@ -1,17 +1,9 @@
package org.kar.karusic;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.kar.karusic.db.DBEntry;
import org.kar.karusic.model.User;
import org.kar.karusic.model.UserSmall;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDB {
@ -19,7 +11,9 @@ public class UserDB {
public UserDB() {
}
public static User getUsers(long userId) {
public static User getUsers(long userId) throws Exception {
return SqlWrapper.get(User.class, userId);
/*
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "SELECT * FROM user WHERE id = ?";
try {
@ -36,10 +30,11 @@ public class UserDB {
}
entry.disconnect();
return null;
*/
}
public static User getUserOrCreate(long userId, String userLogin) {
public static User getUserOrCreate(long userId, String userLogin) throws Exception {
User user = getUsers(userId);
if (user != null) {
/*

View File

@ -1,6 +1,7 @@
package org.kar.karusic;
import java.net.URI;
import java.util.List;
import javax.ws.rs.core.UriBuilder;
@ -9,28 +10,19 @@ import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.kar.karusic.api.AlbumResource;
import org.kar.karusic.api.ArtistResource;
import org.kar.karusic.api.DataResource;
import org.kar.karusic.api.Front;
import org.kar.karusic.api.GenderResource;
import org.kar.karusic.api.HealthCheck;
import org.kar.karusic.api.SeasonResource;
import org.kar.karusic.api.SeriesResource;
import org.kar.karusic.api.TypeResource;
import org.kar.karusic.api.UniverseResource;
import org.kar.karusic.api.PlaylistResource;
import org.kar.karusic.api.TrackResource;
import org.kar.karusic.api.UserResource;
import org.kar.karusic.api.VideoResource;
import org.kar.karusic.db.DBConfig;
import org.kar.karusic.filter.AuthenticationFilter;
import org.kar.karusic.filter.CORSFilter;
import org.kar.karusic.filter.OptionFilter;
import org.kar.karusic.model.Album;
import org.kar.karusic.model.Artist;
import org.kar.karusic.model.Artist;
import org.kar.karusic.model.DataSmall;
import org.kar.karusic.model.Gender;
import org.kar.karusic.model.Playlist;
import org.kar.karusic.model.Track;
import org.kar.karusic.model.User;
import org.kar.karusic.util.ConfigVariable;
import org.kar.karusic.util.JWTWrapper;
@ -54,49 +46,58 @@ public class WebLauncher {
}
public static void main(String[] args) {
Track tmpTrack = new Track();
tmpTrack.dataId = (long) 542;
tmpTrack.genderId = (long) 15;
tmpTrack.description = "my beautifull description";
tmpTrack.name = "I am singging in the rain.";
try {
Track tmpTrack2 = new SqlWrapper().insert(tmpTrack);
System.out.print("receive data = " + tmpTrack2);
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
if (false) {
// generate the BDD:
try {
String out = "";
out += new SqlWrapper().createTable(User.class);
out += new SqlWrapper().createTable(Track.class);
out += new SqlWrapper().createTable(Artist.class);
out += new SqlWrapper().createTable(Gender.class);
out += new SqlWrapper().createTable(Playlist.class);
out += new SqlWrapper().createTable(Album.class);
System.out.println(out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
if (false) {
// generate the BDD:
/*
String out = new Artist().getQueryString();
System.out.println("The query:");
System.out.println(out);
return;
*/
}
//
// if (false) {
// Track tmpTrack = new Track();
// tmpTrack.dataId = (long) 542;
// tmpTrack.genderId = (long) 15;
// tmpTrack.description = "my beautifull description";
// tmpTrack.name = "I am singging in the rain.";
// try {
// //Track tmpTrack2 = new SqlWrapper().insert(tmpTrack);
// //System.out.println("receive data = " + tmpTrack2);
//
// SqlWrapper.update(Track.class, 2, "{\"deleted\": true }");
// Object gettedValue = SqlWrapper.get(Track.class, 2);
// System.out.println("retreive data = " + gettedValue);
// List<Track> allValues = SqlWrapper.gets(Track.class, true);
// System.out.println("retreive data:");
// for (Object elem: allValues) {
// System.out.println(" - " + elem);
// }
// } catch (Exception e2) {
// // TODO Auto-generated catch block
// e2.printStackTrace();
// }
// }
//
// if (false) {
// // generate the BDD:
// try {
// String out = "";
// out += SqlWrapper.createTable(User.class);
// out += SqlWrapper.createTable(Track.class);
// out += SqlWrapper.createTable(Artist.class);
// out += SqlWrapper.createTable(Gender.class);
// out += SqlWrapper.createTable(Playlist.class);
// out += SqlWrapper.createTable(Album.class);
// System.out.println(out);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return;
// }
// if (false) {
// // generate the BDD:
// /*
// String out = new Artist().getQueryString();
// System.out.println("The query:");
// System.out.println(out);
// return;
// */
// }
//
ResourceConfig rc = new ResourceConfig();
// need to uppgrade when server call us...
try {
@ -114,27 +115,22 @@ public class WebLauncher {
}
// add multipart models ..
//rc.register(new MultiPartFeature());
//rc.register(new InjectionBinder());
rc.register(new MultiPartFeature());
//rc.register(new MyFileUploader());
// global authentication system
rc.register(new OptionFilter());
// remove cors ==> all time called by an other system...
rc.register(new CORSFilter());
// global authentication system
//rc.register(new AuthenticationFilter());
rc.registerClasses(AuthenticationFilter.class);
// add default resource:
rc.registerClasses(UserResource.class);
rc.registerClasses(AlbumResource.class);
rc.registerClasses(ArtistResource.class);
rc.registerClasses(GenderResource.class);
rc.registerClasses(PlaylistResource.class);
rc.registerClasses(TrackResource.class);
rc.registerClasses(DataResource.class);
/*
rc.registerClasses(SeasonResource.class);
rc.registerClasses(TypeResource.class);
rc.registerClasses(UniverseResource.class);
rc.registerClasses(VideoResource.class);
*/
rc.registerClasses(HealthCheck.class);
rc.registerClasses(Front.class);

View File

@ -0,0 +1,96 @@
package org.kar.karusic.api;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.SqlWrapper;
import org.kar.karusic.model.Album;
import org.kar.karusic.model.Track;
import org.kar.karusic.util.CoverTools;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.List;
@Path("/album")
@Produces({MediaType.APPLICATION_JSON})
public class AlbumResource {
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Album getWithId(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Album.class, id);
}
@GET
@RolesAllowed("USER")
public List<Album> get() throws Exception {
return SqlWrapper.gets(Album.class, false);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Album put(String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Album.class, jsonRequest);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Album put(@PathParam("id") Long id, String jsonRequest) throws Exception {
SqlWrapper.update(Album.class, id, jsonRequest);
return SqlWrapper.get(Album.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.setDelete(Album.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_track/{trackId}")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Album addTrack(@PathParam("id") Long id,@PathParam("trackId") Long trackId) throws Exception {
SqlWrapper.removeLink(Album.class, id, "track", trackId);
return SqlWrapper.get(Album.class, id);
}
@GET
@Path("{id}/rm_track/{trackId}")
@RolesAllowed("ADMIN")
public Album removeTrack(@PathParam("id") Long id, @PathParam("trackId") Long trackId) throws Exception {
SqlWrapper.removeLink(Album.class, id, "track", trackId);
return SqlWrapper.get(Album.class, id);
}
@POST
@Path("{id}/add_cover")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadCover(@PathParam("id") Long id,
@FormDataParam("fileName") String fileName,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
return CoverTools.uploadCover(Album.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception {
SqlWrapper.removeLink(Album.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Album.class, id)).build();
}
}

View File

@ -2,14 +2,15 @@ package org.kar.karusic.api;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.SqlWrapper;
import org.kar.karusic.model.Artist;
import org.kar.karusic.model.NodeSmall;
import org.kar.karusic.util.CoverTools;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.List;
@ -20,36 +21,39 @@ public class ArtistResource {
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Object getWithId(@PathParam("id") Long id) {
return NodeInterface.getWithId(new Artist(), id);
}
public static Object getOrCreate(int season, Long seriesId) {
//return NodeInterface.getOrCreate(Integer.toString(season), seriesId);
return null;
public static Artist getWithId(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Artist.class, id);
}
@GET
@RolesAllowed("USER")
public List<Object> get() {
return NodeInterface.get(new Artist());
public List<Artist> get() throws Exception {
return SqlWrapper.gets(Artist.class, false);
}
/*
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Artist put(String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Artist.class, jsonRequest);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Response put(@PathParam("id") Long id, String jsonRequest) {
return NodeInterface.put(typeInNode, id, jsonRequest);
public Artist put(@PathParam("id") Long id, String jsonRequest) throws Exception {
SqlWrapper.update(Artist.class, id, jsonRequest);
return SqlWrapper.get(Artist.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) {
return NodeInterface.delete(typeInNode, id);
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.setDelete(Artist.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_cover")
@RolesAllowed("ADMIN")
@ -59,13 +63,16 @@ public class ArtistResource {
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
return NodeInterface.uploadCover(typeInNode, id, fileName, fileInputStream, fileMetaData);
return CoverTools.uploadCover(Artist.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{cover_id}")
@Path("{id}/rm_cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") Long nodeId, @PathParam("cover_id") Long coverId) {
return NodeInterface.removeCover(typeInNode, nodeId, coverId);
public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception {
SqlWrapper.removeLink(Artist.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Artist.class, id)).build();
}
*/
}

View File

@ -0,0 +1,79 @@
package org.kar.karusic.api;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.SqlWrapper;
import org.kar.karusic.model.Gender;
import org.kar.karusic.util.CoverTools;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.List;
@Path("/gender")
@Produces({MediaType.APPLICATION_JSON})
public class GenderResource {
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Gender getWithId(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Gender.class, id);
}
@GET
@RolesAllowed("USER")
public List<Gender> get() throws Exception {
return SqlWrapper.gets(Gender.class, false);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Gender put(String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Gender.class, jsonRequest);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Gender put(@PathParam("id") Long id, String jsonRequest) throws Exception {
SqlWrapper.update(Gender.class, id, jsonRequest);
return SqlWrapper.get(Gender.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.setDelete(Gender.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_cover")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadCover(@PathParam("id") Long id,
@FormDataParam("fileName") String fileName,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
return CoverTools.uploadCover(Gender.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception {
SqlWrapper.removeLink(Gender.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Gender.class, id)).build();
}
}

View File

@ -1,321 +0,0 @@
package org.kar.karusic.api;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.kar.karusic.WebLauncher;
import org.kar.karusic.db.DBEntry;
import org.kar.karusic.model.Artist;
import org.kar.karusic.model.Data;
import org.kar.karusic.model.GenericTable;
import org.kar.karusic.model.NodeSmall;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class NodeInterface {
/* test en SQL qui fait joli...
SELECT node.id,
node.name,
node.description,
node.parent_id,
GROUP_CONCAT(cover_link_node.data_id SEPARATOR '-') as covers
FROM node, cover_link_node
WHERE node.deleted = false AND cover_link_node.deleted = false AND node.type = "TYPE" AND cover_link_node.node_id = node.id
GROUP BY node.id
ORDER BY node.name
// bon c'est bien mais c'est mieux en faisant un left join avec préfiltrage ...
SELECT node.id,
node.name,
node.description,
node.parent_id,
cover_link_node.data_id
FROM node
LEFT JOIN cover_link_node
ON node.id = cover_link_node.node_id
AND cover_link_node.deleted = false
WHERE node.deleted = false
AND node.type = "TYPE"
ORDER BY node.name
// marche pas:
SELECT node.id,
node.name,
node.description,
node.parent_id,
`extract.covers`
FROM node
LEFT JOIN (SELECT tmp.node_id,
GROUP_CONCAT(`tmp.data_id` SEPARATOR '-') as `covers`
FROM cover_link_node tmp
WHERE tmp.deleted = false
GROUP BY tmp.node_id) extract
ON node.id = extract.node_id
WHERE node.deleted = false
AND node.type = "TYPE"
ORDER BY node.name
// et enfin une version qui fonctionne ...
SELECT node.id,
node.name,
node.description,
node.parent_id,
(SELECT GROUP_CONCAT(tmp.data_id)
FROM cover_link_node tmp
WHERE tmp.deleted = false
AND node.id = tmp.node_id
GROUP BY tmp.node_id) AS covers
FROM node
WHERE node.deleted = false
AND node.type = "TYPE"
ORDER BY node.name
*/
public static Object getWithId(GenericTable type, long id) {
return null;
}
public static List<Object> get(GenericTable object) {
// TODO Auto-generated method stub
return object.get();
}
/*
public static NodeSmall getWithId(String typeInNode, long id) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "SELECT node.id," +
" node.name," +
" node.description," +
" node.parent_id," +
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM cover_link_node tmp" +
" WHERE tmp.deleted = false" +
" AND node.id = tmp.node_id" +
" GROUP BY tmp.node_id) AS covers" +
" FROM node" +
" WHERE node.deleted = false " +
" AND node.type = ?" +
" AND node.id = ?" +
" ORDER BY node.name";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setString(iii++, typeInNode);
ps.setLong(iii++, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
NodeSmall out = new NodeSmall(rs);
entry.disconnect();
entry = null;
return out;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
entry = null;
return null;
}
public static List<NodeSmall> getWithName(String typeInNode, String name) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
List<NodeSmall> out = new ArrayList<>();
String query = "SELECT node.id," +
" node.name," +
" node.description," +
" node.parent_id," +
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM cover_link_node tmp" +
" WHERE tmp.deleted = false" +
" AND node.id = tmp.node_id" +
" GROUP BY tmp.node_id) AS covers" +
" FROM node" +
" WHERE node.deleted = false " +
" AND node.type = ?" +
" AND node.name = ?" +
" ORDER BY node.name";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setString(iii++, typeInNode);
ps.setString(iii++, name);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
out.add(new NodeSmall(rs));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
entry = null;
return out;
}
public static NodeSmall getWithNameAndParent(String typeInNode, String name, long parentId) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "SELECT node.id," +
" node.name," +
" node.description," +
" node.parent_id," +
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM cover_link_node tmp" +
" WHERE tmp.deleted = false" +
" AND node.id = tmp.node_id" +
" GROUP BY tmp.node_id) AS covers" +
" FROM node" +
" WHERE node.deleted = false " +
" AND node.type = ?" +
" AND node.name = ?" +
" AND node.parent_id = ?" +
" ORDER BY node.name";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setString(iii++, typeInNode);
ps.setString(iii++, name);
ps.setLong(iii++, parentId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
NodeSmall out = new NodeSmall(rs);
entry.disconnect();
entry = null;
return out;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
entry = null;
return null;
}
public static NodeSmall createNode(String typeInNode, String name, String descrition, Long parentId) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
long uniqueSQLID = -1;
// real add in the BDD:
try {
// prepare the request:
String query = "INSERT INTO node (`type`, `name`, `description`, `parent_id`) VALUES (?, ?, ?, ?)";
PreparedStatement ps = entry.connection.prepareStatement(query,
Statement.RETURN_GENERATED_KEYS);
int iii = 1;
ps.setString(iii++, typeInNode);
ps.setString(iii++, name);
if (descrition == null) {
ps.setNull(iii++, Types.VARCHAR);
} else {
ps.setString(iii++, descrition);
}
if (parentId == null) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, parentId);
}
// execute the request
int affectedRows = ps.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating node failed, no rows affected.");
}
// retreive uid inserted
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
uniqueSQLID = generatedKeys.getLong(1);
} else {
throw new SQLException("Creating node failed, no ID obtained (1).");
}
} catch (Exception ex) {
System.out.println("Can not get the UID key inserted ... ");
ex.printStackTrace();
throw new SQLException("Creating node failed, no ID obtained (2).");
}
//ps.execute();
} catch (SQLException ex) {
ex.printStackTrace();
}
return getWithId(typeInNode, uniqueSQLID);
}
public static NodeSmall getOrCreate(String typeInNode, String name, Long parentId) {
if (name == null || name.isEmpty()) {
return null;
}
NodeSmall node = getWithNameAndParent(typeInNode, name, parentId);
if (node != null) {
return node;
}
return createNode(typeInNode, name, null, parentId);
}
static public Response put(String typeInNode, Long id, String jsonRequest) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode root = mapper.readTree(jsonRequest);
String query = "UPDATE `node` SET `modify_date`=now(3)";
if (!root.path("name").isMissingNode()) {
query += ", `name` = ? ";
}
if (!root.path("description").isMissingNode()) {
query += ", `description` = ? ";
}
if (!root.path("parentId").isMissingNode()) {
query += ", `parent_id` = ? ";
}
query += " WHERE `id` = ?";
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
if (!root.path("name").isMissingNode()) {
if (root.path("name").isNull()) {
ps.setString(iii++, "???");
} else {
ps.setString(iii++, root.path("name").asText());
}
}
if (!root.path("description").isMissingNode()) {
if (root.path("description").isNull()) {
ps.setNull(iii++, Types.VARCHAR);
} else {
ps.setString(iii++, root.path("description").asText());
}
}
if (!root.path("parentId").isMissingNode()) {
if (root.path("parentId").isNull()) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, root.path("parentId").asLong());
}
}
ps.setLong(iii++, id);
System.out.println(" request : " + ps.toString());
ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
entry.disconnect();
entry = null;
return Response.notModified("SQL error").build();
}
entry.disconnect();
entry = null;
} catch (IOException e) {
e.printStackTrace();
return Response.notModified("input json error error").build();
}
return Response.ok(getWithId(typeInNode, id)).build();
}
*/
}

View File

@ -0,0 +1,98 @@
package org.kar.karusic.api;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.SqlWrapper;
import org.kar.karusic.model.Playlist;
import org.kar.karusic.util.CoverTools;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.List;
@Path("/playlist")
@Produces({MediaType.APPLICATION_JSON})
public class PlaylistResource {
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Playlist getWithId(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Playlist.class, id);
}
@GET
@RolesAllowed("USER")
public List<Playlist> get() throws Exception {
return SqlWrapper.gets(Playlist.class, false);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Playlist put(String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Playlist.class, jsonRequest);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Playlist put(@PathParam("id") Long id, String jsonRequest) throws Exception {
SqlWrapper.update(Playlist.class, id, jsonRequest);
return SqlWrapper.get(Playlist.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.setDelete(Playlist.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_track/{trackId}")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Playlist addTrack(@PathParam("id") Long id,@PathParam("trackId") Long trackId) throws Exception {
SqlWrapper.removeLink(Playlist.class, id, "track", trackId);
return SqlWrapper.get(Playlist.class, id);
}
@GET
@Path("{id}/rm_track/{trackId}")
@RolesAllowed("ADMIN")
public Playlist removeTrack(@PathParam("id") Long id, @PathParam("trackId") Long trackId) throws Exception {
SqlWrapper.removeLink(Playlist.class, id, "track", trackId);
return SqlWrapper.get(Playlist.class, id);
}
@POST
@Path("{id}/add_cover")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadCover(@PathParam("id") Long id,
@FormDataParam("fileName") String fileName,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
return CoverTools.uploadCover(Playlist.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception {
SqlWrapper.removeLink(Playlist.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Playlist.class, id)).build();
}
}

View File

@ -1,77 +0,0 @@
package org.kar.karusic.api;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.model.NodeSmall;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.List;
@Path("/series")
@Produces({MediaType.APPLICATION_JSON})
public class SeriesResource {
private static final String typeInNode = "SERIES";
@GET
@Path("{id}")
@RolesAllowed("USER")
public static NodeSmall getWithId(@PathParam("id") Long id) {
return NodeInterface.getWithId(typeInNode, id);
}
public static List<NodeSmall> getWithName(String name) {
return NodeInterface.getWithName(typeInNode, name);
}
public static NodeSmall getOrCreate(String series, Long typeId) {
return NodeInterface.getOrCreate(typeInNode, series, typeId);
}
@GET
@RolesAllowed("USER")
public List<NodeSmall> get() {
return NodeInterface.get(typeInNode);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Response put(@PathParam("id") Long id, String jsonRequest) {
return NodeInterface.put(typeInNode, id, jsonRequest);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) {
return NodeInterface.delete(typeInNode, id);
}
@POST
@Path("{id}/add_cover")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadCover(@PathParam("id") Long id,
@FormDataParam("fileName") String fileName,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
return NodeInterface.uploadCover(typeInNode, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") Long nodeId, @PathParam("coverId") Long coverId) {
return NodeInterface.removeCover(typeInNode, nodeId, coverId);
}
}

View File

@ -0,0 +1,98 @@
package org.kar.karusic.api;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.SqlWrapper;
import org.kar.karusic.model.Track;
import org.kar.karusic.util.CoverTools;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.List;
@Path("/track")
@Produces({MediaType.APPLICATION_JSON})
public class TrackResource {
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Track getWithId(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Track.class, id);
}
@GET
@RolesAllowed("USER")
public List<Track> get() throws Exception {
return SqlWrapper.gets(Track.class, false);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Track put(String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Track.class, jsonRequest);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Track put(@PathParam("id") Long id, String jsonRequest) throws Exception {
SqlWrapper.update(Track.class, id, jsonRequest);
return SqlWrapper.get(Track.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.setDelete(Track.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_artist/{artistId}")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Track addTrack(@PathParam("id") Long id,@PathParam("artistId") Long artistId) throws Exception {
SqlWrapper.removeLink(Track.class, id, "artist", artistId);
return SqlWrapper.get(Track.class, id);
}
@GET
@Path("{id}/rm_artist/{trackId}")
@RolesAllowed("ADMIN")
public Track removeTrack(@PathParam("id") Long id, @PathParam("artistId") Long artistId) throws Exception {
SqlWrapper.removeLink(Track.class, id, "artist", artistId);
return SqlWrapper.get(Track.class, id);
}
@POST
@Path("{id}/add_cover")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadCover(@PathParam("id") Long id,
@FormDataParam("fileName") String fileName,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
return CoverTools.uploadCover(Track.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception {
SqlWrapper.removeLink(Track.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Track.class, id)).build();
}
}

View File

@ -1,73 +0,0 @@
package org.kar.karusic.api;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.model.NodeSmall;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.List;
@Path("/universe")
@Produces({MediaType.APPLICATION_JSON})
public class UniverseResource {
private static final String typeInNode = "UNIVERSE";
@GET
@Path("{id}")
@RolesAllowed("USER")
public static NodeSmall getWithId(@PathParam("id") Long id) {
return NodeInterface.getWithId(typeInNode, id);
}
public static List<NodeSmall> getWithName(String name) {
return NodeInterface.getWithName(typeInNode, name);
}
public static NodeSmall getOrCreate(String universe) {
return NodeInterface.getOrCreate(typeInNode, universe, null);
}
@GET
@RolesAllowed("USER")
public List<NodeSmall> get() {
return NodeInterface.get(typeInNode);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Response put(@PathParam("id") Long id, String jsonRequest) {
return NodeInterface.put(typeInNode, id, jsonRequest);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) {
return NodeInterface.delete(typeInNode, id);
}
@POST
@Path("{id}/add_cover")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadCover(@PathParam("id") Long id,
@FormDataParam("fileName") String fileName,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
return NodeInterface.uploadCover(typeInNode, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{cover_id}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") Long nodeId, @PathParam("cover_id") Long coverId) {
return NodeInterface.removeCover(typeInNode, nodeId, coverId);
}
}

View File

@ -1,6 +1,7 @@
package org.kar.karusic.api;
import org.kar.karusic.UserDB;
import org.kar.karusic.SqlWrapper;
//import org.kar.karusic.UserDB;
import org.kar.karusic.WebLauncher;
import org.kar.karusic.db.DBEntry;
import org.kar.karusic.filter.GenericContext;
@ -34,18 +35,18 @@ public class UserResource {
public UserResource() {
}
private static String randomString(int count) {
Random rand = new Random(System.nanoTime());
String s = new String();
int nbChar = count;
for (int i = 0; i < nbChar; i++) {
char c = (char) rand.nextInt();
while ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9'))
c = (char) rand.nextInt();
s = s + c;
}
return s;
}
// private static String randomString(int count) {
// Random rand = new Random(System.nanoTime());
// String s = new String();
// int nbChar = count;
// for (int i = 0; i < nbChar; i++) {
// char c = (char) rand.nextInt();
// while ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9'))
// c = (char) rand.nextInt();
// s = s + c;
// }
// return s;
// }
// I do not understand why angular request option before, but this is needed..
/*
@ -61,23 +62,15 @@ public class UserResource {
// curl http://localhost:9993/api/users
@GET
@RolesAllowed("ADMIN")
public List<UserExtern> getUsers() {
public List<User> getUsers() {
System.out.println("getUsers");
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
List<UserExtern> out = new ArrayList<>();
String query = "SELECT * FROM user";
try {
Statement st = entry.connection.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
out.add(new UserExtern(new User(rs)));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
entry = null;
return out;
return SqlWrapper.gets(User.class, false);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// I do not understand why angular request option before, but this is needed..
@ -96,13 +89,19 @@ public class UserResource {
@GET
@Path("{id}")
@RolesAllowed("ADMIN")
public UserExtern getUsers(@Context SecurityContext sc, @PathParam("id") long userId) {
public User getUsers(@Context SecurityContext sc, @PathParam("id") long userId) {
System.out.println("getUser " + userId);
GenericContext gc = (GenericContext) sc.getUserPrincipal();
System.out.println("===================================================");
System.out.println("== USER ? " + gc.user);
System.out.println("===================================================");
return new UserExtern(UserDB.getUsers(userId));
try {
return SqlWrapper.get(User.class, userId);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*
@ -119,13 +118,13 @@ public class UserResource {
@GET
@Path("me")
@RolesAllowed("USER")
public UserPerso getMe(@Context SecurityContext sc) {
public User getMe(@Context SecurityContext sc) {
System.out.println("getMe()");
GenericContext gc = (GenericContext) sc.getUserPrincipal();
System.out.println("===================================================");
System.out.println("== USER ? " + gc.user);
System.out.println("===================================================");
return new UserPerso(gc.user);
return gc.user;
}
// curl -d '{"id":3,"login":"HeeroYui","password":"bouloued","email":"yui.heero@gmail.com","emailValidate":0,"newEmail":null,"authorisationLevel":"ADMIN"}' -H "Content-Type: application/json" -X POST http://localhost:9993/api/users

View File

@ -1,573 +0,0 @@
package org.kar.karusic.api;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.WebLauncher;
import org.kar.karusic.db.DBEntry;
import org.kar.karusic.model.Data;
import org.kar.karusic.model.MediaSmall;
import org.kar.karusic.model.NodeSmall;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@Path("/video")
@Produces({MediaType.APPLICATION_JSON})
public class VideoResource {
// UPDATE `node` SET `type` = "SEASON" WHERE `type` = "SAISON"
// UPDATE `node` SET `type` = "UNIVERSE" WHERE `type` = "UNIVERS"
// UPDATE `node` SET `type` = "SERIES" WHERE `type` = "SERIE"
@GET
@RolesAllowed("USER")
public List<MediaSmall> get() {
System.out.println("VIDEO get");
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
List<MediaSmall> out = new ArrayList<>();
String query = "SELECT media.id," +
" media.name," +
" media.description," +
" media.data_id," +
" media.type_id," +
" media.universe_id," +
" media.series_id," +
" media.season_id," +
" media.episode," +
" media.date," +
" media.time," +
" media.age_limit," +
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM cover_link_media tmp" +
" WHERE tmp.deleted = false" +
" AND media.id = tmp.media_id" +
" GROUP BY tmp.media_id) AS covers" +
" FROM media" +
" WHERE media.deleted = false " +
" GROUP BY media.id" +
" ORDER BY media.name";
try {
Statement st = entry.connection.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
out.add(new MediaSmall(rs));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
entry = null;
System.out.println("retrieve " + out.size() + " VIDEO");
return out;
}
@GET
@Path("{id}")
@RolesAllowed("USER")
public MediaSmall get(@PathParam("id") Long id) {
System.out.println("VIDEO get " + id);
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "SELECT media.id," +
" media.name," +
" media.description," +
" media.data_id," +
" media.type_id," +
" media.universe_id," +
" media.series_id," +
" media.season_id," +
" media.episode," +
" media.date," +
" media.time," +
" media.age_limit," +
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM cover_link_media tmp" +
" WHERE tmp.deleted = false" +
" AND media.id = tmp.media_id" +
" GROUP BY tmp.media_id) AS covers" +
" FROM media" +
" WHERE media.deleted = false " +
" AND media.id = ? " +
" GROUP BY media.id" +
" ORDER BY media.name";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setLong(iii++, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
MediaSmall out = new MediaSmall(rs);
entry.disconnect();
entry = null;
return out;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
entry = null;
return null;
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Response put(@PathParam("id") Long id, String jsonRequest) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode root = mapper.readTree(jsonRequest);
String query = "UPDATE `media` SET `modify_date`=now(3)";
if (!root.path("name").isMissingNode()) {
query += ", `name` = ? ";
}
if (!root.path("description").isMissingNode()) {
query += ", `description` = ? ";
}
if (!root.path("episode").isMissingNode()) {
query += ", `episode` = ? ";
}
if (!root.path("time").isMissingNode()) {
query += ", `time` = ? ";
}
if (!root.path("typeId").isMissingNode()) {
query += ", `type_id` = ? ";
}
if (!root.path("universeId").isMissingNode()) {
query += ", `universe_id` = ? ";
}
if (!root.path("seriesId").isMissingNode()) {
query += ", `series_id` = ? ";
}
if (!root.path("seasonId").isMissingNode()) {
query += ", `season_id` = ? ";
}
query += " WHERE `id` = ?";
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
if (!root.path("name").isMissingNode()) {
if (root.path("name").isNull()) {
ps.setString(iii++, "???");
} else {
ps.setString(iii++, root.path("name").asText());
}
}
if (!root.path("description").isMissingNode()) {
if (root.path("description").isNull()) {
ps.setNull(iii++, Types.VARCHAR);
} else {
ps.setString(iii++, root.path("description").asText());
}
}
if (!root.path("episode").isMissingNode()) {
if (root.path("episode").isNull()) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setInt(iii++, root.path("episode").asInt());
}
}
if (!root.path("time").isMissingNode()) {
if (root.path("time").isNull()) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setInt(iii++, root.path("time").asInt());
}
}
if (!root.path("typeId").isMissingNode()) {
if (root.path("typeId").isNull()) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, root.path("typeId").asLong());
}
}
if (!root.path("universe_id").isMissingNode()) {
if (root.path("universe_id").isNull()) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, root.path("universeId").asLong());
}
}
if (!root.path("seriesId").isMissingNode()) {
if (root.path("seriesId").isNull()) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, root.path("seriesId").asLong());
}
}
if (!root.path("seasonId").isMissingNode()) {
if (root.path("seasonId").isNull()) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, root.path("seasonId").asLong());
}
}
ps.setLong(iii++, id);
System.out.println(" request : " + ps.toString());
ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
entry.disconnect();
entry = null;
return Response.notModified("SQL error").build();
}
entry.disconnect();
entry = null;
} catch (IOException e) {
e.printStackTrace();
return Response.notModified("input json error error").build();
}
return Response.ok(get(id)).build();
}
/*
public static void update_time(String table, Long id, Timestamp dateCreate, Timestamp dateModify) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "UPDATE " + table + " SET create_date = ?, modify_date = ? WHERE id = ?";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
ps.setTimestamp(1, dateCreate);
ps.setTimestamp(2, dateModify);
ps.setLong(3, id);
ps.execute();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
}
*/
private String multipartCorrection(String data) {
if (data == null) {
return null;
}
if (data.isEmpty()) {
return null;
}
if (data.contentEquals("null")) {
return null;
}
return data;
}
@POST
@Path("/upload/")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadFile(@FormDataParam("fileName") String fileName,
@FormDataParam("universe") String universe,
@FormDataParam("series") String series,
//@FormDataParam("seriesId") String seriesId, Not used ...
@FormDataParam("season") String season,
@FormDataParam("episode") String episode,
@FormDataParam("title") String title,
@FormDataParam("typeId") String typeId,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
try {
// correct input string stream :
fileName = multipartCorrection(fileName);
universe = multipartCorrection(universe);
series = multipartCorrection(series);
season = multipartCorrection(season);
episode = multipartCorrection(episode);
title = multipartCorrection(title);
typeId = multipartCorrection(typeId);
//public NodeSmall uploadFile(final FormDataMultiPart form) {
System.out.println("Upload media file: " + fileMetaData);
System.out.println(" - fileName: " + fileName);
System.out.println(" - universe: " + universe);
System.out.println(" - series: " + series);
System.out.println(" - season: " + season);
System.out.println(" - episode: " + episode);
System.out.println(" - title: " + title);
System.out.println(" - type: " + typeId);
System.out.println(" - fileInputStream: " + fileInputStream);
System.out.println(" - fileMetaData: " + fileMetaData);
System.out.flush();
if (typeId == null) {
return Response.status(406).
entity("Missong Input 'type'").
type("text/plain").
build();
}
long tmpUID = DataResource.getTmpDataId();
String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID);
Data data = DataResource.getWithSha512(sha512);
if (data == null) {
System.out.println("Need to add the data in the BDD ... ");
System.out.flush();
try {
data = DataResource.createNewData(tmpUID, fileName, sha512);
} catch (IOException ex) {
DataResource.removeTemporaryFile(tmpUID);
ex.printStackTrace();
return Response.notModified("can not create input media").build();
} catch (SQLException ex) {
ex.printStackTrace();
DataResource.removeTemporaryFile(tmpUID);
return Response.notModified("Error in SQL insertion ...").build();
}
} else if (data.deleted == true) {
System.out.println("Data already exist but deleted");
System.out.flush();
DataResource.undelete(data.id);
data.deleted = false;
} else {
System.out.println("Data already exist ... all good");
System.out.flush();
}
// Fist step: retive all the Id of each parents:...
System.out.println("Find typeNode");
// check if id of type exist:
NodeSmall typeNode = TypeResource.getWithId(Long.parseLong(typeId));
if (typeNode == null) {
DataResource.removeTemporaryFile(tmpUID);
return Response.notModified("TypeId does not exist ...").build();
}
System.out.println(" ==> " + typeNode);
System.out.println("Find universeNode");
// get id of universe:
NodeSmall universeNode = UniverseResource.getOrCreate(universe);
System.out.println(" ==> " + universeNode);
System.out.println("Find seriesNode");
// get uid of group:
NodeSmall seriesNode = SeriesResource.getOrCreate(series, typeNode.id);
System.out.println(" ==> " + seriesNode);
System.out.println("Find seasonNode");
// get uid of season:
Integer seasonId = null;
NodeSmall seasonNode = null;
try {
seasonId = Integer.parseInt(season);
seasonNode = SeasonResource.getOrCreate(Integer.parseInt(season), seriesNode.id);
} catch (java.lang.NumberFormatException ex) {
// nothing to do ....
}
System.out.println(" ==> " + seasonNode);
System.out.println("add media");
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
long uniqueSQLID = -1;
// real add in the BDD:
try {
// prepare the request:
String query = "INSERT INTO media (create_date, modify_date, name, data_id, type_id, universe_id, series_id, season_id, episode)" +
" VALUES (now(3), now(3), ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = entry.connection.prepareStatement(query,
Statement.RETURN_GENERATED_KEYS);
int iii = 1;
ps.setString(iii++, title);
ps.setLong(iii++, data.id);
ps.setLong(iii++, typeNode.id);
if (universeNode == null) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, universeNode.id);
}
if (seriesNode == null) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, seriesNode.id);
}
if (seasonNode == null) {
ps.setNull(iii++, Types.BIGINT);
} else {
ps.setLong(iii++, seasonNode.id);
}
if (episode == null || episode.contentEquals("")) {
ps.setNull(iii++, Types.INTEGER);
} else {
ps.setInt(iii++, Integer.parseInt(episode));
}
// execute the request
int affectedRows = ps.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating data failed, no rows affected.");
}
// retreive uid inserted
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
uniqueSQLID = generatedKeys.getLong(1);
} else {
throw new SQLException("Creating user failed, no ID obtained (1).");
}
} catch (Exception ex) {
System.out.println("Can not get the UID key inserted ... ");
ex.printStackTrace();
throw new SQLException("Creating user failed, no ID obtained (2).");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
// if we do not une the file .. remove it ... otherwise this is meamory leak...
DataResource.removeTemporaryFile(tmpUID);
System.out.println("uploaded .... compleate: " + uniqueSQLID);
MediaSmall creation = get(uniqueSQLID);
return Response.ok(creation).build();
} catch (Exception ex) {
System.out.println("Catch an unexpected error ... " + ex.getMessage());
ex.printStackTrace();
return Response.status(417).
entity("Back-end error : " + ex.getMessage()).
type("text/plain").
build();
}
}
@POST
@Path("{id}/add_cover")
@RolesAllowed("ADMIN")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadCover(@PathParam("id") Long id,
@FormDataParam("fileName") String fileName,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
try {
// correct input string stream :
fileName = multipartCorrection(fileName);
//public NodeSmall uploadFile(final FormDataMultiPart form) {
System.out.println("Upload media file: " + fileMetaData);
System.out.println(" - id: " + id);
System.out.println(" - fileName: " + fileName);
System.out.println(" - fileInputStream: " + fileInputStream);
System.out.println(" - fileMetaData: " + fileMetaData);
System.out.flush();
MediaSmall media = get(id);
if (media == null) {
return Response.notModified("Media Id does not exist or removed...").build();
}
long tmpUID = DataResource.getTmpDataId();
String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID);
Data data = DataResource.getWithSha512(sha512);
if (data == null) {
System.out.println("Need to add the data in the BDD ... ");
System.out.flush();
try {
data = DataResource.createNewData(tmpUID, fileName, sha512);
} catch (IOException ex) {
DataResource.removeTemporaryFile(tmpUID);
ex.printStackTrace();
return Response.notModified("can not create input media").build();
} catch (SQLException ex) {
ex.printStackTrace();
DataResource.removeTemporaryFile(tmpUID);
return Response.notModified("Error in SQL insertion ...").build();
}
} else if (data.deleted == true) {
System.out.println("Data already exist but deleted");
System.out.flush();
DataResource.undelete(data.id);
data.deleted = false;
} else {
System.out.println("Data already exist ... all good");
System.out.flush();
}
// Fist step: retrieve all the Id of each parents:...
System.out.println("Find typeNode");
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
long uniqueSQLID = -1;
// real add in the BDD:
try {
// prepare the request:
String query = "INSERT INTO cover_link_media (create_date, modify_date, media_id, data_id)" +
" VALUES (now(3), now(3), ?, ?)";
PreparedStatement ps = entry.connection.prepareStatement(query,
Statement.RETURN_GENERATED_KEYS);
int iii = 1;
ps.setLong(iii++, media.id);
ps.setLong(iii++, data.id);
// execute the request
int affectedRows = ps.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating data failed, no rows affected.");
}
// retreive uid inserted
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
uniqueSQLID = generatedKeys.getLong(1);
} else {
throw new SQLException("Creating user failed, no ID obtained (1).");
}
} catch (Exception ex) {
System.out.println("Can not get the UID key inserted ... ");
ex.printStackTrace();
throw new SQLException("Creating user failed, no ID obtained (2).");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
// if we do not une the file .. remove it ... otherwise this is meamory leak...
DataResource.removeTemporaryFile(tmpUID);
System.out.println("uploaded .... compleate: " + uniqueSQLID);
MediaSmall creation = get(id);
return Response.ok(creation).build();
} catch (Exception ex) {
System.out.println("Cat ann unexpected error ... ");
ex.printStackTrace();
}
return Response.serverError().build();
}
@GET
@Path("{id}/rm_cover/{cover_id}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") Long mediaId, @PathParam("cover_id") Long coverId) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "UPDATE `cover_link_media` SET `modify_date`=now(3), `deleted`=true WHERE `media_id` = ? AND `data_id` = ?";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setLong(iii++, mediaId);
ps.setLong(iii++, coverId);
ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
entry.disconnect();
return Response.serverError().build();
}
entry.disconnect();
return Response.ok(get(mediaId)).build();
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "UPDATE `media` SET `modify_date`=now(3), `deleted`=true WHERE `id` = ? and `deleted` = false ";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setLong(iii++, id);
ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
entry.disconnect();
return Response.serverError().build();
}
entry.disconnect();
return Response.ok().build();
}
}

View File

@ -1,70 +0,0 @@
package org.kar.karusic.model;
/*
CREATE TABLE `node` (
`id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY,
`deleted` BOOLEAN NOT NULL DEFAULT false,
`create_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been created',
`modify_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been update',
`type` enum("TYPE", "UNIVERS", "SERIE", "SAISON", "MEDIA") NOT NULL DEFAULT 'TYPE',
`name` TEXT COLLATE 'utf8_general_ci' NOT NULL,
`description` TEXT COLLATE 'utf8_general_ci',
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Album extends Playlist {
Date publication = null;
public Album() {
}
protected Album(String tableName, ResultSet rs) {
super(tableName, rs);
int iii = super.getRsCount();;
try {
this.publication = rs.getDate(iii++);
if (rs.wasNull()) {
this.publication = null;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public Album(ResultSet rs) {
this("album", rs);
}
@Override
public int getRsCount() {
return super.getRsCount() + 1;
}
@Override
public String toString() {
return "Album [id=" + id + ", name=" + name + ", description=" + description + ", covers=" + covers
+ ", tracks=" + tracks + ", publication=" + publication + "]";
}
@Override
public String getTableSqlModel() {
return super.getTableSqlModel().replaceAll("<<<TABLE_ADDITION>>>", """
`publication` timestamp(3) NULL COMMENT 'death date of the artist',
<<<TABLE_ADDITION>>>
""");
}
protected String getQueryString() {
return super.getQueryString().replaceAll("<<<ELEMENT_LIST>>>", ", <<<TABLE_NAME>>>.publication <<<ELEMENT_LIST>>>");
}
Object createObject(ResultSet rs) {
return new Album(rs);
}
}

View File

@ -1,87 +0,0 @@
package org.kar.karusic.model;
/*
CREATE TABLE `node` (
`id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY,
`deleted` BOOLEAN NOT NULL DEFAULT false,
`create_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been created',
`modify_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been update',
`type` enum("TYPE", "UNIVERS", "SERIE", "SAISON", "MEDIA") NOT NULL DEFAULT 'TYPE',
`name` TEXT COLLATE 'utf8_general_ci' NOT NULL,
`description` TEXT COLLATE 'utf8_general_ci',
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Artist extends NodeSmall {
String firstName = null;
String surname = null;
Date birth = null;
Date death = null;
public Artist() {
super("artist");
}
public Artist(String tableName, ResultSet rs) {
super("artist", rs);
int iii = super.getRsCount();;
try {
this.firstName = rs.getString(iii++);
if (rs.wasNull()) {
this.firstName = null;
}
this.surname = rs.getString(iii++);
if (rs.wasNull()) {
this.surname = null;
}
this.birth = rs.getDate(iii++);
if (rs.wasNull()) {
this.birth = null;
}
this.death = rs.getDate(iii++);
if (rs.wasNull()) {
this.death = null;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public Artist(ResultSet rs) {
this("artist", rs);
}
@Override
public int getRsCount() {
return super.getRsCount() + 4;
}
@Override
public String toString() {
return "Artist [id=" + id + ", name=" + name + ", description=" + description + ", covers=" + covers +
", firstName=" + firstName + ", surname=" + surname + ", birth=" + birth + ", death=" + death + "]";
}
@Override
public String getTableSqlModel() {
return super.getTableSqlModel().replaceAll("<<<TABLE_ADDITION>>>", """
`firstName` varchar(256) NOT NULL,
`surname` varchar(256) NOT NULL,
`birth` timestamp(3) NULL COMMENT 'birth date of the artist',
`death` timestamp(3) NULL COMMENT 'death date of the artist',
<<<TABLE_ADDITION>>>
""");
}
@Override
public String getQueryString() {
return super.getQueryString().replaceAll("<<<ELEMENT_LIST>>>", ", <<<TABLE_NAME>>>.firstName, <<<TABLE_NAME>>>.surname, <<<TABLE_NAME>>>.birth, <<<TABLE_NAME>>>.death <<<ELEMENT_LIST>>>");
}
@Override
Object createObject(ResultSet rs) {
return new Album(rs);
}
}

View File

@ -1,18 +1,15 @@
package org.kar.karusic.model;
import java.sql.Timestamp;
import java.util.Date;
import org.kar.karusic.annotation.SQLAutoIncrement;
import org.kar.karusic.annotation.SQLComment;
import org.kar.karusic.annotation.SQLCreateTime;
import org.kar.karusic.annotation.SQLDefault;
import org.kar.karusic.annotation.SQLIfNotExists;
import org.kar.karusic.annotation.SQLNotNull;
import org.kar.karusic.annotation.SQLNotRead;
import org.kar.karusic.annotation.SQLPrimaryKey;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.kar.karusic.annotation.SQLUpdateTime;
public class GenericTable {
@SQLAutoIncrement // Add AUTO_INCREMENT modifier
@ -23,7 +20,7 @@ public class GenericTable {
@SQLNotRead
@SQLNotNull
@SQLDefault("'0'")
@SQLComment("When delet initm, they are not removed, they are just set in a deleted state")
@SQLComment("When delete, they are not removed, they are just set in a deleted state")
public Boolean deleted = null;
@SQLNotRead
@SQLCreateTime
@ -31,7 +28,7 @@ public class GenericTable {
@SQLComment("Create time of the object")
public Timestamp create_date = null;
@SQLNotRead
@SQLCreateTime
@SQLUpdateTime
@SQLNotNull
@SQLComment("When update the object")
public Timestamp modify_date = null;

View File

@ -1,193 +0,0 @@
package org.kar.karusic.model;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Response;
import org.kar.karusic.WebLauncher;
import org.kar.karusic.db.DBEntry;
public class GenericTable {
protected String tableName = "plopppppp";
public Long id = null;
GenericTable(String tableName) {
this.tableName = tableName;
}
protected GenericTable(String tableName, ResultSet rs) {
this.tableName = tableName;
int iii = 1;
try {
this.id = rs.getLong(iii++);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
protected GenericTable(ResultSet rs) {
this.tableName = "genericTable";
int iii = 1;
try {
this.id = rs.getLong(iii++);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
protected List<Long> getListOfIds(ResultSet rs, int iii) throws SQLException {
String trackString = rs.getString(iii);
if (rs.wasNull()) {
return null;
}
List<Long> out = new ArrayList<>();
String[] elements = trackString.split("-");
for (String elem : elements) {
Long tmp = Long.parseLong(elem);
out.add(tmp);
}
return out;
}
public String toStringSmall() {
return "id=" + this.id;
}
public int getRsCount() {
return 1 + 1;
}
public String getQueryLinkString(String from, String to, String as) {
String out = " (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM <<<FROM>>>_link_<<<TO>>> tmp" +
" WHERE tmp.deleted = false" +
" AND <<<TABLE_NAME>>>.id = <<<FROM>>>.<<<TABLE_NAME>>>_id" +
" GROUP BY tmp.<<<TABLE_NAME>>>_id) AS <<<AS>>>";
return out.replaceAll("<<<FROM>>>", from).replaceAll("<<<TO>>>", to).replaceAll("<<<AS>>>", as);
}
public String getTableLinkSql(String from, String to) {
return """
DROP TABLE IF EXISTS `<<<FROM>>>_link_<<<TO>>>`;
CREATE TABLE `<<<FROM>>>_link_<<<TO>>>` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'table ID',
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`create_date` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`modify_date` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`<<<FROM>>>_id` bigint NOT NULL,
`<<<TO>>>_id` bigint NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
<<<TABLE_OTHER>>>
""".replaceAll("<<<FROM>>>", from).replaceAll("<<<TO>>>", to);
}
public String getTableSqlModel() {
return """
DROP TABLE IF EXISTS `<<<TABLE_NAME>>>`;
CREATE TABLE `<<<TABLE_NAME>>>` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'table ID',
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`create_date` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Time the element has been created',
`modify_date` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Time the element has been update',
<<<TABLE_ADDITION>>>
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
<<<TABLE_OTHER>>>
""";
}
public final String getTableSql() {
return getTableSqlModel().replace("<<<TABLE_NAME>>>", tableName).replaceAll("<<<.*>>>", "");
}
public Response dbDelete(Long nodeId) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "UPDATE `" + tableName + "` SET `modify_date`=now(3), `deleted`=true WHERE `id` = ?";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setLong(iii++, nodeId);
ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
entry.disconnect();
return Response.serverError().build();
}
entry.disconnect();
return Response.ok().build();
}
public GenericTable dbGetWithId(String typeInNode, long id) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "SELECT " + tableName + ".id," +
" FROM " + tableName +
" WHERE " + tableName + ".deleted = false " +
" AND " + tableName + ".id = ?" +
" ORDER BY node.name";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setString(iii++, typeInNode);
ps.setLong(iii++, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
GenericTable out = new GenericTable(this.tableName, rs);
entry.disconnect();
entry = null;
return out;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
entry = null;
return null;
}
Object createObject(ResultSet rs) {
return null;
}
protected String getQueryString() {
return "SELECT <<<TABLE_NAME>>>.id" +
" <<<ELEMENT_LIST>>>" +
" FROM <<<TABLE_NAME>>>" +
" WHERE <<<TABLE_NAME>>>.deleted = false ";
}
public List<Object> get() {
System.out.println("'" + tableName + "' get ...");
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
List<Object> out = new ArrayList<>();
String query = getQueryString();
/*"SELECT <<<TABLE_NAME>>>.id" +
" <<<ELEMENT_LIST>>>" +
" node.name," +
" node.description," +
" node.parent_id," +
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
" FROM cover_link_node tmp" +
" WHERE tmp.deleted = false" +
" AND node.id = tmp.node_id" +
" GROUP BY tmp.node_id) AS covers" +
" FROM <<<TABLE_NAME>>>" +
" WHERE <<<TABLE_NAME>>>.deleted = false ";
*/
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ResultSet rs = ps.executeQuery();
while (rs.next()) {
out.add(this.createObject(rs));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
entry.disconnect();
entry = null;
System.out.println("retrieve " + out.size() + " '" + tableName + "'");
return out;
}
}

View File

@ -1,209 +0,0 @@
package org.kar.karusic.model;
/*
CREATE TABLE `node` (
`id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY,
`deleted` BOOLEAN NOT NULL DEFAULT false,
`create_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been created',
`modify_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been update',
`type` enum("TYPE", "UNIVERS", "SERIE", "SAISON", "MEDIA") NOT NULL DEFAULT 'TYPE',
`name` TEXT COLLATE 'utf8_general_ci' NOT NULL,
`description` TEXT COLLATE 'utf8_general_ci',
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.kar.karusic.WebLauncher;
import org.kar.karusic.api.DataResource;
import org.kar.karusic.db.DBEntry;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class NodeSmall extends GenericTable {
public String name;
public String description;
public List<Long> covers = null;
protected NodeSmall(String tableName) {
super(tableName);
}
protected NodeSmall(String tableName, ResultSet rs) {
super(tableName, rs);
int iii = super.getRsCount();
try {
this.name = rs.getString(iii++);
this.description = rs.getString(iii++);
this.covers = getListOfIds(rs, iii++);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
@Override
public String toStringSmall() {
return super.toStringSmall() +
", name='" + name + '\'' +
", description='" + description + '\'' +
", covers=" + covers +
'}';
}
@Override
public int getRsCount() {
return super.getRsCount() + 3;
}
@Override
public String getTableSqlModel() {
return super.getTableSqlModel().replaceAll("<<<TABLE_ADDITION>>>", """
`name` text CHARACTER SET utf8mb3 COLLATE utf8_general_ci NOT NULL,
`description` text CHARACTER SET utf8mb3 COLLATE utf8_general_ci,
<<<TABLE_ADDITION>>>
""").replaceAll("<<<TABLE_OTHER>>>", getTableLinkSql("<<<TABLE_NAME>>>", "cover"));
}
@Override
protected String getQueryString() {
return super.getQueryString().replaceAll("<<<ELEMENT_LIST>>>", ", <<<TABLE_NAME>>>.name, <<<TABLE_NAME>>>.description, " + getQueryLinkString("<<<TABLE_NAME>>>", "cover", "covers") + " <<<ELEMENT_LIST>>>");
}
@Override
Object createObject(ResultSet rs) {
return null;//new NodeSmall(rs);
}
static private String multipartCorrection(String data) {
if (data == null) {
return null;
}
if (data.isEmpty()) {
return null;
}
if (data.contentEquals("null")) {
return null;
}
return data;
}
public Response dbUploadCover(String typeInNode,
Long nodeId,
String file_name,
InputStream fileInputStream,
FormDataContentDisposition fileMetaData
) {
try {
// correct input string stream :
file_name = multipartCorrection(file_name);
//public NodeSmall uploadFile(final FormDataMultiPart form) {
System.out.println("Upload media file: " + fileMetaData);
System.out.println(" - id: " + nodeId);
System.out.println(" - file_name: " + file_name);
System.out.println(" - fileInputStream: " + fileInputStream);
System.out.println(" - fileMetaData: " + fileMetaData);
System.out.flush();
GenericTable media = dbGetWithId(typeInNode, nodeId);
if (media == null) {
return Response.notModified("Media Id does not exist or removed...").build();
}
long tmpUID = DataResource.getTmpDataId();
String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID);
Data data = DataResource.getWithSha512(sha512);
if (data == null) {
System.out.println("Need to add the data in the BDD ... ");
System.out.flush();
try {
data = DataResource.createNewData(tmpUID, file_name, sha512);
} catch (IOException ex) {
DataResource.removeTemporaryFile(tmpUID);
ex.printStackTrace();
return Response.notModified("can not create input media").build();
} catch (SQLException ex) {
ex.printStackTrace();
DataResource.removeTemporaryFile(tmpUID);
return Response.notModified("Error in SQL insertion ...").build();
}
} else if (data.deleted == true) {
System.out.println("Data already exist but deleted");
System.out.flush();
DataResource.undelete(data.id);
data.deleted = false;
} else {
System.out.println("Data already exist ... all good");
System.out.flush();
}
// Fist step: retrieve all the Id of each parents:...
System.out.println("Find typeNode");
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
long uniqueSQLID = -1;
// real add in the BDD:
try {
// prepare the request:
String query = "INSERT INTO " + this.tableName + "_link_cover (create_date, modify_date, " + this.tableName + "_id, cover_id)" +
" VALUES (now(3), now(3), ?, ?)";
PreparedStatement ps = entry.connection.prepareStatement(query,
Statement.RETURN_GENERATED_KEYS);
int iii = 1;
ps.setLong(iii++, media.id);
ps.setLong(iii++, data.id);
// execute the request
int affectedRows = ps.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating data failed, no rows affected.");
}
// retreive uid inserted
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
uniqueSQLID = generatedKeys.getLong(1);
} else {
throw new SQLException("Creating user failed, no ID obtained (1).");
}
} catch (Exception ex) {
System.out.println("Can not get the UID key inserted ... ");
ex.printStackTrace();
throw new SQLException("Creating user failed, no ID obtained (2).");
}
} catch (SQLException ex) {
ex.printStackTrace();
entry.disconnect();
return Response.serverError().build();
}
// if we do not une the file .. remove it ... otherwise this is meamory leak...
DataResource.removeTemporaryFile(tmpUID);
System.out.println("uploaded .... compleate: " + uniqueSQLID);
return Response.ok(dbGetWithId(typeInNode, nodeId)).build();
} catch (Exception ex) {
System.out.println("Cat ann unexpected error ... ");
ex.printStackTrace();
}
return Response.serverError().build();
}
public Response dbRemoveCover(String typeInNode, Long nodeId, Long coverId) {
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
String query = "UPDATE `" + this.tableName + "_link_cover` SET `modify_date`=now(3), `deleted`=true WHERE `" + this.tableName + "_id` = ? AND `cover_id` = ?";
try {
PreparedStatement ps = entry.connection.prepareStatement(query);
int iii = 1;
ps.setLong(iii++, nodeId);
ps.setLong(iii++, coverId);
ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
entry.disconnect();
return Response.serverError().build();
}
entry.disconnect();
return Response.ok(dbGetWithId(typeInNode, nodeId)).build();
}
}

View File

@ -1,72 +0,0 @@
package org.kar.karusic.model;
/*
CREATE TABLE `node` (
`id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY,
`deleted` BOOLEAN NOT NULL DEFAULT false,
`create_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been created',
`modify_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been update',
`type` enum("TYPE", "UNIVERS", "SERIE", "SAISON", "MEDIA") NOT NULL DEFAULT 'TYPE',
`name` TEXT COLLATE 'utf8_general_ci' NOT NULL,
`description` TEXT COLLATE 'utf8_general_ci',
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Playlist extends NodeSmall {
List<Long> tracks = null;
public Playlist() {
super("playlist");
}
protected Playlist(String tableName, ResultSet rs) {
super(tableName, rs);
int iii = super.getRsCount();;
try {
String trackString = rs.getString(iii++);
if (!rs.wasNull()) {
this.tracks = new ArrayList<>();
String[] elements = trackString.split("-");
for (String elem : elements) {
Long tmp = Long.parseLong(elem);
this.tracks.add(tmp);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public Playlist(ResultSet rs) {
this("playlist", rs);
}
@Override
public int getRsCount() {
return super.getRsCount() + 1;
}
@Override
public String toString() {
return "Artist [id=" + id + ", name=" + name + ", description=" + description + ", covers=" + covers +
", tracksId=" + tracks + "]";
}
@Override
public String getTableSqlModel() {
return super.getTableSqlModel().replaceAll("<<<TABLE_OTHER>>>", getTableLinkSql("<<<TABLE_NAME>>>", "track"));
}
protected String getQueryString() {
return super.getQueryString().replaceAll("<<<ELEMENT_LIST>>>", ", " + getQueryLinkString("<<<TABLE_NAME>>>", "track", "tracks") + " <<<ELEMENT_LIST>>>");
}
Object createObject(ResultSet rs) {
return new Playlist(rs);
}
}

View File

@ -1,77 +0,0 @@
package org.kar.karusic.model;
/*
CREATE TABLE `node` (
`id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY,
`deleted` BOOLEAN NOT NULL DEFAULT false,
`create_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been created',
`modify_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been update',
`type` enum("TYPE", "UNIVERS", "SERIE", "SAISON", "MEDIA") NOT NULL DEFAULT 'TYPE',
`name` TEXT COLLATE 'utf8_general_ci' NOT NULL,
`description` TEXT COLLATE 'utf8_general_ci',
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Track extends NodeSmall {
Long genderId = null;
Long dataId = null;
List<Long> artistId = null;
public Track() {
super("track");
}
protected Track(String tableName, ResultSet rs) {
super(tableName, rs);
int iii = super.getRsCount();;
try {
this.genderId = rs.getLong(iii++);
if (rs.wasNull()) {
this.genderId = null;
}
this.dataId = rs.getLong(iii++);
if (rs.wasNull()) {
this.dataId = null;
}
this.artistId = getListOfIds(rs, iii++);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public Track(ResultSet rs) {
this("track", rs);
}
@Override
public int getRsCount() {
return super.getRsCount() + 4;
}
@Override
public String toString() {
return "Tracks [id=" + id + ", name=" + name + ", description=" + description + ", covers=" + covers +
", genderId=" + genderId + ", dataId=" + dataId + ", artistId=" + artistId + "]";
}
@Override
public String getTableSqlModel() {
return super.getTableSqlModel().replaceAll("<<<TABLE_ADDITION>>>", """
`genderId` bigint NULL,
`dataId` bigint NULL,
<<<TABLE_ADDITION>>>
""").replaceAll("<<<TABLE_OTHER>>>", getTableLinkSql("<<<TABLE_NAME>>>", "artist"));
}
protected String getQueryString() {
return super.getQueryString().replaceAll("<<<ELEMENT_LIST>>>", ", <<<TABLE_NAME>>>.genderId, <<<TABLE_NAME>>>.dataId, " + getQueryLinkString("<<<TABLE_NAME>>>", "artist", "artists") + " <<<ELEMENT_LIST>>>");
}
Object createObject(ResultSet rs) {
return new Track(rs);
}
}

View File

@ -40,6 +40,7 @@ public class User {
public Long id = null;
@SQLLimitSize(256)
public String login = null;
public Timestamp lastConnection = null;
@SQLDefault("'0'")
@SQLNotNull

View File

@ -0,0 +1,87 @@
package org.kar.karusic.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.kar.karusic.SqlWrapper;
import org.kar.karusic.api.DataResource;
import org.kar.karusic.model.Data;
public class CoverTools {
static private String multipartCorrection(String data) {
if (data == null) {
return null;
}
if (data.isEmpty()) {
return null;
}
if (data.contentEquals("null")) {
return null;
}
return data;
}
public static <T> Response uploadCover(Class<T> clazz,
Long id,
String fileName,
InputStream fileInputStream,
FormDataContentDisposition fileMetaData
) {
try {
// correct input string stream :
fileName = multipartCorrection(fileName);
//public NodeSmall uploadFile(final FormDataMultiPart form) {
System.out.println("Upload media file: " + fileMetaData);
System.out.println(" - id: " + id);
System.out.println(" - file_name: " + fileName);
System.out.println(" - fileInputStream: " + fileInputStream);
System.out.println(" - fileMetaData: " + fileMetaData);
System.out.flush();
T media = SqlWrapper.get(clazz, id);
if (media == null) {
return Response.notModified("Media Id does not exist or removed...").build();
}
long tmpUID = DataResource.getTmpDataId();
String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID);
Data data = DataResource.getWithSha512(sha512);
if (data == null) {
System.out.println("Need to add the data in the BDD ... ");
System.out.flush();
try {
data = DataResource.createNewData(tmpUID, fileName, sha512);
} catch (IOException ex) {
DataResource.removeTemporaryFile(tmpUID);
ex.printStackTrace();
return Response.notModified("can not create input media").build();
} catch (SQLException ex) {
ex.printStackTrace();
DataResource.removeTemporaryFile(tmpUID);
return Response.notModified("Error in SQL insertion ...").build();
}
} else if (data.deleted == true) {
System.out.println("Data already exist but deleted");
System.out.flush();
DataResource.undelete(data.id);
data.deleted = false;
} else {
System.out.println("Data already exist ... all good");
System.out.flush();
}
// Fist step: retrieve all the Id of each parents:...
System.out.println("Find typeNode");
SqlWrapper.addLink(clazz, id, "cover", data.id);
return Response.ok(SqlWrapper.get(clazz, id)).build();
} catch (Exception ex) {
System.out.println("Cat ann unexpected error ... ");
ex.printStackTrace();
}
return Response.serverError().build();
}
}