[DEV] start add hooks
This commit is contained in:
parent
b48916be07
commit
49480bc0aa
@ -27,7 +27,6 @@
|
|||||||
</classpathentry>
|
</classpathentry>
|
||||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
|
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
|
||||||
<attributes>
|
<attributes>
|
||||||
<attribute name="module" value="true"/>
|
|
||||||
<attribute name="maven.pomderived" value="true"/>
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
</classpathentry>
|
</classpathentry>
|
||||||
|
16
README.md
16
README.md
@ -14,12 +14,28 @@ mvn clean compile assembly:single
|
|||||||
generic interface for all KAR web application
|
generic interface for all KAR web application
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Somes tools:
|
||||||
|
============
|
||||||
|
|
||||||
|
Auto-update dependency:
|
||||||
|
-----------------------
|
||||||
|
|
||||||
auto-update to the last version dependency:
|
auto-update to the last version dependency:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
mvn versions:use-latest-versions
|
mvn versions:use-latest-versions
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Format the code
|
||||||
|
---------------
|
||||||
|
|
||||||
|
Simply run the cmd-line:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn formatter:format
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
Add Gitea in the dependency for the registry:
|
Add Gitea in the dependency for the registry:
|
||||||
=============================================
|
=============================================
|
||||||
|
40
pom.xml
40
pom.xml
@ -223,6 +223,46 @@
|
|||||||
<nohelp>true</nohelp>
|
<nohelp>true</nohelp>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<!-- Check the style of the code -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||||
|
<version>3.1.0</version>
|
||||||
|
<configuration>
|
||||||
|
<configLocation>CheckStyle.xml</configLocation>
|
||||||
|
<consoleOutput>true</consoleOutput>
|
||||||
|
<failOnViolation>true</failOnViolation>
|
||||||
|
<failsOnError>true</failsOnError>
|
||||||
|
<includeTestSourceDirectory>true</includeTestSourceDirectory>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>net.revelc.code.formatter</groupId>
|
||||||
|
<artifactId>formatter-maven-plugin</artifactId>
|
||||||
|
<version>2.12.2</version>
|
||||||
|
<configuration>
|
||||||
|
<encoding>UTF-8</encoding>
|
||||||
|
<lineEnding>LF</lineEnding>
|
||||||
|
<configFile>Formatter.xml</configFile>
|
||||||
|
<directories>
|
||||||
|
<directory>src/</directory>
|
||||||
|
<directory>test/src</directory>
|
||||||
|
</directories>
|
||||||
|
<includes>
|
||||||
|
<include>**/*.java</include>
|
||||||
|
</includes>
|
||||||
|
<excludes>
|
||||||
|
<exclude>module-info.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>validate</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
<!-- Generate Java-docs As Part Of Project Reports -->
|
<!-- Generate Java-docs As Part Of Project Reports -->
|
||||||
|
@ -6,14 +6,8 @@ import org.kar.archidata.util.ConfigBaseVariable;
|
|||||||
public class GlobalConfiguration {
|
public class GlobalConfiguration {
|
||||||
public static DBConfig dbConfig = null;
|
public static DBConfig dbConfig = null;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
dbConfig = new DBConfig(ConfigBaseVariable.getDBType(),
|
dbConfig = new DBConfig(ConfigBaseVariable.getDBType(), ConfigBaseVariable.getDBHost(), Integer.parseInt(ConfigBaseVariable.getDBPort()), ConfigBaseVariable.getDBLogin(),
|
||||||
ConfigBaseVariable.getDBHost(),
|
ConfigBaseVariable.getDBPassword(), ConfigBaseVariable.getDBName(), ConfigBaseVariable.getDBKeepConnected());
|
||||||
Integer.parseInt(ConfigBaseVariable.getDBPort()),
|
}
|
||||||
ConfigBaseVariable.getDBLogin(),
|
|
||||||
ConfigBaseVariable.getDBPassword(),
|
|
||||||
ConfigBaseVariable.getDBName(),
|
|
||||||
ConfigBaseVariable.getDBKeepConnected());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -5,18 +5,19 @@ import org.kar.archidata.util.JWTWrapper;
|
|||||||
|
|
||||||
public class UpdateJwtPublicKey extends Thread {
|
public class UpdateJwtPublicKey extends Thread {
|
||||||
boolean kill = false;
|
boolean kill = false;
|
||||||
|
|
||||||
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
if (ConfigBaseVariable.getSSOAddress() == null) {
|
if (ConfigBaseVariable.getSSOAddress() == null) {
|
||||||
System.out.println("SSO INTERFACE is not provided ==> work alone.");
|
System.out.println("SSO INTERFACE is not provided ==> work alone.");
|
||||||
// No SO provided, kill the thread.
|
// No SO provided, kill the thread.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
while (this.kill == false) {
|
while (!this.kill) {
|
||||||
// need to upgrade when server call us...
|
// need to upgrade when server call us...
|
||||||
try {
|
try {
|
||||||
JWTWrapper.initLocalTokenRemote(ConfigBaseVariable.getSSOAddress(), "archidata");
|
JWTWrapper.initLocalTokenRemote(ConfigBaseVariable.getSSOAddress(), "archidata");
|
||||||
} catch (Exception e1) {
|
} catch (final Exception e1) {
|
||||||
e1.printStackTrace();
|
e1.printStackTrace();
|
||||||
System.out.println("Can not retreive the basic tocken");
|
System.out.println("Can not retreive the basic tocken");
|
||||||
return;
|
return;
|
||||||
@ -24,13 +25,13 @@ public class UpdateJwtPublicKey extends Thread {
|
|||||||
try {
|
try {
|
||||||
// update every 5 minutes the master token
|
// update every 5 minutes the master token
|
||||||
Thread.sleep(1000 * 60 * 5, 0);
|
Thread.sleep(1000 * 60 * 5, 0);
|
||||||
} catch (InterruptedException e) {
|
} catch (final InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void kill() {
|
public void kill() {
|
||||||
this.kill = true;
|
this.kill = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,13 +11,13 @@ import org.kar.archidata.model.User;
|
|||||||
public class UserDB {
|
public class UserDB {
|
||||||
|
|
||||||
public UserDB() {}
|
public UserDB() {}
|
||||||
|
|
||||||
public static User getUsers(long userId) throws Exception {
|
public static User getUsers(final long userId) throws Exception {
|
||||||
return DataAccess.get(User.class, userId);
|
return DataAccess.get(User.class, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static User getUserOrCreate(long userId, String userLogin) throws Exception {
|
public static User getUserOrCreate(final long userId, final String userLogin) throws Exception {
|
||||||
User user = getUsers(userId);
|
final User user = getUsers(userId);
|
||||||
if (user != null) {
|
if (user != null) {
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
@ -25,19 +25,18 @@ public class UserDB {
|
|||||||
return getUsers(userId);
|
return getUsers(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void createUsersInfoFromOAuth(long userId, String login) throws IOException {
|
private static void createUsersInfoFromOAuth(final long userId, final String login) throws IOException {
|
||||||
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
String query = "INSERT INTO `user` (`id`, `login`, `lastConnection`, `admin`, `blocked`, `removed`) VALUE (?,?,now(3),'0','0','0')";
|
final String query = "INSERT INTO `user` (`id`, `login`, `lastConnection`, `admin`, `blocked`, `removed`) VALUE (?,?,now(3),'0','0','0')";
|
||||||
try {
|
try {
|
||||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
final PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||||
ps.setLong(1, userId);
|
ps.setLong(1, userId);
|
||||||
ps.setString(2, login);
|
ps.setString(2, login);
|
||||||
ps.executeUpdate();
|
ps.executeUpdate();
|
||||||
} catch (SQLException throwables) {
|
} catch (final SQLException throwables) {
|
||||||
throwables.printStackTrace();
|
throwables.printStackTrace();
|
||||||
} finally {
|
} finally {
|
||||||
entry.close();
|
entry.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -29,7 +29,7 @@ public class AnnotationTools {
|
|||||||
}
|
}
|
||||||
return AnnotationTools.getTableName(clazz);
|
return AnnotationTools.getTableName(clazz);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getTableName(final Class<?> element) throws Exception {
|
public static String getTableName(final Class<?> element) throws Exception {
|
||||||
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Table.class);
|
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Table.class);
|
||||||
if (annotation.length == 0) {
|
if (annotation.length == 0) {
|
||||||
@ -153,11 +153,11 @@ public class AnnotationTools {
|
|||||||
public static boolean isDeletedField(final Field element) throws Exception {
|
public static boolean isDeletedField(final Field element) throws Exception {
|
||||||
return element.getDeclaredAnnotationsByType(DataDeleted.class).length != 0;
|
return element.getDeclaredAnnotationsByType(DataDeleted.class).length != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isCreatedAtField(final Field element) throws Exception {
|
public static boolean isCreatedAtField(final Field element) throws Exception {
|
||||||
return element.getDeclaredAnnotationsByType(CreationTimestamp.class).length != 0;
|
return element.getDeclaredAnnotationsByType(CreationTimestamp.class).length != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isUpdateAtField(final Field element) throws Exception {
|
public static boolean isUpdateAtField(final Field element) throws Exception {
|
||||||
return element.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0;
|
return element.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0;
|
||||||
}
|
}
|
||||||
@ -220,15 +220,15 @@ public class AnnotationTools {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<String> getFieldsNames(final Class<?> clazz) throws Exception {
|
public static List<String> getFieldsNames(final Class<?> clazz) throws Exception {
|
||||||
return getFieldsNamesFilter(clazz, false);
|
return getFieldsNamesFilter(clazz, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<String> getAllFieldsNames(final Class<?> clazz) throws Exception {
|
public static List<String> getAllFieldsNames(final Class<?> clazz) throws Exception {
|
||||||
return getFieldsNamesFilter(clazz, true);
|
return getFieldsNamesFilter(clazz, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<String> getFieldsNamesFilter(final Class<?> clazz, final boolean full) throws Exception {
|
private static List<String> getFieldsNamesFilter(final Class<?> clazz, final boolean full) throws Exception {
|
||||||
final List<String> out = new ArrayList<>();
|
final List<String> out = new ArrayList<>();
|
||||||
for (final Field field : clazz.getFields()) {
|
for (final Field field : clazz.getFields()) {
|
||||||
|
@ -8,5 +8,5 @@ import java.lang.annotation.Target;
|
|||||||
@Target(ElementType.FIELD)
|
@Target(ElementType.FIELD)
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface CreationTimestamp {
|
public @interface CreationTimestamp {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@ import java.lang.annotation.Target;
|
|||||||
@Target({ ElementType.TYPE, ElementType.FIELD })
|
@Target({ ElementType.TYPE, ElementType.FIELD })
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface DataComment {
|
public @interface DataComment {
|
||||||
|
|
||||||
String value();
|
String value();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@ import java.lang.annotation.Target;
|
|||||||
@Target({ ElementType.TYPE, ElementType.FIELD })
|
@Target({ ElementType.TYPE, ElementType.FIELD })
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface DataDefault {
|
public @interface DataDefault {
|
||||||
|
|
||||||
String value();
|
String value();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,5 +8,5 @@ import java.lang.annotation.Target;
|
|||||||
@Target(ElementType.FIELD)
|
@Target(ElementType.FIELD)
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface DataDeleted {
|
public @interface DataDeleted {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,5 +8,5 @@ import java.lang.annotation.Target;
|
|||||||
@Target(ElementType.TYPE)
|
@Target(ElementType.TYPE)
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface DataIfNotExists {
|
public @interface DataIfNotExists {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,5 +8,5 @@ import java.lang.annotation.Target;
|
|||||||
@Target(ElementType.FIELD)
|
@Target(ElementType.FIELD)
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface DataNotRead {
|
public @interface DataNotRead {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,5 +8,5 @@ import java.lang.annotation.Target;
|
|||||||
@Target(ElementType.FIELD)
|
@Target(ElementType.FIELD)
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface UpdateTimestamp {
|
public @interface UpdateTimestamp {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -57,14 +57,12 @@ public class DataResource {
|
|||||||
private static final Logger LOGGER = LoggerFactory.getLogger(MediaType.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(MediaType.class);
|
||||||
private final static int CHUNK_SIZE = 1024 * 1024; // 1MB chunks
|
private final static int CHUNK_SIZE = 1024 * 1024; // 1MB chunks
|
||||||
private final static int CHUNK_SIZE_IN = 50 * 1024 * 1024; // 1MB chunks
|
private final static int CHUNK_SIZE_IN = 50 * 1024 * 1024; // 1MB chunks
|
||||||
/**
|
/** Upload some datas */
|
||||||
* Upload some datas
|
|
||||||
*/
|
|
||||||
private static long tmpFolderId = 1;
|
private static long tmpFolderId = 1;
|
||||||
|
|
||||||
private static void createFolder(final String path) throws IOException {
|
private static void createFolder(final String path) throws IOException {
|
||||||
if (!Files.exists(java.nio.file.Path.of(path))) {
|
if (!Files.exists(java.nio.file.Path.of(path))) {
|
||||||
//Log.print("Create folder: " + path);
|
// Log.print("Create folder: " + path);
|
||||||
Files.createDirectories(java.nio.file.Path.of(path));
|
Files.createDirectories(java.nio.file.Path.of(path));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -114,20 +112,20 @@ public class DataResource {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Data createNewData(final long tmpUID, final String originalFileName, final String sha512) throws IOException {
|
public static Data createNewData(final long tmpUID, final String originalFileName, final String sha512) throws IOException {
|
||||||
// determine mime type:
|
// determine mime type:
|
||||||
Data injectedData = new Data();
|
Data injectedData = new Data();
|
||||||
String mimeType = "";
|
String mimeType = "";
|
||||||
final String extension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1);
|
final String extension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1);
|
||||||
mimeType = switch (extension.toLowerCase()) {
|
mimeType = switch (extension.toLowerCase()) {
|
||||||
case "jpg", "jpeg" -> "image/jpeg";
|
case "jpg", "jpeg" -> "image/jpeg";
|
||||||
case "png" -> "image/png";
|
case "png" -> "image/png";
|
||||||
case "webp" -> "image/webp";
|
case "webp" -> "image/webp";
|
||||||
case "mka" -> "audio/x-matroska";
|
case "mka" -> "audio/x-matroska";
|
||||||
case "mkv" -> "video/x-matroska";
|
case "mkv" -> "video/x-matroska";
|
||||||
case "webm" -> "video/webm";
|
case "webm" -> "video/webm";
|
||||||
default -> throw new IOException("Can not find the mime type of data input: '" + extension + "'");
|
default -> throw new IOException("Can not find the mime type of data input: '" + extension + "'");
|
||||||
};
|
};
|
||||||
injectedData.mimeType = mimeType;
|
injectedData.mimeType = mimeType;
|
||||||
injectedData.sha512 = sha512;
|
injectedData.sha512 = sha512;
|
||||||
@ -176,7 +174,7 @@ public class DataResource {
|
|||||||
|
|
||||||
outpuStream = new FileOutputStream(new File(serverLocation));
|
outpuStream = new FileOutputStream(new File(serverLocation));
|
||||||
while ((read = uploadedInputStream.read(bytes)) != -1) {
|
while ((read = uploadedInputStream.read(bytes)) != -1) {
|
||||||
//logger.info("write {}", read);
|
// logger.info("write {}", read);
|
||||||
md.update(bytes, 0, read);
|
md.update(bytes, 0, read);
|
||||||
outpuStream.write(bytes, 0, read);
|
outpuStream.write(bytes, 0, read);
|
||||||
}
|
}
|
||||||
@ -226,7 +224,7 @@ public class DataResource {
|
|||||||
LOGGER.info("===================================================");
|
LOGGER.info("===================================================");
|
||||||
LOGGER.info("== DATA uploadFile {}", (gc == null ? "null" : gc.userByToken));
|
LOGGER.info("== DATA uploadFile {}", (gc == null ? "null" : gc.userByToken));
|
||||||
LOGGER.info("===================================================");
|
LOGGER.info("===================================================");
|
||||||
//public NodeSmall uploadFile(final FormDataMultiPart form) {
|
// public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||||
LOGGER.info("Upload file: ");
|
LOGGER.info("Upload file: ");
|
||||||
final String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
final String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
||||||
try {
|
try {
|
||||||
@ -236,7 +234,7 @@ public class DataResource {
|
|||||||
}
|
}
|
||||||
saveFile(fileInputStream, filePath);
|
saveFile(fileInputStream, filePath);
|
||||||
return Response.ok("Data uploaded successfully !!").build();
|
return Response.ok("Data uploaded successfully !!").build();
|
||||||
//return null;
|
// return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@ -247,9 +245,9 @@ public class DataResource {
|
|||||||
public Response retriveDataId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
public Response retriveDataId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
||||||
@PathParam("id") final Long id) throws Exception {
|
@PathParam("id") final Long id) throws Exception {
|
||||||
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
||||||
//logger.info("===================================================");
|
// logger.info("===================================================");
|
||||||
LOGGER.info("== DATA retriveDataId ? id={} user={}", id, (gc == null ? "null" : gc.userByToken));
|
LOGGER.info("== DATA retriveDataId ? id={} user={}", id, (gc == null ? "null" : gc.userByToken));
|
||||||
//logger.info("===================================================");
|
// logger.info("===================================================");
|
||||||
final Data value = getSmall(id);
|
final Data value = getSmall(id);
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
||||||
@ -262,13 +260,13 @@ public class DataResource {
|
|||||||
@RolesAllowed("USER")
|
@RolesAllowed("USER")
|
||||||
@PermitTokenInURI
|
@PermitTokenInURI
|
||||||
@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
//@CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
// @CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
||||||
public Response retriveDataThumbnailId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
public Response retriveDataThumbnailId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
||||||
@PathParam("id") final Long id) throws Exception {
|
@PathParam("id") final Long id) throws Exception {
|
||||||
//GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
// GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
||||||
//logger.info("===================================================");
|
// logger.info("===================================================");
|
||||||
//logger.info("== DATA retriveDataThumbnailId ? {}", (gc==null?"null":gc.user));
|
// logger.info("== DATA retriveDataThumbnailId ? {}", (gc==null?"null":gc.user));
|
||||||
//logger.info("===================================================");
|
// logger.info("===================================================");
|
||||||
final Data value = getSmall(id);
|
final Data value = getSmall(id);
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
return Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
return Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
||||||
@ -279,7 +277,7 @@ public class DataResource {
|
|||||||
return Response.status(404).entity("{\"error\":\"media Does not exist: " + id + "\"}").type("application/json").build();
|
return Response.status(404).entity("{\"error\":\"media Does not exist: " + id + "\"}").type("application/json").build();
|
||||||
}
|
}
|
||||||
if (value.mimeType.contentEquals("image/jpeg") || value.mimeType.contentEquals("image/png")
|
if (value.mimeType.contentEquals("image/jpeg") || value.mimeType.contentEquals("image/png")
|
||||||
// || value.mimeType.contentEquals("image/webp")
|
// || value.mimeType.contentEquals("image/webp")
|
||||||
) {
|
) {
|
||||||
// reads input image
|
// reads input image
|
||||||
final BufferedImage inputImage = ImageIO.read(inputFile);
|
final BufferedImage inputImage = ImageIO.read(inputFile);
|
||||||
@ -302,7 +300,7 @@ public class DataResource {
|
|||||||
return Response.status(500).entity("Internal Error: resize fail: " + e.getMessage()).type("text/plain").build();
|
return Response.status(500).entity("Internal Error: resize fail: " + e.getMessage()).type("text/plain").build();
|
||||||
}
|
}
|
||||||
final byte[] imageData = baos.toByteArray();
|
final byte[] imageData = baos.toByteArray();
|
||||||
//Response.ok(new ByteArrayInputStream(imageData)).build();
|
// Response.ok(new ByteArrayInputStream(imageData)).build();
|
||||||
final Response.ResponseBuilder out = Response.ok(imageData).header(HttpHeaders.CONTENT_LENGTH, imageData.length);
|
final Response.ResponseBuilder out = Response.ok(imageData).header(HttpHeaders.CONTENT_LENGTH, imageData.length);
|
||||||
out.type("image/jpeg");
|
out.type("image/jpeg");
|
||||||
// TODO: move this in a decorator !!!
|
// TODO: move this in a decorator !!!
|
||||||
@ -315,7 +313,7 @@ public class DataResource {
|
|||||||
return buildStream(filePathName, range, value.mimeType);
|
return buildStream(filePathName, range, value.mimeType);
|
||||||
}
|
}
|
||||||
|
|
||||||
//@Secured
|
// @Secured
|
||||||
@GET
|
@GET
|
||||||
@Path("{id}/{name}")
|
@Path("{id}/{name}")
|
||||||
@PermitTokenInURI
|
@PermitTokenInURI
|
||||||
@ -324,9 +322,9 @@ public class DataResource {
|
|||||||
public Response retriveDataFull(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
public Response retriveDataFull(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
||||||
@PathParam("id") final Long id, @PathParam("name") final String name) throws Exception {
|
@PathParam("id") final Long id, @PathParam("name") final String name) throws Exception {
|
||||||
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
||||||
//logger.info("===================================================");
|
// logger.info("===================================================");
|
||||||
LOGGER.info("== DATA retriveDataFull ? id={} user={}", id, (gc == null ? "null" : gc.userByToken));
|
LOGGER.info("== DATA retriveDataFull ? id={} user={}", id, (gc == null ? "null" : gc.userByToken));
|
||||||
//logger.info("===================================================");
|
// logger.info("===================================================");
|
||||||
final Data value = getSmall(id);
|
final Data value = getSmall(id);
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
||||||
@ -334,16 +332,14 @@ public class DataResource {
|
|||||||
return buildStream(ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
|
return buildStream(ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Adapted from http://stackoverflow.com/questions/12768812/video-streaming-to-ipad-does-not-work-with-tapestry5/12829541#12829541
|
||||||
* Adapted from http://stackoverflow.com/questions/12768812/video-streaming-to-ipad-does-not-work-with-tapestry5/12829541#12829541
|
|
||||||
*
|
*
|
||||||
* @param range range header
|
* @param range range header
|
||||||
* @return Streaming output
|
* @return Streaming output
|
||||||
* @throws Exception IOException if an error occurs in streaming.
|
* @throws Exception IOException if an error occurs in streaming. */
|
||||||
*/
|
|
||||||
private Response buildStream(final String filename, final String range, final String mimeType) throws Exception {
|
private Response buildStream(final String filename, final String range, final String mimeType) throws Exception {
|
||||||
final File file = new File(filename);
|
final File file = new File(filename);
|
||||||
//logger.info("request range : {}", range);
|
// logger.info("request range : {}", range);
|
||||||
// range not requested : Firefox does not send range headers
|
// range not requested : Firefox does not send range headers
|
||||||
if (range == null) {
|
if (range == null) {
|
||||||
final StreamingOutput output = new StreamingOutput() {
|
final StreamingOutput output = new StreamingOutput() {
|
||||||
@ -356,7 +352,7 @@ public class DataResource {
|
|||||||
try {
|
try {
|
||||||
out.write(buf, 0, len);
|
out.write(buf, 0, len);
|
||||||
out.flush();
|
out.flush();
|
||||||
//logger.info("---- wrote {} bytes file ----", len);
|
// logger.info("---- wrote {} bytes file ----", len);
|
||||||
} catch (final IOException ex) {
|
} catch (final IOException ex) {
|
||||||
LOGGER.info("remote close connection");
|
LOGGER.info("remote close connection");
|
||||||
break;
|
break;
|
||||||
@ -378,8 +374,8 @@ public class DataResource {
|
|||||||
final String[] ranges = range.split("=")[1].split("-");
|
final String[] ranges = range.split("=")[1].split("-");
|
||||||
final long from = Long.parseLong(ranges[0]);
|
final long from = Long.parseLong(ranges[0]);
|
||||||
|
|
||||||
//logger.info("request range : {}", ranges.length);
|
// logger.info("request range : {}", ranges.length);
|
||||||
//Chunk media if the range upper bound is unspecified. Chrome, Opera sends "bytes=0-"
|
// Chunk media if the range upper bound is unspecified. Chrome, Opera sends "bytes=0-"
|
||||||
long to = CHUNK_SIZE + from;
|
long to = CHUNK_SIZE + from;
|
||||||
if (ranges.length == 1) {
|
if (ranges.length == 1) {
|
||||||
to = file.length() - 1;
|
to = file.length() - 1;
|
||||||
@ -387,7 +383,7 @@ public class DataResource {
|
|||||||
to = file.length() - 1;
|
to = file.length() - 1;
|
||||||
}
|
}
|
||||||
final String responseRange = String.format("bytes %d-%d/%d", from, to, file.length());
|
final String responseRange = String.format("bytes %d-%d/%d", from, to, file.length());
|
||||||
//logger.info("responseRange: {}", responseRange);
|
// logger.info("responseRange: {}", responseRange);
|
||||||
final RandomAccessFile raf = new RandomAccessFile(file, "r");
|
final RandomAccessFile raf = new RandomAccessFile(file, "r");
|
||||||
raf.seek(from);
|
raf.seek(from);
|
||||||
|
|
||||||
|
@ -28,7 +28,7 @@ public class FrontGeneric {
|
|||||||
}
|
}
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
private Response retrive(final String fileName) throws Exception {
|
private Response retrive(final String fileName) throws Exception {
|
||||||
String filePathName = this.baseFrontFolder + File.separator + fileName;
|
String filePathName = this.baseFrontFolder + File.separator + fileName;
|
||||||
final String extention = getExtension(filePathName);
|
final String extention = getExtension(filePathName);
|
||||||
@ -76,7 +76,7 @@ public class FrontGeneric {
|
|||||||
}
|
}
|
||||||
final ResponseBuilder response = Response.ok(download);
|
final ResponseBuilder response = Response.ok(download);
|
||||||
// use this if I want to download the file:
|
// use this if I want to download the file:
|
||||||
//response.header("Content-Disposition", "attachment; filename=" + fileName);
|
// response.header("Content-Disposition", "attachment; filename=" + fileName);
|
||||||
final CacheControl cc = new CacheControl();
|
final CacheControl cc = new CacheControl();
|
||||||
cc.setMaxAge(60);
|
cc.setMaxAge(60);
|
||||||
cc.setNoCache(false);
|
cc.setNoCache(false);
|
||||||
@ -88,8 +88,8 @@ public class FrontGeneric {
|
|||||||
|
|
||||||
@GET
|
@GET
|
||||||
@PermitAll()
|
@PermitAll()
|
||||||
//@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
// @Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
//@CacheMaxAge(time = 1, unit = TimeUnit.DAYS)
|
// @CacheMaxAge(time = 1, unit = TimeUnit.DAYS)
|
||||||
public Response retrive0() throws Exception {
|
public Response retrive0() throws Exception {
|
||||||
return retrive("index.html");
|
return retrive("index.html");
|
||||||
}
|
}
|
||||||
@ -97,8 +97,8 @@ public class FrontGeneric {
|
|||||||
@GET
|
@GET
|
||||||
@Path("{any: .*}")
|
@Path("{any: .*}")
|
||||||
@PermitAll()
|
@PermitAll()
|
||||||
//@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
// @Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
//@CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
// @CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
||||||
public Response retrive1(@PathParam("any") final List<PathSegment> segments) throws Exception {
|
public Response retrive1(@PathParam("any") final List<PathSegment> segments) throws Exception {
|
||||||
String filename = "";
|
String filename = "";
|
||||||
for (final PathSegment elem : segments) {
|
for (final PathSegment elem : segments) {
|
||||||
|
@ -19,14 +19,14 @@ public class MediaStreamer implements StreamingOutput {
|
|||||||
private final RandomAccessFile raf;
|
private final RandomAccessFile raf;
|
||||||
|
|
||||||
public MediaStreamer(final long length, final RandomAccessFile raf) throws IOException {
|
public MediaStreamer(final long length, final RandomAccessFile raf) throws IOException {
|
||||||
//logger.info("request stream of {} data", length / 1024);
|
// logger.info("request stream of {} data", length / 1024);
|
||||||
if (length < 0) {
|
if (length < 0) {
|
||||||
throw new IOException("Wrong size of the file to stream: " + length);
|
throw new IOException("Wrong size of the file to stream: " + length);
|
||||||
}
|
}
|
||||||
this.length = length;
|
this.length = length;
|
||||||
this.raf = raf;
|
this.raf = raf;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void write(final OutputStream outputStream) {
|
public void write(final OutputStream outputStream) {
|
||||||
try {
|
try {
|
||||||
|
@ -4,26 +4,26 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class BackupEngine {
|
public class BackupEngine {
|
||||||
|
|
||||||
public enum StoreMode {
|
public enum StoreMode {
|
||||||
JSON, SQL
|
JSON, SQL
|
||||||
}
|
}
|
||||||
|
|
||||||
private final String pathStore;
|
private final String pathStore;
|
||||||
private final StoreMode mode;
|
private final StoreMode mode;
|
||||||
private List<Class<?>> classes = new ArrayList<>();
|
private final List<Class<?>> classes = new ArrayList<>();
|
||||||
|
|
||||||
public BackupEngine(String pathToStoreDB, StoreMode mode) {
|
public BackupEngine(final String pathToStoreDB, final StoreMode mode) {
|
||||||
this.pathStore = pathToStoreDB;
|
this.pathStore = pathToStoreDB;
|
||||||
this.mode = mode;
|
this.mode = mode;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addClass(Class<?> clazz) {
|
public void addClass(final Class<?> clazz) {
|
||||||
classes.add(clazz);
|
this.classes.add(clazz);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void store() {
|
public void store() {
|
||||||
// TODO ...
|
// TODO ...
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,18 +9,18 @@ import jakarta.ws.rs.ext.ExceptionMapper;
|
|||||||
|
|
||||||
public class ExceptionCatcher implements ExceptionMapper<Exception> {
|
public class ExceptionCatcher implements ExceptionMapper<Exception> {
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatcher.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatcher.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Response toResponse(Exception exception) {
|
public Response toResponse(final Exception exception) {
|
||||||
LOGGER.warn("Catch exception (not managed...):");
|
LOGGER.warn("Catch exception (not managed...):");
|
||||||
RestErrorResponse ret = build(exception);
|
final RestErrorResponse ret = build(exception);
|
||||||
LOGGER.error("Error UUID={}", ret.uuid);
|
LOGGER.error("Error UUID={}", ret.uuid);
|
||||||
exception.printStackTrace();
|
exception.printStackTrace();
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private RestErrorResponse build(Exception exception) {
|
private RestErrorResponse build(final Exception exception) {
|
||||||
return new RestErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Catch Unknown Exception", exception.getMessage());
|
return new RestErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Catch Unknown Exception", exception.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -10,18 +10,18 @@ import jakarta.ws.rs.ext.ExceptionMapper;
|
|||||||
|
|
||||||
public class FailExceptionCatcher implements ExceptionMapper<FailException> {
|
public class FailExceptionCatcher implements ExceptionMapper<FailException> {
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(FailExceptionCatcher.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(FailExceptionCatcher.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Response toResponse(FailException exception) {
|
public Response toResponse(final FailException exception) {
|
||||||
RestErrorResponse ret = build(exception);
|
final RestErrorResponse ret = build(exception);
|
||||||
LOGGER.error("Error UUID={}", ret.uuid);
|
LOGGER.error("Error UUID={}", ret.uuid);
|
||||||
// Not display backtrace ==> this may be a normal case ...
|
// Not display backtrace ==> this may be a normal case ...
|
||||||
//exception.printStackTrace();
|
// exception.printStackTrace();
|
||||||
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private RestErrorResponse build(FailException exception) {
|
private RestErrorResponse build(final FailException exception) {
|
||||||
return new RestErrorResponse(exception.status, "Request Fail", exception.getMessage());
|
return new RestErrorResponse(exception.status, "Request Fail", exception.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -10,17 +10,17 @@ import jakarta.ws.rs.ext.ExceptionMapper;
|
|||||||
|
|
||||||
public class InputExceptionCatcher implements ExceptionMapper<InputException> {
|
public class InputExceptionCatcher implements ExceptionMapper<InputException> {
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(InputExceptionCatcher.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(InputExceptionCatcher.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Response toResponse(InputException exception) {
|
public Response toResponse(final InputException exception) {
|
||||||
RestErrorResponse ret = build(exception);
|
final RestErrorResponse ret = build(exception);
|
||||||
LOGGER.error("Error UUID={}", ret.uuid);
|
LOGGER.error("Error UUID={}", ret.uuid);
|
||||||
exception.printStackTrace();
|
exception.printStackTrace();
|
||||||
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private RestErrorResponse build(InputException exception) {
|
private RestErrorResponse build(final InputException exception) {
|
||||||
return new RestErrorResponse(exception.status, "Error on input='" + exception.missingVariable + "'", exception.getMessage());
|
return new RestErrorResponse(exception.status, "Error on input='" + exception.missingVariable + "'", exception.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -12,27 +12,27 @@ public class RestErrorResponse {
|
|||||||
public String message;
|
public String message;
|
||||||
final public int status;
|
final public int status;
|
||||||
final public String statusMessage;
|
final public String statusMessage;
|
||||||
|
|
||||||
public RestErrorResponse(Response.Status status, String time, String error, String message) {
|
public RestErrorResponse(final Response.Status status, final String time, final String error, final String message) {
|
||||||
this.time = time;
|
this.time = time;
|
||||||
this.error = error;
|
this.error = error;
|
||||||
this.message = message;
|
this.message = message;
|
||||||
this.status = status.getStatusCode();
|
this.status = status.getStatusCode();
|
||||||
this.statusMessage = status.getReasonPhrase();
|
this.statusMessage = status.getReasonPhrase();
|
||||||
}
|
}
|
||||||
|
|
||||||
public RestErrorResponse(Response.Status status, String error, String message) {
|
public RestErrorResponse(final Response.Status status, final String error, final String message) {
|
||||||
this.time = Instant.now().toString();
|
this.time = Instant.now().toString();
|
||||||
this.error = error;
|
this.error = error;
|
||||||
this.message = message;
|
this.message = message;
|
||||||
this.status = status.getStatusCode();
|
this.status = status.getStatusCode();
|
||||||
this.statusMessage = status.getReasonPhrase();
|
this.statusMessage = status.getReasonPhrase();
|
||||||
}
|
}
|
||||||
|
|
||||||
public RestErrorResponse(Response.Status status) {
|
public RestErrorResponse(final Response.Status status) {
|
||||||
this.time = Instant.now().toString();
|
this.time = Instant.now().toString();
|
||||||
this.status = status.getStatusCode();
|
this.status = status.getStatusCode();
|
||||||
this.statusMessage = status.getReasonPhrase();
|
this.statusMessage = status.getReasonPhrase();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -10,17 +10,17 @@ import jakarta.ws.rs.ext.ExceptionMapper;
|
|||||||
|
|
||||||
public class SystemExceptionCatcher implements ExceptionMapper<SystemException> {
|
public class SystemExceptionCatcher implements ExceptionMapper<SystemException> {
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(SystemExceptionCatcher.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(SystemExceptionCatcher.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Response toResponse(SystemException exception) {
|
public Response toResponse(final SystemException exception) {
|
||||||
RestErrorResponse ret = build(exception);
|
final RestErrorResponse ret = build(exception);
|
||||||
LOGGER.error("Error UUID={}", ret.uuid);
|
LOGGER.error("Error UUID={}", ret.uuid);
|
||||||
exception.printStackTrace();
|
exception.printStackTrace();
|
||||||
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private RestErrorResponse build(SystemException exception) {
|
private RestErrorResponse build(final SystemException exception) {
|
||||||
return new RestErrorResponse(exception.status, "System error", exception.getMessage());
|
return new RestErrorResponse(exception.status, "System error", exception.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,7 @@ public class CountInOut {
|
|||||||
public CountInOut(final int i) {
|
public CountInOut(final int i) {
|
||||||
this.value = i;
|
this.value = i;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void inc() {
|
public void inc() {
|
||||||
this.value++;
|
this.value++;
|
||||||
}
|
}
|
||||||
|
@ -84,10 +84,10 @@ public class DataAccess {
|
|||||||
// TODO : Maybe connect with a temporary not specified connection interface to a db ...
|
// TODO : Maybe connect with a temporary not specified connection interface to a db ...
|
||||||
final PreparedStatement ps = entry.connection.prepareStatement("show databases");
|
final PreparedStatement ps = entry.connection.prepareStatement("show databases");
|
||||||
final ResultSet rs = ps.executeQuery();
|
final ResultSet rs = ps.executeQuery();
|
||||||
//LOGGER.info("List all tables: equals? '{}'", name);
|
// LOGGER.info("List all tables: equals? '{}'", name);
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
final String data = rs.getString(1);
|
final String data = rs.getString(1);
|
||||||
//LOGGER.info(" - '{}'", data);
|
// LOGGER.info(" - '{}'", data);
|
||||||
if (name.equals(data)) {
|
if (name.equals(data)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -132,7 +132,7 @@ public class DataAccess {
|
|||||||
WHERE type = 'table'
|
WHERE type = 'table'
|
||||||
AND name = ?;
|
AND name = ?;
|
||||||
""";
|
""";
|
||||||
// PreparedStatement ps = entry.connection.prepareStatement("show tables");
|
// PreparedStatement ps = entry.connection.prepareStatement("show tables");
|
||||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
final PreparedStatement ps = entry.connection.prepareStatement(request);
|
final PreparedStatement ps = entry.connection.prepareStatement(request);
|
||||||
ps.setString(1, name);
|
ps.setString(1, name);
|
||||||
@ -144,10 +144,10 @@ public class DataAccess {
|
|||||||
// TODO : Maybe connect with a temporary not specified connection interface to a db ...
|
// TODO : Maybe connect with a temporary not specified connection interface to a db ...
|
||||||
final PreparedStatement ps = entry.connection.prepareStatement("show tables");
|
final PreparedStatement ps = entry.connection.prepareStatement("show tables");
|
||||||
final ResultSet rs = ps.executeQuery();
|
final ResultSet rs = ps.executeQuery();
|
||||||
//LOGGER.info("List all tables: equals? '{}'", name);
|
// LOGGER.info("List all tables: equals? '{}'", name);
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
final String data = rs.getString(1);
|
final String data = rs.getString(1);
|
||||||
//LOGGER.info(" - '{}'", data);
|
// LOGGER.info(" - '{}'", data);
|
||||||
if (name.equals(data)) {
|
if (name.equals(data)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -162,13 +162,11 @@ public class DataAccess {
|
|||||||
throw new InternalServerErrorException("Can Not manage the DB-access");
|
throw new InternalServerErrorException("Can Not manage the DB-access");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** extract a list of "-" separated element from a SQL input data.
|
||||||
* extract a list of "-" separated element from a SQL input data.
|
|
||||||
* @param rs Result Set of the BDD
|
* @param rs Result Set of the BDD
|
||||||
* @param iii Id in the result set
|
* @param iii Id in the result set
|
||||||
* @return The list of Long value
|
* @return The list of Long value
|
||||||
* @throws SQLException if an error is generated in the sql request.
|
* @throws SQLException if an error is generated in the sql request. */
|
||||||
*/
|
|
||||||
public static List<Long> getListOfIds(final ResultSet rs, final int iii, final String separator) throws SQLException {
|
public static List<Long> getListOfIds(final ResultSet rs, final int iii, final String separator) throws SQLException {
|
||||||
final String trackString = rs.getString(iii);
|
final String trackString = rs.getString(iii);
|
||||||
if (rs.wasNull()) {
|
if (rs.wasNull()) {
|
||||||
@ -279,7 +277,7 @@ public class DataAccess {
|
|||||||
}
|
}
|
||||||
iii.inc();
|
iii.inc();
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: maybe wrap this if the use of sqlite ==> maybe some problems came with sqlite ...
|
// TODO: maybe wrap this if the use of sqlite ==> maybe some problems came with sqlite ...
|
||||||
protected static <T> void setValueFromDb(final Class<?> type, final Object data, final CountInOut count, final Field field, final ResultSet rs, final CountInOut countNotNull) throws Exception {
|
protected static <T> void setValueFromDb(final Class<?> type, final Object data, final CountInOut count, final Field field, final ResultSet rs, final CountInOut countNotNull) throws Exception {
|
||||||
if (type == Long.class) {
|
if (type == Long.class) {
|
||||||
@ -287,14 +285,14 @@ public class DataAccess {
|
|||||||
if (rs.wasNull()) {
|
if (rs.wasNull()) {
|
||||||
field.set(data, null);
|
field.set(data, null);
|
||||||
} else {
|
} else {
|
||||||
//logger.debug(" ==> {}", tmp);
|
// logger.debug(" ==> {}", tmp);
|
||||||
field.set(data, tmp);
|
field.set(data, tmp);
|
||||||
countNotNull.inc();
|
countNotNull.inc();
|
||||||
}
|
}
|
||||||
} else if (type == long.class) {
|
} else if (type == long.class) {
|
||||||
final Long tmp = rs.getLong(count.value);
|
final Long tmp = rs.getLong(count.value);
|
||||||
if (rs.wasNull()) {
|
if (rs.wasNull()) {
|
||||||
//field.set(data, null);
|
// field.set(data, null);
|
||||||
} else {
|
} else {
|
||||||
field.setLong(data, tmp);
|
field.setLong(data, tmp);
|
||||||
countNotNull.inc();
|
countNotNull.inc();
|
||||||
@ -310,7 +308,7 @@ public class DataAccess {
|
|||||||
} else if (type == int.class) {
|
} else if (type == int.class) {
|
||||||
final Integer tmp = rs.getInt(count.value);
|
final Integer tmp = rs.getInt(count.value);
|
||||||
if (rs.wasNull()) {
|
if (rs.wasNull()) {
|
||||||
//field.set(data, null);
|
// field.set(data, null);
|
||||||
} else {
|
} else {
|
||||||
field.setInt(data, tmp);
|
field.setInt(data, tmp);
|
||||||
countNotNull.inc();
|
countNotNull.inc();
|
||||||
@ -326,7 +324,7 @@ public class DataAccess {
|
|||||||
} else if (type == float.class) {
|
} else if (type == float.class) {
|
||||||
final Float tmp = rs.getFloat(count.value);
|
final Float tmp = rs.getFloat(count.value);
|
||||||
if (rs.wasNull()) {
|
if (rs.wasNull()) {
|
||||||
//field.set(data, null);
|
// field.set(data, null);
|
||||||
} else {
|
} else {
|
||||||
field.setFloat(data, tmp);
|
field.setFloat(data, tmp);
|
||||||
countNotNull.inc();
|
countNotNull.inc();
|
||||||
@ -342,7 +340,7 @@ public class DataAccess {
|
|||||||
} else if (type == double.class) {
|
} else if (type == double.class) {
|
||||||
final Double tmp = rs.getDouble(count.value);
|
final Double tmp = rs.getDouble(count.value);
|
||||||
if (rs.wasNull()) {
|
if (rs.wasNull()) {
|
||||||
//field.set(data, null);
|
// field.set(data, null);
|
||||||
} else {
|
} else {
|
||||||
field.setDouble(data, tmp);
|
field.setDouble(data, tmp);
|
||||||
countNotNull.inc();
|
countNotNull.inc();
|
||||||
@ -358,7 +356,7 @@ public class DataAccess {
|
|||||||
} else if (type == boolean.class) {
|
} else if (type == boolean.class) {
|
||||||
final Boolean tmp = rs.getBoolean(count.value);
|
final Boolean tmp = rs.getBoolean(count.value);
|
||||||
if (rs.wasNull()) {
|
if (rs.wasNull()) {
|
||||||
//field.set(data, null);
|
// field.set(data, null);
|
||||||
} else {
|
} else {
|
||||||
field.setBoolean(data, tmp);
|
field.setBoolean(data, tmp);
|
||||||
countNotNull.inc();
|
countNotNull.inc();
|
||||||
@ -448,7 +446,7 @@ public class DataAccess {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T> List<T> insertMultiple(final List<T> data, final QueryOptions options) throws Exception {
|
public static <T> List<T> insertMultiple(final List<T> data, final QueryOptions options) throws Exception {
|
||||||
final List<T> out = new ArrayList<>();
|
final List<T> out = new ArrayList<>();
|
||||||
for (final T elem : data) {
|
for (final T elem : data) {
|
||||||
@ -461,15 +459,15 @@ public class DataAccess {
|
|||||||
public static <T> T insert(final T data) throws Exception {
|
public static <T> T insert(final T data) throws Exception {
|
||||||
return insert(data, null);
|
return insert(data, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T> T insert(final T data, final QueryOptions options) throws Exception {
|
public static <T> T insert(final T data, final QueryOptions options) throws Exception {
|
||||||
final Class<?> clazz = data.getClass();
|
final Class<?> clazz = data.getClass();
|
||||||
|
|
||||||
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
// real add in the BDD:
|
// real add in the BDD:
|
||||||
try {
|
try {
|
||||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||||
//boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
|
// boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
|
||||||
final StringBuilder query = new StringBuilder();
|
final StringBuilder query = new StringBuilder();
|
||||||
query.append("INSERT INTO `");
|
query.append("INSERT INTO `");
|
||||||
query.append(tableName);
|
query.append(tableName);
|
||||||
@ -594,7 +592,7 @@ public class DataAccess {
|
|||||||
LOGGER.error("Can not manage the primary filed !!!");
|
LOGGER.error("Can not manage the primary filed !!!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//ps.execute();
|
// ps.execute();
|
||||||
} catch (final SQLException ex) {
|
} catch (final SQLException ex) {
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
} finally {
|
} finally {
|
||||||
@ -627,17 +625,15 @@ public class DataAccess {
|
|||||||
return new QueryCondition(AnnotationTools.getFieldName(idField), "=", idKey);
|
return new QueryCondition(AnnotationTools.getFieldName(idField), "=", idKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Update an object with the inserted json data
|
||||||
* Update an object with the inserted json data
|
|
||||||
*
|
*
|
||||||
* @param <T> Type of the object to insert
|
* @param <T> Type of the object to insert
|
||||||
* @param <ID_TYPE> Master key on the object manage with @Id
|
* @param <ID_TYPE> Master key on the object manage with @Id
|
||||||
* @param clazz Class reference of the insertion model
|
* @param clazz Class reference of the insertion model
|
||||||
* @param id Key to insert data
|
* @param id Key to insert data
|
||||||
* @param jsonData Json data (partial) values to update
|
* @param jsonData Json data (partial) values to update
|
||||||
* @return the number of object updated
|
* @return the number of object updated
|
||||||
* @throws Exception
|
* @throws Exception */
|
||||||
*/
|
|
||||||
public static <T, ID_TYPE> int updateWithJson(final Class<T> clazz, final ID_TYPE id, final String jsonData) throws Exception {
|
public static <T, ID_TYPE> int updateWithJson(final Class<T> clazz, final ID_TYPE id, final String jsonData) throws Exception {
|
||||||
return updateWhereWithJson(clazz, getTableIdCondition(clazz, id), jsonData);
|
return updateWhereWithJson(clazz, getTableIdCondition(clazz, id), jsonData);
|
||||||
}
|
}
|
||||||
@ -661,29 +657,26 @@ public class DataAccess {
|
|||||||
public static <T> int updateWhere(final T data, final QueryItem condition) throws Exception {
|
public static <T> int updateWhere(final T data, final QueryItem condition) throws Exception {
|
||||||
return updateWhere(data, condition, null, null);
|
return updateWhere(data, condition, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @param <T>
|
||||||
*
|
|
||||||
* @param <T>
|
|
||||||
* @param data
|
* @param data
|
||||||
* @param id
|
* @param id
|
||||||
* @param filterValue
|
* @param filterValue
|
||||||
* @return the affected rows.
|
* @return the affected rows.
|
||||||
* @throws Exception
|
* @throws Exception */
|
||||||
*/
|
|
||||||
public static <T, ID_TYPE> int update(final T data, final ID_TYPE id, final List<String> filterValue) throws Exception {
|
public static <T, ID_TYPE> int update(final T data, final ID_TYPE id, final List<String> filterValue) throws Exception {
|
||||||
return updateWhere(data, getTableIdCondition(data.getClass(), id), null, filterValue);
|
return updateWhere(data, getTableIdCondition(data.getClass(), id), null, filterValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T> int updateWhere(final T data, final QueryItem condition, final QueryOptions options, final List<String> filterValue) throws Exception {
|
public static <T> int updateWhere(final T data, final QueryItem condition, final QueryOptions options, final List<String> filterValue) throws Exception {
|
||||||
final Class<?> clazz = data.getClass();
|
final Class<?> clazz = data.getClass();
|
||||||
//public static NodeSmall createNode(String typeInNode, String name, String description, Long parentId) {
|
// public static NodeSmall createNode(String typeInNode, String name, String description, Long parentId) {
|
||||||
|
|
||||||
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
// real add in the BDD:
|
// real add in the BDD:
|
||||||
try {
|
try {
|
||||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||||
//boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
|
// boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
|
||||||
final StringBuilder query = new StringBuilder();
|
final StringBuilder query = new StringBuilder();
|
||||||
query.append("UPDATE `");
|
query.append("UPDATE `");
|
||||||
query.append(tableName);
|
query.append(tableName);
|
||||||
@ -761,7 +754,7 @@ public class DataAccess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
whereInjectValue(ps, condition, iii);
|
whereInjectValue(ps, condition, iii);
|
||||||
|
|
||||||
return ps.executeUpdate();
|
return ps.executeUpdate();
|
||||||
} catch (final SQLException ex) {
|
} catch (final SQLException ex) {
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
@ -830,7 +823,7 @@ public class DataAccess {
|
|||||||
}
|
}
|
||||||
query.append(" WHERE (");
|
query.append(" WHERE (");
|
||||||
condition.generateQuerry(query, tableName);
|
condition.generateQuerry(query, tableName);
|
||||||
|
|
||||||
query.append(") ");
|
query.append(") ");
|
||||||
if (exclude_deleted && deletedFieldName != null) {
|
if (exclude_deleted && deletedFieldName != null) {
|
||||||
query.append("AND ");
|
query.append("AND ");
|
||||||
@ -896,7 +889,7 @@ public class DataAccess {
|
|||||||
final boolean readAllfields = QueryOptions.readAllFields(options);
|
final boolean readAllfields = QueryOptions.readAllFields(options);
|
||||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||||
boolean firstField = true;
|
boolean firstField = true;
|
||||||
|
|
||||||
for (final Field elem : clazz.getFields()) {
|
for (final Field elem : clazz.getFields()) {
|
||||||
// static field is only for internal global declaration ==> remove it ..
|
// static field is only for internal global declaration ==> remove it ..
|
||||||
if (java.lang.reflect.Modifier.isStatic(elem.getModifiers())) {
|
if (java.lang.reflect.Modifier.isStatic(elem.getModifiers())) {
|
||||||
@ -1015,7 +1008,7 @@ public class DataAccess {
|
|||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO : detect the @Id
|
// TODO : detect the @Id
|
||||||
public static <T, ID_TYPE> T get(final Class<T> clazz, final ID_TYPE id) throws Exception {
|
public static <T, ID_TYPE> T get(final Class<T> clazz, final ID_TYPE id) throws Exception {
|
||||||
return get(clazz, id, null);
|
return get(clazz, id, null);
|
||||||
@ -1068,7 +1061,7 @@ public class DataAccess {
|
|||||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||||
final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
|
final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
|
||||||
// find the deleted field
|
// find the deleted field
|
||||||
|
|
||||||
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
final StringBuilder query = new StringBuilder();
|
final StringBuilder query = new StringBuilder();
|
||||||
query.append("DELETE FROM `");
|
query.append("DELETE FROM `");
|
||||||
@ -1101,12 +1094,7 @@ public class DataAccess {
|
|||||||
public static int deleteSoftWhere(final Class<?> clazz, final QueryItem condition, final QueryOptions options) throws Exception {
|
public static int deleteSoftWhere(final Class<?> clazz, final QueryItem condition, final QueryOptions options) throws Exception {
|
||||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||||
final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
|
final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
|
||||||
/*
|
/* String updateFieldName = null; if ("sqlite".equalsIgnoreCase(ConfigBaseVariable.getDBType())) { updateFieldName = AnnotationTools.getUpdatedFieldName(clazz); } */
|
||||||
String updateFieldName = null;
|
|
||||||
if ("sqlite".equalsIgnoreCase(ConfigBaseVariable.getDBType())) {
|
|
||||||
updateFieldName = AnnotationTools.getUpdatedFieldName(clazz);
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
// find the deleted field
|
// find the deleted field
|
||||||
|
|
||||||
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
@ -1116,15 +1104,8 @@ public class DataAccess {
|
|||||||
query.append("` SET `");
|
query.append("` SET `");
|
||||||
query.append(deletedFieldName);
|
query.append(deletedFieldName);
|
||||||
query.append("`=true ");
|
query.append("`=true ");
|
||||||
/*
|
/* The trigger work well, but the timestamp is store @ seconds... if (updateFieldName != null) { // done only in SQLite (the trigger does not work... query.append(", `");
|
||||||
* The trigger work well, but the timestamp is store @ seconds...
|
* query.append(updateFieldName); query.append("`=DATE()"); } */
|
||||||
if (updateFieldName != null) {
|
|
||||||
// done only in SQLite (the trigger does not work...
|
|
||||||
query.append(", `");
|
|
||||||
query.append(updateFieldName);
|
|
||||||
query.append("`=DATE()");
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
whereAppendQuery(query, tableName, condition, null, deletedFieldName);
|
whereAppendQuery(query, tableName, condition, null, deletedFieldName);
|
||||||
try {
|
try {
|
||||||
LOGGER.debug("APPLY UPDATE: {}", query.toString());
|
LOGGER.debug("APPLY UPDATE: {}", query.toString());
|
||||||
@ -1137,11 +1118,11 @@ public class DataAccess {
|
|||||||
entry = null;
|
entry = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <ID_TYPE> int unsetDelete(final Class<?> clazz, final ID_TYPE id) throws Exception {
|
public static <ID_TYPE> int unsetDelete(final Class<?> clazz, final ID_TYPE id) throws Exception {
|
||||||
return unsetDeleteWhere(clazz, getTableIdCondition(clazz, id), null);
|
return unsetDeleteWhere(clazz, getTableIdCondition(clazz, id), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <ID_TYPE> int unsetDelete(final Class<?> clazz, final ID_TYPE id, final QueryOptions options) throws Exception {
|
public static <ID_TYPE> int unsetDelete(final Class<?> clazz, final ID_TYPE id, final QueryOptions options) throws Exception {
|
||||||
return unsetDeleteWhere(clazz, getTableIdCondition(clazz, id), options);
|
return unsetDeleteWhere(clazz, getTableIdCondition(clazz, id), options);
|
||||||
}
|
}
|
||||||
@ -1159,12 +1140,7 @@ public class DataAccess {
|
|||||||
query.append("` SET `");
|
query.append("` SET `");
|
||||||
query.append(deletedFieldName);
|
query.append(deletedFieldName);
|
||||||
query.append("`=false ");
|
query.append("`=false ");
|
||||||
/*
|
/* is is needed only for SQLite ??? query.append("`modify_date`="); query.append(getDBNow()); query.append(", "); */
|
||||||
* is is needed only for SQLite ???
|
|
||||||
query.append("`modify_date`=");
|
|
||||||
query.append(getDBNow());
|
|
||||||
query.append(", ");
|
|
||||||
*/
|
|
||||||
// need to disable the deleted false because the model must be unselected to be updated.
|
// need to disable the deleted false because the model must be unselected to be updated.
|
||||||
options.put(QueryOptions.SQL_DELETED_DISABLE, true);
|
options.put(QueryOptions.SQL_DELETED_DISABLE, true);
|
||||||
whereAppendQuery(query, tableName, condition, options, deletedFieldName);
|
whereAppendQuery(query, tableName, condition, options, deletedFieldName);
|
||||||
@ -1178,5 +1154,5 @@ public class DataAccess {
|
|||||||
entry = null;
|
entry = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -9,39 +9,31 @@ import java.util.List;
|
|||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
|
||||||
public interface DataAccessAddOn {
|
public interface DataAccessAddOn {
|
||||||
/**
|
/** Get the Class of the declaration annotation
|
||||||
* Get the Class of the declaration annotation
|
* @return The annotation class */
|
||||||
* @return The annotation class
|
|
||||||
*/
|
|
||||||
Class<?> getAnnotationClass();
|
Class<?> getAnnotationClass();
|
||||||
|
|
||||||
/**
|
/** Get the SQL type that is needed to declare for the specific Field Type.
|
||||||
* Get the SQL type that is needed to declare for the specific Field Type.
|
|
||||||
* @param elem Field to declare.
|
* @param elem Field to declare.
|
||||||
* @return SQL type to create.
|
* @return SQL type to create. */
|
||||||
*/
|
|
||||||
String getSQLFieldType(Field elem) throws Exception;
|
String getSQLFieldType(Field elem) throws Exception;
|
||||||
|
|
||||||
/**
|
/** Check if the field is manage by the local add-on
|
||||||
* Check if the field is manage by the local add-on
|
|
||||||
* @param elem Field to inspect.
|
* @param elem Field to inspect.
|
||||||
* @return True of the field is manage by the current Add-on.
|
* @return True of the field is manage by the current Add-on. */
|
||||||
*/
|
|
||||||
boolean isCompatibleField(Field elem);
|
boolean isCompatibleField(Field elem);
|
||||||
|
|
||||||
/**
|
/** Insert data in the specific field (the field must be in the current db, otherwiise it does not work at all.
|
||||||
* Insert data in the specific field (the field must be in the current db, otherwiise it does not work at all.
|
|
||||||
* @param ps DB statement interface.
|
* @param ps DB statement interface.
|
||||||
* @param data The date to inject.
|
* @param data The date to inject.
|
||||||
* @param iii The index of injection
|
* @param iii The index of injection
|
||||||
* @return the new index of injection in case of multiple value management
|
* @return the new index of injection in case of multiple value management
|
||||||
* @throws SQLException
|
* @throws SQLException */
|
||||||
*/
|
|
||||||
void insertData(PreparedStatement ps, final Field field, Object data, CountInOut iii) throws Exception, SQLException, IllegalArgumentException, IllegalAccessException;
|
void insertData(PreparedStatement ps, final Field field, Object data, CountInOut iii) throws Exception, SQLException, IllegalArgumentException, IllegalAccessException;
|
||||||
|
|
||||||
// Element can insert in the single request
|
// Element can insert in the single request
|
||||||
boolean canInsert(final Field field);
|
boolean canInsert(final Field field);
|
||||||
|
|
||||||
// Element can be retrieve with the specific mode
|
// Element can be retrieve with the specific mode
|
||||||
boolean canRetrieve(final Field field);
|
boolean canRetrieve(final Field field);
|
||||||
|
|
||||||
@ -52,8 +44,7 @@ public interface DataAccessAddOn {
|
|||||||
void fillFromQuerry(ResultSet rs, Field field, Object data, CountInOut count, QueryOptions options, final List<LazyGetter> lazyCall)
|
void fillFromQuerry(ResultSet rs, Field field, Object data, CountInOut count, QueryOptions options, final List<LazyGetter> lazyCall)
|
||||||
throws Exception, SQLException, IllegalArgumentException, IllegalAccessException;
|
throws Exception, SQLException, IllegalArgumentException, IllegalAccessException;
|
||||||
|
|
||||||
/**
|
/** Create associated table of the specific element.
|
||||||
* Create associated table of the specific element.
|
|
||||||
* @param tableName
|
* @param tableName
|
||||||
* @param elem
|
* @param elem
|
||||||
* @param mainTableBuilder
|
* @param mainTableBuilder
|
||||||
@ -61,8 +52,7 @@ public interface DataAccessAddOn {
|
|||||||
* @param createIfNotExist
|
* @param createIfNotExist
|
||||||
* @param createDrop
|
* @param createDrop
|
||||||
* @param fieldId
|
* @param fieldId
|
||||||
* @throws Exception
|
* @throws Exception */
|
||||||
*/
|
|
||||||
void createTables(String tableName, Field field, StringBuilder mainTableBuilder, List<String> preActionList, List<String> postActionList, boolean createIfNotExist, boolean createDrop, int fieldId)
|
void createTables(String tableName, Field field, StringBuilder mainTableBuilder, List<String> preActionList, List<String> postActionList, boolean createIfNotExist, boolean createDrop, int fieldId)
|
||||||
throws Exception;
|
throws Exception;
|
||||||
|
|
||||||
|
@ -126,21 +126,21 @@ public class DataFactory {
|
|||||||
}
|
}
|
||||||
throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName());
|
throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void createTablesSpecificType(final String tableName, final Field elem, final StringBuilder mainTableBuilder, final List<String> preOtherTables, final List<String> postOtherTables,
|
public static void createTablesSpecificType(final String tableName, final Field elem, final StringBuilder mainTableBuilder, final List<String> preOtherTables, final List<String> postOtherTables,
|
||||||
final boolean createIfNotExist, final boolean createDrop, final int fieldId, final Class<?> classModel) throws Exception {
|
final boolean createIfNotExist, final boolean createDrop, final int fieldId, final Class<?> classModel) throws Exception {
|
||||||
final String name = AnnotationTools.getFieldName(elem);
|
final String name = AnnotationTools.getFieldName(elem);
|
||||||
final Integer limitSize = AnnotationTools.getLimitSize(elem);
|
final Integer limitSize = AnnotationTools.getLimitSize(elem);
|
||||||
final boolean notNull = AnnotationTools.getNotNull(elem);
|
final boolean notNull = AnnotationTools.getNotNull(elem);
|
||||||
|
|
||||||
final boolean primaryKey = AnnotationTools.isPrimaryKey(elem);
|
final boolean primaryKey = AnnotationTools.isPrimaryKey(elem);
|
||||||
final GenerationType strategy = AnnotationTools.getStrategy(elem);
|
final GenerationType strategy = AnnotationTools.getStrategy(elem);
|
||||||
|
|
||||||
final boolean createTime = elem.getDeclaredAnnotationsByType(CreationTimestamp.class).length != 0;
|
final boolean createTime = elem.getDeclaredAnnotationsByType(CreationTimestamp.class).length != 0;
|
||||||
final boolean updateTime = elem.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0;
|
final boolean updateTime = elem.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0;
|
||||||
final String comment = AnnotationTools.getComment(elem);
|
final String comment = AnnotationTools.getComment(elem);
|
||||||
final String defaultValue = AnnotationTools.getDefault(elem);
|
final String defaultValue = AnnotationTools.getDefault(elem);
|
||||||
|
|
||||||
if (fieldId == 0) {
|
if (fieldId == 0) {
|
||||||
mainTableBuilder.append("\n\t\t`");
|
mainTableBuilder.append("\n\t\t`");
|
||||||
} else {
|
} else {
|
||||||
@ -183,12 +183,7 @@ public class DataFactory {
|
|||||||
mainTableBuilder.append("(3)");
|
mainTableBuilder.append("(3)");
|
||||||
} else {
|
} else {
|
||||||
// TODO: add trigger:
|
// TODO: add trigger:
|
||||||
/*
|
/* CREATE TRIGGER your_table_trig AFTER UPDATE ON your_table BEGIN update your_table SET updated_on = datetime('now') WHERE user_id = NEW.user_id; END; */
|
||||||
CREATE TRIGGER your_table_trig AFTER UPDATE ON your_table
|
|
||||||
BEGIN
|
|
||||||
update your_table SET updated_on = datetime('now') WHERE user_id = NEW.user_id;
|
|
||||||
END;
|
|
||||||
*/
|
|
||||||
final StringBuilder triggerBuilder = new StringBuilder();
|
final StringBuilder triggerBuilder = new StringBuilder();
|
||||||
triggerBuilder.append("CREATE TRIGGER ");
|
triggerBuilder.append("CREATE TRIGGER ");
|
||||||
triggerBuilder.append(tableName);
|
triggerBuilder.append(tableName);
|
||||||
@ -200,10 +195,10 @@ public class DataFactory {
|
|||||||
triggerBuilder.append(name);
|
triggerBuilder.append(name);
|
||||||
triggerBuilder.append(" = datetime('now') WHERE id = NEW.id; \n");
|
triggerBuilder.append(" = datetime('now') WHERE id = NEW.id; \n");
|
||||||
triggerBuilder.append("END;");
|
triggerBuilder.append("END;");
|
||||||
|
|
||||||
postOtherTables.add(triggerBuilder.toString());
|
postOtherTables.add(triggerBuilder.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
mainTableBuilder.append(" ");
|
mainTableBuilder.append(" ");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -238,11 +233,11 @@ public class DataFactory {
|
|||||||
mainTableBuilder.append("DEFAULT ");
|
mainTableBuilder.append("DEFAULT ");
|
||||||
mainTableBuilder.append(defaultValue);
|
mainTableBuilder.append(defaultValue);
|
||||||
mainTableBuilder.append(" ");
|
mainTableBuilder.append(" ");
|
||||||
|
|
||||||
}
|
}
|
||||||
if (primaryKey && "sqlite".equals(ConfigBaseVariable.getDBType())) {
|
if (primaryKey && "sqlite".equals(ConfigBaseVariable.getDBType())) {
|
||||||
mainTableBuilder.append("PRIMARY KEY ");
|
mainTableBuilder.append("PRIMARY KEY ");
|
||||||
|
|
||||||
}
|
}
|
||||||
if (strategy == GenerationType.IDENTITY) {
|
if (strategy == GenerationType.IDENTITY) {
|
||||||
if (!"sqlite".equals(ConfigBaseVariable.getDBType())) {
|
if (!"sqlite".equals(ConfigBaseVariable.getDBType())) {
|
||||||
@ -253,14 +248,14 @@ public class DataFactory {
|
|||||||
} else if (strategy != null) {
|
} else if (strategy != null) {
|
||||||
throw new DataAccessException("Can not generate a stategy different of IDENTITY");
|
throw new DataAccessException("Can not generate a stategy different of IDENTITY");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (comment != null && !"sqlite".equals(ConfigBaseVariable.getDBType())) {
|
if (comment != null && !"sqlite".equals(ConfigBaseVariable.getDBType())) {
|
||||||
mainTableBuilder.append("COMMENT '");
|
mainTableBuilder.append("COMMENT '");
|
||||||
mainTableBuilder.append(comment.replace('\'', '\''));
|
mainTableBuilder.append(comment.replace('\'', '\''));
|
||||||
mainTableBuilder.append("' ");
|
mainTableBuilder.append("' ");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean isFieldFromSuperClass(final Class<?> model, final String filedName) {
|
private static boolean isFieldFromSuperClass(final Class<?> model, final String filedName) {
|
||||||
final Class<?> superClass = model.getSuperclass();
|
final Class<?> superClass = model.getSuperclass();
|
||||||
if (superClass == null) {
|
if (superClass == null) {
|
||||||
@ -280,14 +275,14 @@ public class DataFactory {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<String> createTable(final Class<?> clazz) throws Exception {
|
public static List<String> createTable(final Class<?> clazz) throws Exception {
|
||||||
return createTable(clazz, null);
|
return createTable(clazz, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<String> createTable(final Class<?> clazz, final QueryOptions options) throws Exception {
|
public static List<String> createTable(final Class<?> clazz, final QueryOptions options) throws Exception {
|
||||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||||
|
|
||||||
boolean createDrop = false;
|
boolean createDrop = false;
|
||||||
if (options != null) {
|
if (options != null) {
|
||||||
final Object data = options.get(QueryOptions.CREATE_DROP_TABLE);
|
final Object data = options.get(QueryOptions.CREATE_DROP_TABLE);
|
||||||
@ -297,7 +292,7 @@ public class DataFactory {
|
|||||||
LOGGER.error("'{}' ==> has not a Boolean value: {}", QueryOptions.CREATE_DROP_TABLE, data);
|
LOGGER.error("'{}' ==> has not a Boolean value: {}", QueryOptions.CREATE_DROP_TABLE, data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(DataIfNotExists.class).length != 0;
|
final boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(DataIfNotExists.class).length != 0;
|
||||||
final List<String> preActionList = new ArrayList<>();
|
final List<String> preActionList = new ArrayList<>();
|
||||||
final List<String> postActionList = new ArrayList<>();
|
final List<String> postActionList = new ArrayList<>();
|
||||||
@ -317,7 +312,7 @@ public class DataFactory {
|
|||||||
int fieldId = 0;
|
int fieldId = 0;
|
||||||
LOGGER.debug("===> TABLE `{}`", tableName);
|
LOGGER.debug("===> TABLE `{}`", tableName);
|
||||||
final List<String> primaryKeys = new ArrayList<>();
|
final List<String> primaryKeys = new ArrayList<>();
|
||||||
|
|
||||||
for (final Field elem : clazz.getFields()) {
|
for (final Field elem : clazz.getFields()) {
|
||||||
// DEtect the primary key (support only one primary key right now...
|
// DEtect the primary key (support only one primary key right now...
|
||||||
if (AnnotationTools.isPrimaryKey(elem)) {
|
if (AnnotationTools.isPrimaryKey(elem)) {
|
||||||
@ -398,5 +393,5 @@ public class DataFactory {
|
|||||||
preActionList.addAll(postActionList);
|
preActionList.addAll(postActionList);
|
||||||
return preActionList;
|
return preActionList;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -5,12 +5,12 @@ package org.kar.archidata.dataAccess;
|
|||||||
public class Foreign<T> {
|
public class Foreign<T> {
|
||||||
public final Long id;
|
public final Long id;
|
||||||
public final T data;
|
public final T data;
|
||||||
|
|
||||||
public Foreign(final Long id) {
|
public Foreign(final Long id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.data = null;
|
this.data = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Foreign(final T data) {
|
public Foreign(final T data) {
|
||||||
this.id = null;
|
this.id = null;
|
||||||
this.data = data;
|
this.data = data;
|
||||||
|
@ -12,32 +12,32 @@ public class QueryOptions {
|
|||||||
public static final String SQL_DELETED_DISABLE = "SQLDeleted_disable";
|
public static final String SQL_DELETED_DISABLE = "SQLDeleted_disable";
|
||||||
public static final String OVERRIDE_TABLE_NAME = "SQL_OVERRIDE_TABLE_NAME";
|
public static final String OVERRIDE_TABLE_NAME = "SQL_OVERRIDE_TABLE_NAME";
|
||||||
public static final String CREATE_DROP_TABLE = "CREATE_DROP_TABLE";
|
public static final String CREATE_DROP_TABLE = "CREATE_DROP_TABLE";
|
||||||
|
|
||||||
private final Map<String, Object> options = new HashMap<>();
|
private final Map<String, Object> options = new HashMap<>();
|
||||||
|
|
||||||
public QueryOptions() {
|
public QueryOptions() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public QueryOptions(final String key, final Object value) {
|
public QueryOptions(final String key, final Object value) {
|
||||||
this.options.put(key, value);
|
this.options.put(key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public QueryOptions(final String key, final Object value, final String key2, final Object value2) {
|
public QueryOptions(final String key, final Object value, final String key2, final Object value2) {
|
||||||
this.options.put(key, value);
|
this.options.put(key, value);
|
||||||
this.options.put(key2, value2);
|
this.options.put(key2, value2);
|
||||||
}
|
}
|
||||||
|
|
||||||
public QueryOptions(final String key, final Object value, final String key2, final Object value2, final String key3, final Object value3) {
|
public QueryOptions(final String key, final Object value, final String key2, final Object value2, final String key3, final Object value3) {
|
||||||
this.options.put(key, value);
|
this.options.put(key, value);
|
||||||
this.options.put(key2, value2);
|
this.options.put(key2, value2);
|
||||||
this.options.put(key3, value3);
|
this.options.put(key3, value3);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void put(final String key, final Object value) {
|
public void put(final String key, final Object value) {
|
||||||
this.options.put(key, value);
|
this.options.put(key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Object get(final String value) {
|
public Object get(final String value) {
|
||||||
return this.options.get(value);
|
return this.options.get(value);
|
||||||
}
|
}
|
||||||
@ -53,5 +53,5 @@ public class QueryOptions {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -5,11 +5,11 @@ import java.util.List;
|
|||||||
|
|
||||||
public class QueryOr implements QueryItem {
|
public class QueryOr implements QueryItem {
|
||||||
protected final List<QueryItem> childs;
|
protected final List<QueryItem> childs;
|
||||||
|
|
||||||
public QueryOr(final List<QueryItem> childs) {
|
public QueryOr(final List<QueryItem> childs) {
|
||||||
this.childs = childs;
|
this.childs = childs;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void generateQuerry(final StringBuilder querry, final String tableName) {
|
public void generateQuerry(final StringBuilder querry, final String tableName) {
|
||||||
if (this.childs.size() >= 1) {
|
if (this.childs.size() >= 1) {
|
||||||
@ -28,7 +28,7 @@ public class QueryOr implements QueryItem {
|
|||||||
querry.append(")");
|
querry.append(")");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void injectQuerry(final PreparedStatement ps, final CountInOut iii) throws Exception {
|
public void injectQuerry(final PreparedStatement ps, final CountInOut iii) throws Exception {
|
||||||
for (final QueryItem elem : this.childs) {
|
for (final QueryItem elem : this.childs) {
|
||||||
|
@ -23,24 +23,24 @@ import jakarta.validation.constraints.NotNull;
|
|||||||
|
|
||||||
public class AddOnDataJson implements DataAccessAddOn {
|
public class AddOnDataJson implements DataAccessAddOn {
|
||||||
static final Logger LOGGER = LoggerFactory.getLogger(AddOnDataJson.class);
|
static final Logger LOGGER = LoggerFactory.getLogger(AddOnDataJson.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Class<?> getAnnotationClass() {
|
public Class<?> getAnnotationClass() {
|
||||||
return DataJson.class;
|
return DataJson.class;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getSQLFieldType(final Field elem) throws Exception {
|
public String getSQLFieldType(final Field elem) throws Exception {
|
||||||
final String fieldName = AnnotationTools.getFieldName(elem);
|
final String fieldName = AnnotationTools.getFieldName(elem);
|
||||||
return DataFactory.convertTypeInSQL(String.class, fieldName);
|
return DataFactory.convertTypeInSQL(String.class, fieldName);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isCompatibleField(final Field elem) {
|
public boolean isCompatibleField(final Field elem) {
|
||||||
final DataJson decorators = elem.getDeclaredAnnotation(DataJson.class);
|
final DataJson decorators = elem.getDeclaredAnnotation(DataJson.class);
|
||||||
return decorators != null;
|
return decorators != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) throws Exception {
|
public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) throws Exception {
|
||||||
final Object data = field.get(rootObject);
|
final Object data = field.get(rootObject);
|
||||||
@ -52,17 +52,17 @@ public class AddOnDataJson implements DataAccessAddOn {
|
|||||||
ps.setString(iii.value, dataString);
|
ps.setString(iii.value, dataString);
|
||||||
iii.inc();
|
iii.inc();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canInsert(final Field field) {
|
public boolean canInsert(final Field field) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canRetrieve(final Field field) {
|
public boolean canRetrieve(final Field field) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void generateQuerry(@NotNull final String tableName, @NotNull final Field field, @NotNull final StringBuilder querrySelect, @NotNull final StringBuilder querry, @NotNull final String name,
|
public void generateQuerry(@NotNull final String tableName, @NotNull final Field field, @NotNull final StringBuilder querrySelect, @NotNull final StringBuilder querry, @NotNull final String name,
|
||||||
@NotNull final CountInOut elemCount, final QueryOptions options) throws Exception {
|
@NotNull final CountInOut elemCount, final QueryOptions options) throws Exception {
|
||||||
@ -73,7 +73,7 @@ public class AddOnDataJson implements DataAccessAddOn {
|
|||||||
elemCount.inc();
|
elemCount.inc();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void fillFromQuerry(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List<LazyGetter> lazyCall) throws Exception {
|
public void fillFromQuerry(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List<LazyGetter> lazyCall) throws Exception {
|
||||||
final String jsonData = rs.getString(count.value);
|
final String jsonData = rs.getString(count.value);
|
||||||
@ -84,7 +84,7 @@ public class AddOnDataJson implements DataAccessAddOn {
|
|||||||
field.set(data, dataParsed);
|
field.set(data, dataParsed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void createTables(final String tableName, final Field field, final StringBuilder mainTableBuilder, final List<String> preActionList, final List<String> postActionList,
|
public void createTables(final String tableName, final Field field, final StringBuilder mainTableBuilder, final List<String> preActionList, final List<String> postActionList,
|
||||||
final boolean createIfNotExist, final boolean createDrop, final int fieldId) throws Exception {
|
final boolean createIfNotExist, final boolean createDrop, final int fieldId) throws Exception {
|
||||||
|
@ -32,43 +32,43 @@ import jakarta.validation.constraints.NotNull;
|
|||||||
public class AddOnManyToMany implements DataAccessAddOn {
|
public class AddOnManyToMany implements DataAccessAddOn {
|
||||||
static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class);
|
static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class);
|
||||||
static final String SEPARATOR = "-";
|
static final String SEPARATOR = "-";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Class<?> getAnnotationClass() {
|
public Class<?> getAnnotationClass() {
|
||||||
return ManyToMany.class;
|
return ManyToMany.class;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getSQLFieldType(final Field elem) {
|
public String getSQLFieldType(final Field elem) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isCompatibleField(final Field elem) {
|
public boolean isCompatibleField(final Field elem) {
|
||||||
final ManyToMany decorators = elem.getDeclaredAnnotation(ManyToMany.class);
|
final ManyToMany decorators = elem.getDeclaredAnnotation(ManyToMany.class);
|
||||||
return decorators != null;
|
return decorators != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) throws SQLException, IllegalArgumentException, IllegalAccessException {
|
public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) throws SQLException, IllegalArgumentException, IllegalAccessException {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canInsert(final Field field) {
|
public boolean canInsert(final Field field) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canRetrieve(final Field field) {
|
public boolean canRetrieve(final Field field) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String generateLinkTableNameField(final String tableName, final Field field) throws Exception {
|
public static String generateLinkTableNameField(final String tableName, final Field field) throws Exception {
|
||||||
final String name = AnnotationTools.getFieldName(field);
|
final String name = AnnotationTools.getFieldName(field);
|
||||||
return generateLinkTableName(tableName, name);
|
return generateLinkTableName(tableName, name);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String generateLinkTableName(final String tableName, final String name) {
|
public static String generateLinkTableName(final String tableName, final String name) {
|
||||||
String localName = name;
|
String localName = name;
|
||||||
if (name.endsWith("s")) {
|
if (name.endsWith("s")) {
|
||||||
@ -76,7 +76,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
|
|||||||
}
|
}
|
||||||
return tableName + "_link_" + localName;
|
return tableName + "_link_" + localName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void generateConcatQuerry(@NotNull final String tableName, @NotNull final Field field, @NotNull final StringBuilder querrySelect, @NotNull final StringBuilder querry,
|
public void generateConcatQuerry(@NotNull final String tableName, @NotNull final Field field, @NotNull final StringBuilder querrySelect, @NotNull final StringBuilder querry,
|
||||||
@NotNull final String name, @NotNull final CountInOut elemCount, final QueryOptions options) {
|
@NotNull final String name, @NotNull final CountInOut elemCount, final QueryOptions options) {
|
||||||
|
|
||||||
@ -112,16 +112,11 @@ public class AddOnManyToMany implements DataAccessAddOn {
|
|||||||
querrySelect.append(") AS ");
|
querrySelect.append(") AS ");
|
||||||
querrySelect.append(name);
|
querrySelect.append(name);
|
||||||
querrySelect.append(" ");
|
querrySelect.append(" ");
|
||||||
/*
|
/* " (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" + " FROM cover_link_node tmp" + " WHERE tmp.deleted = false" +
|
||||||
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
|
* " AND node.id = tmp.node_id" + " GROUP BY tmp.node_id) AS covers" + */
|
||||||
" FROM cover_link_node tmp" +
|
|
||||||
" WHERE tmp.deleted = false" +
|
|
||||||
" AND node.id = tmp.node_id" +
|
|
||||||
" GROUP BY tmp.node_id) AS covers" +
|
|
||||||
*/
|
|
||||||
elemCount.inc();
|
elemCount.inc();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void generateQuerry(@NotNull final String tableName, @NotNull final Field field, @NotNull final StringBuilder querrySelect, @NotNull final StringBuilder querry, @NotNull final String name,
|
public void generateQuerry(@NotNull final String tableName, @NotNull final Field field, @NotNull final StringBuilder querrySelect, @NotNull final StringBuilder querry, @NotNull final String name,
|
||||||
@NotNull final CountInOut elemCount, final QueryOptions options) throws Exception {
|
@NotNull final CountInOut elemCount, final QueryOptions options) throws Exception {
|
||||||
@ -144,7 +139,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void fillFromQuerry(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List<LazyGetter> lazyCall) throws Exception {
|
public void fillFromQuerry(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List<LazyGetter> lazyCall) throws Exception {
|
||||||
if (field.getType() != List.class) {
|
if (field.getType() != List.class) {
|
||||||
@ -165,7 +160,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
|
|||||||
throw new DataAccessException("EAGER is not supported for list of element...");
|
throw new DataAccessException("EAGER is not supported for list of element...");
|
||||||
} else {
|
} else {
|
||||||
final List<Long> idList = DataAccess.getListOfIds(rs, count.value, SEPARATOR);
|
final List<Long> idList = DataAccess.getListOfIds(rs, count.value, SEPARATOR);
|
||||||
//field.set(data, idList);
|
// field.set(data, idList);
|
||||||
count.inc();
|
count.inc();
|
||||||
if (idList != null && idList.size() > 0) {
|
if (idList != null && idList.size() > 0) {
|
||||||
final String idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass));
|
final String idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass));
|
||||||
@ -187,16 +182,16 @@ public class AddOnManyToMany implements DataAccessAddOn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void addLink(final Class<?> clazz, final long localKey, final String column, final long remoteKey) throws Exception {
|
public static void addLink(final Class<?> clazz, final long localKey, final String column, final long remoteKey) throws Exception {
|
||||||
final String tableName = AnnotationTools.getTableName(clazz);
|
final String tableName = AnnotationTools.getTableName(clazz);
|
||||||
final String linkTableName = generateLinkTableName(tableName, column);
|
final String linkTableName = generateLinkTableName(tableName, column);
|
||||||
final LinkTable insertElement = new LinkTable(localKey, remoteKey);
|
final LinkTable insertElement = new LinkTable(localKey, remoteKey);
|
||||||
final QueryOptions options = new QueryOptions(QueryOptions.OVERRIDE_TABLE_NAME, linkTableName);
|
final QueryOptions options = new QueryOptions(QueryOptions.OVERRIDE_TABLE_NAME, linkTableName);
|
||||||
DataAccess.insert(insertElement, options);
|
DataAccess.insert(insertElement, options);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int removeLink(final Class<?> clazz, final long localKey, final String column, final long remoteKey) throws Exception {
|
public static int removeLink(final Class<?> clazz, final long localKey, final String column, final long remoteKey) throws Exception {
|
||||||
final String tableName = AnnotationTools.getTableName(clazz);
|
final String tableName = AnnotationTools.getTableName(clazz);
|
||||||
final String linkTableName = generateLinkTableName(tableName, column);
|
final String linkTableName = generateLinkTableName(tableName, column);
|
||||||
@ -204,7 +199,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
|
|||||||
final QueryAnd condition = new QueryAnd(new QueryCondition("object1Id", "=", localKey), new QueryCondition("object2Id", "=", remoteKey));
|
final QueryAnd condition = new QueryAnd(new QueryCondition("object1Id", "=", localKey), new QueryCondition("object2Id", "=", remoteKey));
|
||||||
return DataAccess.deleteWhere(LinkTable.class, condition, options);
|
return DataAccess.deleteWhere(LinkTable.class, condition, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void createTables(final String tableName, final Field field, final StringBuilder mainTableBuilder, final List<String> preActionList, final List<String> postActionList,
|
public void createTables(final String tableName, final Field field, final StringBuilder mainTableBuilder, final List<String> preActionList, final List<String> postActionList,
|
||||||
final boolean createIfNotExist, final boolean createDrop, final int fieldId) throws Exception {
|
final boolean createIfNotExist, final boolean createDrop, final int fieldId) throws Exception {
|
||||||
|
@ -132,11 +132,7 @@ public class AddOnManyToOne implements DataAccessAddOn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/* SELECT k.id, r.id FROM `right` k LEFT OUTER JOIN `rightDescription` r ON k.rightDescriptionId=r.id */
|
||||||
SELECT k.id, r.id
|
|
||||||
FROM `right` k
|
|
||||||
LEFT OUTER JOIN `rightDescription` r ON k.rightDescriptionId=r.id
|
|
||||||
*/
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -24,23 +24,19 @@ import jakarta.validation.constraints.NotNull;
|
|||||||
public class AddOnOneToMany implements DataAccessAddOn {
|
public class AddOnOneToMany implements DataAccessAddOn {
|
||||||
static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class);
|
static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class);
|
||||||
|
|
||||||
/**
|
/** Convert the list if external id in a string '-' separated
|
||||||
* Convert the list if external id in a string '-' separated
|
|
||||||
* @param ids List of value (null are removed)
|
* @param ids List of value (null are removed)
|
||||||
* @return '-' string separated
|
* @return '-' string separated */
|
||||||
*/
|
|
||||||
protected static String getStringOfIds(final List<Long> ids) {
|
protected static String getStringOfIds(final List<Long> ids) {
|
||||||
final List<Long> tmp = new ArrayList<>(ids);
|
final List<Long> tmp = new ArrayList<>(ids);
|
||||||
return tmp.stream().map(String::valueOf).collect(Collectors.joining("-"));
|
return tmp.stream().map(String::valueOf).collect(Collectors.joining("-"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** extract a list of "-" separated element from a SQL input data.
|
||||||
* extract a list of "-" separated element from a SQL input data.
|
|
||||||
* @param rs Result Set of the BDD
|
* @param rs Result Set of the BDD
|
||||||
* @param iii Id in the result set
|
* @param iii Id in the result set
|
||||||
* @return The list of Long value
|
* @return The list of Long value
|
||||||
* @throws SQLException if an error is generated in the sql request.
|
* @throws SQLException if an error is generated in the sql request. */
|
||||||
*/
|
|
||||||
protected static List<Long> getListOfIds(final ResultSet rs, final int iii) throws SQLException {
|
protected static List<Long> getListOfIds(final ResultSet rs, final int iii) throws SQLException {
|
||||||
final String trackString = rs.getString(iii);
|
final String trackString = rs.getString(iii);
|
||||||
if (rs.wasNull()) {
|
if (rs.wasNull()) {
|
||||||
@ -95,7 +91,7 @@ public class AddOnOneToMany implements DataAccessAddOn {
|
|||||||
public boolean canInsert(final Field field) {
|
public boolean canInsert(final Field field) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canRetrieve(final Field field) {
|
public boolean canRetrieve(final Field field) {
|
||||||
return false;
|
return false;
|
||||||
@ -117,7 +113,7 @@ public class AddOnOneToMany implements DataAccessAddOn {
|
|||||||
final Long foreignKey = rs.getLong(count.value);
|
final Long foreignKey = rs.getLong(count.value);
|
||||||
count.inc();
|
count.inc();
|
||||||
if (!rs.wasNull()) {
|
if (!rs.wasNull()) {
|
||||||
|
|
||||||
field.set(data, foreignKey);
|
field.set(data, foreignKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,22 +25,20 @@ import jakarta.validation.constraints.NotNull;
|
|||||||
public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn {
|
public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn {
|
||||||
static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class);
|
static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class);
|
||||||
static final String SEPARATOR = "-";
|
static final String SEPARATOR = "-";
|
||||||
|
|
||||||
/**
|
/** Convert the list if external id in a string '-' separated
|
||||||
* Convert the list if external id in a string '-' separated
|
|
||||||
* @param ids List of value (null are removed)
|
* @param ids List of value (null are removed)
|
||||||
* @return '-' string separated
|
* @return '-' string separated */
|
||||||
*/
|
|
||||||
protected static String getStringOfIds(final List<Long> ids) {
|
protected static String getStringOfIds(final List<Long> ids) {
|
||||||
final List<Long> tmp = new ArrayList<>(ids);
|
final List<Long> tmp = new ArrayList<>(ids);
|
||||||
return tmp.stream().map(String::valueOf).collect(Collectors.joining(SEPARATOR));
|
return tmp.stream().map(String::valueOf).collect(Collectors.joining(SEPARATOR));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Class<?> getAnnotationClass() {
|
public Class<?> getAnnotationClass() {
|
||||||
return SQLTableExternalForeinKeyAsList.class;
|
return SQLTableExternalForeinKeyAsList.class;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getSQLFieldType(final Field field) throws Exception {
|
public String getSQLFieldType(final Field field) throws Exception {
|
||||||
final String fieldName = AnnotationTools.getFieldName(field);
|
final String fieldName = AnnotationTools.getFieldName(field);
|
||||||
@ -52,13 +50,13 @@ public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isCompatibleField(final Field field) {
|
public boolean isCompatibleField(final Field field) {
|
||||||
final SQLTableExternalForeinKeyAsList decorators = field.getDeclaredAnnotation(SQLTableExternalForeinKeyAsList.class);
|
final SQLTableExternalForeinKeyAsList decorators = field.getDeclaredAnnotation(SQLTableExternalForeinKeyAsList.class);
|
||||||
return decorators != null;
|
return decorators != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) throws SQLException, IllegalArgumentException, IllegalAccessException {
|
public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) throws SQLException, IllegalArgumentException, IllegalAccessException {
|
||||||
final Object data = field.get(rootObject);
|
final Object data = field.get(rootObject);
|
||||||
@ -71,17 +69,17 @@ public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn {
|
|||||||
ps.setString(iii.value, dataTmp);
|
ps.setString(iii.value, dataTmp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canInsert(final Field field) {
|
public boolean canInsert(final Field field) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canRetrieve(final Field field) {
|
public boolean canRetrieve(final Field field) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void generateQuerry(@NotNull final String tableName, @NotNull final Field field, @NotNull final StringBuilder querrySelect, @NotNull final StringBuilder querry, @NotNull final String name,
|
public void generateQuerry(@NotNull final String tableName, @NotNull final Field field, @NotNull final StringBuilder querrySelect, @NotNull final StringBuilder querry, @NotNull final String name,
|
||||||
@NotNull final CountInOut elemCount, final QueryOptions options) {
|
@NotNull final CountInOut elemCount, final QueryOptions options) {
|
||||||
@ -91,7 +89,7 @@ public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn {
|
|||||||
querrySelect.append(".");
|
querrySelect.append(".");
|
||||||
querrySelect.append(name);
|
querrySelect.append(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void fillFromQuerry(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List<LazyGetter> lazyCall)
|
public void fillFromQuerry(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List<LazyGetter> lazyCall)
|
||||||
throws SQLException, IllegalArgumentException, IllegalAccessException {
|
throws SQLException, IllegalArgumentException, IllegalAccessException {
|
||||||
@ -99,12 +97,12 @@ public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn {
|
|||||||
field.set(data, idList);
|
field.set(data, idList);
|
||||||
count.inc();
|
count.inc();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void createTables(final String tableName, final Field field, final StringBuilder mainTableBuilder, final List<String> preActionList, final List<String> postActionList,
|
public void createTables(final String tableName, final Field field, final StringBuilder mainTableBuilder, final List<String> preActionList, final List<String> postActionList,
|
||||||
final boolean createIfNotExist, final boolean createDrop, final int fieldId) throws Exception {
|
final boolean createIfNotExist, final boolean createDrop, final int fieldId) throws Exception {
|
||||||
// TODO Auto-generated method stub
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, createIfNotExist, createDrop, fieldId, String.class);
|
DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, createIfNotExist, createDrop, fieldId, String.class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,12 +9,12 @@ public class LinkTable extends GenericDataSoftDelete {
|
|||||||
public LinkTable() {
|
public LinkTable() {
|
||||||
// nothing to do...
|
// nothing to do...
|
||||||
}
|
}
|
||||||
|
|
||||||
public LinkTable(final long object1Id, final long object2Id) {
|
public LinkTable(final long object1Id, final long object2Id) {
|
||||||
this.object1Id = object1Id;
|
this.object1Id = object1Id;
|
||||||
this.object2Id = object2Id;
|
this.object2Id = object2Id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@DataComment("Object reference 1")
|
@DataComment("Object reference 1")
|
||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
public Long object1Id;
|
public Long object1Id;
|
||||||
|
@ -13,8 +13,8 @@ public class DBConfig {
|
|||||||
private final String password;
|
private final String password;
|
||||||
private final String dbName;
|
private final String dbName;
|
||||||
private final boolean keepConnected;
|
private final boolean keepConnected;
|
||||||
|
|
||||||
public DBConfig(String type, String hostname, Integer port, String login, String password, String dbName, boolean keepConnected) {
|
public DBConfig(final String type, final String hostname, final Integer port, final String login, final String password, final String dbName, final boolean keepConnected) {
|
||||||
if (type == null) {
|
if (type == null) {
|
||||||
this.type = "mysql";
|
this.type = "mysql";
|
||||||
} else {
|
} else {
|
||||||
@ -35,43 +35,44 @@ public class DBConfig {
|
|||||||
this.dbName = dbName;
|
this.dbName = dbName;
|
||||||
this.keepConnected = keepConnected;
|
this.keepConnected = keepConnected;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "DBConfig{type='" + type + '\'' + ", hostname='" + hostname + '\'' + ", port=" + port + ", login='" + login + '\'' + ", password='" + password + '\'' + ", dbName='" + dbName + "' }";
|
return "DBConfig{type='" + this.type + '\'' + ", hostname='" + this.hostname + '\'' + ", port=" + this.port + ", login='" + this.login + '\'' + ", password='" + this.password + '\''
|
||||||
|
+ ", dbName='" + this.dbName + "' }";
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getHostname() {
|
public String getHostname() {
|
||||||
return hostname;
|
return this.hostname;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getPort() {
|
public int getPort() {
|
||||||
return port;
|
return this.port;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getLogin() {
|
public String getLogin() {
|
||||||
return login;
|
return this.login;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPassword() {
|
public String getPassword() {
|
||||||
return password;
|
return this.password;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDbName() {
|
public String getDbName() {
|
||||||
return dbName;
|
return this.dbName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean getKeepConnected() {
|
public boolean getKeepConnected() {
|
||||||
return keepConnected;
|
return this.keepConnected;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUrl() {
|
public String getUrl() {
|
||||||
return getUrl(false);
|
return getUrl(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getUrl(boolean isRoot) {
|
public String getUrl(final boolean isRoot) {
|
||||||
if (type.equals("sqlite")) {
|
if (this.type.equals("sqlite")) {
|
||||||
if (isRoot == true) {
|
if (isRoot) {
|
||||||
LOGGER.error("Can not manage root connection on SQLite...");
|
LOGGER.error("Can not manage root connection on SQLite...");
|
||||||
}
|
}
|
||||||
if (this.hostname.equals("memory")) {
|
if (this.hostname.equals("memory")) {
|
||||||
|
@ -16,7 +16,7 @@ public class DBEntry implements Closeable {
|
|||||||
public DBConfig config;
|
public DBConfig config;
|
||||||
public Connection connection;
|
public Connection connection;
|
||||||
private static List<DBEntry> stored = new ArrayList<>();
|
private static List<DBEntry> stored = new ArrayList<>();
|
||||||
|
|
||||||
private DBEntry(final DBConfig config, final boolean root) throws IOException {
|
private DBEntry(final DBConfig config, final boolean root) throws IOException {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
if (root) {
|
if (root) {
|
||||||
@ -25,11 +25,11 @@ public class DBEntry implements Closeable {
|
|||||||
connect();
|
connect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static DBEntry createInterface(final DBConfig config) throws IOException {
|
public static DBEntry createInterface(final DBConfig config) throws IOException {
|
||||||
return createInterface(config, false);
|
return createInterface(config, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static DBEntry createInterface(final DBConfig config, final boolean root) throws IOException {
|
public static DBEntry createInterface(final DBConfig config, final boolean root) throws IOException {
|
||||||
if (config.getKeepConnected()) {
|
if (config.getKeepConnected()) {
|
||||||
for (final DBEntry elem : stored) {
|
for (final DBEntry elem : stored) {
|
||||||
@ -47,25 +47,25 @@ public class DBEntry implements Closeable {
|
|||||||
return new DBEntry(config, root);
|
return new DBEntry(config, root);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void connectRoot() throws IOException {
|
public void connectRoot() throws IOException {
|
||||||
try {
|
try {
|
||||||
this.connection = DriverManager.getConnection(this.config.getUrl(true), this.config.getLogin(), this.config.getPassword());
|
this.connection = DriverManager.getConnection(this.config.getUrl(true), this.config.getLogin(), this.config.getPassword());
|
||||||
} catch (final SQLException ex) {
|
} catch (final SQLException ex) {
|
||||||
throw new IOException("Connection db fail: " + ex.getMessage());
|
throw new IOException("Connection db fail: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void connect() throws IOException {
|
public void connect() throws IOException {
|
||||||
try {
|
try {
|
||||||
this.connection = DriverManager.getConnection(this.config.getUrl(), this.config.getLogin(), this.config.getPassword());
|
this.connection = DriverManager.getConnection(this.config.getUrl(), this.config.getLogin(), this.config.getPassword());
|
||||||
} catch (final SQLException ex) {
|
} catch (final SQLException ex) {
|
||||||
throw new IOException("Connection db fail: " + ex.getMessage());
|
throw new IOException("Connection db fail: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
if (this.config.getKeepConnected()) {
|
if (this.config.getKeepConnected()) {
|
||||||
@ -73,16 +73,16 @@ public class DBEntry implements Closeable {
|
|||||||
}
|
}
|
||||||
closeForce();
|
closeForce();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void closeForce() throws IOException {
|
public void closeForce() throws IOException {
|
||||||
try {
|
try {
|
||||||
//connection.commit();
|
// connection.commit();
|
||||||
this.connection.close();
|
this.connection.close();
|
||||||
} catch (final SQLException ex) {
|
} catch (final SQLException ex) {
|
||||||
throw new IOException("Dis-connection db fail: " + ex.getMessage());
|
throw new IOException("Dis-connection db fail: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void closeAllForceMode() throws IOException {
|
public static void closeAllForceMode() throws IOException {
|
||||||
for (final DBEntry entry : stored) {
|
for (final DBEntry entry : stored) {
|
||||||
entry.closeForce();
|
entry.closeForce();
|
||||||
|
@ -5,15 +5,15 @@ import jakarta.ws.rs.core.Response;
|
|||||||
public class FailException extends Exception {
|
public class FailException extends Exception {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
public final Response.Status status;
|
public final Response.Status status;
|
||||||
|
|
||||||
public FailException(Response.Status status, String message) {
|
public FailException(final Response.Status status, final String message) {
|
||||||
super(message);
|
super(message);
|
||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
public FailException(String message) {
|
public FailException(final String message) {
|
||||||
super(message);
|
super(message);
|
||||||
this.status = Response.Status.BAD_REQUEST;
|
this.status = Response.Status.BAD_REQUEST;
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,14 +6,14 @@ public class InputException extends Exception {
|
|||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
public final String missingVariable;
|
public final String missingVariable;
|
||||||
public final Response.Status status;
|
public final Response.Status status;
|
||||||
|
|
||||||
public InputException(Response.Status status, String variable, String message) {
|
public InputException(final Response.Status status, final String variable, final String message) {
|
||||||
super(message);
|
super(message);
|
||||||
this.missingVariable = variable;
|
this.missingVariable = variable;
|
||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
public InputException(String variable, String message) {
|
public InputException(final String variable, final String message) {
|
||||||
super(message);
|
super(message);
|
||||||
this.missingVariable = variable;
|
this.missingVariable = variable;
|
||||||
this.status = Response.Status.NOT_ACCEPTABLE;
|
this.status = Response.Status.NOT_ACCEPTABLE;
|
||||||
|
@ -4,8 +4,8 @@ import jakarta.ws.rs.core.Response;
|
|||||||
|
|
||||||
public class NotFoundException extends FailException {
|
public class NotFoundException extends FailException {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
public NotFoundException(String message) {
|
public NotFoundException(final String message) {
|
||||||
super(Response.Status.NOT_FOUND, message);
|
super(Response.Status.NOT_FOUND, message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,9 +9,8 @@ public class RESTErrorResponseExeption extends Exception {
|
|||||||
public String message;
|
public String message;
|
||||||
public int status;
|
public int status;
|
||||||
public String statusMessage;
|
public String statusMessage;
|
||||||
|
|
||||||
public RESTErrorResponseExeption() {
|
public RESTErrorResponseExeption() {
|
||||||
super();
|
|
||||||
this.uuid = null;
|
this.uuid = null;
|
||||||
this.time = null;
|
this.time = null;
|
||||||
this.error = null;
|
this.error = null;
|
||||||
@ -19,9 +18,8 @@ public class RESTErrorResponseExeption extends Exception {
|
|||||||
this.status = 0;
|
this.status = 0;
|
||||||
this.statusMessage = null;
|
this.statusMessage = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public RESTErrorResponseExeption(UUID uuid, String time, String error, String message, int status, String statusMessage) {
|
public RESTErrorResponseExeption(final UUID uuid, final String time, final String error, final String message, final int status, final String statusMessage) {
|
||||||
super();
|
|
||||||
this.uuid = uuid;
|
this.uuid = uuid;
|
||||||
this.time = time;
|
this.time = time;
|
||||||
this.error = error;
|
this.error = error;
|
||||||
@ -29,10 +27,11 @@ public class RESTErrorResponseExeption extends Exception {
|
|||||||
this.status = status;
|
this.status = status;
|
||||||
this.statusMessage = statusMessage;
|
this.statusMessage = statusMessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "RESTErrorResponseExeption [uuid=" + uuid + ", time=" + time + ", error=" + error + ", message=" + message + ", status=" + status + ", statusMessage=" + statusMessage + "]";
|
return "RESTErrorResponseExeption [uuid=" + this.uuid + ", time=" + this.time + ", error=" + this.error + ", message=" + this.message + ", status=" + this.status + ", statusMessage="
|
||||||
|
+ this.statusMessage + "]";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -5,13 +5,13 @@ import jakarta.ws.rs.core.Response;
|
|||||||
public class SystemException extends Exception {
|
public class SystemException extends Exception {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
public final Response.Status status;
|
public final Response.Status status;
|
||||||
|
|
||||||
public SystemException(Response.Status status, String message) {
|
public SystemException(final Response.Status status, final String message) {
|
||||||
super(message);
|
super(message);
|
||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SystemException(String message) {
|
public SystemException(final String message) {
|
||||||
super(message);
|
super(message);
|
||||||
this.status = Response.Status.INTERNAL_SERVER_ERROR;
|
this.status = Response.Status.INTERNAL_SERVER_ERROR;
|
||||||
}
|
}
|
||||||
|
@ -4,8 +4,8 @@ import jakarta.ws.rs.core.Response;
|
|||||||
|
|
||||||
public class UnAuthorizedException extends FailException {
|
public class UnAuthorizedException extends FailException {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
public UnAuthorizedException(String message) {
|
public UnAuthorizedException(final String message) {
|
||||||
super(Response.Status.UNAUTHORIZED, message);
|
super(Response.Status.UNAUTHORIZED, message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -49,15 +49,11 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
|||||||
public AuthenticationFilter(final String applicationName) {
|
public AuthenticationFilter(final String applicationName) {
|
||||||
this.applicationName = applicationName;
|
this.applicationName = applicationName;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void filter(final ContainerRequestContext requestContext) throws IOException {
|
public void filter(final ContainerRequestContext requestContext) throws IOException {
|
||||||
/*
|
/* logger.debug("-----------------------------------------------------"); logger.debug("---- Check if have authorization ----");
|
||||||
logger.debug("-----------------------------------------------------");
|
* logger.debug("-----------------------------------------------------"); logger.debug(" for:{}", requestContext.getUriInfo().getPath()); */
|
||||||
logger.debug("---- Check if have authorization ----");
|
|
||||||
logger.debug("-----------------------------------------------------");
|
|
||||||
logger.debug(" for:{}", requestContext.getUriInfo().getPath());
|
|
||||||
*/
|
|
||||||
final Method method = this.resourceInfo.getResourceMethod();
|
final Method method = this.resourceInfo.getResourceMethod();
|
||||||
// Access denied for all
|
// Access denied for all
|
||||||
if (method.isAnnotationPresent(DenyAll.class)) {
|
if (method.isAnnotationPresent(DenyAll.class)) {
|
||||||
@ -66,9 +62,9 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Access allowed for all
|
// Access allowed for all
|
||||||
if (method.isAnnotationPresent(PermitAll.class)) {
|
if (method.isAnnotationPresent(PermitAll.class)) {
|
||||||
//logger.debug(" ==> permit all " + requestContext.getUriInfo().getPath());
|
// logger.debug(" ==> permit all " + requestContext.getUriInfo().getPath());
|
||||||
// no control ...
|
// no control ...
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -81,7 +77,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
|||||||
|
|
||||||
// Get the Authorization header from the request
|
// Get the Authorization header from the request
|
||||||
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
|
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
|
||||||
//logger.debug("authorizationHeader: {}", authorizationHeader);
|
// logger.debug("authorizationHeader: {}", authorizationHeader);
|
||||||
if (authorizationHeader == null && method.isAnnotationPresent(PermitTokenInURI.class)) {
|
if (authorizationHeader == null && method.isAnnotationPresent(PermitTokenInURI.class)) {
|
||||||
final MultivaluedMap<String, String> quaryparam = requestContext.getUriInfo().getQueryParameters();
|
final MultivaluedMap<String, String> quaryparam = requestContext.getUriInfo().getQueryParameters();
|
||||||
for (final Entry<String, List<String>> item : quaryparam.entrySet()) {
|
for (final Entry<String, List<String>> item : quaryparam.entrySet()) {
|
||||||
@ -106,7 +102,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
|||||||
if (isJwtToken) {
|
if (isJwtToken) {
|
||||||
// Extract the token from the Authorization header (Remove "Yota ")
|
// Extract the token from the Authorization header (Remove "Yota ")
|
||||||
final String token = authorizationHeader.substring(AUTHENTICATION_SCHEME.length()).trim();
|
final String token = authorizationHeader.substring(AUTHENTICATION_SCHEME.length()).trim();
|
||||||
//logger.debug("token: {}", token);
|
// logger.debug("token: {}", token);
|
||||||
try {
|
try {
|
||||||
userByToken = validateJwtToken(token);
|
userByToken = validateJwtToken(token);
|
||||||
} catch (final Exception e) {
|
} catch (final Exception e) {
|
||||||
@ -122,7 +118,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
|||||||
} else {
|
} else {
|
||||||
// Extract the token from the Authorization header (Remove "Zota ")
|
// Extract the token from the Authorization header (Remove "Zota ")
|
||||||
final String token = authorizationHeader.substring(AUTHENTICATION_TOKEN_SCHEME.length()).trim();
|
final String token = authorizationHeader.substring(AUTHENTICATION_TOKEN_SCHEME.length()).trim();
|
||||||
//logger.debug("token: {}", token);
|
// logger.debug("token: {}", token);
|
||||||
try {
|
try {
|
||||||
userByToken = validateToken(token);
|
userByToken = validateToken(token);
|
||||||
} catch (final Exception e) {
|
} catch (final Exception e) {
|
||||||
@ -151,7 +147,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Is user valid?
|
// Is user valid?
|
||||||
if (!haveRight) {
|
if (!haveRight) {
|
||||||
this.logger.error("REJECTED not enought right : {} require: {}", requestContext.getUriInfo().getPath(), roles);
|
this.logger.error("REJECTED not enought right : {} require: {}", requestContext.getUriInfo().getPath(), roles);
|
||||||
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity("Not enought RIGHT !!!").build());
|
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity("Not enought RIGHT !!!").build());
|
||||||
@ -193,7 +189,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
|||||||
|
|
||||||
// must be override to be good implementation
|
// must be override to be good implementation
|
||||||
protected UserByToken validateJwtToken(final String authorization) throws Exception {
|
protected UserByToken validateJwtToken(final String authorization) throws Exception {
|
||||||
//logger.debug(" validate token : " + authorization);
|
// logger.debug(" validate token : " + authorization);
|
||||||
final JWTClaimsSet ret = JWTWrapper.validateToken(authorization, "KarAuth", null);
|
final JWTClaimsSet ret = JWTWrapper.validateToken(authorization, "KarAuth", null);
|
||||||
// check the token is valid !!! (signed and coherent issuer...
|
// check the token is valid !!! (signed and coherent issuer...
|
||||||
if (ret == null) {
|
if (ret == null) {
|
||||||
@ -216,8 +212,8 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
|||||||
this.logger.error("Connect with no right for this application='{}' full Right='{}'", this.applicationName, rights);
|
this.logger.error("Connect with no right for this application='{}' full Right='{}'", this.applicationName, rights);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//logger.debug("request user: '{}' right: '{}' row='{}'", userUID, user.right, rowRight);
|
// logger.debug("request user: '{}' right: '{}' row='{}'", userUID, user.right, rowRight);
|
||||||
return user;
|
return user;
|
||||||
//return UserDB.getUserOrCreate(id, (String)ret.getClaim("login") );
|
// return UserDB.getUserOrCreate(id, (String)ret.getClaim("login") );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,14 +9,14 @@ import jakarta.ws.rs.ext.Provider;
|
|||||||
|
|
||||||
@Provider
|
@Provider
|
||||||
public class CORSFilter implements ContainerResponseFilter {
|
public class CORSFilter implements ContainerResponseFilter {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
|
public void filter(final ContainerRequestContext request, final ContainerResponseContext response) throws IOException {
|
||||||
//System.err.println("filter cors ..." + request.toString());
|
// System.err.println("filter cors ..." + request.toString());
|
||||||
|
|
||||||
response.getHeaders().add("Access-Control-Allow-Origin", "*");
|
response.getHeaders().add("Access-Control-Allow-Origin", "*");
|
||||||
response.getHeaders().add("Access-Control-Allow-Headers", "*");
|
response.getHeaders().add("Access-Control-Allow-Headers", "*");
|
||||||
// "Origin, content-type, Content-type, Accept, authorization, mime-type, filename");
|
// "Origin, content-type, Content-type, Accept, authorization, mime-type, filename");
|
||||||
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
|
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
|
||||||
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
|
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
|
||||||
}
|
}
|
||||||
|
@ -5,13 +5,13 @@ import java.security.Principal;
|
|||||||
import org.kar.archidata.model.UserByToken;
|
import org.kar.archidata.model.UserByToken;
|
||||||
|
|
||||||
public class GenericContext implements Principal {
|
public class GenericContext implements Principal {
|
||||||
|
|
||||||
public UserByToken userByToken;
|
public UserByToken userByToken;
|
||||||
|
|
||||||
public GenericContext(UserByToken userByToken) {
|
public GenericContext(final UserByToken userByToken) {
|
||||||
this.userByToken = userByToken;
|
this.userByToken = userByToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
if (this.userByToken == null) {
|
if (this.userByToken == null) {
|
||||||
|
@ -8,42 +8,42 @@ import jakarta.ws.rs.core.SecurityContext;
|
|||||||
|
|
||||||
// https://simplapi.wordpress.com/2015/09/19/jersey-jax-rs-securitycontext-in-action/
|
// https://simplapi.wordpress.com/2015/09/19/jersey-jax-rs-securitycontext-in-action/
|
||||||
class MySecurityContext implements SecurityContext {
|
class MySecurityContext implements SecurityContext {
|
||||||
|
|
||||||
private final GenericContext contextPrincipale;
|
private final GenericContext contextPrincipale;
|
||||||
private final String sheme;
|
private final String sheme;
|
||||||
|
|
||||||
public MySecurityContext(UserByToken userByToken, String sheme) {
|
public MySecurityContext(final UserByToken userByToken, final String sheme) {
|
||||||
this.contextPrincipale = new GenericContext(userByToken);
|
this.contextPrincipale = new GenericContext(userByToken);
|
||||||
this.sheme = sheme;
|
this.sheme = sheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Principal getUserPrincipal() {
|
public Principal getUserPrincipal() {
|
||||||
return contextPrincipale;
|
return this.contextPrincipale;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isUserInRole(String role) {
|
public boolean isUserInRole(final String role) {
|
||||||
if (contextPrincipale.userByToken != null) {
|
if (this.contextPrincipale.userByToken != null) {
|
||||||
Object value = this.contextPrincipale.userByToken.right.get(role);
|
final Object value = this.contextPrincipale.userByToken.right.get(role);
|
||||||
if (value instanceof Boolean ret) {
|
if (value instanceof final Boolean ret) {
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isSecure() {
|
public boolean isSecure() {
|
||||||
return sheme.equalsIgnoreCase("https");
|
return this.sheme.equalsIgnoreCase("https");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getAuthenticationScheme() {
|
public String getAuthenticationScheme() {
|
||||||
if (contextPrincipale.userByToken != null) {
|
if (this.contextPrincipale.userByToken != null) {
|
||||||
return "Zota";
|
return "Zota";
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -12,7 +12,7 @@ import jakarta.ws.rs.ext.Provider;
|
|||||||
@PreMatching
|
@PreMatching
|
||||||
public class OptionFilter implements ContainerRequestFilter {
|
public class OptionFilter implements ContainerRequestFilter {
|
||||||
@Override
|
@Override
|
||||||
public void filter(ContainerRequestContext requestContext) throws IOException {
|
public void filter(final ContainerRequestContext requestContext) throws IOException {
|
||||||
if (requestContext.getMethod().contentEquals("OPTIONS")) {
|
if (requestContext.getMethod().contentEquals("OPTIONS")) {
|
||||||
requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build());
|
requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build());
|
||||||
}
|
}
|
||||||
|
@ -16,49 +16,39 @@ import org.slf4j.LoggerFactory;
|
|||||||
|
|
||||||
public class MigrationEngine {
|
public class MigrationEngine {
|
||||||
final static Logger LOGGER = LoggerFactory.getLogger(MigrationEngine.class);
|
final static Logger LOGGER = LoggerFactory.getLogger(MigrationEngine.class);
|
||||||
|
|
||||||
// List of order migrations
|
// List of order migrations
|
||||||
private final List<MigrationInterface> datas;
|
private final List<MigrationInterface> datas;
|
||||||
// initialization of the migration if the DB is not present...
|
// initialization of the migration if the DB is not present...
|
||||||
private MigrationInterface init;
|
private MigrationInterface init;
|
||||||
|
|
||||||
/**
|
/** Migration engine constructor (empty). */
|
||||||
* Migration engine constructor (empty).
|
|
||||||
*/
|
|
||||||
public MigrationEngine() {
|
public MigrationEngine() {
|
||||||
this(new ArrayList<>(), null);
|
this(new ArrayList<>(), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Migration engine constructor (specific mode).
|
||||||
* Migration engine constructor (specific mode).
|
|
||||||
* @param datas All the migration ordered.
|
* @param datas All the migration ordered.
|
||||||
* @param init Initialization migration model.
|
* @param init Initialization migration model. */
|
||||||
*/
|
|
||||||
public MigrationEngine(final List<MigrationInterface> datas, final MigrationInterface init) {
|
public MigrationEngine(final List<MigrationInterface> datas, final MigrationInterface init) {
|
||||||
this.datas = datas;
|
this.datas = datas;
|
||||||
this.init = init;
|
this.init = init;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Add a Migration in the list
|
||||||
* Add a Migration in the list
|
* @param migration Migration to add. */
|
||||||
* @param migration Migration to add.
|
|
||||||
*/
|
|
||||||
public void add(final MigrationInterface migration) {
|
public void add(final MigrationInterface migration) {
|
||||||
this.datas.add(migration);
|
this.datas.add(migration);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Set first initialization class
|
||||||
* Set first initialization class
|
* @param migration migration class for first init. */
|
||||||
* @param migration migration class for first init.
|
|
||||||
*/
|
|
||||||
public void setInit(final MigrationInterface migration) {
|
public void setInit(final MigrationInterface migration) {
|
||||||
this.init = migration;
|
this.init = migration;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Get the current version/migration name
|
||||||
* Get the current version/migration name
|
* @return Model represent the last migration. If null then no migration has been done. */
|
||||||
* @return Model represent the last migration. If null then no migration has been done.
|
|
||||||
*/
|
|
||||||
public Migration getCurrentVersion() {
|
public Migration getCurrentVersion() {
|
||||||
if (!DataAccess.isTableExist("KAR_migration")) {
|
if (!DataAccess.isTableExist("KAR_migration")) {
|
||||||
return null;
|
return null;
|
||||||
@ -84,16 +74,14 @@ public class MigrationEngine {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Process the automatic migration of the system
|
||||||
* Process the automatic migration of the system
|
|
||||||
* @param config SQL connection for the migration
|
* @param config SQL connection for the migration
|
||||||
* @throws InterruptedException user interrupt the migration
|
* @throws InterruptedException user interrupt the migration
|
||||||
* @throws IOException Error if access on the DB
|
* @throws IOException Error if access on the DB */
|
||||||
*/
|
|
||||||
public void migrate(final DBConfig config) throws InterruptedException, IOException {
|
public void migrate(final DBConfig config) throws InterruptedException, IOException {
|
||||||
LOGGER.info("Execute migration ... [BEGIN]");
|
LOGGER.info("Execute migration ... [BEGIN]");
|
||||||
|
|
||||||
// STEP 1: Check the DB exist:
|
// STEP 1: Check the DB exist:
|
||||||
LOGGER.info("Verify existance of '{}'", config.getDbName());
|
LOGGER.info("Verify existance of '{}'", config.getDbName());
|
||||||
boolean exist = DataAccess.isDBExist(config.getDbName());
|
boolean exist = DataAccess.isDBExist(config.getDbName());
|
||||||
@ -140,7 +128,7 @@ public class MigrationEngine {
|
|||||||
final Migration currentVersion = getCurrentVersion();
|
final Migration currentVersion = getCurrentVersion();
|
||||||
List<MigrationInterface> toApply = new ArrayList<>();
|
List<MigrationInterface> toApply = new ArrayList<>();
|
||||||
if (currentVersion == null) {
|
if (currentVersion == null) {
|
||||||
//This is a first migration
|
// This is a first migration
|
||||||
LOGGER.info("First installation of the system ==> Create the DB");
|
LOGGER.info("First installation of the system ==> Create the DB");
|
||||||
if (this.init == null) {
|
if (this.init == null) {
|
||||||
toApply = this.datas;
|
toApply = this.datas;
|
||||||
@ -197,7 +185,7 @@ public class MigrationEngine {
|
|||||||
}
|
}
|
||||||
LOGGER.info("Execute migration ... [ END ]");
|
LOGGER.info("Execute migration ... [ END ]");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void migrateSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) {
|
public void migrateSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) {
|
||||||
LOGGER.info("---------------------------------------------------------");
|
LOGGER.info("---------------------------------------------------------");
|
||||||
LOGGER.info("-- Migrate: [{}/{}] {} [BEGIN]", id, count, elem.getName());
|
LOGGER.info("-- Migrate: [{}/{}] {} [BEGIN]", id, count, elem.getName());
|
||||||
@ -216,7 +204,7 @@ public class MigrationEngine {
|
|||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (elem.applyMigration(entry, log, migrationResult)) {
|
if (elem.applyMigration(entry, log, migrationResult)) {
|
||||||
migrationResult.terminated = true;
|
migrationResult.terminated = true;
|
||||||
try {
|
try {
|
||||||
@ -245,7 +233,7 @@ public class MigrationEngine {
|
|||||||
}
|
}
|
||||||
LOGGER.info("Migrate: [{}/{}] {} [ END ]", id, count, elem.getName());
|
LOGGER.info("Migrate: [{}/{}] {} [ END ]", id, count, elem.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
public void revertTo(final DBEntry entry, final String migrationName) {
|
public void revertTo(final DBEntry entry, final String migrationName) {
|
||||||
final Migration currentVersion = getCurrentVersion();
|
final Migration currentVersion = getCurrentVersion();
|
||||||
final List<MigrationInterface> toApply = new ArrayList<>();
|
final List<MigrationInterface> toApply = new ArrayList<>();
|
||||||
@ -268,10 +256,10 @@ public class MigrationEngine {
|
|||||||
revertSingle(entry, elem, id, count);
|
revertSingle(entry, elem, id, count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void revertSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) {
|
public void revertSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) {
|
||||||
LOGGER.info("Revert migration: {} [BEGIN]", elem.getName());
|
LOGGER.info("Revert migration: {} [BEGIN]", elem.getName());
|
||||||
|
|
||||||
LOGGER.info("Revert migration: {} [ END ]", elem.getName());
|
LOGGER.info("Revert migration: {} [ END ]", elem.getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package org.kar.archidata.migration;
|
package org.kar.archidata.migration;
|
||||||
|
|
||||||
public class MigrationException extends Exception {
|
public class MigrationException extends Exception {
|
||||||
|
|
||||||
private static final long serialVersionUID = 20230502L;
|
private static final long serialVersionUID = 20230502L;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -4,32 +4,24 @@ import org.kar.archidata.db.DBEntry;
|
|||||||
import org.kar.archidata.migration.model.Migration;
|
import org.kar.archidata.migration.model.Migration;
|
||||||
|
|
||||||
public interface MigrationInterface {
|
public interface MigrationInterface {
|
||||||
/**
|
/** Get Name of the migration
|
||||||
* Get Name of the migration
|
* @return Migration name */
|
||||||
* @return Migration name
|
|
||||||
*/
|
|
||||||
String getName();
|
String getName();
|
||||||
|
|
||||||
/**
|
/** Migrate the system to a new version.
|
||||||
* Migrate the system to a new version.
|
|
||||||
* @param entry DB interface for the migration.
|
* @param entry DB interface for the migration.
|
||||||
* @param log Stored data in the BDD for the migration progression.
|
* @param log Stored data in the BDD for the migration progression.
|
||||||
* @param migration Migration post data on each step...
|
* @param migration Migration post data on each step...
|
||||||
* @return true if migration is finished.
|
* @return true if migration is finished. */
|
||||||
*/
|
|
||||||
boolean applyMigration(DBEntry entry, StringBuilder log, Migration model);
|
boolean applyMigration(DBEntry entry, StringBuilder log, Migration model);
|
||||||
|
|
||||||
/**
|
/** Remove a migration the system to the previous version.
|
||||||
* Remove a migration the system to the previous version.
|
|
||||||
* @param entry DB interface for the migration.
|
* @param entry DB interface for the migration.
|
||||||
* @param log Stored data in the BDD for the migration progression.
|
* @param log Stored data in the BDD for the migration progression.
|
||||||
* @return true if migration is finished.
|
* @return true if migration is finished. */
|
||||||
*/
|
|
||||||
boolean revertMigration(DBEntry entry, StringBuilder log);
|
boolean revertMigration(DBEntry entry, StringBuilder log);
|
||||||
|
|
||||||
/**
|
/** Get the number of step in the migration process.
|
||||||
* Get the number of step in the migration process.
|
* @return count of SQL access. */
|
||||||
* @return count of SQL access.
|
|
||||||
*/
|
|
||||||
int getNumberOfStep();
|
int getNumberOfStep();
|
||||||
}
|
}
|
||||||
|
@ -13,13 +13,11 @@ import org.kar.archidata.util.ConfigBaseVariable;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
record Action(
|
record Action(String action, List<String> filterDB) {
|
||||||
String action,
|
|
||||||
List<String> filterDB) {
|
|
||||||
public Action(final String action) {
|
public Action(final String action) {
|
||||||
this(action, List.of());
|
this(action, List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
public Action(final String action, final String filterDB) {
|
public Action(final String action, final String filterDB) {
|
||||||
this(action, List.of(filterDB));
|
this(action, List.of(filterDB));
|
||||||
}
|
}
|
||||||
@ -28,26 +26,26 @@ record Action(
|
|||||||
public class MigrationSqlStep implements MigrationInterface {
|
public class MigrationSqlStep implements MigrationInterface {
|
||||||
final static Logger LOGGER = LoggerFactory.getLogger(MigrationSqlStep.class);
|
final static Logger LOGGER = LoggerFactory.getLogger(MigrationSqlStep.class);
|
||||||
private final List<Action> actions = new ArrayList<>();
|
private final List<Action> actions = new ArrayList<>();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return getClass().getCanonicalName();
|
return getClass().getCanonicalName();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void display() {
|
public void display() {
|
||||||
for (int iii = 0; iii < this.actions.size(); iii++) {
|
for (int iii = 0; iii < this.actions.size(); iii++) {
|
||||||
final Action action = this.actions.get(iii);
|
final Action action = this.actions.get(iii);
|
||||||
LOGGER.info(" >>>> SQL ACTION : {}/{} ==> filter='{}'\n{}", iii, this.actions.size(), action.filterDB(), action.action());
|
LOGGER.info(" >>>> SQL ACTION : {}/{} ==> filter='{}'\n{}", iii, this.actions.size(), action.filterDB(), action.action());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean applyMigration(final DBEntry entry, final StringBuilder log, final Migration model) {
|
public boolean applyMigration(final DBEntry entry, final StringBuilder log, final Migration model) {
|
||||||
for (int iii = 0; iii < this.actions.size(); iii++) {
|
for (int iii = 0; iii < this.actions.size(); iii++) {
|
||||||
log.append("action [" + (iii + 1) + "/" + this.actions.size() + "]\n");
|
log.append("action [" + (iii + 1) + "/" + this.actions.size() + "]\n");
|
||||||
LOGGER.info(" >>>> SQL ACTION : {}/{}", iii + 1, this.actions.size());
|
LOGGER.info(" >>>> SQL ACTION : {}/{}", iii + 1, this.actions.size());
|
||||||
final Action action = this.actions.get(iii);
|
final Action action = this.actions.get(iii);
|
||||||
|
|
||||||
LOGGER.info("SQL request: ```{}``` on '{}' current={}", action.action(), action.filterDB(), ConfigBaseVariable.getDBType());
|
LOGGER.info("SQL request: ```{}``` on '{}' current={}", action.action(), action.filterDB(), ConfigBaseVariable.getDBType());
|
||||||
log.append("SQL: " + action.action() + " on " + action.filterDB() + "\n");
|
log.append("SQL: " + action.action() + " on " + action.filterDB() + "\n");
|
||||||
boolean isValid = true;
|
boolean isValid = true;
|
||||||
@ -98,30 +96,30 @@ public class MigrationSqlStep implements MigrationInterface {
|
|||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean revertMigration(final DBEntry entry, final StringBuilder log) {
|
public boolean revertMigration(final DBEntry entry, final StringBuilder log) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addAction(final String action) {
|
public void addAction(final String action) {
|
||||||
this.actions.add(new Action(action));
|
this.actions.add(new Action(action));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addAction(final String action, final String filterdBType) {
|
public void addAction(final String action, final String filterdBType) {
|
||||||
this.actions.add(new Action(action, filterdBType));
|
this.actions.add(new Action(action, filterdBType));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addClass(final Class<?> clazz) throws Exception {
|
public void addClass(final Class<?> clazz) throws Exception {
|
||||||
final List<String> tmp = DataFactory.createTable(clazz);
|
final List<String> tmp = DataFactory.createTable(clazz);
|
||||||
for (final String elem : tmp) {
|
for (final String elem : tmp) {
|
||||||
this.actions.add(new Action(elem));
|
this.actions.add(new Action(elem));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getNumberOfStep() {
|
public int getNumberOfStep() {
|
||||||
return this.actions.size();
|
return this.actions.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -12,7 +12,7 @@ import jakarta.persistence.Table;
|
|||||||
@DataIfNotExists
|
@DataIfNotExists
|
||||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
public class Data extends GenericDataSoftDelete {
|
public class Data extends GenericDataSoftDelete {
|
||||||
|
|
||||||
@Column(length = 128, nullable = false)
|
@Column(length = 128, nullable = false)
|
||||||
@DataComment("Sha512 of the data")
|
@DataComment("Sha512 of the data")
|
||||||
public String sha512;
|
public String sha512;
|
||||||
|
@ -3,5 +3,5 @@ package org.kar.archidata.model;
|
|||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
|
||||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
public record GetToken(
|
public record GetToken(String jwt) {
|
||||||
String jwt) {}
|
}
|
||||||
|
@ -2,5 +2,5 @@ package org.kar.archidata.model;
|
|||||||
|
|
||||||
public class Migration extends GenericDataSoftDelete {
|
public class Migration extends GenericDataSoftDelete {
|
||||||
public String migrationId;
|
public String migrationId;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -9,18 +9,18 @@ public class Token {
|
|||||||
public String token;
|
public String token;
|
||||||
public String createTime;
|
public String createTime;
|
||||||
public String endValidityTime;
|
public String endValidityTime;
|
||||||
|
|
||||||
public Token() {}
|
public Token() {}
|
||||||
|
|
||||||
public Token(long id, long userId, String token, String createTime, String endValidityTime) {
|
public Token(final long id, final long userId, final String token, final String createTime, final String endValidityTime) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.userId = userId;
|
this.userId = userId;
|
||||||
this.token = token;
|
this.token = token;
|
||||||
this.createTime = createTime;
|
this.createTime = createTime;
|
||||||
this.endValidityTime = endValidityTime;
|
this.endValidityTime = endValidityTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Token(ResultSet rs) {
|
public Token(final ResultSet rs) {
|
||||||
int iii = 1;
|
int iii = 1;
|
||||||
try {
|
try {
|
||||||
this.id = rs.getLong(iii++);
|
this.id = rs.getLong(iii++);
|
||||||
@ -28,13 +28,13 @@ public class Token {
|
|||||||
this.token = rs.getString(iii++);
|
this.token = rs.getString(iii++);
|
||||||
this.createTime = rs.getString(iii++);
|
this.createTime = rs.getString(iii++);
|
||||||
this.endValidityTime = rs.getString(iii++);
|
this.endValidityTime = rs.getString(iii++);
|
||||||
} catch (SQLException ex) {
|
} catch (final SQLException ex) {
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Token{" + "id=" + id + ", userId=" + userId + ", token='" + token + '\'' + ", createTime=" + createTime + ", endValidityTime=" + endValidityTime + '}';
|
return "Token{" + "id=" + this.id + ", userId=" + this.userId + ", token='" + this.token + '\'' + ", createTime=" + this.createTime + ", endValidityTime=" + this.endValidityTime + '}';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -33,7 +33,7 @@ import jakarta.persistence.Table;
|
|||||||
public class User extends GenericDataSoftDelete {
|
public class User extends GenericDataSoftDelete {
|
||||||
@Column(length = 128)
|
@Column(length = 128)
|
||||||
public String login = null;
|
public String login = null;
|
||||||
|
|
||||||
public Timestamp lastConnection = null;
|
public Timestamp lastConnection = null;
|
||||||
@DataDefault("'0'")
|
@DataDefault("'0'")
|
||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
@ -44,13 +44,13 @@ public class User extends GenericDataSoftDelete {
|
|||||||
@DataDefault("'0'")
|
@DataDefault("'0'")
|
||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
public boolean removed = false;
|
public boolean removed = false;
|
||||||
|
|
||||||
@ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class)
|
@ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class)
|
||||||
public List<Long> covers;
|
public List<Long> covers;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "User [login=" + login + ", last=" + lastConnection + ", admin=" + admin + "]";
|
return "User [login=" + this.login + ", last=" + this.lastConnection + ", admin=" + this.admin + "]";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -8,44 +8,44 @@ public class UserByToken {
|
|||||||
public static final int TYPE_APPLICATION = -2;
|
public static final int TYPE_APPLICATION = -2;
|
||||||
// application internal management type: an application generic Id
|
// application internal management type: an application generic Id
|
||||||
public Integer type = null;
|
public Integer type = null;
|
||||||
|
|
||||||
public Long id = null;
|
public Long id = null;
|
||||||
public Long parentId = null; // FOr application, this is the id of the application, and of user token, this is the USERID
|
public Long parentId = null; // FOr application, this is the id of the application, and of user token, this is the USERID
|
||||||
public String name = null;
|
public String name = null;
|
||||||
// Right map
|
// Right map
|
||||||
public Map<String, Object> right = new HashMap<>();
|
public Map<String, Object> right = new HashMap<>();
|
||||||
|
|
||||||
public boolean hasRight(String key, Object value) {
|
public boolean hasRight(final String key, final Object value) {
|
||||||
if (!this.right.containsKey(key)) {
|
if (!this.right.containsKey(key)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
Object data = this.right.get(key);
|
final Object data = this.right.get(key);
|
||||||
if (data instanceof Boolean elem) {
|
if (data instanceof final Boolean elem) {
|
||||||
if (value instanceof Boolean castVal) {
|
if (value instanceof final Boolean castVal) {
|
||||||
if (elem == castVal) {
|
if (elem == castVal) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (data instanceof String elem) {
|
if (data instanceof final String elem) {
|
||||||
if (value instanceof String castVal) {
|
if (value instanceof final String castVal) {
|
||||||
if (elem.equals(castVal)) {
|
if (elem.equals(castVal)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (data instanceof Long elem) {
|
if (data instanceof final Long elem) {
|
||||||
if (value instanceof Long castVal) {
|
if (value instanceof final Long castVal) {
|
||||||
if (elem == castVal) {
|
if (elem == castVal) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (data instanceof Double elem) {
|
if (data instanceof final Double elem) {
|
||||||
if (value instanceof Double castVal) {
|
if (value instanceof final Double castVal) {
|
||||||
if (elem == castVal) {
|
if (elem == castVal) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -54,5 +54,5 @@ public class UserByToken {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -31,11 +31,11 @@ public class ConfigBaseVariable {
|
|||||||
ssoToken = System.getenv("SSO_TOKEN");
|
ssoToken = System.getenv("SSO_TOKEN");
|
||||||
testMode = System.getenv("TEST_MODE");
|
testMode = System.getenv("TEST_MODE");
|
||||||
}
|
}
|
||||||
|
|
||||||
static {
|
static {
|
||||||
clearAllValue();
|
clearAllValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getTmpDataFolder() {
|
public static String getTmpDataFolder() {
|
||||||
if (tmpDataFolder == null) {
|
if (tmpDataFolder == null) {
|
||||||
return "/application/data/tmp";
|
return "/application/data/tmp";
|
||||||
@ -109,11 +109,11 @@ public class ConfigBaseVariable {
|
|||||||
public static String getSSOAddress() {
|
public static String getSSOAddress() {
|
||||||
return ssoAdress;
|
return ssoAdress;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String ssoToken() {
|
public static String ssoToken() {
|
||||||
return ssoToken;
|
return ssoToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean getTestMode() {
|
public static boolean getTestMode() {
|
||||||
if (testMode == null) {
|
if (testMode == null) {
|
||||||
return false;
|
return false;
|
||||||
|
@ -14,9 +14,9 @@ import java.sql.SQLException;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||||
|
import org.kar.archidata.dataAccess.DataAccess;
|
||||||
import org.kar.archidata.dataAccess.QueryAnd;
|
import org.kar.archidata.dataAccess.QueryAnd;
|
||||||
import org.kar.archidata.dataAccess.QueryCondition;
|
import org.kar.archidata.dataAccess.QueryCondition;
|
||||||
import org.kar.archidata.dataAccess.DataAccess;
|
|
||||||
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
|
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
|
||||||
import org.kar.archidata.model.Data;
|
import org.kar.archidata.model.Data;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@ -26,104 +26,88 @@ import jakarta.ws.rs.core.Response;
|
|||||||
|
|
||||||
public class DataTools {
|
public class DataTools {
|
||||||
private final static Logger LOGGER = LoggerFactory.getLogger(DataTools.class);
|
private final static Logger LOGGER = LoggerFactory.getLogger(DataTools.class);
|
||||||
|
|
||||||
public final static int CHUNK_SIZE = 1024 * 1024; // 1MB chunks
|
public final static int CHUNK_SIZE = 1024 * 1024; // 1MB chunks
|
||||||
public final static int CHUNK_SIZE_IN = 50 * 1024 * 1024; // 1MB chunks
|
public final static int CHUNK_SIZE_IN = 50 * 1024 * 1024; // 1MB chunks
|
||||||
/**
|
/** Upload some data */
|
||||||
* Upload some data
|
|
||||||
*/
|
|
||||||
private static long tmpFolderId = 1;
|
private static long tmpFolderId = 1;
|
||||||
|
|
||||||
public static void createFolder(String path) throws IOException {
|
public static void createFolder(final String path) throws IOException {
|
||||||
if (!Files.exists(java.nio.file.Path.of(path))) {
|
if (!Files.exists(java.nio.file.Path.of(path))) {
|
||||||
LOGGER.info("Create folder: " + path);
|
LOGGER.info("Create folder: " + path);
|
||||||
Files.createDirectories(java.nio.file.Path.of(path));
|
Files.createDirectories(java.nio.file.Path.of(path));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static long getTmpDataId() {
|
public static long getTmpDataId() {
|
||||||
return tmpFolderId++;
|
return tmpFolderId++;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getTmpFileInData(long tmpFolderId) {
|
public static String getTmpFileInData(final long tmpFolderId) {
|
||||||
String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId;
|
final String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId;
|
||||||
try {
|
try {
|
||||||
createFolder(ConfigBaseVariable.getTmpDataFolder() + File.separator);
|
createFolder(ConfigBaseVariable.getTmpDataFolder() + File.separator);
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getTmpFolder() {
|
public static String getTmpFolder() {
|
||||||
String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
final String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
||||||
try {
|
try {
|
||||||
createFolder(ConfigBaseVariable.getTmpDataFolder() + File.separator);
|
createFolder(ConfigBaseVariable.getTmpDataFolder() + File.separator);
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String getFileData(long tmpFolderId) {
|
public static String getFileData(final long tmpFolderId) {
|
||||||
String filePath = ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + "data";
|
final String filePath = ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + "data";
|
||||||
try {
|
try {
|
||||||
createFolder(ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator);
|
createFolder(ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator);
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Data getWithSha512(String sha512) {
|
public static Data getWithSha512(final String sha512) {
|
||||||
try {
|
try {
|
||||||
return DataAccess.getWhere(Data.class, new QueryCondition("sha512", "=", sha512));
|
return DataAccess.getWhere(Data.class, new QueryCondition("sha512", "=", sha512));
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Data getWithId(long id) {
|
public static Data getWithId(final long id) {
|
||||||
try {
|
try {
|
||||||
return DataAccess.getWhere(Data.class, new QueryAnd(List.of(new QueryCondition("deleted", "=", false), new QueryCondition("id", "=", id))));
|
return DataAccess.getWhere(Data.class, new QueryAnd(List.of(new QueryCondition("deleted", "=", false), new QueryCondition("id", "=", id))));
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Data createNewData(long tmpUID, String originalFileName, String sha512) throws IOException, SQLException {
|
public static Data createNewData(final long tmpUID, final String originalFileName, final String sha512) throws IOException, SQLException {
|
||||||
// determine mime type:
|
// determine mime type:
|
||||||
String mimeType = "";
|
String mimeType = "";
|
||||||
String extension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1);
|
final String extension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1);
|
||||||
switch (extension.toLowerCase()) {
|
mimeType = switch (extension.toLowerCase()) {
|
||||||
case "jpg":
|
case "jpg", "jpeg" -> "image/jpeg";
|
||||||
case "jpeg":
|
case "png" -> "image/png";
|
||||||
mimeType = "image/jpeg";
|
case "webp" -> "image/webp";
|
||||||
break;
|
case "mka" -> "audio/x-matroska";
|
||||||
case "png":
|
case "mkv" -> "video/x-matroska";
|
||||||
mimeType = "image/png";
|
case "webm" -> "video/webm";
|
||||||
break;
|
default -> throw new IOException("Can not find the mime type of data input: '" + extension + "'");
|
||||||
case "webp":
|
};
|
||||||
mimeType = "image/webp";
|
final String tmpPath = getTmpFileInData(tmpUID);
|
||||||
break;
|
final long fileSize = Files.size(Paths.get(tmpPath));
|
||||||
case "mka":
|
|
||||||
mimeType = "audio/x-matroska";
|
|
||||||
break;
|
|
||||||
case "mkv":
|
|
||||||
mimeType = "video/x-matroska";
|
|
||||||
break;
|
|
||||||
case "webm":
|
|
||||||
mimeType = "video/webm";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
throw new IOException("Can not find the mime type of data input: '" + extension + "'");
|
|
||||||
}
|
|
||||||
String tmpPath = getTmpFileInData(tmpUID);
|
|
||||||
long fileSize = Files.size(Paths.get(tmpPath));
|
|
||||||
Data out = new Data();
|
Data out = new Data();
|
||||||
;
|
;
|
||||||
try {
|
try {
|
||||||
@ -131,62 +115,62 @@ public class DataTools {
|
|||||||
out.mimeType = mimeType;
|
out.mimeType = mimeType;
|
||||||
out.size = fileSize;
|
out.size = fileSize;
|
||||||
out = DataAccess.insert(out);
|
out = DataAccess.insert(out);
|
||||||
} catch (SQLException ex) {
|
} catch (final SQLException ex) {
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
String mediaPath = getFileData(out.id);
|
final String mediaPath = getFileData(out.id);
|
||||||
LOGGER.info("src = {}", tmpPath);
|
LOGGER.info("src = {}", tmpPath);
|
||||||
LOGGER.info("dst = {}", mediaPath);
|
LOGGER.info("dst = {}", mediaPath);
|
||||||
Files.move(Paths.get(tmpPath), Paths.get(mediaPath), StandardCopyOption.ATOMIC_MOVE);
|
Files.move(Paths.get(tmpPath), Paths.get(mediaPath), StandardCopyOption.ATOMIC_MOVE);
|
||||||
|
|
||||||
LOGGER.info("Move done");
|
LOGGER.info("Move done");
|
||||||
// all is done the file is correctly installed...
|
// all is done the file is correctly installed...
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void undelete(Long id) {
|
public static void undelete(final Long id) {
|
||||||
try {
|
try {
|
||||||
DataAccess.unsetDelete(Data.class, id);
|
DataAccess.unsetDelete(Data.class, id);
|
||||||
} catch (Exception e) {
|
} catch (final Exception e) {
|
||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String saveTemporaryFile(InputStream uploadedInputStream, long idData) {
|
public static String saveTemporaryFile(final InputStream uploadedInputStream, final long idData) {
|
||||||
return saveFile(uploadedInputStream, getTmpFileInData(idData));
|
return saveFile(uploadedInputStream, getTmpFileInData(idData));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void removeTemporaryFile(long idData) {
|
public static void removeTemporaryFile(final long idData) {
|
||||||
String filepath = getTmpFileInData(idData);
|
final String filepath = getTmpFileInData(idData);
|
||||||
if (Files.exists(Paths.get(filepath))) {
|
if (Files.exists(Paths.get(filepath))) {
|
||||||
try {
|
try {
|
||||||
Files.delete(Paths.get(filepath));
|
Files.delete(Paths.get(filepath));
|
||||||
} catch (IOException e) {
|
} catch (final IOException e) {
|
||||||
LOGGER.info("can not delete temporary file : {}", Paths.get(filepath));
|
LOGGER.info("can not delete temporary file : {}", Paths.get(filepath));
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// save uploaded file to a defined location on the server
|
// save uploaded file to a defined location on the server
|
||||||
public static String saveFile(InputStream uploadedInputStream, String serverLocation) {
|
public static String saveFile(final InputStream uploadedInputStream, final String serverLocation) {
|
||||||
String out = "";
|
String out = "";
|
||||||
try {
|
try {
|
||||||
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
|
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
|
||||||
int read = 0;
|
int read = 0;
|
||||||
byte[] bytes = new byte[CHUNK_SIZE_IN];
|
final byte[] bytes = new byte[CHUNK_SIZE_IN];
|
||||||
MessageDigest md = MessageDigest.getInstance("SHA-512");
|
final MessageDigest md = MessageDigest.getInstance("SHA-512");
|
||||||
|
|
||||||
outpuStream = new FileOutputStream(new File(serverLocation));
|
outpuStream = new FileOutputStream(new File(serverLocation));
|
||||||
while ((read = uploadedInputStream.read(bytes)) != -1) {
|
while ((read = uploadedInputStream.read(bytes)) != -1) {
|
||||||
//logger.debug("write {}", read);
|
// logger.debug("write {}", read);
|
||||||
md.update(bytes, 0, read);
|
md.update(bytes, 0, read);
|
||||||
outpuStream.write(bytes, 0, read);
|
outpuStream.write(bytes, 0, read);
|
||||||
}
|
}
|
||||||
@ -194,41 +178,36 @@ public class DataTools {
|
|||||||
outpuStream.flush();
|
outpuStream.flush();
|
||||||
outpuStream.close();
|
outpuStream.close();
|
||||||
// create the end of sha512
|
// create the end of sha512
|
||||||
byte[] sha512Digest = md.digest();
|
final byte[] sha512Digest = md.digest();
|
||||||
// convert in hexadecimal
|
// convert in hexadecimal
|
||||||
out = bytesToHex(sha512Digest);
|
out = bytesToHex(sha512Digest);
|
||||||
uploadedInputStream.close();
|
uploadedInputStream.close();
|
||||||
} catch (IOException ex) {
|
} catch (final IOException ex) {
|
||||||
LOGGER.error("Can not write in temporary file ... ");
|
LOGGER.error("Can not write in temporary file ... ");
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
} catch (NoSuchAlgorithmException ex) {
|
} catch (final NoSuchAlgorithmException ex) {
|
||||||
LOGGER.error("Can not find sha512 algorithms");
|
LOGGER.error("Can not find sha512 algorithms");
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// curl http://localhost:9993/api/users/3
|
// curl http://localhost:9993/api/users/3
|
||||||
//@Secured
|
// @Secured
|
||||||
/*
|
/* @GET
|
||||||
@GET
|
* @Path("{id}") //@RolesAllowed("GUEST")
|
||||||
@Path("{id}")
|
* @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response retriveData(@HeaderParam("Range") String range, @PathParam("id") Long id) throws Exception { return retriveDataFull(range, id,
|
||||||
//@RolesAllowed("GUEST")
|
* "no-name"); } */
|
||||||
@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
|
||||||
public Response retriveData(@HeaderParam("Range") String range, @PathParam("id") Long id) throws Exception {
|
public static String bytesToHex(final byte[] bytes) {
|
||||||
return retriveDataFull(range, id, "no-name");
|
final StringBuilder sb = new StringBuilder();
|
||||||
}
|
for (final byte b : bytes) {
|
||||||
*/
|
|
||||||
|
|
||||||
public static String bytesToHex(byte[] bytes) {
|
|
||||||
StringBuilder sb = new StringBuilder();
|
|
||||||
for (byte b : bytes) {
|
|
||||||
sb.append(String.format("%02x", b));
|
sb.append(String.format("%02x", b));
|
||||||
}
|
}
|
||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String multipartCorrection(String data) {
|
public static String multipartCorrection(final String data) {
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -240,40 +219,40 @@ public class DataTools {
|
|||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static <T> Response uploadCover(Class<T> clazz, Long id, String fileName, InputStream fileInputStream, FormDataContentDisposition fileMetaData) {
|
public static <T> Response uploadCover(final Class<T> clazz, final Long id, String fileName, final InputStream fileInputStream, final FormDataContentDisposition fileMetaData) {
|
||||||
try {
|
try {
|
||||||
// correct input string stream :
|
// correct input string stream :
|
||||||
fileName = multipartCorrection(fileName);
|
fileName = multipartCorrection(fileName);
|
||||||
|
|
||||||
//public NodeSmall uploadFile(final FormDataMultiPart form) {
|
// public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||||
LOGGER.info("Upload media file: {}", fileMetaData);
|
LOGGER.info("Upload media file: {}", fileMetaData);
|
||||||
LOGGER.info(" - id: {}", id);
|
LOGGER.info(" - id: {}", id);
|
||||||
LOGGER.info(" - file_name: ", fileName);
|
LOGGER.info(" - file_name: ", fileName);
|
||||||
LOGGER.info(" - fileInputStream: {}", fileInputStream);
|
LOGGER.info(" - fileInputStream: {}", fileInputStream);
|
||||||
LOGGER.info(" - fileMetaData: {}", fileMetaData);
|
LOGGER.info(" - fileMetaData: {}", fileMetaData);
|
||||||
T media = DataAccess.get(clazz, id);
|
final T media = DataAccess.get(clazz, id);
|
||||||
if (media == null) {
|
if (media == null) {
|
||||||
return Response.notModified("Media Id does not exist or removed...").build();
|
return Response.notModified("Media Id does not exist or removed...").build();
|
||||||
}
|
}
|
||||||
|
|
||||||
long tmpUID = getTmpDataId();
|
final long tmpUID = getTmpDataId();
|
||||||
String sha512 = saveTemporaryFile(fileInputStream, tmpUID);
|
final String sha512 = saveTemporaryFile(fileInputStream, tmpUID);
|
||||||
Data data = getWithSha512(sha512);
|
Data data = getWithSha512(sha512);
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
LOGGER.info("Need to add the data in the BDD ... ");
|
LOGGER.info("Need to add the data in the BDD ... ");
|
||||||
try {
|
try {
|
||||||
data = createNewData(tmpUID, fileName, sha512);
|
data = createNewData(tmpUID, fileName, sha512);
|
||||||
} catch (IOException ex) {
|
} catch (final IOException ex) {
|
||||||
removeTemporaryFile(tmpUID);
|
removeTemporaryFile(tmpUID);
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
return Response.notModified("can not create input media").build();
|
return Response.notModified("can not create input media").build();
|
||||||
} catch (SQLException ex) {
|
} catch (final SQLException ex) {
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
removeTemporaryFile(tmpUID);
|
removeTemporaryFile(tmpUID);
|
||||||
return Response.notModified("Error in SQL insertion ...").build();
|
return Response.notModified("Error in SQL insertion ...").build();
|
||||||
}
|
}
|
||||||
} else if (data.deleted == true) {
|
} else if (data.deleted) {
|
||||||
LOGGER.error("Data already exist but deleted");
|
LOGGER.error("Data already exist but deleted");
|
||||||
undelete(data.id);
|
undelete(data.id);
|
||||||
data.deleted = false;
|
data.deleted = false;
|
||||||
@ -284,7 +263,7 @@ public class DataTools {
|
|||||||
LOGGER.info("Find typeNode");
|
LOGGER.info("Find typeNode");
|
||||||
AddOnManyToMany.addLink(clazz, id, "cover", data.id);
|
AddOnManyToMany.addLink(clazz, id, "cover", data.id);
|
||||||
return Response.ok(DataAccess.get(clazz, id)).build();
|
return Response.ok(DataAccess.get(clazz, id)).build();
|
||||||
} catch (Exception ex) {
|
} catch (final Exception ex) {
|
||||||
System.out.println("Cat ann unexpected error ... ");
|
System.out.println("Cat ann unexpected error ... ");
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
}
|
}
|
||||||
|
@ -33,23 +33,16 @@ import com.nimbusds.jwt.SignedJWT;
|
|||||||
|
|
||||||
class TestSigner implements JWSSigner {
|
class TestSigner implements JWSSigner {
|
||||||
public static String test_signature = "TEST_SIGNATURE_FOR_LOCAL_TEST_AND_TEST_E2E";
|
public static String test_signature = "TEST_SIGNATURE_FOR_LOCAL_TEST_AND_TEST_E2E";
|
||||||
|
|
||||||
/**
|
/** Signs the specified {@link JWSObject#getSigningInput input} of a {@link JWSObject JWS object}.
|
||||||
* Signs the specified {@link JWSObject#getSigningInput input} of a
|
|
||||||
* {@link JWSObject JWS object}.
|
|
||||||
*
|
*
|
||||||
* @param header The JSON Web Signature (JWS) header. Must
|
* @param header The JSON Web Signature (JWS) header. Must specify a supported JWS algorithm and must not be {@code null}.
|
||||||
* specify a supported JWS algorithm and must not
|
|
||||||
* be {@code null}.
|
|
||||||
* @param signingInput The input to sign. Must not be {@code null}.
|
* @param signingInput The input to sign. Must not be {@code null}.
|
||||||
*
|
*
|
||||||
* @return The resulting signature part (third part) of the JWS object.
|
* @return The resulting signature part (third part) of the JWS object.
|
||||||
*
|
*
|
||||||
* @throws JOSEException If the JWS algorithm is not supported, if a
|
* @throws JOSEException If the JWS algorithm is not supported, if a critical header parameter is not supported or marked for deferral to the application, or if signing failed for some other
|
||||||
* critical header parameter is not supported or
|
* internal reason. */
|
||||||
* marked for deferral to the application, or if
|
|
||||||
* signing failed for some other internal reason.
|
|
||||||
*/
|
|
||||||
@Override
|
@Override
|
||||||
public Base64URL sign(final JWSHeader header, final byte[] signingInput) throws JOSEException {
|
public Base64URL sign(final JWSHeader header, final byte[] signingInput) throws JOSEException {
|
||||||
return new Base64URL(test_signature);
|
return new Base64URL(test_signature);
|
||||||
@ -87,7 +80,7 @@ public class JWTWrapper {
|
|||||||
public static void initLocalTokenRemote(final String ssoUri, final String application) throws IOException, ParseException {
|
public static void initLocalTokenRemote(final String ssoUri, final String application) throws IOException, ParseException {
|
||||||
// check Token:
|
// check Token:
|
||||||
final URL obj = new URL(ssoUri + "public_key");
|
final URL obj = new URL(ssoUri + "public_key");
|
||||||
//LOGGER.debug("Request token from: {}", obj);
|
// LOGGER.debug("Request token from: {}", obj);
|
||||||
final HttpURLConnection con = (HttpURLConnection) obj.openConnection();
|
final HttpURLConnection con = (HttpURLConnection) obj.openConnection();
|
||||||
con.setRequestMethod("GET");
|
con.setRequestMethod("GET");
|
||||||
con.setRequestProperty("User-Agent", application);
|
con.setRequestProperty("User-Agent", application);
|
||||||
@ -100,7 +93,7 @@ public class JWTWrapper {
|
|||||||
}
|
}
|
||||||
final int responseCode = con.getResponseCode();
|
final int responseCode = con.getResponseCode();
|
||||||
|
|
||||||
//LOGGER.debug("GET Response Code :: {}", responseCode);
|
// LOGGER.debug("GET Response Code :: {}", responseCode);
|
||||||
if (responseCode == HttpURLConnection.HTTP_OK) { // success
|
if (responseCode == HttpURLConnection.HTTP_OK) { // success
|
||||||
final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
||||||
|
|
||||||
@ -111,7 +104,7 @@ public class JWTWrapper {
|
|||||||
}
|
}
|
||||||
in.close();
|
in.close();
|
||||||
// print result
|
// print result
|
||||||
//LOGGER.debug(response.toString());
|
// LOGGER.debug(response.toString());
|
||||||
final ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
final PublicKey values = mapper.readValue(response.toString(), PublicKey.class);
|
final PublicKey values = mapper.readValue(response.toString(), PublicKey.class);
|
||||||
rsaPublicJWK = RSAKey.parse(values.key);
|
rsaPublicJWK = RSAKey.parse(values.key);
|
||||||
@ -169,25 +162,19 @@ public class JWTWrapper {
|
|||||||
return rsaPublicJWK.toRSAPublicKey();
|
return rsaPublicJWK.toRSAPublicKey();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Create a token with the provided elements
|
||||||
* Create a token with the provided elements
|
|
||||||
* @param userID UniqueId of the USER (global unique ID)
|
* @param userID UniqueId of the USER (global unique ID)
|
||||||
* @param userLogin Login of the user (never change)
|
* @param userLogin Login of the user (never change)
|
||||||
* @param isuer The one who provide the Token
|
* @param isuer The one who provide the Token
|
||||||
* @param timeOutInMunites Expiration of the token.
|
* @param timeOutInMunites Expiration of the token.
|
||||||
* @return the encoded token
|
* @return the encoded token */
|
||||||
*/
|
|
||||||
public static String generateJWToken(final long userID, final String userLogin, final String isuer, final String application, final Map<String, Object> rights, final int timeOutInMunites) {
|
public static String generateJWToken(final long userID, final String userLogin, final String isuer, final String application, final Map<String, Object> rights, final int timeOutInMunites) {
|
||||||
if (rsaJWK == null) {
|
if (rsaJWK == null) {
|
||||||
LOGGER.warn("JWT private key is not present !!!");
|
LOGGER.warn("JWT private key is not present !!!");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
/*
|
/* LOGGER.debug(" ===> expire in : " + timeOutInMunites); LOGGER.debug(" ===>" + new Date().getTime()); LOGGER.debug(" ===>" + new Date(new Date().getTime())); LOGGER.debug(" ===>" + new
|
||||||
LOGGER.debug(" ===> expire in : " + timeOutInMunites);
|
* Date(new Date().getTime() - 60 * timeOutInMunites * 1000)); */
|
||||||
LOGGER.debug(" ===>" + new Date().getTime());
|
|
||||||
LOGGER.debug(" ===>" + new Date(new Date().getTime()));
|
|
||||||
LOGGER.debug(" ===>" + new Date(new Date().getTime() - 60 * timeOutInMunites * 1000));
|
|
||||||
*/
|
|
||||||
try {
|
try {
|
||||||
// Create RSA-signer with the private key
|
// Create RSA-signer with the private key
|
||||||
final JWSSigner signer = new RSASSASigner(rsaJWK);
|
final JWSSigner signer = new RSASSASigner(rsaJWK);
|
||||||
@ -206,7 +193,7 @@ public class JWTWrapper {
|
|||||||
}
|
}
|
||||||
// Prepare JWT with claims set
|
// Prepare JWT with claims set
|
||||||
final JWTClaimsSet claimsSet = builder.build();
|
final JWTClaimsSet claimsSet = builder.build();
|
||||||
final SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT)/*.keyID(rsaJWK.getKeyID())*/.build(), claimsSet);
|
final SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT)/* .keyID(rsaJWK.getKeyID()) */.build(), claimsSet);
|
||||||
|
|
||||||
// Compute the RSA signature
|
// Compute the RSA signature
|
||||||
signedJWT.sign(signer);
|
signedJWT.sign(signer);
|
||||||
@ -222,7 +209,7 @@ public class JWTWrapper {
|
|||||||
try {
|
try {
|
||||||
// On the consumer side, parse the JWS and verify its RSA signature
|
// On the consumer side, parse the JWS and verify its RSA signature
|
||||||
final SignedJWT signedJWT = SignedJWT.parse(signedToken);
|
final SignedJWT signedJWT = SignedJWT.parse(signedToken);
|
||||||
|
|
||||||
if (rsaPublicJWK == null) {
|
if (rsaPublicJWK == null) {
|
||||||
LOGGER.warn("JWT public key is not present !!!");
|
LOGGER.warn("JWT public key is not present !!!");
|
||||||
if (!ConfigBaseVariable.getTestMode()) {
|
if (!ConfigBaseVariable.getTestMode()) {
|
||||||
@ -253,8 +240,8 @@ public class JWTWrapper {
|
|||||||
// TODO: verify the token is used for the correct application.
|
// TODO: verify the token is used for the correct application.
|
||||||
}
|
}
|
||||||
// the element must be validated outside ...
|
// the element must be validated outside ...
|
||||||
//LOGGER.debug("JWT token is verified 'alice' =?= '" + signedJWT.getJWTClaimsSet().getSubject() + "'");
|
// LOGGER.debug("JWT token is verified 'alice' =?= '" + signedJWT.getJWTClaimsSet().getSubject() + "'");
|
||||||
//LOGGER.debug("JWT token isuer 'https://c2id.com' =?= '" + signedJWT.getJWTClaimsSet().getIssuer() + "'");
|
// LOGGER.debug("JWT token isuer 'https://c2id.com' =?= '" + signedJWT.getJWTClaimsSet().getIssuer() + "'");
|
||||||
return signedJWT.getJWTClaimsSet();
|
return signedJWT.getJWTClaimsSet();
|
||||||
} catch (final JOSEException ex) {
|
} catch (final JOSEException ex) {
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
@ -271,10 +258,10 @@ public class JWTWrapper {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
final int timeOutInMunites = 3600 * 24 * 31;
|
final int timeOutInMunites = 3600 * 24 * 31;
|
||||||
|
|
||||||
final Date now = new Date();
|
final Date now = new Date();
|
||||||
final Date expiration = new Date(new Date().getTime() - 60 * timeOutInMunites * 1000 /* millisecond */);
|
final Date expiration = new Date(new Date().getTime() - 60 * timeOutInMunites * 1000 /* millisecond */);
|
||||||
|
|
||||||
final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder().subject(Long.toString(userID)).claim("login", userLogin).claim("application", application).issuer(isuer).issueTime(now)
|
final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder().subject(Long.toString(userID)).claim("login", userLogin).claim("application", application).issuer(isuer).issueTime(now)
|
||||||
.expirationTime(expiration); // Do not ask why we need a "-" here ... this have no meaning
|
.expirationTime(expiration); // Do not ask why we need a "-" here ... this have no meaning
|
||||||
// add right if needed:
|
// add right if needed:
|
||||||
@ -283,11 +270,11 @@ public class JWTWrapper {
|
|||||||
}
|
}
|
||||||
// Prepare JWT with claims set
|
// Prepare JWT with claims set
|
||||||
final JWTClaimsSet claimsSet = builder.build();
|
final JWTClaimsSet claimsSet = builder.build();
|
||||||
final SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT)/*.keyID(rsaJWK.getKeyID())*/.build(), claimsSet);
|
final SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT)/* .keyID(rsaJWK.getKeyID()) */.build(), claimsSet);
|
||||||
|
|
||||||
// Compute the RSA signature
|
// Compute the RSA signature
|
||||||
signedJWT.sign(new TestSigner());
|
signedJWT.sign(new TestSigner());
|
||||||
|
|
||||||
// serialize the output...
|
// serialize the output...
|
||||||
return signedJWT.serialize();
|
return signedJWT.serialize();
|
||||||
} catch (final Exception ex) {
|
} catch (final Exception ex) {
|
||||||
|
@ -2,8 +2,8 @@ package org.kar.archidata.util;
|
|||||||
|
|
||||||
public class PublicKey {
|
public class PublicKey {
|
||||||
public String key;
|
public String key;
|
||||||
|
|
||||||
public PublicKey(String key) {
|
public PublicKey(final String key) {
|
||||||
this.key = key;
|
this.key = key;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -23,162 +23,162 @@ public class RESTApi {
|
|||||||
final static Logger LOGGER = LoggerFactory.getLogger(RESTApi.class);
|
final static Logger LOGGER = LoggerFactory.getLogger(RESTApi.class);
|
||||||
final String baseUrl;
|
final String baseUrl;
|
||||||
private String token = null;
|
private String token = null;
|
||||||
|
|
||||||
public RESTApi(String baseUrl) {
|
public RESTApi(final String baseUrl) {
|
||||||
this.baseUrl = baseUrl;
|
this.baseUrl = baseUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setToken(String token) {
|
public void setToken(final String token) {
|
||||||
this.token = token;
|
this.token = token;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> List<T> gets(Class<T> clazz, String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
public <T> List<T> gets(final Class<T> clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
final HttpClient client = HttpClient.newHttpClient();
|
||||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||||
if (token != null) {
|
if (this.token != null) {
|
||||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||||
}
|
}
|
||||||
HttpRequest request = requestBuilding.GET().build();
|
final HttpRequest request = requestBuilding.GET().build();
|
||||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||||
throw out;
|
throw out;
|
||||||
}
|
}
|
||||||
List<T> out = mapper.readValue(httpResponse.body(), new TypeReference<List<T>>() {});
|
final List<T> out = mapper.readValue(httpResponse.body(), new TypeReference<List<T>>() {});
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> T get(Class<T> clazz, String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
public <T> T get(final Class<T> clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
final HttpClient client = HttpClient.newHttpClient();
|
||||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||||
if (token != null) {
|
if (this.token != null) {
|
||||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||||
}
|
}
|
||||||
HttpRequest request = requestBuilding.GET().build();
|
final HttpRequest request = requestBuilding.GET().build();
|
||||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||||
//LOGGER.error("catch error from REST API: {}", httpResponse.body());
|
// LOGGER.error("catch error from REST API: {}", httpResponse.body());
|
||||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||||
throw new RESTErrorResponseExeption(out.uuid, out.time, out.error, out.message, out.status, out.statusMessage);
|
throw new RESTErrorResponseExeption(out.uuid, out.time, out.error, out.message, out.status, out.statusMessage);
|
||||||
}
|
}
|
||||||
//LOGGER.error("status code: {}", httpResponse.statusCode());
|
// LOGGER.error("status code: {}", httpResponse.statusCode());
|
||||||
//LOGGER.error("data: {}", httpResponse.body());
|
// LOGGER.error("data: {}", httpResponse.body());
|
||||||
if (clazz.equals(String.class)) {
|
if (clazz.equals(String.class)) {
|
||||||
return (T) httpResponse.body();
|
return (T) httpResponse.body();
|
||||||
}
|
}
|
||||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T, U> T post(Class<T> clazz, String urlOffset, U data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
public <T, U> T post(final Class<T> clazz, final String urlOffset, final U data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
final HttpClient client = HttpClient.newHttpClient();
|
||||||
String body = mapper.writeValueAsString(data);
|
final String body = mapper.writeValueAsString(data);
|
||||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||||
if (token != null) {
|
if (this.token != null) {
|
||||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||||
}
|
}
|
||||||
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
||||||
HttpRequest request = requestBuilding.POST(BodyPublishers.ofString(body)).build();
|
final HttpRequest request = requestBuilding.POST(BodyPublishers.ofString(body)).build();
|
||||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||||
LOGGER.error("status code: {}", httpResponse.statusCode());
|
LOGGER.error("status code: {}", httpResponse.statusCode());
|
||||||
LOGGER.error("data: {}", httpResponse.body());
|
LOGGER.error("data: {}", httpResponse.body());
|
||||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||||
throw out;
|
throw out;
|
||||||
}
|
}
|
||||||
if (clazz.equals(String.class)) {
|
if (clazz.equals(String.class)) {
|
||||||
return (T) httpResponse.body();
|
return (T) httpResponse.body();
|
||||||
}
|
}
|
||||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> T postMap(Class<T> clazz, String urlOffset, Map<String, Object> data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
public <T> T postMap(final Class<T> clazz, final String urlOffset, final Map<String, Object> data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
final HttpClient client = HttpClient.newHttpClient();
|
||||||
String body = mapper.writeValueAsString(data);
|
final String body = mapper.writeValueAsString(data);
|
||||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||||
if (token != null) {
|
if (this.token != null) {
|
||||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||||
}
|
}
|
||||||
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
||||||
HttpRequest request = requestBuilding.POST(BodyPublishers.ofString(body)).build();
|
final HttpRequest request = requestBuilding.POST(BodyPublishers.ofString(body)).build();
|
||||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||||
throw out;
|
throw out;
|
||||||
}
|
}
|
||||||
if (clazz.equals(String.class)) {
|
if (clazz.equals(String.class)) {
|
||||||
return (T) httpResponse.body();
|
return (T) httpResponse.body();
|
||||||
}
|
}
|
||||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T, U> T put(Class<T> clazz, String urlOffset, U data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
public <T, U> T put(final Class<T> clazz, final String urlOffset, final U data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
final HttpClient client = HttpClient.newHttpClient();
|
||||||
String body = mapper.writeValueAsString(data);
|
final String body = mapper.writeValueAsString(data);
|
||||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||||
if (token != null) {
|
if (this.token != null) {
|
||||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||||
}
|
}
|
||||||
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
||||||
HttpRequest request = requestBuilding.PUT(BodyPublishers.ofString(body)).build();
|
final HttpRequest request = requestBuilding.PUT(BodyPublishers.ofString(body)).build();
|
||||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||||
throw out;
|
throw out;
|
||||||
}
|
}
|
||||||
if (clazz.equals(String.class)) {
|
if (clazz.equals(String.class)) {
|
||||||
return (T) httpResponse.body();
|
return (T) httpResponse.body();
|
||||||
}
|
}
|
||||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T> T putMap(Class<T> clazz, String urlOffset, Map<String, Object> data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
public <T> T putMap(final Class<T> clazz, final String urlOffset, final Map<String, Object> data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
final HttpClient client = HttpClient.newHttpClient();
|
||||||
String body = mapper.writeValueAsString(data);
|
final String body = mapper.writeValueAsString(data);
|
||||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||||
if (token != null) {
|
if (this.token != null) {
|
||||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||||
}
|
}
|
||||||
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
||||||
HttpRequest request = requestBuilding.PUT(BodyPublishers.ofString(body)).build();
|
final HttpRequest request = requestBuilding.PUT(BodyPublishers.ofString(body)).build();
|
||||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||||
throw out;
|
throw out;
|
||||||
}
|
}
|
||||||
if (clazz.equals(String.class)) {
|
if (clazz.equals(String.class)) {
|
||||||
return (T) httpResponse.body();
|
return (T) httpResponse.body();
|
||||||
}
|
}
|
||||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
public <T, U> T delete(Class<T> clazz, String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
public <T, U> T delete(final Class<T> clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
final ObjectMapper mapper = new ObjectMapper();
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
final HttpClient client = HttpClient.newHttpClient();
|
||||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||||
if (token != null) {
|
if (this.token != null) {
|
||||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||||
}
|
}
|
||||||
HttpRequest request = requestBuilding.DELETE().build();
|
final HttpRequest request = requestBuilding.DELETE().build();
|
||||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||||
throw out;
|
throw out;
|
||||||
}
|
}
|
||||||
if (clazz.equals(String.class)) {
|
if (clazz.equals(String.class)) {
|
||||||
return (T) httpResponse.body();
|
return (T) httpResponse.body();
|
||||||
}
|
}
|
||||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -26,26 +26,26 @@ import test.kar.archidata.model.SimpleTable;
|
|||||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||||
public class TestJson {
|
public class TestJson {
|
||||||
final static private Logger LOGGER = LoggerFactory.getLogger(TestJson.class);
|
final static private Logger LOGGER = LoggerFactory.getLogger(TestJson.class);
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
public static void configureWebServer() throws Exception {
|
public static void configureWebServer() throws Exception {
|
||||||
ConfigBaseVariable.dbType = "sqlite";
|
ConfigBaseVariable.dbType = "sqlite";
|
||||||
ConfigBaseVariable.dbHost = "memory";
|
ConfigBaseVariable.dbHost = "memory";
|
||||||
// for test we need to connect all time the DB
|
// for test we need to connect all time the DB
|
||||||
ConfigBaseVariable.dbKeepConnected = "true";
|
ConfigBaseVariable.dbKeepConnected = "true";
|
||||||
|
|
||||||
// Connect the dataBase...
|
// Connect the dataBase...
|
||||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
entry.connect();
|
entry.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterAll
|
@AfterAll
|
||||||
public static void removeDataBase() throws IOException {
|
public static void removeDataBase() throws IOException {
|
||||||
LOGGER.info("Remove the test db");
|
LOGGER.info("Remove the test db");
|
||||||
DBEntry.closeAllForceMode();
|
DBEntry.closeAllForceMode();
|
||||||
ConfigBaseVariable.clearAllValue();
|
ConfigBaseVariable.clearAllValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(1)
|
@Order(1)
|
||||||
@Test
|
@Test
|
||||||
public void testTableInsertAndRetrieve() throws Exception {
|
public void testTableInsertAndRetrieve() throws Exception {
|
||||||
@ -64,17 +64,17 @@ public class TestJson {
|
|||||||
test.data.data = "plopppopql";
|
test.data.data = "plopppopql";
|
||||||
|
|
||||||
final SerializeAsJson insertedData = DataAccess.insert(test);
|
final SerializeAsJson insertedData = DataAccess.insert(test);
|
||||||
|
|
||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
Assertions.assertNotNull(insertedData.data);
|
Assertions.assertNotNull(insertedData.data);
|
||||||
Assertions.assertNotNull(insertedData.data.data);
|
Assertions.assertNotNull(insertedData.data.data);
|
||||||
Assertions.assertEquals(test.data.data, insertedData.data.data);
|
Assertions.assertEquals(test.data.data, insertedData.data.data);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final SerializeAsJson retrieve = DataAccess.get(SerializeAsJson.class, insertedData.id);
|
final SerializeAsJson retrieve = DataAccess.get(SerializeAsJson.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertTrue(retrieve.id >= 0);
|
Assertions.assertTrue(retrieve.id >= 0);
|
||||||
@ -82,5 +82,5 @@ public class TestJson {
|
|||||||
Assertions.assertNotNull(retrieve.data.data);
|
Assertions.assertNotNull(retrieve.data.data);
|
||||||
Assertions.assertEquals(test.data.data, retrieve.data.data);
|
Assertions.assertEquals(test.data.data, retrieve.data.data);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -59,7 +59,7 @@ public class TestManyToMany {
|
|||||||
DataAccess.executeSimpleQuerry(elem, false);
|
DataAccess.executeSimpleQuerry(elem, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(2)
|
@Order(2)
|
||||||
@Test
|
@Test
|
||||||
public void testSimpleInsertAndRetieve() throws Exception {
|
public void testSimpleInsertAndRetieve() throws Exception {
|
||||||
@ -80,7 +80,7 @@ public class TestManyToMany {
|
|||||||
Assertions.assertNotNull(retrieve.otherData);
|
Assertions.assertNotNull(retrieve.otherData);
|
||||||
Assertions.assertEquals(insertedData.otherData, retrieve.otherData);
|
Assertions.assertEquals(insertedData.otherData, retrieve.otherData);
|
||||||
Assertions.assertNull(retrieve.remote);
|
Assertions.assertNull(retrieve.remote);
|
||||||
|
|
||||||
DataAccess.delete(TypeManyToManyRoot.class, insertedData.id);
|
DataAccess.delete(TypeManyToManyRoot.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,7 +92,7 @@ public class TestManyToMany {
|
|||||||
remote.data = "remote1";
|
remote.data = "remote1";
|
||||||
final TypeManyToManyRemote insertedRemote1 = DataAccess.insert(remote);
|
final TypeManyToManyRemote insertedRemote1 = DataAccess.insert(remote);
|
||||||
Assertions.assertEquals(insertedRemote1.data, remote.data);
|
Assertions.assertEquals(insertedRemote1.data, remote.data);
|
||||||
|
|
||||||
remote = new TypeManyToManyRemote();
|
remote = new TypeManyToManyRemote();
|
||||||
remote.data = "remote2";
|
remote.data = "remote2";
|
||||||
final TypeManyToManyRemote insertedRemote2 = DataAccess.insert(remote);
|
final TypeManyToManyRemote insertedRemote2 = DataAccess.insert(remote);
|
||||||
@ -105,7 +105,7 @@ public class TestManyToMany {
|
|||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
Assertions.assertNull(insertedData.remote);
|
Assertions.assertNull(insertedData.remote);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
TypeManyToManyRoot retrieve = DataAccess.get(TypeManyToManyRoot.class, insertedData.id);
|
TypeManyToManyRoot retrieve = DataAccess.get(TypeManyToManyRoot.class, insertedData.id);
|
||||||
|
|
||||||
@ -119,9 +119,9 @@ public class TestManyToMany {
|
|||||||
// Add remote elements
|
// Add remote elements
|
||||||
AddOnManyToMany.addLink(TypeManyToManyRoot.class, retrieve.id, "remote", insertedRemote1.id);
|
AddOnManyToMany.addLink(TypeManyToManyRoot.class, retrieve.id, "remote", insertedRemote1.id);
|
||||||
AddOnManyToMany.addLink(TypeManyToManyRoot.class, retrieve.id, "remote", insertedRemote2.id);
|
AddOnManyToMany.addLink(TypeManyToManyRoot.class, retrieve.id, "remote", insertedRemote2.id);
|
||||||
|
|
||||||
retrieve = DataAccess.get(TypeManyToManyRoot.class, insertedData.id);
|
retrieve = DataAccess.get(TypeManyToManyRoot.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -131,9 +131,9 @@ public class TestManyToMany {
|
|||||||
Assertions.assertEquals(retrieve.remote.size(), 2);
|
Assertions.assertEquals(retrieve.remote.size(), 2);
|
||||||
Assertions.assertEquals(retrieve.remote.get(0), insertedRemote1.id);
|
Assertions.assertEquals(retrieve.remote.get(0), insertedRemote1.id);
|
||||||
Assertions.assertEquals(retrieve.remote.get(1), insertedRemote2.id);
|
Assertions.assertEquals(retrieve.remote.get(1), insertedRemote2.id);
|
||||||
|
|
||||||
final TypeManyToManyRootExpand retrieveExpand = DataAccess.get(TypeManyToManyRootExpand.class, insertedData.id);
|
final TypeManyToManyRootExpand retrieveExpand = DataAccess.get(TypeManyToManyRootExpand.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieveExpand);
|
Assertions.assertNotNull(retrieveExpand);
|
||||||
Assertions.assertNotNull(retrieveExpand.id);
|
Assertions.assertNotNull(retrieveExpand.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieveExpand.id);
|
Assertions.assertEquals(insertedData.id, retrieveExpand.id);
|
||||||
@ -143,7 +143,7 @@ public class TestManyToMany {
|
|||||||
Assertions.assertEquals(retrieveExpand.remote.size(), 2);
|
Assertions.assertEquals(retrieveExpand.remote.size(), 2);
|
||||||
Assertions.assertEquals(retrieveExpand.remote.get(0).id, insertedRemote1.id);
|
Assertions.assertEquals(retrieveExpand.remote.get(0).id, insertedRemote1.id);
|
||||||
Assertions.assertEquals(retrieveExpand.remote.get(1).id, insertedRemote2.id);
|
Assertions.assertEquals(retrieveExpand.remote.get(1).id, insertedRemote2.id);
|
||||||
|
|
||||||
// Remove an element
|
// Remove an element
|
||||||
int count = AddOnManyToMany.removeLink(TypeManyToManyRoot.class, retrieve.id, "remote", insertedRemote1.id);
|
int count = AddOnManyToMany.removeLink(TypeManyToManyRoot.class, retrieve.id, "remote", insertedRemote1.id);
|
||||||
Assertions.assertEquals(1, count);
|
Assertions.assertEquals(1, count);
|
||||||
@ -158,28 +158,23 @@ public class TestManyToMany {
|
|||||||
Assertions.assertNotNull(retrieve.remote);
|
Assertions.assertNotNull(retrieve.remote);
|
||||||
Assertions.assertEquals(retrieve.remote.size(), 1);
|
Assertions.assertEquals(retrieve.remote.size(), 1);
|
||||||
Assertions.assertEquals(retrieve.remote.get(0), insertedRemote2.id);
|
Assertions.assertEquals(retrieve.remote.get(0), insertedRemote2.id);
|
||||||
|
|
||||||
// Remove the second element
|
// Remove the second element
|
||||||
count = AddOnManyToMany.removeLink(TypeManyToManyRoot.class, retrieve.id, "remote", insertedRemote2.id);
|
count = AddOnManyToMany.removeLink(TypeManyToManyRoot.class, retrieve.id, "remote", insertedRemote2.id);
|
||||||
Assertions.assertEquals(1, count);
|
Assertions.assertEquals(1, count);
|
||||||
|
|
||||||
retrieve = DataAccess.get(TypeManyToManyRoot.class, insertedData.id);
|
retrieve = DataAccess.get(TypeManyToManyRoot.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
Assertions.assertNotNull(retrieve.otherData);
|
Assertions.assertNotNull(retrieve.otherData);
|
||||||
Assertions.assertEquals(insertedData.otherData, retrieve.otherData);
|
Assertions.assertEquals(insertedData.otherData, retrieve.otherData);
|
||||||
Assertions.assertNull(retrieve.remote);
|
Assertions.assertNull(retrieve.remote);
|
||||||
|
|
||||||
DataAccess.delete(TypeManyToManyRoot.class, insertedData.id);
|
DataAccess.delete(TypeManyToManyRoot.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/* API TODO: - Replace list (permet de les ordonnées) - remove all links - delete en cascade .... (compliqué...) */
|
||||||
API TODO:
|
|
||||||
- Replace list (permet de les ordonnées)
|
|
||||||
- remove all links
|
|
||||||
- delete en cascade .... (compliqué...)
|
|
||||||
*/
|
|
||||||
|
|
||||||
}
|
}
|
@ -58,7 +58,7 @@ public class TestManyToOne {
|
|||||||
DataAccess.executeSimpleQuerry(elem, false);
|
DataAccess.executeSimpleQuerry(elem, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(2)
|
@Order(2)
|
||||||
@Test
|
@Test
|
||||||
public void testAddAlements() throws Exception {
|
public void testAddAlements() throws Exception {
|
||||||
@ -71,7 +71,7 @@ public class TestManyToOne {
|
|||||||
remote.data = "remote2";
|
remote.data = "remote2";
|
||||||
final TypeManyToOneRemote insertedRemote2 = DataAccess.insert(remote);
|
final TypeManyToOneRemote insertedRemote2 = DataAccess.insert(remote);
|
||||||
Assertions.assertEquals(insertedRemote2.data, remote.data);
|
Assertions.assertEquals(insertedRemote2.data, remote.data);
|
||||||
|
|
||||||
final TypeManyToOneRoot test = new TypeManyToOneRoot();
|
final TypeManyToOneRoot test = new TypeManyToOneRoot();
|
||||||
test.otherData = "kjhlkjlkj";
|
test.otherData = "kjhlkjlkj";
|
||||||
test.remoteId = insertedRemote2.id;
|
test.remoteId = insertedRemote2.id;
|
||||||
@ -101,9 +101,9 @@ public class TestManyToOne {
|
|||||||
// remove values:
|
// remove values:
|
||||||
final int count = DataAccess.delete(TypeManyToOneRemote.class, remote.id);
|
final int count = DataAccess.delete(TypeManyToOneRemote.class, remote.id);
|
||||||
Assertions.assertEquals(1, count);
|
Assertions.assertEquals(1, count);
|
||||||
|
|
||||||
// check fail:
|
// check fail:
|
||||||
|
|
||||||
retrieve = DataAccess.get(TypeManyToOneRoot.class, insertedData.id);
|
retrieve = DataAccess.get(TypeManyToOneRoot.class, insertedData.id);
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
|
@ -53,10 +53,10 @@ public class TestOneToMany {
|
|||||||
DataAccess.executeSimpleQuerry(elem, false);
|
DataAccess.executeSimpleQuerry(elem, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(2)
|
@Order(2)
|
||||||
@Test
|
@Test
|
||||||
public void testPlop() throws Exception {
|
public void testPlop() throws Exception {
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -33,30 +33,30 @@ public class TestSimpleTable {
|
|||||||
private static final String DATA_INJECTED_2 = "dsqfsdfqsdfsqdf";
|
private static final String DATA_INJECTED_2 = "dsqfsdfqsdfsqdf";
|
||||||
private static Long idOfTheObject = null;
|
private static Long idOfTheObject = null;
|
||||||
private static Timestamp startAction = null;
|
private static Timestamp startAction = null;
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
public static void configureWebServer() throws Exception {
|
public static void configureWebServer() throws Exception {
|
||||||
ConfigBaseVariable.dbType = "sqlite";
|
ConfigBaseVariable.dbType = "sqlite";
|
||||||
ConfigBaseVariable.dbHost = "memory";
|
ConfigBaseVariable.dbHost = "memory";
|
||||||
// for test we need to connect all time the DB
|
// for test we need to connect all time the DB
|
||||||
ConfigBaseVariable.dbKeepConnected = "true";
|
ConfigBaseVariable.dbKeepConnected = "true";
|
||||||
|
|
||||||
// Clear the static test:
|
// Clear the static test:
|
||||||
idOfTheObject = null;
|
idOfTheObject = null;
|
||||||
startAction = null;
|
startAction = null;
|
||||||
|
|
||||||
// Connect the dataBase...
|
// Connect the dataBase...
|
||||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
entry.connect();
|
entry.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterAll
|
@AfterAll
|
||||||
public static void removeDataBase() throws IOException {
|
public static void removeDataBase() throws IOException {
|
||||||
LOGGER.info("Remove the test db");
|
LOGGER.info("Remove the test db");
|
||||||
DBEntry.closeAllForceMode();
|
DBEntry.closeAllForceMode();
|
||||||
ConfigBaseVariable.clearAllValue();
|
ConfigBaseVariable.clearAllValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(1)
|
@Order(1)
|
||||||
@Test
|
@Test
|
||||||
public void testTableInsertAndRetrieve() throws Exception {
|
public void testTableInsertAndRetrieve() throws Exception {
|
||||||
@ -69,14 +69,14 @@ public class TestSimpleTable {
|
|||||||
final SimpleTable test = new SimpleTable();
|
final SimpleTable test = new SimpleTable();
|
||||||
test.data = TestSimpleTable.DATA_INJECTED;
|
test.data = TestSimpleTable.DATA_INJECTED;
|
||||||
final SimpleTable insertedData = DataAccess.insert(test);
|
final SimpleTable insertedData = DataAccess.insert(test);
|
||||||
|
|
||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, insertedData.id);
|
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -85,13 +85,13 @@ public class TestSimpleTable {
|
|||||||
Assertions.assertNull(retrieve.updatedAt);
|
Assertions.assertNull(retrieve.updatedAt);
|
||||||
TestSimpleTable.idOfTheObject = retrieve.id;
|
TestSimpleTable.idOfTheObject = retrieve.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(2)
|
@Order(2)
|
||||||
@Test
|
@Test
|
||||||
public void testReadAllValuesUnreadable() throws Exception {
|
public void testReadAllValuesUnreadable() throws Exception {
|
||||||
// check the full values
|
// check the full values
|
||||||
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.SQL_NOT_READ_DISABLE, true));
|
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.SQL_NOT_READ_DISABLE, true));
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(TestSimpleTable.idOfTheObject, retrieve.id);
|
Assertions.assertEquals(TestSimpleTable.idOfTheObject, retrieve.id);
|
||||||
@ -104,7 +104,7 @@ public class TestSimpleTable {
|
|||||||
// Assertions.assertTrue(retrieve.updatedAt.after(this.startAction));
|
// Assertions.assertTrue(retrieve.updatedAt.after(this.startAction));
|
||||||
Assertions.assertEquals(retrieve.createdAt, retrieve.updatedAt);
|
Assertions.assertEquals(retrieve.createdAt, retrieve.updatedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(3)
|
@Order(3)
|
||||||
@Test
|
@Test
|
||||||
public void testUpdateData() throws Exception {
|
public void testUpdateData() throws Exception {
|
||||||
@ -113,7 +113,7 @@ public class TestSimpleTable {
|
|||||||
} else {
|
} else {
|
||||||
Thread.sleep(Duration.ofMillis(15));
|
Thread.sleep(Duration.ofMillis(15));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete the entry:
|
// Delete the entry:
|
||||||
final SimpleTable test = new SimpleTable();
|
final SimpleTable test = new SimpleTable();
|
||||||
test.data = TestSimpleTable.DATA_INJECTED_2;
|
test.data = TestSimpleTable.DATA_INJECTED_2;
|
||||||
@ -128,7 +128,7 @@ public class TestSimpleTable {
|
|||||||
LOGGER.info("created @ {} updated @ {}", retrieve.createdAt, retrieve.updatedAt);
|
LOGGER.info("created @ {} updated @ {}", retrieve.createdAt, retrieve.updatedAt);
|
||||||
Assertions.assertTrue(retrieve.updatedAt.after(retrieve.createdAt));
|
Assertions.assertTrue(retrieve.updatedAt.after(retrieve.createdAt));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(4)
|
@Order(4)
|
||||||
@Test
|
@Test
|
||||||
public void testDeleteTheObject() throws Exception {
|
public void testDeleteTheObject() throws Exception {
|
||||||
@ -137,17 +137,17 @@ public class TestSimpleTable {
|
|||||||
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject);
|
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject);
|
||||||
Assertions.assertNull(retrieve);
|
Assertions.assertNull(retrieve);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(5)
|
@Order(5)
|
||||||
@Test
|
@Test
|
||||||
public void testReadDeletedObject() throws Exception {
|
public void testReadDeletedObject() throws Exception {
|
||||||
|
|
||||||
// check if we set get deleted element
|
// check if we set get deleted element
|
||||||
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true));
|
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true));
|
||||||
Assertions.assertNull(retrieve);
|
Assertions.assertNull(retrieve);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(6)
|
@Order(6)
|
||||||
@Test
|
@Test
|
||||||
public void testReadAllValuesUnreadableOfDeletedObject() throws Exception {
|
public void testReadAllValuesUnreadableOfDeletedObject() throws Exception {
|
||||||
@ -155,6 +155,6 @@ public class TestSimpleTable {
|
|||||||
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject,
|
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject,
|
||||||
new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true, QueryOptions.SQL_NOT_READ_DISABLE, true));
|
new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true, QueryOptions.SQL_NOT_READ_DISABLE, true));
|
||||||
Assertions.assertNull(retrieve);
|
Assertions.assertNull(retrieve);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -33,30 +33,30 @@ public class TestSimpleTableSoftDelete {
|
|||||||
private static final String DATA_INJECTED_2 = "qsdfqsdfqsdfsqdf";
|
private static final String DATA_INJECTED_2 = "qsdfqsdfqsdfsqdf";
|
||||||
private static Long idOfTheObject = null;
|
private static Long idOfTheObject = null;
|
||||||
private static Timestamp startAction = null;
|
private static Timestamp startAction = null;
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
public static void configureWebServer() throws Exception {
|
public static void configureWebServer() throws Exception {
|
||||||
ConfigBaseVariable.dbType = "sqlite";
|
ConfigBaseVariable.dbType = "sqlite";
|
||||||
ConfigBaseVariable.dbHost = "memory";
|
ConfigBaseVariable.dbHost = "memory";
|
||||||
// for test we need to connect all time the DB
|
// for test we need to connect all time the DB
|
||||||
ConfigBaseVariable.dbKeepConnected = "true";
|
ConfigBaseVariable.dbKeepConnected = "true";
|
||||||
|
|
||||||
// Clear the static test:
|
// Clear the static test:
|
||||||
idOfTheObject = null;
|
idOfTheObject = null;
|
||||||
startAction = null;
|
startAction = null;
|
||||||
|
|
||||||
// Connect the dataBase...
|
// Connect the dataBase...
|
||||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
entry.connect();
|
entry.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterAll
|
@AfterAll
|
||||||
public static void removeDataBase() throws IOException {
|
public static void removeDataBase() throws IOException {
|
||||||
LOGGER.info("Remove the test db");
|
LOGGER.info("Remove the test db");
|
||||||
DBEntry.closeAllForceMode();
|
DBEntry.closeAllForceMode();
|
||||||
ConfigBaseVariable.clearAllValue();
|
ConfigBaseVariable.clearAllValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(1)
|
@Order(1)
|
||||||
@Test
|
@Test
|
||||||
public void testTableInsertAndRetrieve() throws Exception {
|
public void testTableInsertAndRetrieve() throws Exception {
|
||||||
@ -69,14 +69,14 @@ public class TestSimpleTableSoftDelete {
|
|||||||
final SimpleTableSoftDelete test = new SimpleTableSoftDelete();
|
final SimpleTableSoftDelete test = new SimpleTableSoftDelete();
|
||||||
test.data = TestSimpleTableSoftDelete.DATA_INJECTED;
|
test.data = TestSimpleTableSoftDelete.DATA_INJECTED;
|
||||||
final SimpleTableSoftDelete insertedData = DataAccess.insert(test);
|
final SimpleTableSoftDelete insertedData = DataAccess.insert(test);
|
||||||
|
|
||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, insertedData.id);
|
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -86,13 +86,13 @@ public class TestSimpleTableSoftDelete {
|
|||||||
Assertions.assertNull(retrieve.deleted);
|
Assertions.assertNull(retrieve.deleted);
|
||||||
TestSimpleTableSoftDelete.idOfTheObject = retrieve.id;
|
TestSimpleTableSoftDelete.idOfTheObject = retrieve.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(2)
|
@Order(2)
|
||||||
@Test
|
@Test
|
||||||
public void testReadAllValuesUnreadable() throws Exception {
|
public void testReadAllValuesUnreadable() throws Exception {
|
||||||
// check the full values
|
// check the full values
|
||||||
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, new QueryOptions(QueryOptions.SQL_NOT_READ_DISABLE, true));
|
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, new QueryOptions(QueryOptions.SQL_NOT_READ_DISABLE, true));
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id);
|
Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id);
|
||||||
@ -107,7 +107,7 @@ public class TestSimpleTableSoftDelete {
|
|||||||
Assertions.assertNotNull(retrieve.deleted);
|
Assertions.assertNotNull(retrieve.deleted);
|
||||||
Assertions.assertEquals(false, retrieve.deleted);
|
Assertions.assertEquals(false, retrieve.deleted);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(3)
|
@Order(3)
|
||||||
@Test
|
@Test
|
||||||
public void testUpdateData() throws Exception {
|
public void testUpdateData() throws Exception {
|
||||||
@ -116,7 +116,7 @@ public class TestSimpleTableSoftDelete {
|
|||||||
} else {
|
} else {
|
||||||
Thread.sleep(Duration.ofMillis(15));
|
Thread.sleep(Duration.ofMillis(15));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete the entry:
|
// Delete the entry:
|
||||||
final SimpleTableSoftDelete test = new SimpleTableSoftDelete();
|
final SimpleTableSoftDelete test = new SimpleTableSoftDelete();
|
||||||
test.data = TestSimpleTableSoftDelete.DATA_INJECTED_2;
|
test.data = TestSimpleTableSoftDelete.DATA_INJECTED_2;
|
||||||
@ -134,7 +134,7 @@ public class TestSimpleTableSoftDelete {
|
|||||||
Assertions.assertNotNull(retrieve.deleted);
|
Assertions.assertNotNull(retrieve.deleted);
|
||||||
Assertions.assertEquals(false, retrieve.deleted);
|
Assertions.assertEquals(false, retrieve.deleted);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(4)
|
@Order(4)
|
||||||
@Test
|
@Test
|
||||||
public void testSoftDeleteTheObject() throws Exception {
|
public void testSoftDeleteTheObject() throws Exception {
|
||||||
@ -148,11 +148,11 @@ public class TestSimpleTableSoftDelete {
|
|||||||
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject);
|
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject);
|
||||||
Assertions.assertNull(retrieve);
|
Assertions.assertNull(retrieve);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(5)
|
@Order(5)
|
||||||
@Test
|
@Test
|
||||||
public void testReadDeletedObject() throws Exception {
|
public void testReadDeletedObject() throws Exception {
|
||||||
|
|
||||||
// check if we set get deleted element
|
// check if we set get deleted element
|
||||||
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true));
|
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true));
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
@ -162,9 +162,9 @@ public class TestSimpleTableSoftDelete {
|
|||||||
Assertions.assertNull(retrieve.createdAt);
|
Assertions.assertNull(retrieve.createdAt);
|
||||||
Assertions.assertNull(retrieve.updatedAt);
|
Assertions.assertNull(retrieve.updatedAt);
|
||||||
Assertions.assertNull(retrieve.deleted);
|
Assertions.assertNull(retrieve.deleted);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(6)
|
@Order(6)
|
||||||
@Test
|
@Test
|
||||||
public void testReadAllValuesUnreadableOfDeletedObject() throws Exception {
|
public void testReadAllValuesUnreadableOfDeletedObject() throws Exception {
|
||||||
@ -181,6 +181,6 @@ public class TestSimpleTableSoftDelete {
|
|||||||
Assertions.assertTrue(retrieve.updatedAt.after(retrieve.createdAt));
|
Assertions.assertTrue(retrieve.updatedAt.after(retrieve.createdAt));
|
||||||
Assertions.assertNotNull(retrieve.deleted);
|
Assertions.assertNotNull(retrieve.deleted);
|
||||||
Assertions.assertEquals(true, retrieve.deleted);
|
Assertions.assertEquals(true, retrieve.deleted);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -26,26 +26,26 @@ import test.kar.archidata.model.TypesEnum1;
|
|||||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||||
public class TestTypeEnum1 {
|
public class TestTypeEnum1 {
|
||||||
final static private Logger LOGGER = LoggerFactory.getLogger(TestTypeEnum1.class);
|
final static private Logger LOGGER = LoggerFactory.getLogger(TestTypeEnum1.class);
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
public static void configureWebServer() throws Exception {
|
public static void configureWebServer() throws Exception {
|
||||||
ConfigBaseVariable.dbType = "sqlite";
|
ConfigBaseVariable.dbType = "sqlite";
|
||||||
ConfigBaseVariable.dbHost = "memory";
|
ConfigBaseVariable.dbHost = "memory";
|
||||||
// for test we need to connect all time the DB
|
// for test we need to connect all time the DB
|
||||||
ConfigBaseVariable.dbKeepConnected = "true";
|
ConfigBaseVariable.dbKeepConnected = "true";
|
||||||
|
|
||||||
// Connect the dataBase...
|
// Connect the dataBase...
|
||||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
entry.connect();
|
entry.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterAll
|
@AfterAll
|
||||||
public static void removeDataBase() throws IOException {
|
public static void removeDataBase() throws IOException {
|
||||||
LOGGER.info("Remove the test db");
|
LOGGER.info("Remove the test db");
|
||||||
DBEntry.closeAllForceMode();
|
DBEntry.closeAllForceMode();
|
||||||
ConfigBaseVariable.clearAllValue();
|
ConfigBaseVariable.clearAllValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(1)
|
@Order(1)
|
||||||
@Test
|
@Test
|
||||||
public void testCreateTable() throws Exception {
|
public void testCreateTable() throws Exception {
|
||||||
@ -66,10 +66,10 @@ public class TestTypeEnum1 {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesEnum1 retrieve = DataAccess.get(TypesEnum1.class, insertedData.id);
|
final TypesEnum1 retrieve = DataAccess.get(TypesEnum1.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
|
@ -26,26 +26,26 @@ import test.kar.archidata.model.TypesEnum2;
|
|||||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||||
public class TestTypeEnum2 {
|
public class TestTypeEnum2 {
|
||||||
final static private Logger LOGGER = LoggerFactory.getLogger(TestTypeEnum2.class);
|
final static private Logger LOGGER = LoggerFactory.getLogger(TestTypeEnum2.class);
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
public static void configureWebServer() throws Exception {
|
public static void configureWebServer() throws Exception {
|
||||||
ConfigBaseVariable.dbType = "sqlite";
|
ConfigBaseVariable.dbType = "sqlite";
|
||||||
ConfigBaseVariable.dbHost = "memory";
|
ConfigBaseVariable.dbHost = "memory";
|
||||||
// for test we need to connect all time the DB
|
// for test we need to connect all time the DB
|
||||||
ConfigBaseVariable.dbKeepConnected = "true";
|
ConfigBaseVariable.dbKeepConnected = "true";
|
||||||
|
|
||||||
// Connect the dataBase...
|
// Connect the dataBase...
|
||||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
entry.connect();
|
entry.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterAll
|
@AfterAll
|
||||||
public static void removeDataBase() throws IOException {
|
public static void removeDataBase() throws IOException {
|
||||||
LOGGER.info("Remove the test db");
|
LOGGER.info("Remove the test db");
|
||||||
DBEntry.closeAllForceMode();
|
DBEntry.closeAllForceMode();
|
||||||
ConfigBaseVariable.clearAllValue();
|
ConfigBaseVariable.clearAllValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(1)
|
@Order(1)
|
||||||
@Test
|
@Test
|
||||||
public void testCreateTable() throws Exception {
|
public void testCreateTable() throws Exception {
|
||||||
@ -66,7 +66,7 @@ public class TestTypeEnum2 {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
TypesEnum2 retrieve = DataAccess.get(TypesEnum2.class, insertedData.id);
|
TypesEnum2 retrieve = DataAccess.get(TypesEnum2.class, insertedData.id);
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
@ -79,18 +79,18 @@ public class TestTypeEnum2 {
|
|||||||
retrieve.data = null;
|
retrieve.data = null;
|
||||||
int ret = DataAccess.update(retrieve, retrieve.id);
|
int ret = DataAccess.update(retrieve, retrieve.id);
|
||||||
Assertions.assertEquals(1, ret);
|
Assertions.assertEquals(1, ret);
|
||||||
|
|
||||||
// get new data
|
// get new data
|
||||||
retrieve = DataAccess.get(TypesEnum2.class, insertedData.id);
|
retrieve = DataAccess.get(TypesEnum2.class, insertedData.id);
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
Assertions.assertNull(retrieve.data);
|
Assertions.assertNull(retrieve.data);
|
||||||
|
|
||||||
// Remove the data
|
// Remove the data
|
||||||
ret = DataAccess.delete(TypesEnum2.class, insertedData.id);
|
ret = DataAccess.delete(TypesEnum2.class, insertedData.id);
|
||||||
Assertions.assertEquals(1, ret);
|
Assertions.assertEquals(1, ret);
|
||||||
|
|
||||||
// Get the removed data:
|
// Get the removed data:
|
||||||
retrieve = DataAccess.get(TypesEnum2.class, insertedData.id);
|
retrieve = DataAccess.get(TypesEnum2.class, insertedData.id);
|
||||||
Assertions.assertNull(retrieve);
|
Assertions.assertNull(retrieve);
|
||||||
@ -106,10 +106,10 @@ public class TestTypeEnum2 {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesEnum2 retrieve = DataAccess.get(TypesEnum2.class, insertedData.id);
|
final TypesEnum2 retrieve = DataAccess.get(TypesEnum2.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
|
@ -30,26 +30,26 @@ import test.kar.archidata.model.TypesTable;
|
|||||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||||
public class TestTypes {
|
public class TestTypes {
|
||||||
final static private Logger LOGGER = LoggerFactory.getLogger(TestTypes.class);
|
final static private Logger LOGGER = LoggerFactory.getLogger(TestTypes.class);
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
public static void configureWebServer() throws Exception {
|
public static void configureWebServer() throws Exception {
|
||||||
ConfigBaseVariable.dbType = "sqlite";
|
ConfigBaseVariable.dbType = "sqlite";
|
||||||
ConfigBaseVariable.dbHost = "memory";
|
ConfigBaseVariable.dbHost = "memory";
|
||||||
// for test we need to connect all time the DB
|
// for test we need to connect all time the DB
|
||||||
ConfigBaseVariable.dbKeepConnected = "true";
|
ConfigBaseVariable.dbKeepConnected = "true";
|
||||||
|
|
||||||
// Connect the dataBase...
|
// Connect the dataBase...
|
||||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||||
entry.connect();
|
entry.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterAll
|
@AfterAll
|
||||||
public static void removeDataBase() throws IOException {
|
public static void removeDataBase() throws IOException {
|
||||||
LOGGER.info("Remove the test db");
|
LOGGER.info("Remove the test db");
|
||||||
DBEntry.closeAllForceMode();
|
DBEntry.closeAllForceMode();
|
||||||
ConfigBaseVariable.clearAllValue();
|
ConfigBaseVariable.clearAllValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(1)
|
@Order(1)
|
||||||
@Test
|
@Test
|
||||||
public void testCreateTable() throws Exception {
|
public void testCreateTable() throws Exception {
|
||||||
@ -70,10 +70,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -82,7 +82,7 @@ public class TestTypes {
|
|||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(3)
|
@Order(3)
|
||||||
@Test
|
@Test
|
||||||
public void testLong() throws Exception {
|
public void testLong() throws Exception {
|
||||||
@ -93,10 +93,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -105,7 +105,7 @@ public class TestTypes {
|
|||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(4)
|
@Order(4)
|
||||||
@Test
|
@Test
|
||||||
public void testfloat() throws Exception {
|
public void testfloat() throws Exception {
|
||||||
@ -116,10 +116,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -139,16 +139,16 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
Assertions.assertNotNull(retrieve.doubleData);
|
Assertions.assertNotNull(retrieve.doubleData);
|
||||||
Assertions.assertEquals(insertedData.doubleData, retrieve.doubleData);
|
Assertions.assertEquals(insertedData.doubleData, retrieve.doubleData);
|
||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -162,10 +162,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -185,10 +185,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -208,10 +208,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -231,10 +231,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -243,7 +243,7 @@ public class TestTypes {
|
|||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(10)
|
@Order(10)
|
||||||
@Test
|
@Test
|
||||||
public void testTimeStamp() throws Exception {
|
public void testTimeStamp() throws Exception {
|
||||||
@ -255,22 +255,22 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
LOGGER.debug("Retreive Timestamp = {}", retrieve.timeStampData);
|
LOGGER.debug("Retreive Timestamp = {}", retrieve.timeStampData);
|
||||||
Assertions.assertNotNull(retrieve.timeStampData);
|
Assertions.assertNotNull(retrieve.timeStampData);
|
||||||
// Can not compare the exact timestamp due to aproximation and model of storing data :
|
// Can not compare the exact timestamp due to aproximation and model of storing data :
|
||||||
//Assertions.assertEquals(insertedData.timeStampData, retrieve.timeStampData);
|
// Assertions.assertEquals(insertedData.timeStampData, retrieve.timeStampData);
|
||||||
Assertions.assertEquals(insertedData.timeStampData.toInstant().toEpochMilli(), retrieve.timeStampData.toInstant().toEpochMilli());
|
Assertions.assertEquals(insertedData.timeStampData.toInstant().toEpochMilli(), retrieve.timeStampData.toInstant().toEpochMilli());
|
||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(11)
|
@Order(11)
|
||||||
@Test
|
@Test
|
||||||
public void testDate() throws Exception {
|
public void testDate() throws Exception {
|
||||||
@ -282,10 +282,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -295,7 +295,7 @@ public class TestTypes {
|
|||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(12)
|
@Order(12)
|
||||||
@Test
|
@Test
|
||||||
public void testLocalDate() throws Exception {
|
public void testLocalDate() throws Exception {
|
||||||
@ -307,10 +307,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -320,7 +320,7 @@ public class TestTypes {
|
|||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(13)
|
@Order(13)
|
||||||
@Test
|
@Test
|
||||||
public void testLocalTime() throws Exception {
|
public void testLocalTime() throws Exception {
|
||||||
@ -332,10 +332,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -360,10 +360,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -382,7 +382,7 @@ public class TestTypes {
|
|||||||
|
|
||||||
// Get new data
|
// Get new data
|
||||||
final TypesTable retrieve2 = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve2 = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve2);
|
Assertions.assertNotNull(retrieve2);
|
||||||
Assertions.assertNotNull(retrieve2.id);
|
Assertions.assertNotNull(retrieve2.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve2.id);
|
Assertions.assertEquals(insertedData.id, retrieve2.id);
|
||||||
@ -401,7 +401,7 @@ public class TestTypes {
|
|||||||
|
|
||||||
// Get new data
|
// Get new data
|
||||||
final TypesTable retrieve3 = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve3 = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve3);
|
Assertions.assertNotNull(retrieve3);
|
||||||
Assertions.assertNotNull(retrieve3.id);
|
Assertions.assertNotNull(retrieve3.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve3.id);
|
Assertions.assertEquals(insertedData.id, retrieve3.id);
|
||||||
@ -411,10 +411,10 @@ public class TestTypes {
|
|||||||
// note: retreive2
|
// note: retreive2
|
||||||
Assertions.assertEquals(retrieve2.booleanData, retrieve3.booleanData);
|
Assertions.assertEquals(retrieve2.booleanData, retrieve3.booleanData);
|
||||||
Assertions.assertNull(retrieve3.varcharData);
|
Assertions.assertNull(retrieve3.varcharData);
|
||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(15)
|
@Order(15)
|
||||||
@Test
|
@Test
|
||||||
public void testTextUpdateJson() throws Exception {
|
public void testTextUpdateJson() throws Exception {
|
||||||
@ -427,10 +427,10 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(insertedData);
|
Assertions.assertNotNull(insertedData);
|
||||||
Assertions.assertNotNull(insertedData.id);
|
Assertions.assertNotNull(insertedData.id);
|
||||||
Assertions.assertTrue(insertedData.id >= 0);
|
Assertions.assertTrue(insertedData.id >= 0);
|
||||||
|
|
||||||
// Try to retrieve all the data:
|
// Try to retrieve all the data:
|
||||||
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve);
|
Assertions.assertNotNull(retrieve);
|
||||||
Assertions.assertNotNull(retrieve.id);
|
Assertions.assertNotNull(retrieve.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve.id);
|
Assertions.assertEquals(insertedData.id, retrieve.id);
|
||||||
@ -453,7 +453,7 @@ public class TestTypes {
|
|||||||
|
|
||||||
// Get new data
|
// Get new data
|
||||||
final TypesTable retrieve2 = DataAccess.get(TypesTable.class, insertedData.id);
|
final TypesTable retrieve2 = DataAccess.get(TypesTable.class, insertedData.id);
|
||||||
|
|
||||||
Assertions.assertNotNull(retrieve2);
|
Assertions.assertNotNull(retrieve2);
|
||||||
Assertions.assertNotNull(retrieve2.id);
|
Assertions.assertNotNull(retrieve2.id);
|
||||||
Assertions.assertEquals(insertedData.id, retrieve2.id);
|
Assertions.assertEquals(insertedData.id, retrieve2.id);
|
||||||
@ -462,7 +462,7 @@ public class TestTypes {
|
|||||||
Assertions.assertNotNull(retrieve2.booleanData);
|
Assertions.assertNotNull(retrieve2.booleanData);
|
||||||
Assertions.assertEquals(retrieve.booleanData, retrieve2.booleanData);
|
Assertions.assertEquals(retrieve.booleanData, retrieve2.booleanData);
|
||||||
Assertions.assertNull(retrieve2.varcharData);
|
Assertions.assertNull(retrieve2.varcharData);
|
||||||
|
|
||||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,9 +2,9 @@ package test.kar.archidata.model;
|
|||||||
|
|
||||||
public enum Enum2ForTest {
|
public enum Enum2ForTest {
|
||||||
ENUM_VALUE_1(5), ENUM_VALUE_2(6), ENUM_VALUE_3(55), ENUM_VALUE_4(84241), ENUM_VALUE_5(54546);
|
ENUM_VALUE_1(5), ENUM_VALUE_2(6), ENUM_VALUE_3(55), ENUM_VALUE_4(84241), ENUM_VALUE_5(54546);
|
||||||
|
|
||||||
private final int value;
|
private final int value;
|
||||||
|
|
||||||
private Enum2ForTest(final int value) {
|
private Enum2ForTest(final int value) {
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}
|
}
|
||||||
|
@ -4,8 +4,8 @@ import org.kar.archidata.annotation.DataJson;
|
|||||||
import org.kar.archidata.model.GenericData;
|
import org.kar.archidata.model.GenericData;
|
||||||
|
|
||||||
public class SerializeAsJson extends GenericData {
|
public class SerializeAsJson extends GenericData {
|
||||||
|
|
||||||
@DataJson
|
@DataJson
|
||||||
public SimpleTable data;
|
public SimpleTable data;
|
||||||
|
|
||||||
}
|
}
|
@ -4,5 +4,5 @@ import org.kar.archidata.model.GenericData;
|
|||||||
|
|
||||||
public class SimpleTable extends GenericData {
|
public class SimpleTable extends GenericData {
|
||||||
public String data;
|
public String data;
|
||||||
|
|
||||||
}
|
}
|
@ -10,6 +10,6 @@ public class TypeManyToManyRemote {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(nullable = false, unique = true)
|
@Column(nullable = false, unique = true)
|
||||||
public Long id = null;
|
public Long id = null;
|
||||||
|
|
||||||
public String data;
|
public String data;
|
||||||
}
|
}
|
@ -16,7 +16,7 @@ public class TypeManyToManyRoot {
|
|||||||
public Long id = null;
|
public Long id = null;
|
||||||
|
|
||||||
public String otherData;
|
public String otherData;
|
||||||
|
|
||||||
@ManyToMany(fetch = FetchType.LAZY, targetEntity = TypeManyToManyRemote.class)
|
@ManyToMany(fetch = FetchType.LAZY, targetEntity = TypeManyToManyRemote.class)
|
||||||
public List<Long> remote;
|
public List<Long> remote;
|
||||||
}
|
}
|
||||||
|
@ -16,7 +16,7 @@ public class TypeManyToManyRootExpand {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(nullable = false, unique = true)
|
@Column(nullable = false, unique = true)
|
||||||
public Long id = null;
|
public Long id = null;
|
||||||
|
|
||||||
public String otherData;
|
public String otherData;
|
||||||
|
|
||||||
@ManyToMany(fetch = FetchType.LAZY, targetEntity = TypeManyToManyRemote.class)
|
@ManyToMany(fetch = FetchType.LAZY, targetEntity = TypeManyToManyRemote.class)
|
||||||
|
@ -10,7 +10,7 @@ public class TypeManyToOneRemote {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(nullable = false, unique = true)
|
@Column(nullable = false, unique = true)
|
||||||
public Long id = null;
|
public Long id = null;
|
||||||
|
|
||||||
public String data;
|
public String data;
|
||||||
|
|
||||||
}
|
}
|
@ -11,9 +11,9 @@ public class TypeManyToOneRoot {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(nullable = false, unique = true)
|
@Column(nullable = false, unique = true)
|
||||||
public Long id = null;
|
public Long id = null;
|
||||||
|
|
||||||
public String otherData;
|
public String otherData;
|
||||||
|
|
||||||
@ManyToOne(targetEntity = TypeManyToOneRemote.class)
|
@ManyToOne(targetEntity = TypeManyToOneRemote.class)
|
||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
public Long remoteId;
|
public Long remoteId;
|
||||||
|
@ -14,7 +14,7 @@ public class TypeManyToOneRootExpand {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(nullable = false, unique = true)
|
@Column(nullable = false, unique = true)
|
||||||
public Long id = null;
|
public Long id = null;
|
||||||
|
|
||||||
public String otherData;
|
public String otherData;
|
||||||
|
|
||||||
@ManyToOne(fetch = FetchType.LAZY, targetEntity = TypeManyToOneRemote.class)
|
@ManyToOne(fetch = FetchType.LAZY, targetEntity = TypeManyToOneRemote.class)
|
||||||
|
@ -10,6 +10,6 @@ public class TypesEnum1 {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(nullable = false, unique = true)
|
@Column(nullable = false, unique = true)
|
||||||
public Long id = null;
|
public Long id = null;
|
||||||
|
|
||||||
public Enum1ForTest data;
|
public Enum1ForTest data;
|
||||||
}
|
}
|
9
tools/configure_precommit.bash
Executable file
9
tools/configure_precommit.bash
Executable file
@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set +e
|
||||||
|
ln -sf ../../tools/pre-commit-hook .git/hooks/pre-commit
|
||||||
|
if [[ 0 != $? ]]; then
|
||||||
|
echo "pre-commit hooks: [ERROR] Cannot configure"
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo "pre-commit hooks: [OK]"
|
||||||
|
fi
|
27
tools/pre-commit
Executable file
27
tools/pre-commit
Executable file
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
# get bash colors and styles here:
|
||||||
|
# http://misc.flogisoft.com/bash/tip_colors_and_formatting
|
||||||
|
C_RESET='\e[0m'
|
||||||
|
C_RED='\e[31m'
|
||||||
|
C_GREEN='\e[32m'
|
||||||
|
C_YELLOW='\e[33m'
|
||||||
|
|
||||||
|
function __run() #(step, name, cmd)
|
||||||
|
{
|
||||||
|
local color output exitcode
|
||||||
|
|
||||||
|
printf "${C_YELLOW}[%s]${C_RESET} %-20s" "$1" "$2"
|
||||||
|
output=$(eval "$3" 2>&1)
|
||||||
|
exitcode=$?
|
||||||
|
|
||||||
|
if [[ 0 == $exitcode ]]; then
|
||||||
|
echo -e "${C_GREEN}OK!${C_RESET}"
|
||||||
|
else
|
||||||
|
echo -e "${C_RED}NOK! (${exitcode})${C_RESET}\n\n$output"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
__run "1/1" "Check JAVA code format" "mvn formatter:verify"
|
||||||
|
|
Loading…
Reference in New Issue
Block a user