[DEV] add simple test and update archidata refacto

This commit is contained in:
Edouard DUPIN 2023-11-11 10:50:11 +01:00
parent 9c8def3341
commit 2e24175899
26 changed files with 545 additions and 363 deletions

7
back/.checkstyle Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<fileset-config file-format-version="1.2.0" simple-config="true" sync-formatter="false">
<fileset name="all" enabled="true" check-config-name="Google Checks" local="false">
<file-match-pattern match-pattern="." include-pattern="true"/>
</fileset>
</fileset-config>

View File

@ -5,11 +5,11 @@ COPY src /tmp/src/
WORKDIR /tmp/
RUN mvn clean compile assembly:single
FROM bellsoft/liberica-openjdk-alpine:latest
ENV LANG=C.UTF-8
# add wget to manage the health check...
RUN apk add --no-cache wget
RUN mkdir /application/
COPY --from=build /tmp/out/maven/*.jar /application/application.jar

View File

@ -2,10 +2,18 @@ Generic backend for karideo in java
===================================
mvn install
mvn compile
mvn package
// download all dependency in out/maven/dependency
mvn dependency:copy-dependencies
java -cp out/maven/kar-karideo-0.1.0.jar org.kar.karideo.WebLauncher
// create a single package jar
mvn clean compile assembly:single

View File

@ -1,61 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_14">
<output url="file://$MODULE_DIR$/out/maven/classes" />
<output-test url="file://$MODULE_DIR$/out/maven/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test/src" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/out/maven" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-multipart:2.32" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-common:2.32" level="project" />
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:1.3.5" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2:osgi-resource-locator:1.0.3" level="project" />
<orderEntry type="library" name="Maven: com.sun.activation:jakarta.activation:1.2.2" level="project" />
<orderEntry type="library" name="Maven: org.jvnet.mimepull:mimepull:1.9.13" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.inject:jersey-hk2:2.32" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-locator:2.6.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2.external:aopalliance-repackaged:2.6.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-api:2.6.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2:hk2-utils:2.6.1" level="project" />
<orderEntry type="library" name="Maven: org.javassist:javassist:3.25.0-GA" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.32" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.hk2.external:jakarta.inject:2.6.1" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-http-server:2.4.4" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-http:2.4.4" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.grizzly:grizzly-framework:2.4.4" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-server:2.32" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.core:jersey-client:2.32" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-jaxb:2.32" level="project" />
<orderEntry type="library" name="Maven: jakarta.validation:jakarta.validation-api:2.0.2" level="project" />
<orderEntry type="library" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:2.3.3" level="project" />
<orderEntry type="library" name="Maven: jakarta.ws.rs:jakarta.ws.rs-api:2.1.6" level="project" />
<orderEntry type="library" name="Maven: javax.xml.bind:jaxb-api:2.3.1" level="project" />
<orderEntry type="library" name="Maven: javax.activation:javax.activation-api:1.2.0" level="project" />
<orderEntry type="library" name="Maven: javax.ws.rs:javax.ws.rs-api:2.1.1" level="project" />
<orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-impl:2.3.1" level="project" />
<orderEntry type="library" name="Maven: com.sun.istack:istack-commons-runtime:3.0.7" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-grizzly2:2.32" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: jakarta.servlet:jakarta.servlet-api:4.0.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.glassfish.jersey.test-framework:jersey-test-framework-core:2.32" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.glassfish.jersey.containers:jersey-container-servlet-core:2.32" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.glassfish.jersey.containers:jersey-container-grizzly2-servlet:2.32" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.glassfish.jersey.containers:jersey-container-servlet:2.32" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.glassfish.grizzly:grizzly-http-servlet:2.4.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.45" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.media:jersey-media-json-jackson:2.32" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jersey.ext:jersey-entity-filtering:2.32" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.10.1" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-jaxb-annotations:2.10.1" level="project" />
<orderEntry type="library" name="Maven: jakarta.activation:jakarta.activation-api:1.2.1" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.8.10" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.8.10" level="project" />
<orderEntry type="library" name="Maven: javax.servlet:javax.servlet-api:3.0.1" level="project" />
<orderEntry type="library" name="Maven: org.jetbrains:annotations:20.1.0" level="project" />
</component>
</module>

View File

@ -1,12 +0,0 @@
/** Basic module interface.
*
* @author Edouard DUPIN */
open module io.scenarium.store {
exports io.scenarium.oauth;
requires java.util;
requires javax.ws.rs.api;
requires java.xml.bind;
requires jackson.annotations;
requires jersey.server;
}

View File

@ -1,8 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>kar</groupId>
<artifactId>karideo</artifactId>
<version>0.2.0</version>
<modelVersion>4.0.0</modelVersion>
<groupId>org.kar</groupId>
<artifactId>karideo</artifactId>
<version>0.2.0</version>
<properties>
<maven.compiler.version>3.1</maven.compiler.version>
<maven.compiler.source>17</maven.compiler.source>
@ -15,7 +16,6 @@
<url>https://gitea.atria-soft.org/api/packages/kangaroo-and-rabbit/maven</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>kangaroo-and-rabbit</groupId>
@ -26,20 +26,39 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.7</version>
<!--<scope>test</scope>-->
</dependency>
</dependencies>
<!--
************************************************************
** TEST dependency **
************************************************************
-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test/src</testSourceDirectory>
<directory>${project.basedir}/out/maven/</directory>
<directory>${project.basedir}/out/maven/</directory>
<resources>
<resource>
<directory>src/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${basedir}/test/resources</directory>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -48,16 +67,15 @@
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<!--<encoding>${project.build.sourceEncoding}</encoding>-->
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<mainClass>org.kar.karideo.WebLauncher</mainClass>
</configuration>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<mainClass>org.kar.karideo.WebLauncher</mainClass>
</configuration>
</plugin>
<!-- Create the source bundle -->
<plugin>
@ -79,27 +97,28 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<!-- Create coverage -->
<!--
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.5</version>
<version>0.8.10</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
@ -111,6 +130,26 @@
<goal>report</goal>
</goals>
</execution>
<execution>
<id>jacoco-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>PACKAGE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.50</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
-->
@ -124,6 +163,23 @@
<nohelp>true</nohelp>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>exec-application</id>
<phase>package</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>org.kar.karideo.WebLauncher</mainClass>
</configuration>
</plugin>
<!-- Check the style of the code -->
<!--
<plugin>
@ -181,5 +237,4 @@
</plugin>
</plugins>
</reporting>
</project>

View File

@ -40,6 +40,7 @@ public class WebLauncher {
final static Logger LOGGER = LoggerFactory.getLogger(WebLauncher.class);
public static DBConfig dbConfig;
protected UpdateJwtPublicKey keyUpdater = null;
protected HttpServer server = null;
public WebLauncher() {
ConfigBaseVariable.bdDatabase = "karideo";
@ -51,7 +52,7 @@ public class WebLauncher {
public void migrateDB() throws Exception {
WebLauncher.LOGGER.info("Create migration engine");
MigrationEngine migrationEngine = new MigrationEngine();
final MigrationEngine migrationEngine = new MigrationEngine();
WebLauncher.LOGGER.info("Add initialization");
migrationEngine.setInit(new Initialization());
WebLauncher.LOGGER.info("Add migration since last version");
@ -62,9 +63,9 @@ public class WebLauncher {
WebLauncher.LOGGER.info("Migrate the DB [STOP]");
}
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
WebLauncher.LOGGER.info("[START] application wake UP");
WebLauncher launcher = new WebLauncher();
final WebLauncher launcher = new WebLauncher();
launcher.migrateDB();
launcher.process();
WebLauncher.LOGGER.info("end-configure the server & wait finish process:");
@ -79,7 +80,7 @@ public class WebLauncher {
// ===================================================================
// Configure resources
// ===================================================================
ResourceConfig rc = new ResourceConfig();
final ResourceConfig rc = new ResourceConfig();
// add multi-part models ..
rc.register(MultiPartFeature.class);
@ -111,12 +112,13 @@ public class WebLauncher {
// enable this to show low level request
//rc.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName());
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
this.server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
final HttpServer serverLink = this.server;
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Stopping server..");
server.shutdownNow();
serverLink.shutdownNow();
}
}, "shutdownHook"));
@ -124,25 +126,32 @@ public class WebLauncher {
// start periodic update of the token ...
// ===================================================================
this.keyUpdater = new UpdateJwtPublicKey();
keyUpdater.start();
this.keyUpdater.start();
// ===================================================================
// run JERSEY
// ===================================================================
try {
server.start();
this.server.start();
LOGGER.info("Jersey app started at {}", getBaseURI());
} catch (Exception e) {
} catch (final Exception e) {
LOGGER.error("There was an error while starting Grizzly HTTP server.");
e.printStackTrace();
}
}
public void stop() {
if (this.server != null) {
this.server.shutdownNow();
this.server = null;
}
}
public void stopOther() {
keyUpdater.kill();
this.keyUpdater.kill();
try {
keyUpdater.join(4000, 0);
} catch (InterruptedException e) {
this.keyUpdater.join(4000, 0);
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

View File

@ -1,32 +1,32 @@
package org.kar.karideo.api;
import org.kar.archidata.annotation.security.PermitAll;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.kar.archidata.exception.FailException;
import org.kar.archidata.util.ConfigBaseVariable;
import org.kar.archidata.util.JWTWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.PermitAll;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/health_check")
@Produces(MediaType.APPLICATION_JSON)
public class HealthCheck {
static final Logger LOGGER = LoggerFactory.getLogger(HealthCheck.class);
public class HealthResult {
public String value;
public HealthResult(String value) {
this.value = value;
public record HealthResult(
String value) {};
@GET
@PermitAll
public HealthResult getHealth() throws FailException {
if (JWTWrapper.getPublicKeyJson() == null && !ConfigBaseVariable.getTestMode()) {
throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Missing Jwt public token");
}
return new HealthResult("alive and kicking");
}
// todo : do it better...
@GET
@PermitAll
public Response getHealth() {
if (JWTWrapper.getPublicKeyJson() == null) {
return Response.status(500).entity(new HealthResult("Missing Jwt public token")).build();
}
return Response.status(200).entity(new HealthResult("alive and kicking")).build();
}
}

View File

@ -5,16 +5,16 @@ import java.util.List;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.security.RolesAllowed;
import org.kar.archidata.sqlWrapper.QuerryAnd;
import org.kar.archidata.sqlWrapper.QuerryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryAnd;
import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.util.DataTools;
import org.kar.karideo.model.Season;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
@ -34,22 +34,22 @@ public class SeasonResource {
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Season getWithId(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Season.class, id);
public static Season getWithId(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Season.class, id);
}
@GET
@RolesAllowed("USER")
public List<Season> get() throws Exception {
return SqlWrapper.gets(Season.class);
return DataAccess.gets(Season.class);
}
@GET
@Path("{id}")
@RolesAllowed("USER")
@Consumes(MediaType.APPLICATION_JSON)
public Season get(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Season.class, id);
public Season get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Season.class, id);
}
/* =============================================================================
@ -59,24 +59,24 @@ public class SeasonResource {
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Season put(String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Season.class, jsonRequest);
public Season put(final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Season.class, jsonRequest);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Season put(@PathParam("id") Long id, String jsonRequest) throws Exception {
SqlWrapper.update(Season.class, id, jsonRequest);
return SqlWrapper.get(Season.class, id);
public Season put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
DataAccess.updateWithJson(Season.class, id, jsonRequest);
return DataAccess.get(Season.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.delete(Season.class, id);
public Response delete(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Season.class, id);
return Response.ok().build();
}
@ -84,30 +84,30 @@ public class SeasonResource {
@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) {
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Season.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 {
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Season.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Season.class, id)).build();
return Response.ok(DataAccess.get(Season.class, id)).build();
}
public static Season getOrCreate(String name, Long seriesId) {
public static Season getOrCreate(final String name, final Long seriesId) {
try {
Season out = SqlWrapper.getWhere(Season.class, new QuerryAnd(new QuerryCondition("name", "=", name), new QuerryCondition("parentId", "=", seriesId)));
Season out = DataAccess.getWhere(Season.class, new QueryAnd(new QueryCondition("name", "=", name), new QueryCondition("parentId", "=", seriesId)));
if (out == null) {
out = new Season();
out.name = name;
out.parentId = seriesId;
out = SqlWrapper.insert(out);
out = DataAccess.insert(out);
}
return out;
} catch (Exception e) {
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

View File

@ -5,16 +5,16 @@ import java.util.List;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.security.RolesAllowed;
import org.kar.archidata.sqlWrapper.QuerryAnd;
import org.kar.archidata.sqlWrapper.QuerryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryAnd;
import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.util.DataTools;
import org.kar.karideo.model.Series;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
@ -30,88 +30,88 @@ import jakarta.ws.rs.core.Response;
@Produces({ MediaType.APPLICATION_JSON })
public class SeriesResource {
static final Logger LOGGER = LoggerFactory.getLogger(SeriesResource.class);
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Series getWithId(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Series.class, id);
public static Series getWithId(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Series.class, id);
}
@GET
@RolesAllowed("USER")
public List<Series> get() throws Exception {
return SqlWrapper.gets(Series.class);
return DataAccess.gets(Series.class);
}
@GET
@Path("{id}")
@RolesAllowed("USER")
@Consumes(MediaType.APPLICATION_JSON)
public Series get(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Series.class, id);
public Series get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Series.class, id);
}
/* =============================================================================
* ADMIN SECTION:
* ============================================================================= */
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Series put(String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Series.class, jsonRequest);
public Series put(final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Series.class, jsonRequest);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Series put(@PathParam("id") Long id, String jsonRequest) throws Exception {
SqlWrapper.update(Series.class, id, jsonRequest);
return SqlWrapper.get(Series.class, id);
public Series put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
DataAccess.updateWithJson(Series.class, id, jsonRequest);
return DataAccess.get(Series.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.delete(Series.class, id);
public Response delete(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Series.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) {
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Series.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 {
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Series.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Series.class, id)).build();
return Response.ok(DataAccess.get(Series.class, id)).build();
}
public static Series getOrCreate(String name, Long typeId) {
public static Series getOrCreate(final String name, final Long typeId) {
try {
Series out = SqlWrapper.getWhere(Series.class, new QuerryAnd(new QuerryCondition("name", "=", name), new QuerryCondition("parentId", "=", typeId)));
Series out = DataAccess.getWhere(Series.class, new QueryAnd(new QueryCondition("name", "=", name), new QueryCondition("parentId", "=", typeId)));
if (out == null) {
out = new Series();
out.name = name;
out.parentId = typeId;
out = SqlWrapper.insert(out);
out = DataAccess.insert(out);
}
return out;
} catch (Exception e) {
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

View File

@ -5,15 +5,15 @@ import java.util.List;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.security.RolesAllowed;
import org.kar.archidata.sqlWrapper.QuerryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.util.DataTools;
import org.kar.karideo.model.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
@ -29,91 +29,91 @@ import jakarta.ws.rs.core.Response;
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class TypeResource {
static final Logger LOGGER = LoggerFactory.getLogger(TypeResource.class);
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Type getWithId(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Type.class, id);
public static Type getWithId(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Type.class, id);
}
@GET
@RolesAllowed("USER")
public List<Type> get() throws Exception {
return SqlWrapper.gets(Type.class);
return DataAccess.gets(Type.class);
}
@GET
@Path("{id}")
@RolesAllowed("USER")
@Consumes(MediaType.APPLICATION_JSON)
public Type get(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Type.class, id);
public Type get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Type.class, id);
}
public static Type getId(Long id) throws Exception {
return SqlWrapper.get(Type.class, id);
public static Type getId(final Long id) throws Exception {
return DataAccess.get(Type.class, id);
}
/* =============================================================================
* ADMIN SECTION:
* ============================================================================= */
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Type put(String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Type.class, jsonRequest);
public Type put(final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Type.class, jsonRequest);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Type put(@PathParam("id") Long id, String jsonRequest) throws Exception {
SqlWrapper.update(Type.class, id, jsonRequest);
return SqlWrapper.get(Type.class, id);
public Type put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
DataAccess.updateWithJson(Type.class, id, jsonRequest);
return DataAccess.get(Type.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.delete(Type.class, id);
public Response delete(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Type.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) {
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Type.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 {
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Type.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Type.class, id)).build();
return Response.ok(DataAccess.get(Type.class, id)).build();
}
public static Type getOrCreate(String name) {
public static Type getOrCreate(final String name) {
try {
Type out = SqlWrapper.getWhere(Type.class, new QuerryCondition("name", "=", name));
Type out = DataAccess.getWhere(Type.class, new QueryCondition("name", "=", name));
if (out == null) {
out = new Type();
out.name = name;
out = SqlWrapper.insert(out);
out = DataAccess.insert(out);
}
return out;
} catch (Exception e) {
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

View File

@ -2,15 +2,15 @@ package org.kar.karideo.api;
import java.util.List;
import org.kar.archidata.annotation.security.RolesAllowed;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryAnd;
import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.filter.GenericContext;
import org.kar.archidata.sqlWrapper.QuerryAnd;
import org.kar.archidata.sqlWrapper.QuerryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.karideo.model.UserMediaAdvancement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
@ -31,16 +31,16 @@ public class UserMediaAdvancementResource {
@GET
@Path("{id}")
@RolesAllowed("USER")
public UserMediaAdvancement getWithId(@Context SecurityContext sc, @PathParam("id") Long id) throws Exception {
GenericContext gc = (GenericContext) sc.getUserPrincipal();
return SqlWrapper.getWhere(UserMediaAdvancement.class, new QuerryAnd(new QuerryCondition("mediaId", "=", id), new QuerryCondition("userId", "=", gc.userByToken.id)));
public UserMediaAdvancement getWithId(@Context final SecurityContext sc, @PathParam("id") final Long id) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
return DataAccess.getWhere(UserMediaAdvancement.class, new QueryAnd(new QueryCondition("mediaId", "=", id), new QueryCondition("userId", "=", gc.userByToken.id)));
}
@GET
@RolesAllowed("USER")
public List<UserMediaAdvancement> gets(@Context SecurityContext sc) throws Exception {
GenericContext gc = (GenericContext) sc.getUserPrincipal();
return SqlWrapper.getsWhere(UserMediaAdvancement.class, new QuerryCondition("userId", "=", gc.userByToken.id));
public List<UserMediaAdvancement> gets(@Context final SecurityContext sc) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
return DataAccess.getsWhere(UserMediaAdvancement.class, new QueryCondition("userId", "=", gc.userByToken.id));
}
/* =============================================================================
@ -56,15 +56,15 @@ public class UserMediaAdvancementResource {
//@Path("{id}")
//@RolesAllowed("USER")
//@Consumes(MediaType.APPLICATION_JSON)
public UserMediaAdvancement post(@Context SecurityContext sc, @PathParam("id") Long id, MediaInformations data) throws Exception {
GenericContext gc = (GenericContext) sc.getUserPrincipal();
UserMediaAdvancement elem = new UserMediaAdvancement();
public UserMediaAdvancement post(@Context final SecurityContext sc, @PathParam("id") final Long id, final MediaInformations data) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
final UserMediaAdvancement elem = new UserMediaAdvancement();
elem.userId = gc.userByToken.id;
elem.mediaId = id;
elem.time = data.time;
elem.percent = data.percent;
elem.count = data.count;
return SqlWrapper.insert(elem);
return DataAccess.insert(elem);
}
public record MediaInformationsDelta(
@ -76,14 +76,14 @@ public class UserMediaAdvancementResource {
@Path("{id}")
@RolesAllowed("USER")
@Consumes(MediaType.APPLICATION_JSON)
public UserMediaAdvancement put(@Context SecurityContext sc, @PathParam("id") Long id, MediaInformationsDelta data) throws Exception {
UserMediaAdvancement elem = this.getWithId(sc, id);
public UserMediaAdvancement put(@Context final SecurityContext sc, @PathParam("id") final Long id, final MediaInformationsDelta data) throws Exception {
final UserMediaAdvancement elem = getWithId(sc, id);
if (elem == null) {
// insert element
if (data.addCount) {
return this.post(sc, id, new MediaInformations(data.time(), data.percent(), 1));
return post(sc, id, new MediaInformations(data.time(), data.percent(), 1));
} else {
return this.post(sc, id, new MediaInformations(data.time(), data.percent(), 0));
return post(sc, id, new MediaInformations(data.time(), data.percent(), 0));
}
}
elem.time = data.time;
@ -92,18 +92,18 @@ public class UserMediaAdvancementResource {
elem.count++;
}
LOGGER.info("{},{},{}", elem.time, elem.percent, elem.count);
int nbAfected = SqlWrapper.update(elem, elem.id, List.of("time", "percent", "count"));
// TODO: manage the fact that no element has been updated ...
UserMediaAdvancement ret = SqlWrapper.get(UserMediaAdvancement.class, elem.id);
final int nbAfected = DataAccess.update(elem, elem.id, List.of("time", "percent", "count"));
// TODO: manage the fact that no element has been updated ...
final UserMediaAdvancement ret = DataAccess.get(UserMediaAdvancement.class, elem.id);
return ret;
}
@DELETE
@Path("{id}")
@RolesAllowed("USER")
public Response delete(@Context SecurityContext sc, @PathParam("id") Long id) throws Exception {
UserMediaAdvancement elem = this.getWithId(sc, id);
SqlWrapper.delete(UserMediaAdvancement.class, elem.id);
public Response delete(@Context final SecurityContext sc, @PathParam("id") final Long id) throws Exception {
final UserMediaAdvancement elem = getWithId(sc, id);
DataAccess.delete(UserMediaAdvancement.class, elem.id);
return Response.ok().build();
}

View File

@ -2,15 +2,15 @@ package org.kar.karideo.api;
import java.util.List;
import org.kar.archidata.annotation.security.RolesAllowed;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.filter.GenericContext;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.karideo.model.UserKarideo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
@ -23,63 +23,62 @@ import jakarta.ws.rs.core.SecurityContext;
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class UserResource {
static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class);
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserOut {
public long id;
public String login;
public UserOut(long id, String login) {
super();
public UserOut(final long id, final String login) {
this.id = id;
this.login = login;
}
}
public UserResource() {}
// curl http://localhost:9993/api/users
@GET
@RolesAllowed("ADMIN")
public List<UserKarideo> getUsers() {
System.out.println("getUsers");
try {
return SqlWrapper.gets(UserKarideo.class);
} catch (Exception e) {
return DataAccess.gets(UserKarideo.class);
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// curl http://localhost:9993/api/users/3
@GET
@Path("{id}")
@RolesAllowed("ADMIN")
public UserKarideo getUsers(@Context SecurityContext sc, @PathParam("id") long userId) {
public UserKarideo getUsers(@Context final SecurityContext sc, @PathParam("id") final long userId) {
System.out.println("getUser " + userId);
GenericContext gc = (GenericContext) sc.getUserPrincipal();
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
System.out.println("===================================================");
System.out.println("== USER ? " + gc.userByToken.name);
System.out.println("===================================================");
try {
return SqlWrapper.get(UserKarideo.class, userId);
} catch (Exception e) {
return DataAccess.get(UserKarideo.class, userId);
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@GET
@Path("me")
@RolesAllowed("USER")
public UserOut getMe(@Context SecurityContext sc) {
public UserOut getMe(@Context final SecurityContext sc) {
LOGGER.debug("getMe()");
GenericContext gc = (GenericContext) sc.getUserPrincipal();
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
LOGGER.debug("== USER ? {}", gc.userByToken);
return new UserOut(gc.userByToken.id, gc.userByToken.name);
}
}

View File

@ -7,13 +7,12 @@ import java.util.List;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.security.RolesAllowed;
import org.kar.archidata.api.DataResource;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.exception.FailException;
import org.kar.archidata.exception.InputException;
import org.kar.archidata.model.Data;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany;
import org.kar.archidata.util.DataTools;
import org.kar.karideo.model.Media;
import org.kar.karideo.model.Season;
@ -22,6 +21,7 @@ import org.kar.karideo.model.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
@ -41,27 +41,27 @@ public class VideoResource {
@GET
@RolesAllowed("USER")
public List<Media> get() throws Exception {
return SqlWrapper.gets(Media.class);
return DataAccess.gets(Media.class);
}
@GET
@Path("{id}")
@RolesAllowed("USER")
public Media get(@PathParam("id") Long id) throws Exception {
return SqlWrapper.get(Media.class, id);
public Media get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Media.class, id);
}
@PUT
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Media put(@PathParam("id") Long id, String jsonRequest) throws Exception {
public Media put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
System.out.println("update video " + id + " ==> '" + jsonRequest + "'");
SqlWrapper.update(Media.class, id, jsonRequest);
return SqlWrapper.get(Media.class, id);
DataAccess.updateWithJson(Media.class, id, jsonRequest);
return DataAccess.get(Media.class, id);
}
private String multipartCorrection(String data) {
private String multipartCorrection(final String data) {
if (data == null) {
return null;
}
@ -81,7 +81,7 @@ public class VideoResource {
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) throws FailException {
@FormDataParam("file") final InputStream fileInputStream, @FormDataParam("file") final FormDataContentDisposition fileMetaData) throws FailException {
try {
// correct input string stream :
fileName = multipartCorrection(fileName);
@ -108,20 +108,20 @@ public class VideoResource {
throw new InputException("typeId", "TypiId is not specified");
}
long tmpUID = DataResource.getTmpDataId();
String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID);
final long tmpUID = DataResource.getTmpDataId();
final 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) {
} catch (final IOException ex) {
DataResource.removeTemporaryFile(tmpUID);
ex.printStackTrace();
throw new FailException("can not create input media (the data model has an internal error");
}
} else if (data.deleted == true) {
} else if (data.deleted) {
System.out.println("Data already exist but deleted");
System.out.flush();
DataResource.undelete(data.id);
@ -133,7 +133,7 @@ public class VideoResource {
// Fist step: retive all the Id of each parents:...
System.out.println("Find typeNode");
// check if id of type exist:
Type typeNode = TypeResource.getId(Long.parseLong(typeId));
final Type typeNode = TypeResource.getId(Long.parseLong(typeId));
if (typeNode == null) {
DataResource.removeTemporaryFile(tmpUID);
throw new InputException("typeId", "TypeId does not exist ...");
@ -161,9 +161,9 @@ public class VideoResource {
System.out.println(" ==> " + seasonNode);
System.out.println("add media");
long uniqueSQLID = -1;
final long uniqueSQLID = -1;
try {
Media media = new Media();
final Media media = new Media();
media.name = title;
media.dataId = data.id;
media.typeId = typeNode.id;
@ -179,17 +179,17 @@ public class VideoResource {
if (episode != null && !episode.contentEquals("")) {
media.episode = Integer.parseInt(episode);
}
Media out = SqlWrapper.insert(media);
final Media out = DataAccess.insert(media);
DataResource.removeTemporaryFile(tmpUID);
System.out.println("uploaded .... compleate: " + uniqueSQLID);
Media creation = get(uniqueSQLID);
final Media creation = get(uniqueSQLID);
return Response.ok(creation).build();
} catch (SQLException ex) {
} catch (final SQLException ex) {
ex.printStackTrace();
System.out.println("Catch error:" + ex.getMessage());
throw new FailException("Catch SQLerror ==> check server logs");
}
} catch (Exception ex) {
} catch (final Exception ex) {
System.out.println("Catch an unexpected error ... " + ex.getMessage());
ex.printStackTrace();
throw new FailException("Catch Exception ==> check server logs");
@ -200,24 +200,24 @@ public class VideoResource {
@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) {
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Media.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 {
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Media.class, id, "cover", coverId);
return Response.ok(SqlWrapper.get(Media.class, id)).build();
return Response.ok(DataAccess.get(Media.class, id)).build();
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") Long id) throws Exception {
SqlWrapper.delete(Media.class, id);
public Response delete(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Media.class, id);
return Response.ok().build();
}
}

View File

@ -10,14 +10,14 @@ import org.kar.karideo.model.Type;
import org.kar.karideo.model.UserMediaAdvancement;
public class Initialization extends MigrationSqlStep {
public static final int KARSO_INITIALISATION_ID = 1;
public static final int KARSO_INITIALISATION_ID = 1;
@Override
public String getName() {
return "Initialization";
}
public Initialization() throws Exception {
addClass(Data.class);
addClass(Media.class);
@ -26,7 +26,7 @@ public class Initialization extends MigrationSqlStep {
addClass(Season.class);
addClass(User.class);
addClass(UserMediaAdvancement.class);
addAction("""
INSERT INTO `type` (`id`, `name`, `description`) VALUES
(1, 'Documentary', 'Documentary (animals, space, earth...)'),
@ -43,22 +43,22 @@ public class Initialization extends MigrationSqlStep {
// set start increment element to permit to add after default elements
addAction("""
ALTER TABLE `data` AUTO_INCREMENT = 1000;
""");
""", "mysql");
addAction("""
ALTER TABLE `media` AUTO_INCREMENT = 1000;
""");
""", "mysql");
addAction("""
ALTER TABLE `type` AUTO_INCREMENT = 1000;
""");
""", "mysql");
addAction("""
ALTER TABLE `series` AUTO_INCREMENT = 1000;
""");
""", "mysql");
addAction("""
ALTER TABLE `season` AUTO_INCREMENT = 1000;
""");
""", "mysql");
addAction("""
ALTER TABLE `userMediaAdvencement` AUTO_INCREMENT = 1000;
""");
""", "mysql");
}
}

View File

@ -3,7 +3,7 @@ package org.kar.karideo.model;
import java.util.List;
import org.kar.archidata.model.Data;
import org.kar.archidata.model.GenericTable;
import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude;
@ -19,7 +19,7 @@ import jakarta.persistence.Table;
@JsonInclude(JsonInclude.Include.NON_NULL)
//@SQLDelete(sql = "UPDATE table_product SET deleted = true WHERE id=?")
//@Where(clause = "deleted=false")
public class Media extends GenericTable {
public class Media extends GenericDataSoftDelete {
// Name of the media (this represent the title)
@Column(nullable = false)
public String name;

View File

@ -2,10 +2,10 @@ package org.kar.karideo.model;
import java.util.List;
import org.kar.archidata.annotation.SQLComment;
import org.kar.archidata.annotation.SQLIfNotExists;
import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.Data;
import org.kar.archidata.model.GenericTable;
import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude;
@ -16,19 +16,19 @@ import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Table(name = "season")
@SQLIfNotExists
@DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Season extends GenericTable {
public class Season extends GenericDataSoftDelete {
@Column(nullable = false)
@SQLComment("Name of the media (this represent the title)")
@DataComment("Name of the media (this represent the title)")
public String name;
@SQLComment("Description of the media")
@DataComment("Description of the media")
public String description;
@Column(nullable = false)
@SQLComment("series parent ID")
@DataComment("series parent ID")
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Series.class)
public Long parentId;
@SQLComment("List of Id of the sopecific covers")
@DataComment("List of Id of the sopecific covers")
@ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class)
public List<Long> covers = null;
}

View File

@ -2,10 +2,10 @@ package org.kar.karideo.model;
import java.util.List;
import org.kar.archidata.annotation.SQLComment;
import org.kar.archidata.annotation.SQLIfNotExists;
import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.Data;
import org.kar.archidata.model.GenericTable;
import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude;
@ -16,19 +16,19 @@ import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Table(name = "series")
@SQLIfNotExists
@DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Series extends GenericTable {
public class Series extends GenericDataSoftDelete {
@Column(nullable = false)
@SQLComment("Name of the media (this represent the title)")
@DataComment("Name of the media (this represent the title)")
public String name;
@SQLComment("Description of the media")
@DataComment("Description of the media")
public String description;
@Column(nullable = false)
@SQLComment("series parent ID")
@DataComment("series parent ID")
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Type.class)
public Long parentId;
@SQLComment("List of Id of the sopecific covers")
@DataComment("List of Id of the sopecific covers")
@ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class)
public List<Long> covers = null;
}

View File

@ -2,10 +2,10 @@ package org.kar.karideo.model;
import java.util.List;
import org.kar.archidata.annotation.SQLComment;
import org.kar.archidata.annotation.SQLIfNotExists;
import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.Data;
import org.kar.archidata.model.GenericTable;
import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude;
@ -15,15 +15,15 @@ import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
@Table(name = "type")
@SQLIfNotExists
@DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Type extends GenericTable {
public class Type extends GenericDataSoftDelete {
@Column(nullable = false)
@SQLComment("Name of the media (this represent the title)")
@DataComment("Name of the media (this represent the title)")
public String name;
@SQLComment("Description of the media")
@DataComment("Description of the media")
public String description;
@SQLComment("List of Id of the sopecific covers")
@DataComment("List of Id of the sopecific covers")
@ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class)
public List<Long> covers = null;
}

View File

@ -1,6 +1,6 @@
package org.kar.karideo.model;
import org.kar.archidata.annotation.SQLIfNotExists;
import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.User;
import com.fasterxml.jackson.annotation.JsonInclude;
@ -8,8 +8,8 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.persistence.Table;
@Table(name = "user")
@SQLIfNotExists
@DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserKarideo extends User {
}

View File

@ -1,8 +1,8 @@
package org.kar.karideo.model;
import org.kar.archidata.annotation.SQLComment;
import org.kar.archidata.annotation.SQLIfNotExists;
import org.kar.archidata.model.GenericTable;
import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude;
@ -12,24 +12,24 @@ import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Table(name = "userMediaAdvancement")
@SQLIfNotExists
@DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserMediaAdvancement extends GenericTable {
public class UserMediaAdvancement extends GenericDataSoftDelete {
@Column(nullable = false)
@SQLComment("Foreign Key Id of the user")
@DataComment("Foreign Key Id of the user")
@ManyToOne(fetch = FetchType.LAZY, targetEntity = UserKarideo.class)
public long userId;
@Column(nullable = false)
@SQLComment("Id of the media")
@DataComment("Id of the media")
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Media.class)
public long mediaId;
@Column(nullable = false)
@SQLComment("Percent of admencement in the media")
@DataComment("Percent of admencement in the media")
public float percent;
@Column(nullable = false)
@SQLComment("Number of second of admencement in the media")
@DataComment("Number of second of admencement in the media")
public int time;
@Column(nullable = false)
@SQLComment("Number of time this media has been read")
@DataComment("Number of time this media has been read")
public int count;
}

View File

@ -0,0 +1,35 @@
# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
org.slf4j.simpleLogger.defaultLogLevel=debug
# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=
# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false
# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
# Set to true if you want to output the current thread name.
# Defaults to true.
org.slf4j.simpleLogger.showThreadName=true
# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true
# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false

View File

@ -0,0 +1,11 @@
package test.kar.karideo;
import java.util.Map;
import org.kar.archidata.util.JWTWrapper;
public class Common {
static String userToken = JWTWrapper.createJwtTestToken(16512, "test_user_login", "KarAuth", "karideo", Map.of("USER", Boolean.TRUE));
static String adminToken = JWTWrapper.createJwtTestToken(16512, "test_admin_login", "KarAuth", "karideo", Map.of("USER", Boolean.TRUE, "ADMIN", Boolean.TRUE));
}

View File

@ -0,0 +1,33 @@
package test.kar.karideo;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
class StepwiseExtension implements ExecutionCondition, TestExecutionExceptionHandler {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext extensionContext) {
final ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
final ExtensionContext.Store store = storeFor(extensionContext, namespace);
final String value = store.get(StepwiseExtension.class, String.class);
return value == null ? ConditionEvaluationResult.enabled("No test failures in stepwise tests")
: ConditionEvaluationResult.disabled(String.format("Stepwise test disabled due to previous failure in '%s'", value));
}
@Override
public void handleTestExecutionException(final ExtensionContext extensionContext, final Throwable throwable) throws Throwable {
final ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
final ExtensionContext.Store store = storeFor(extensionContext, namespace);
store.put(StepwiseExtension.class, extensionContext.getDisplayName());
throw throwable;
}
private ExtensionContext.Namespace namespaceFor(final ExtensionContext extensionContext) {
return ExtensionContext.Namespace.create(StepwiseExtension.class, extensionContext.getParent());
}
private ExtensionContext.Store storeFor(final ExtensionContext extensionContext, final ExtensionContext.Namespace namespace) {
return extensionContext.getParent().get().getStore(namespace);
}
}

View File

@ -0,0 +1,70 @@
package test.kar.karideo;
import java.io.IOException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.kar.archidata.db.DBEntry;
import org.kar.archidata.exception.RESTErrorResponseExeption;
import org.kar.archidata.util.ConfigBaseVariable;
import org.kar.archidata.util.RESTApi;
import org.kar.karideo.api.HealthCheck.HealthResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ExtendWith(StepwiseExtension.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class TestHealthCheck {
private final static Logger LOGGER = LoggerFactory.getLogger(TestHealthCheck.class);
static WebLauncherTest webInterface = null;
static RESTApi api = null;
@BeforeAll
public static void configureWebServer() throws Exception {
LOGGER.info("configure server ...");
webInterface = new WebLauncherTest();
LOGGER.info("Create DB");
try {
webInterface.migrateDB();
} catch (final Exception ex) {
ex.printStackTrace();
LOGGER.error("Detect an error: {}", ex.getMessage());
}
LOGGER.info("Start REST (BEGIN)");
webInterface.process();
LOGGER.info("Start REST (DONE)");
api = new RESTApi(ConfigBaseVariable.apiAdress);
}
@AfterAll
public static void stopWebServer() throws InterruptedException, IOException {
LOGGER.info("Kill the web server");
webInterface.stop();
webInterface = null;
LOGGER.info("Remove the test db");
DBEntry.closeAllForceMode();
ConfigBaseVariable.clearAllValue();
}
@Order(1)
@Test
//@RepeatedTest(10)
public void checkHealthCheck() throws Exception {
final HealthResult result = api.get(HealthResult.class, "health_check");
Assertions.assertEquals(result.value(), "alive and kicking");
}
@Order(2)
@Test
public void checkHealthCheckWrongAPI() throws Exception {
Assertions.assertThrows(RESTErrorResponseExeption.class, () -> api.get(HealthResult.class, "health_checks"));
}
}

View File

@ -0,0 +1,28 @@
package test.kar.karideo;
import org.kar.archidata.util.ConfigBaseVariable;
import org.kar.karideo.WebLauncher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WebLauncherTest extends WebLauncher {
final private static Logger LOGGER = LoggerFactory.getLogger(WebLauncherTest.class);
public WebLauncherTest() {
LOGGER.debug("Configure REST system");
// for local test:
ConfigBaseVariable.apiAdress = "http://127.0.0.1:12345/test/api/";
ConfigBaseVariable.testMode = "true";
//ConfigBaseVariable.dbPort = "3306";
// for the test we a in memory sqlite..
ConfigBaseVariable.dbType = "sqlite";
ConfigBaseVariable.dbHost = "memory";
// for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
//ConfigBaseVariable.dbHost = "localhost";
//ConfigBaseVariable.dbUser = "root";
//ConfigBaseVariable.dbPassword = "ZERTYSDGFVHSDFGHJYZSDFGSQxfgsqdfgsqdrf4564654";
}
}