[DEV] basic sql auto

This commit is contained in:
Edouard DUPIN 2022-06-23 00:26:57 +02:00
parent 6d07dcf15d
commit 6e015aca72
34 changed files with 1262 additions and 755 deletions

View File

@ -0,0 +1,235 @@
package org.kar.karusic;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.sql.Date;
import org.kar.karusic.annotation.SQLAutoIncrement;
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.SQLPrimaryKey;
import org.kar.karusic.annotation.SQLTableLinkGeneric;
import org.kar.karusic.annotation.SQLTableName;
import org.kar.karusic.annotation.SQLUpdateTime;
import org.kar.karusic.annotation.SQLCreateTime;
import org.kar.karusic.annotation.SQLDefault;
public class SqlWrapper {
public SqlWrapper() {
}
public String convertTypeInSQL(Class<?> type) throws Exception {
if (type == Long.class || type == long.class ) {
return "bigint";
}
if (type == Integer.class || type == int.class ) {
return "int";
}
if (type == Boolean.class || type == boolean.class) {
return "tinyint(1)";
}
if (type == Timestamp.class) {
return "timestamp(3)";
}
if (type == Date.class) {
return "date";
}
if (type == String.class) {
return "text";
}
throw new Exception("Imcompatible type of element in object for: " + type.getCanonicalName());
}
public String createTable(Class<?> clazz) throws Exception {
String tableName = getTableName(clazz);
boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
StringBuilder out = new StringBuilder();
StringBuilder otherTable = new StringBuilder();
// Drop Table
if (createIfNotExist) {
out.append("DROP TABLE IF EXISTS `");
out.append(tableName);
out.append("`;\n");
}
// create Table:
out.append("CREATE TABLE `");
out.append(tableName);
out.append("` (");
boolean firstField = true;
System.out.println("===> TABLE `" + tableName + "`");
String primaryKeyValue = null;
for (Field elem : clazz.getFields()) {
String name = elem.getName();
Integer limitSize = getLimitSize(elem);
boolean notNull = elem.getDeclaredAnnotationsByType(SQLNotNull.class).length != 0;
boolean autoIncrement = elem.getDeclaredAnnotationsByType(SQLAutoIncrement.class).length != 0;
boolean primaryKey = elem.getDeclaredAnnotationsByType(SQLPrimaryKey.class).length != 0;
//boolean sqlNotRead = elem.getDeclaredAnnotationsByType(SQLNotRead.class).length != 0;
boolean createTime = elem.getDeclaredAnnotationsByType(SQLCreateTime.class).length != 0;
boolean updateTime = elem.getDeclaredAnnotationsByType(SQLUpdateTime.class).length != 0;
boolean linkGeneric = elem.getDeclaredAnnotationsByType(SQLTableLinkGeneric.class).length != 0;
String comment = getComment(elem);
String defaultValue = getDefault(elem);
System.out.println(" ==> elem `" + name + "` primaryKey=" + primaryKey + " linkGeneric=" + linkGeneric);
if (primaryKey) {
primaryKeyValue = name;
}
// special case with external link table:
if (linkGeneric) {
String localName = name;
if (name.endsWith("s")) {
localName = name.substring(0, name.length()-1);
}
if (createIfNotExist) {
otherTable.append("DROP TABLE IF EXISTS `");
otherTable.append(tableName);
otherTable.append("_link_");
otherTable.append(localName);
otherTable.append("`;\n");
}
otherTable.append("CREATE TABLE `");
otherTable.append(tableName);
otherTable.append("_link_");
otherTable.append(localName);
otherTable.append("`(\n");
otherTable.append("\t\t`id` bigint NOT NULL AUTO_INCREMENT,\n");
otherTable.append("\t\t`deleted` tinyint(1) NOT NULL DEFAULT '0',\n");
otherTable.append("\t\t`create_date` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),\n");
otherTable.append("\t\t`modify_date` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),\n");
otherTable.append("\t\t`");
otherTable.append(tableName);
otherTable.append("_id` bigint NOT NULL,\n");
otherTable.append("\t\t`");
otherTable.append(localName);
otherTable.append("_id` bigint NOT NULL,\n");
otherTable.append("\tPRIMARY KEY (`id`)\n");
otherTable.append("\t) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;\n\n");
} else {
if (firstField) {
out.append("\n\t\t`");
firstField = false;
} else {
out.append(",\n\t\t`");
}
out.append(name);
out.append("` ");
String typeValue = convertTypeInSQL(elem.getType());
if (typeValue.equals("text")) {
if (limitSize != null) {
out.append("varchar(");
out.append(limitSize);
out.append(")");
} else {
out.append("text CHARACTER SET utf8");
}
} else {
out.append(typeValue);
}
out.append(" ");
if (notNull) {
out.append("NOT NULL ");
if (defaultValue == null) {
if (updateTime || createTime) {
out.append("DEFAULT CURRENT_TIMESTAMP(3) ");
}
} else {
out.append("DEFAULT ");
out.append(defaultValue);
out.append(" ");
}
} else if (defaultValue == null) {
if (updateTime || createTime) {
out.append("DEFAULT CURRENT_TIMESTAMP(3) ");
} else {
out.append("DEFAULT NULL ");
}
} else {
out.append("DEFAULT ");
out.append(defaultValue);
out.append(" ");
}
if (autoIncrement) {
out.append("AUTO_INCREMENT ");
}
if (comment != null) {
out.append("COMMENT '");
out.append(comment.replaceAll("'", "\'"));
out.append("' ");
}
}
}
if (primaryKeyValue != null) {
out.append(",\n\tPRIMARY KEY (`");
out.append(primaryKeyValue);
out.append("`)");
}
out.append("\n\t) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;\n");
return out.toString() + otherTable.toString();
}
public String getTableName(final Class<?> element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(SQLTableName.class);
if (annotation.length == 0) {
return null;
}
if (annotation.length > 1) {
throw new Exception("Must not have more than 1 element @AknotDescription on " + element.getClass().getCanonicalName());
}
final String tmp = ((SQLTableName) annotation[0]).value();
if (tmp == null) {
return null;
}
return tmp;
}
public String getComment(final Field element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(SQLComment.class);
if (annotation.length == 0) {
return null;
}
if (annotation.length > 1) {
throw new Exception("Must not have more than 1 element @AknotDescription on " + element.getClass().getCanonicalName());
}
final String tmp = ((SQLComment) annotation[0]).value();
if (tmp == null) {
return null;
}
return tmp;
}
public String getDefault(final Field element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(SQLDefault.class);
if (annotation.length == 0) {
return null;
}
if (annotation.length > 1) {
throw new Exception("Must not have more than 1 element @AknotDescription on " + element.getClass().getCanonicalName());
}
final String tmp = ((SQLDefault) annotation[0]).value();
if (tmp == null) {
return null;
}
return tmp;
}
public Integer getLimitSize(final Field element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(SQLLimitSize.class);
if (annotation.length == 0) {
return null;
}
if (annotation.length > 1) {
throw new Exception("Must not have more than 1 element @AknotDescription on " + element.getClass().getCanonicalName());
}
return ((SQLLimitSize) annotation[0]).value();
}
}

View File

@ -9,6 +9,7 @@ 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.ArtistResource;
import org.kar.karusic.api.DataResource;
import org.kar.karusic.api.Front;
import org.kar.karusic.api.HealthCheck;
@ -24,6 +25,7 @@ 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;
@ -46,16 +48,29 @@ public class WebLauncher {
if (true) {
// generate the BDD:
try {
String out = "";
out += new DataSmall().getTableSql();
out += new User().getTableSql();
out += new Track().getTableSql();
out += new Artist().getTableSql();
out += new Gender().getTableSql();
out += new Playlist().getTableSql();
out += new Album().getTableSql();
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;
*/
}
ResourceConfig rc = new ResourceConfig();
@ -88,14 +103,17 @@ public class WebLauncher {
rc.registerClasses(AuthenticationFilter.class);
// add default resource:
rc.registerClasses(UserResource.class);
rc.registerClasses(SeriesResource.class);
rc.registerClasses(ArtistResource.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);
// add jackson to be discovenr when we are ins standalone server
rc.register(JacksonFeature.class);
// enable this to show low level request

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLAutoIncrement {
}

View File

@ -0,0 +1,14 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLComment {
String value();
}

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLCreateTime {
}

View File

@ -0,0 +1,14 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLDefault {
String value();
}

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLIfNotExists {
}

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLLimitSize {
int value();
}

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLNotNull {
}

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLNotRead {
}

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLPrimaryKey {
}

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLTableLinkGeneric {
}

View File

@ -0,0 +1,14 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLTableName {
String value();
}

View File

@ -0,0 +1,12 @@
package org.kar.karusic.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLUpdateTime {
}

View File

@ -2,6 +2,7 @@ package org.kar.karusic.api;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.karusic.model.Artist;
import org.kar.karusic.model.NodeSmall;
import javax.annotation.security.PermitAll;
@ -12,32 +13,28 @@ import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.List;
@Path("/season")
@Path("/artist")
@Produces({MediaType.APPLICATION_JSON})
public class SeasonResource {
private static final String typeInNode = "SEASON";
public class ArtistResource {
@GET
@Path("{id}")
@RolesAllowed("USER")
public static NodeSmall getWithId(@PathParam("id") Long id) {
return NodeInterface.getWithId(typeInNode, id);
public static Object getWithId(@PathParam("id") Long id) {
return NodeInterface.getWithId(new Artist(), id);
}
public static List<NodeSmall> getWithName(String name) {
return NodeInterface.getWithName(typeInNode, name);
}
public static NodeSmall getOrCreate(int season, Long seriesId) {
return NodeInterface.getOrCreate(typeInNode, Integer.toString(season), seriesId);
public static Object getOrCreate(int season, Long seriesId) {
//return NodeInterface.getOrCreate(Integer.toString(season), seriesId);
return null;
}
@GET
@RolesAllowed("USER")
public List<NodeSmall> get() {
return NodeInterface.get(typeInNode);
public List<Object> get() {
return NodeInterface.get(new Artist());
}
/*
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@ -70,4 +67,5 @@ public class SeasonResource {
public Response removeCover(@PathParam("id") Long nodeId, @PathParam("cover_id") Long coverId) {
return NodeInterface.removeCover(typeInNode, nodeId, coverId);
}
*/
}

View File

@ -5,7 +5,9 @@ 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;
@ -77,6 +79,19 @@ public class NodeInterface {
*/
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," +
@ -301,6 +316,6 @@ public class NodeInterface {
}
return Response.ok(getWithId(typeInNode, id)).build();
}
*/
}

View File

@ -1,69 +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("/type")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class TypeResource {
private static final String typeInNode = "TYPE";
@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);
}
@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("file_name") String file_name,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileMetaData
) {
return NodeInterface.uploadCover(typeInNode, id, file_name, 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

@ -11,60 +11,17 @@ CREATE TABLE `node` (
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import org.kar.karusic.annotation.SQLIfNotExists;
import org.kar.karusic.annotation.SQLTableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@SQLTableName ("album")
@SQLIfNotExists
@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);
}
public Date publication = null;
}

View File

@ -0,0 +1,70 @@
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

@ -12,74 +12,30 @@ CREATE TABLE `node` (
) AUTO_INCREMENT=10;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import org.kar.karusic.annotation.SQLIfNotExists;
import org.kar.karusic.annotation.SQLLimitSize;
import org.kar.karusic.annotation.SQLTableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.sql.Date;
@SQLTableName ("artist")
@SQLIfNotExists
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Artist extends NodeSmall {
String firstName = null;
String surname = null;
Date birth = null;
Date death = null;
@SQLLimitSize(256)
public String firstName = null;
@SQLLimitSize(256)
public String surname = null;
public Date birth = null;
public 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>>>
""");
}
protected String getQueryString() {
return super.getQueryString().replaceAll("<<<ELEMENT_LIST>>>", ", <<<TABLE_NAME>>>.firstName, <<<TABLE_NAME>>>.surname, <<<TABLE_NAME>>>.birth, <<<TABLE_NAME>>>.death <<<ELEMENT_LIST>>>");
}
Object createObject(ResultSet rs) {
return new Album(rs);
}
}

View File

@ -0,0 +1,87 @@
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

@ -14,30 +14,14 @@ CREATE TABLE `node` (
import java.sql.ResultSet;
import org.kar.karusic.annotation.SQLIfNotExists;
import org.kar.karusic.annotation.SQLTableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@SQLTableName ("gender")
@SQLIfNotExists
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Gender extends NodeSmall {
public Gender() {
super("gender");
}
protected Gender(String tableName, ResultSet rs) {
super(tableName, rs);
}
public Gender(ResultSet rs) {
this("gender", rs);
// nothing to do...
}
@Override
public int getRsCount() {
return super.getRsCount() + 0;
}
@Override
public String toString() {
return "Gender [id=" + id + ", name=" + name + ", description=" + description + ", covers=" + covers + "]";
}
}

View File

@ -1,191 +1,38 @@
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 java.sql.Timestamp;
import java.util.Date;
import javax.ws.rs.core.Response;
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 org.kar.karusic.WebLauncher;
import org.kar.karusic.db.DBEntry;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class GenericTable {
protected String tableName = "plopppppp";
@SQLAutoIncrement // Add AUTO_INCREMENT modifier
@SQLPrimaryKey // Create a PRIMARY KEY based on this field
@SQLNotNull
@SQLComment("Primary key of the base")
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;
}
@SQLNotRead
@SQLNotNull
@SQLDefault("'0'")
@SQLComment("When delet initm, they are not removed, they are just set in a deleted state")
public Boolean deleted = null;
@SQLNotRead
@SQLCreateTime
@SQLNotNull
@SQLComment("Create time of the object")
public Timestamp create_date = null;
@SQLNotRead
@SQLCreateTime
@SQLNotNull
@SQLComment("When update the object")
public Timestamp modify_date = null;
}

View File

@ -0,0 +1,193 @@
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

@ -12,196 +12,17 @@ CREATE TABLE `node` (
) 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 org.kar.karusic.annotation.SQLLimitSize;
import org.kar.karusic.annotation.SQLTableLinkGeneric;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class NodeSmall extends GenericTable {
public String name;
public String description;
@SQLLimitSize(256)
public String name = null;
public String description = null;
@SQLTableLinkGeneric
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"));
}
protected String getQueryString() {
return super.getQueryString().replaceAll("<<<ELEMENT_LIST>>>", ", <<<TABLE_NAME>>>.name, <<<TABLE_NAME>>>.description, " + getQueryLinkString("<<<TABLE_NAME>>>", "cover", "covers") + " <<<ELEMENT_LIST>>>");
}
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

@ -0,0 +1,209 @@
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

@ -12,61 +12,18 @@ CREATE TABLE `node` (
) AUTO_INCREMENT=10;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.kar.karusic.annotation.SQLIfNotExists;
import org.kar.karusic.annotation.SQLTableLinkGeneric;
import org.kar.karusic.annotation.SQLTableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@SQLTableName ("playlist")
@SQLIfNotExists
@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);
}
@SQLTableLinkGeneric
public List<Long> tracks = null;
}

View File

@ -0,0 +1,72 @@
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

@ -16,62 +16,19 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.kar.karusic.annotation.SQLIfNotExists;
import org.kar.karusic.annotation.SQLTableLinkGeneric;
import org.kar.karusic.annotation.SQLTableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@SQLTableName ("track")
@SQLIfNotExists
@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);
}
public Long genderId = null;
public Long dataId = null;
@SQLTableLinkGeneric
public List<Long> artists = null;
}

View File

@ -0,0 +1,77 @@
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

@ -18,64 +18,37 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import org.kar.karusic.annotation.SQLAutoIncrement;
import org.kar.karusic.annotation.SQLComment;
import org.kar.karusic.annotation.SQLDefault;
import org.kar.karusic.annotation.SQLIfNotExists;
import org.kar.karusic.annotation.SQLLimitSize;
import org.kar.karusic.annotation.SQLNotNull;
import org.kar.karusic.annotation.SQLPrimaryKey;
import org.kar.karusic.annotation.SQLTableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@SQLTableName ("user")
@SQLIfNotExists
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class User {
public Long id;
public String login;
public Timestamp lastConnection;
public boolean admin;
public boolean blocked;
public boolean removed;
@SQLAutoIncrement // Add AUTO_INCREMENT modifier
@SQLPrimaryKey // Create a PRIMARY KEY based on this field
@SQLNotNull
@SQLComment("Primary key of the base")
public Long id = null;
@SQLLimitSize(256)
public String login = null;
public Timestamp lastConnection = null;
@SQLDefault("'0'")
@SQLNotNull
public boolean admin = false;
@SQLDefault("'0'")
@SQLNotNull
public boolean blocked = false;
@SQLDefault("'0'")
@SQLNotNull
public boolean removed = false;
public User() {
}
public User(Long id, String login, Timestamp lastConnection, String email, boolean admin, boolean blocked, boolean removed, Long avatar) {
this.id = id;
this.login = login;
this.lastConnection = lastConnection;
this.admin = admin;
this.blocked = blocked;
this.removed = removed;
}
public User(ResultSet rs) {
int iii = 1;
try {
this.id = rs.getLong(iii++);
this.lastConnection = rs.getTimestamp(iii++);
this.login = rs.getString(iii++);
this.admin = "TRUE".equals(rs.getString(iii++));
this.blocked = "TRUE".equals(rs.getString(iii++));
this.removed = "TRUE".equals(rs.getString(iii++));
} catch (SQLException ex) {
ex.printStackTrace();
}
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", lastConnection='" + lastConnection + '\'' +
", admin=" + admin +
", blocked=" + blocked +
", removed=" + removed +
'}';
}
public String getTableSql() {
return """
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'table ID',
`lastConnection` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'last connection time',
`login` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8_general_ci NOT NULL COMMENT 'login of the user',
`admin` enum('TRUE','FALSE') NOT NULL DEFAULT 'FALSE',
`blocked` enum('TRUE','FALSE') NOT NULL DEFAULT 'FALSE',
`removed` enum('TRUE','FALSE') NOT NULL DEFAULT 'FALSE',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
""";
}
}