From 45178547498de9bade7c20a266ee60588e1271fc Mon Sep 17 00:00:00 2001 From: Edouard DUPIN Date: Sun, 28 Apr 2024 16:56:33 +0200 Subject: [PATCH] [DEV] update th format of the code --- Formatter.xml | 375 ++++++++++-------- .../kar/archidata/GlobalConfiguration.java | 6 +- src/org/kar/archidata/UserDB.java | 6 +- .../archidata/annotation/AnnotationTools.java | 48 ++- src/org/kar/archidata/api/DataResource.java | 64 ++- src/org/kar/archidata/api/MediaStreamer.java | 3 +- .../kar/archidata/api/openApiResource.java | 3 +- .../archidata/catcher/ExceptionCatcher.java | 6 +- .../catcher/FailException404API.java | 6 +- .../catcher/InputExceptionCatcher.java | 6 +- .../kar/archidata/catcher/JacksonCatcher.java | 6 +- .../archidata/catcher/RestErrorResponse.java | 3 +- .../kar/archidata/dataAccess/DataAccess.java | 112 ++++-- .../archidata/dataAccess/DataAccessAddOn.java | 65 +-- .../kar/archidata/dataAccess/DataExport.java | 29 +- .../kar/archidata/dataAccess/DataFactory.java | 26 +- .../dataAccess/DataFactoryTsApi.java | 30 +- .../archidata/dataAccess/DataFactoryZod.java | 57 ++- .../dataAccess/addOn/AddOnDataJson.java | 102 +++-- .../dataAccess/addOn/AddOnManyToMany.java | 166 ++++---- .../dataAccess/addOn/AddOnManyToOne.java | 88 ++-- .../dataAccess/addOn/AddOnOneToMany.java | 55 +-- .../AddOnSQLTableExternalForeinKeyAsList.java | 60 +-- .../dataAccess/options/CheckJPA.java | 31 +- .../dataAccess/options/Condition.java | 6 +- src/org/kar/archidata/db/DBConfig.java | 14 +- src/org/kar/archidata/db/DBEntry.java | 6 +- .../exception/RESTErrorResponseExeption.java | 8 +- .../filter/AuthenticationFilter.java | 21 +- src/org/kar/archidata/filter/CORSFilter.java | 6 +- .../archidata/migration/MigrationEngine.java | 33 +- .../archidata/migration/MigrationSqlStep.java | 20 +- src/org/kar/archidata/model/GetToken.java | 4 +- src/org/kar/archidata/model/Token.java | 6 +- .../archidata/tools/ConfigBaseVariable.java | 6 +- src/org/kar/archidata/tools/DataTools.java | 29 +- src/org/kar/archidata/tools/JWTWrapper.java | 39 +- src/org/kar/archidata/tools/RESTApi.java | 87 ++-- .../test/kar/archidata/StepwiseExtension.java | 10 +- .../test/kar/archidata/TestSimpleTable.java | 12 +- .../archidata/TestSimpleTableSoftDelete.java | 20 +- test/src/test/kar/archidata/TestTypes.java | 3 +- 42 files changed, 1045 insertions(+), 638 deletions(-) diff --git a/Formatter.xml b/Formatter.xml index b775e22..360f6a5 100644 --- a/Formatter.xml +++ b/Formatter.xml @@ -1,365 +1,400 @@ - - - + + - - - - - - - - + - - - - - - + - - - - - - - - + + - - - - - - - + - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - + - - - - + - - - - - - - - - + - - + - - - + - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - + - - - + + - - - + - - - - - - - + + - - - - - + - - - + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + - + - - - - - - - - - - - - - - - - + diff --git a/src/org/kar/archidata/GlobalConfiguration.java b/src/org/kar/archidata/GlobalConfiguration.java index 8bd9113..dc2d618 100644 --- a/src/org/kar/archidata/GlobalConfiguration.java +++ b/src/org/kar/archidata/GlobalConfiguration.java @@ -7,7 +7,9 @@ public class GlobalConfiguration { public static DBConfig dbConfig = null; static { - dbConfig = new DBConfig(ConfigBaseVariable.getDBType(), ConfigBaseVariable.getDBHost(), Integer.parseInt(ConfigBaseVariable.getDBPort()), ConfigBaseVariable.getDBLogin(), - ConfigBaseVariable.getDBPassword(), ConfigBaseVariable.getDBName(), ConfigBaseVariable.getDBKeepConnected()); + dbConfig = new DBConfig(ConfigBaseVariable.getDBType(), ConfigBaseVariable.getDBHost(), + Integer.parseInt(ConfigBaseVariable.getDBPort()), ConfigBaseVariable.getDBLogin(), + ConfigBaseVariable.getDBPassword(), ConfigBaseVariable.getDBName(), + ConfigBaseVariable.getDBKeepConnected()); } } diff --git a/src/org/kar/archidata/UserDB.java b/src/org/kar/archidata/UserDB.java index 9cb6bdd..54bd41e 100755 --- a/src/org/kar/archidata/UserDB.java +++ b/src/org/kar/archidata/UserDB.java @@ -19,7 +19,8 @@ public class UserDB { return DataAccess.get(User.class, userId, option); } - public static User getUserOrCreate(final long userId, final String userLogin, QueryOption... option) throws Exception { + public static User getUserOrCreate(final long userId, final String userLogin, QueryOption... option) + throws Exception { final User user = getUsers(userId); if (user != null) { return user; @@ -28,7 +29,8 @@ public class UserDB { return getUsers(userId); } - private static void createUsersInfoFromOAuth(final long userId, final String login, QueryOption... option) throws IOException { + private static void createUsersInfoFromOAuth(final long userId, final String login, QueryOption... option) + throws IOException { QueryOptions options = new QueryOptions(option); final DBEntry entry = DBInterfaceOption.getAutoEntry(options); final String query = "INSERT INTO `user` (`id`, `login`, `lastConnection`, `admin`, `blocked`, `removed`) VALUE (?,?,now(3),'0','0','0')"; diff --git a/src/org/kar/archidata/annotation/AnnotationTools.java b/src/org/kar/archidata/annotation/AnnotationTools.java index 83b4001..4e54eb1 100644 --- a/src/org/kar/archidata/annotation/AnnotationTools.java +++ b/src/org/kar/archidata/annotation/AnnotationTools.java @@ -59,7 +59,8 @@ public class AnnotationTools { return false; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); } return ((Schema) annotation[0]).readOnly(); } @@ -70,7 +71,8 @@ public class AnnotationTools { return null; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); } return ((Schema) annotation[0]).example(); } @@ -81,7 +83,8 @@ public class AnnotationTools { return null; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); } return ((Schema) annotation[0]).description(); } @@ -92,7 +95,8 @@ public class AnnotationTools { return null; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); } return ((Schema) annotation[0]).description(); } @@ -103,7 +107,8 @@ public class AnnotationTools { return getSchemaDescription(element); } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @DataComment on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @DataComment on " + element.getClass().getCanonicalName()); } return ((DataComment) annotation[0]).value(); } @@ -114,7 +119,8 @@ public class AnnotationTools { return null; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @DataDefault on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @DataDefault on " + element.getClass().getCanonicalName()); } return ((DefaultValue) annotation[0]).value(); } @@ -125,7 +131,8 @@ public class AnnotationTools { return null; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @ManyToOne on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @ManyToOne on " + element.getClass().getCanonicalName()); } return (ManyToOne) annotation[0]; } @@ -136,7 +143,8 @@ public class AnnotationTools { return null; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @ManyToOne on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @ManyToOne on " + element.getClass().getCanonicalName()); } return (DataJson) annotation[0]; } @@ -169,7 +177,8 @@ public class AnnotationTools { return 255; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); } final int length = ((Column) annotation[0]).length(); return length <= 0 ? 0 : length; @@ -192,7 +201,8 @@ public class AnnotationTools { return null; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Pattern on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Pattern on " + element.getClass().getCanonicalName()); } return ((Pattern) annotation[0]).regexp(); } @@ -226,7 +236,8 @@ public class AnnotationTools { return element.getName(); } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); } final String name = ((Column) annotation[0]).name(); if (name.isBlank()) { @@ -241,7 +252,8 @@ public class AnnotationTools { return false; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); } return !((Column) annotation[0]).nullable(); } @@ -252,7 +264,8 @@ public class AnnotationTools { return false; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @NotNull on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @NotNull on " + element.getClass().getCanonicalName()); } return true; } @@ -284,7 +297,8 @@ public class AnnotationTools { return false; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); } return ((Column) annotation[0]).unique(); } @@ -295,7 +309,8 @@ public class AnnotationTools { return null; } if (annotation.length > 1) { - throw new Exception("Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); + throw new Exception( + "Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); } return ((GeneratedValue) annotation[0]).strategy(); } @@ -395,7 +410,8 @@ public class AnnotationTools { } public static boolean isGenericField(final Field elem) throws Exception { - return AnnotationTools.isPrimaryKey(elem) || AnnotationTools.isCreatedAtField(elem) || AnnotationTools.isUpdateAtField(elem) || AnnotationTools.isDeletedField(elem); + return AnnotationTools.isPrimaryKey(elem) || AnnotationTools.isCreatedAtField(elem) + || AnnotationTools.isUpdateAtField(elem) || AnnotationTools.isDeletedField(elem); } public static Field getFieldOfId(final Class clazz) throws Exception { diff --git a/src/org/kar/archidata/api/DataResource.java b/src/org/kar/archidata/api/DataResource.java index 80a1de0..78d75e2 100644 --- a/src/org/kar/archidata/api/DataResource.java +++ b/src/org/kar/archidata/api/DataResource.java @@ -85,7 +85,8 @@ public class DataResource { } public static String getFileDataOld(final long tmpFolderId) { - final String filePath = ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + "data"; + final String filePath = ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + + "data"; try { createFolder(ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator); } catch (final IOException e) { @@ -100,7 +101,8 @@ public class DataResource { final String part2 = stringUUID.substring(2, 4); final String part3 = stringUUID.substring(4); final String finalPath = part1 + File.separator + part2; - String filePath = ConfigBaseVariable.getMediaDataFolder() + "_uuid" + File.separator + finalPath + File.separator; + String filePath = ConfigBaseVariable.getMediaDataFolder() + "_uuid" + File.separator + finalPath + + File.separator; try { createFolder(filePath); } catch (final IOException e) { @@ -136,19 +138,20 @@ public class DataResource { 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: Data injectedData = new Data(); String mimeType = ""; final String extension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1); mimeType = switch (extension.toLowerCase()) { - case "jpg", "jpeg" -> "image/jpeg"; - case "png" -> "image/png"; - case "webp" -> "image/webp"; - case "mka" -> "audio/x-matroska"; - case "mkv" -> "video/x-matroska"; - case "webm" -> "video/webm"; - default -> throw new IOException("Can not find the mime type of data input: '" + extension + "'"); + case "jpg", "jpeg" -> "image/jpeg"; + case "png" -> "image/png"; + case "webp" -> "image/webp"; + case "mka" -> "audio/x-matroska"; + case "mkv" -> "video/x-matroska"; + case "webm" -> "video/webm"; + default -> throw new IOException("Can not find the mime type of data input: '" + extension + "'"); }; injectedData.mimeType = mimeType; injectedData.sha512 = sha512; @@ -261,7 +264,10 @@ public class DataResource { @Consumes({ MediaType.MULTIPART_FORM_DATA }) @RolesAllowed("ADMIN") @Operation(description = "Insert a new data in the data environment", tags = "SYSTEM") - public void uploadFile(@Context final SecurityContext sc, @FormDataParam("file") final InputStream fileInputStream, @FormDataParam("file") final FormDataContentDisposition fileMetaData) { + public void uploadFile( + @Context final SecurityContext sc, + @FormDataParam("file") final InputStream fileInputStream, + @FormDataParam("file") final FormDataContentDisposition fileMetaData) { final GenericContext gc = (GenericContext) sc.getUserPrincipal(); LOGGER.info("==================================================="); LOGGER.info("== DATA uploadFile {}", (gc == null ? "null" : gc.userByToken)); @@ -283,7 +289,10 @@ public class DataResource { @RolesAllowed("USER") @Produces(MediaType.APPLICATION_OCTET_STREAM) @Operation(description = "Get back some data from the data environment", tags = "SYSTEM") - public Response retrieveDataId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range, + public Response retrieveDataId( + @Context final SecurityContext sc, + @QueryParam(HttpHeaders.AUTHORIZATION) final String token, + @HeaderParam("Range") final String range, @PathParam("uuid") final UUID uuid) throws Exception { final GenericContext gc = (GenericContext) sc.getUserPrincipal(); // logger.info("==================================================="); @@ -303,7 +312,10 @@ public class DataResource { @Produces(MediaType.APPLICATION_OCTET_STREAM) @Operation(description = "Get a thumbnail of from the data environment (if resize is possible)", tags = "SYSTEM") // @CacheMaxAge(time = 10, unit = TimeUnit.DAYS) - public Response retrieveDataThumbnailId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range, + public Response retrieveDataThumbnailId( + @Context final SecurityContext sc, + @QueryParam(HttpHeaders.AUTHORIZATION) final String token, + @HeaderParam("Range") final String range, @PathParam("uuid") final UUID uuid) throws Exception { // GenericContext gc = (GenericContext) sc.getUserPrincipal(); // logger.info("==================================================="); @@ -316,7 +328,8 @@ public class DataResource { final String filePathName = getFileData(uuid); final File inputFile = new File(filePathName); if (!inputFile.exists()) { - return Response.status(404).entity("{\"error\":\"media Does not exist: " + uuid + "\"}").type("application/json").build(); + return Response.status(404).entity("{\"error\":\"media Does not exist: " + uuid + "\"}") + .type("application/json").build(); } if (value.mimeType.contentEquals("image/jpeg") || value.mimeType.contentEquals("image/png") // || value.mimeType.contentEquals("image/webp") @@ -324,7 +337,8 @@ public class DataResource { // reads input image final BufferedImage inputImage = ImageIO.read(inputFile); final int scaledWidth = 250; - final int scaledHeight = (int) ((float) inputImage.getHeight() / (float) inputImage.getWidth() * scaledWidth); + final int scaledHeight = (int) ((float) inputImage.getHeight() / (float) inputImage.getWidth() + * scaledWidth); // creates output image final BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType()); @@ -339,11 +353,13 @@ public class DataResource { ImageIO.write(outputImage, "JPG", baos); } catch (final IOException e) { e.printStackTrace(); - 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(); // 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"); // TODO: move this in a decorator !!! final CacheControl cc = new CacheControl(); @@ -361,8 +377,12 @@ public class DataResource { @RolesAllowed("USER") @Produces(MediaType.APPLICATION_OCTET_STREAM) @Operation(description = "Get back some data from the data environment (with a beautiful name (permit download with basic name)", tags = "SYSTEM") - public Response retrieveDataFull(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range, - @PathParam("uuid") final UUID uuid, @PathParam("name") final String name) throws Exception { + public Response retrieveDataFull( + @Context final SecurityContext sc, + @QueryParam(HttpHeaders.AUTHORIZATION) final String token, + @HeaderParam("Range") final String range, + @PathParam("uuid") final UUID uuid, + @PathParam("name") final String name) throws Exception { final GenericContext gc = (GenericContext) sc.getUserPrincipal(); // logger.info("==================================================="); LOGGER.info("== DATA retrieveDataFull ? id={} user={}", uuid, (gc == null ? "null" : gc.userByToken)); @@ -431,8 +451,10 @@ public class DataResource { final long len = to - from + 1; final MediaStreamer streamer = new MediaStreamer(len, raf); - final Response.ResponseBuilder out = Response.ok(streamer).status(Response.Status.PARTIAL_CONTENT).header("Accept-Ranges", "bytes").header("Content-Range", responseRange) - .header(HttpHeaders.CONTENT_LENGTH, streamer.getLenth()).header(HttpHeaders.LAST_MODIFIED, new Date(file.lastModified())); + final Response.ResponseBuilder out = Response.ok(streamer).status(Response.Status.PARTIAL_CONTENT) + .header("Accept-Ranges", "bytes").header("Content-Range", responseRange) + .header(HttpHeaders.CONTENT_LENGTH, streamer.getLenth()) + .header(HttpHeaders.LAST_MODIFIED, new Date(file.lastModified())); if (mimeType != null) { out.type(mimeType); } diff --git a/src/org/kar/archidata/api/MediaStreamer.java b/src/org/kar/archidata/api/MediaStreamer.java index 879fa45..9525395 100644 --- a/src/org/kar/archidata/api/MediaStreamer.java +++ b/src/org/kar/archidata/api/MediaStreamer.java @@ -31,7 +31,8 @@ public class MediaStreamer implements StreamingOutput { public void write(final OutputStream outputStream) { try { while (this.length != 0) { - final int read = this.raf.read(this.buf, 0, this.buf.length > this.length ? (int) this.length : this.buf.length); + final int read = this.raf.read(this.buf, 0, + this.buf.length > this.length ? (int) this.length : this.buf.length); try { outputStream.write(this.buf, 0, read); } catch (final IOException ex) { diff --git a/src/org/kar/archidata/api/openApiResource.java b/src/org/kar/archidata/api/openApiResource.java index 93dedf0..4de2866 100644 --- a/src/org/kar/archidata/api/openApiResource.java +++ b/src/org/kar/archidata/api/openApiResource.java @@ -27,7 +27,8 @@ public class openApiResource extends BaseOpenApiResource { @Produces({ MediaType.APPLICATION_JSON }) @PermitAll @Operation(hidden = true, description = "Get the OPEN-API description", tags = "SYSTEM") - public Response getDescription(@Context final HttpHeaders headers, @Context final UriInfo uriInfo) throws Exception { + public Response getDescription(@Context final HttpHeaders headers, @Context final UriInfo uriInfo) + throws Exception { return getOpenApi(headers, this.config, this.app, uriInfo, "json"); } } diff --git a/src/org/kar/archidata/catcher/ExceptionCatcher.java b/src/org/kar/archidata/catcher/ExceptionCatcher.java index f1137d3..6a49218 100644 --- a/src/org/kar/archidata/catcher/ExceptionCatcher.java +++ b/src/org/kar/archidata/catcher/ExceptionCatcher.java @@ -16,11 +16,13 @@ public class ExceptionCatcher implements ExceptionMapper { final RestErrorResponse ret = build(exception); LOGGER.error("Error UUID={}", ret.uuid); 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(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()); } } diff --git a/src/org/kar/archidata/catcher/FailException404API.java b/src/org/kar/archidata/catcher/FailException404API.java index f928166..b0f1c51 100644 --- a/src/org/kar/archidata/catcher/FailException404API.java +++ b/src/org/kar/archidata/catcher/FailException404API.java @@ -15,11 +15,13 @@ public class FailException404API implements ExceptionMapper { public Response toResponse(final InputException exception) { LOGGER.warn("Catch InputException:"); final RestErrorResponse ret = build(exception); - LOGGER.error("Error UUID={} ==> '{}'=>'{}'", ret.uuid, exception.missingVariable, exception.getLocalizedMessage()); + LOGGER.error("Error UUID={} ==> '{}'=>'{}'", ret.uuid, exception.missingVariable, + exception.getLocalizedMessage()); // exception.printStackTrace(); return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build(); } 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()); } } diff --git a/src/org/kar/archidata/catcher/JacksonCatcher.java b/src/org/kar/archidata/catcher/JacksonCatcher.java index c447cf9..19113e0 100644 --- a/src/org/kar/archidata/catcher/JacksonCatcher.java +++ b/src/org/kar/archidata/catcher/JacksonCatcher.java @@ -18,11 +18,13 @@ public class JacksonCatcher implements ExceptionMapper final RestErrorResponse ret = build(exception); LOGGER.error("Error UUID={}", ret.uuid); 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(final Exception exception) { - return new RestErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Catch JSON Exception", exception.getMessage()); + return new RestErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Catch JSON Exception", + exception.getMessage()); } } diff --git a/src/org/kar/archidata/catcher/RestErrorResponse.java b/src/org/kar/archidata/catcher/RestErrorResponse.java index 7b51a09..c009234 100644 --- a/src/org/kar/archidata/catcher/RestErrorResponse.java +++ b/src/org/kar/archidata/catcher/RestErrorResponse.java @@ -15,7 +15,8 @@ public class RestErrorResponse { final public int status; final public String statusMessage; - public RestErrorResponse(final Response.Status status, final String time, final String error, final String message) { + public RestErrorResponse(final Response.Status status, final String time, final String error, + final String message) { this.time = time; this.name = error; this.message = message; diff --git a/src/org/kar/archidata/dataAccess/DataAccess.java b/src/org/kar/archidata/dataAccess/DataAccess.java index 88f77c2..11d249e 100644 --- a/src/org/kar/archidata/dataAccess/DataAccess.java +++ b/src/org/kar/archidata/dataAccess/DataAccess.java @@ -74,7 +74,8 @@ public class DataAccess { } - public static boolean isDBExist(final String name, final QueryOption... option) throws InternalServerErrorException { + public static boolean isDBExist(final String name, final QueryOption... option) + throws InternalServerErrorException { final QueryOptions options = new QueryOptions(option); if ("sqlite".equals(ConfigBaseVariable.getDBType())) { // no base manage in sqLite ... @@ -134,7 +135,8 @@ public class DataAccess { } } - public static boolean isTableExist(final String name, final QueryOption... option) throws InternalServerErrorException { + public static boolean isTableExist(final String name, final QueryOption... option) + throws InternalServerErrorException { final QueryOptions options = new QueryOptions(option); try { String request = ""; @@ -180,7 +182,8 @@ public class DataAccess { * @param iii Id in the result set * @return The list of Long value * @throws SQLException if an error is generated in the SQL request. */ - public static List getListOfIds(final ResultSet rs, final int iii, final String separator) throws SQLException { + public static List getListOfIds(final ResultSet rs, final int iii, final String separator) + throws SQLException { final String trackString = rs.getString(iii); if (rs.wasNull()) { return null; @@ -199,7 +202,8 @@ public class DataAccess { * @param iii Id in the result set * @return The list of Long value * @throws SQLException if an error is generated in the SQL request. */ - public static List getListOfUUIDs(final ResultSet rs, final int iii, final String separator) throws SQLException { + public static List getListOfUUIDs(final ResultSet rs, final int iii, final String separator) + throws SQLException { final String trackString = rs.getString(iii); if (rs.wasNull()) { return null; @@ -227,7 +231,8 @@ public class DataAccess { return groups; } - public static List getListOfRawUUIDs(final ResultSet rs, final int iii) throws SQLException, DataAccessException { + public static List getListOfRawUUIDs(final ResultSet rs, final int iii) + throws SQLException, DataAccessException { final byte[] trackString = rs.getBytes(iii); if (rs.wasNull()) { return null; @@ -241,7 +246,12 @@ public class DataAccess { return out; } - protected static void setValuedb(final Class type, final T data, final CountInOut iii, final Field field, final PreparedStatement ps) throws Exception { + protected static void setValuedb( + final Class type, + final T data, + final CountInOut iii, + final Field field, + final PreparedStatement ps) throws Exception { if (type == UUID.class) { final Object tmp = field.get(data); if (tmp == null) { @@ -354,7 +364,13 @@ public class DataAccess { iii.inc(); } - protected static void setValueFromDb(final Class type, final Object data, final CountInOut count, final Field field, final ResultSet rs, final CountInOut countNotNull) throws Exception { + protected static void setValueFromDb( + final Class type, + final Object data, + final CountInOut count, + final Field field, + final ResultSet rs, + final CountInOut countNotNull) throws Exception { if (type == UUID.class) { final byte[] tmp = rs.getBytes(count.value); // final UUID tmp = rs.getObject(count.value, UUID.class); @@ -877,7 +893,8 @@ public class DataAccess { } LOGGER.warn("generate the query: '{}'", query.toString()); // prepare the request: - final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); + final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), + Statement.RETURN_GENERATED_KEYS); final CountInOut iii = new CountInOut(1); UUID uuid = null; @@ -998,11 +1015,13 @@ public class DataAccess { return insert(data); } - public static QueryCondition getTableIdCondition(final Class clazz, final ID_TYPE idKey) throws Exception { + public static QueryCondition getTableIdCondition(final Class clazz, final ID_TYPE idKey) + throws Exception { // Find the ID field type .... final Field idField = AnnotationTools.getIdField(clazz); if (idField == null) { - throw new DataAccessException("The class have no annotation @Id ==> can not determine the default type searching"); + throw new DataAccessException( + "The class have no annotation @Id ==> can not determine the default type searching"); } // check the compatibility of the id and the declared ID final Class typeClass = idField.getType(); @@ -1011,7 +1030,8 @@ public class DataAccess { } if (idKey.getClass() != typeClass) { if (idKey.getClass() == Condition.class) { - throw new DataAccessException("Try to identify the ID type on a condition 'close' internal API error use xxxWhere(...) instead."); + throw new DataAccessException( + "Try to identify the ID type on a condition 'close' internal API error use xxxWhere(...) instead."); } throw new DataAccessException("Request update with the wrong type ..."); } @@ -1027,7 +1047,11 @@ public class DataAccess { * @param jsonData Json data (partial) values to update * @return the number of object updated * @throws Exception */ - public static int updateWithJson(final Class clazz, final ID_TYPE id, final String jsonData, final QueryOption... option) throws Exception { + public static int updateWithJson( + final Class clazz, + final ID_TYPE id, + final String jsonData, + final QueryOption... option) throws Exception { final QueryOptions options = new QueryOptions(option); final Condition condition = options.get(Condition.class); if (condition != null) { @@ -1039,7 +1063,8 @@ public class DataAccess { return updateWhereWithJson(clazz, jsonData, options.getAllArray()); } - public static int updateWhereWithJson(final Class clazz, final String jsonData, final QueryOption... option) throws Exception { + public static int updateWhereWithJson(final Class clazz, final String jsonData, final QueryOption... option) + throws Exception { final QueryOptions options = new QueryOptions(option); final Condition condition = options.get(Condition.class); if (condition == null) { @@ -1067,7 +1092,11 @@ public class DataAccess { * @param filterValue * @return the affected rows. * @throws Exception */ - public static int update(final T data, final ID_TYPE id, final List updateColomn, final QueryOption... option) throws Exception { + public static int update( + final T data, + final ID_TYPE id, + final List updateColomn, + final QueryOption... option) throws Exception { final QueryOptions options = new QueryOptions(option); options.add(new Condition(getTableIdCondition(data.getClass(), id))); options.add(new FilterValue(updateColomn)); @@ -1159,7 +1188,8 @@ public class DataAccess { if (!firstField) { LOGGER.debug("generate the query: '{}'", query.toString()); // prepare the request: - final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); + final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), + Statement.RETURN_GENERATED_KEYS); final CountInOut iii = new CountInOut(1); for (final Field field : clazz.getFields()) { // static field is only for internal global declaration ==> remove it .. @@ -1249,14 +1279,16 @@ public class DataAccess { } } - public static int executeSimpleQuery(final String query, final QueryOption... option) throws SQLException, IOException { + public static int executeSimpleQuery(final String query, final QueryOption... option) + throws SQLException, IOException { final QueryOptions options = new QueryOptions(option); final DBEntry entry = DBInterfaceOption.getAutoEntry(options); final Statement stmt = entry.connection.createStatement(); return stmt.executeUpdate(query); } - public static boolean executeQuery(final String query, final QueryOption... option) throws SQLException, IOException { + public static boolean executeQuery(final String query, final QueryOption... option) + throws SQLException, IOException { final QueryOptions options = new QueryOptions(option); final DBEntry entry = DBInterfaceOption.getAutoEntry(options); final Statement stmt = entry.connection.createStatement(); @@ -1360,7 +1392,8 @@ public class DataAccess { } LOGGER.warn("generate the query: '{}'", query.toString()); // prepare the request: - final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); + final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), + Statement.RETURN_GENERATED_KEYS); final CountInOut iii = new CountInOut(1); condition.injectQuery(ps, iii); if (limit != null) { @@ -1390,7 +1423,12 @@ public class DataAccess { return outs; } - public static Object createObjectFromSQLRequest(final ResultSet rs, final Class clazz, final CountInOut count, final CountInOut countNotNull, final QueryOptions options, + public static Object createObjectFromSQLRequest( + final ResultSet rs, + final Class clazz, + final CountInOut count, + final CountInOut countNotNull, + final QueryOptions options, final List lazyCall) throws Exception { final boolean readAllfields = QueryOptions.readAllColomn(options); // TODO: manage class that is defined inside a class ==> Not manage for now... @@ -1401,7 +1439,8 @@ public class DataAccess { } } if (data == null) { - throw new DataAccessException("Can not find the default constructor for the class: " + clazz.getCanonicalName()); + throw new DataAccessException( + "Can not find the default constructor for the class: " + clazz.getCanonicalName()); } for (final Field elem : clazz.getFields()) { // static field is only for internal global declaration ==> remove it .. @@ -1452,7 +1491,8 @@ public class DataAccess { } LOGGER.warn("generate the query: '{}'", query.toString()); // prepare the request: - final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); + final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), + Statement.RETURN_GENERATED_KEYS); final CountInOut iii = new CountInOut(1); condition.injectQuery(ps, iii); if (limit != null) { @@ -1475,7 +1515,8 @@ public class DataAccess { return count; } - public static T get(final Class clazz, final ID_TYPE id, final QueryOption... option) throws Exception { + public static T get(final Class clazz, final ID_TYPE id, final QueryOption... option) + throws Exception { final QueryOptions options = new QueryOptions(option); options.add(new Condition(getTableIdCondition(clazz, id))); return DataAccess.getWhere(clazz, options.getAllArray()); @@ -1499,7 +1540,8 @@ public class DataAccess { * @param id Unique Id of the model * @param options (Optional) Options of the request * @return Number of element that is removed. */ - public static int delete(final Class clazz, final ID_TYPE id, final QueryOption... options) throws Exception { + public static int delete(final Class clazz, final ID_TYPE id, final QueryOption... options) + throws Exception { final String hasDeletedFieldName = AnnotationTools.getDeletedFieldName(clazz); if (hasDeletedFieldName != null) { return deleteSoft(clazz, id, options); @@ -1523,7 +1565,8 @@ public class DataAccess { } } - public static int deleteHard(final Class clazz, final ID_TYPE id, final QueryOption... option) throws Exception { + public static int deleteHard(final Class clazz, final ID_TYPE id, final QueryOption... option) + throws Exception { final QueryOptions options = new QueryOptions(option); options.add(new Condition(getTableIdCondition(clazz, id))); return deleteHardWhere(clazz, options.getAllArray()); @@ -1555,7 +1598,8 @@ public class DataAccess { } } - private static int deleteSoft(final Class clazz, final ID_TYPE id, final QueryOption... option) throws Exception { + private static int deleteSoft(final Class clazz, final ID_TYPE id, final QueryOption... option) + throws Exception { final QueryOptions options = new QueryOptions(option); options.add(new Condition(getTableIdCondition(clazz, id))); return deleteSoftWhere(clazz, options.getAllArray()); @@ -1596,7 +1640,8 @@ public class DataAccess { return unsetDeleteWhere(clazz, new Condition(getTableIdCondition(clazz, id))); } - public static int unsetDelete(final Class clazz, final ID_TYPE id, final QueryOption... option) throws Exception { + public static int unsetDelete(final Class clazz, final ID_TYPE id, final QueryOption... option) + throws Exception { final QueryOptions options = new QueryOptions(option); options.add(new Condition(getTableIdCondition(clazz, id))); return unsetDeleteWhere(clazz, options.getAllArray()); @@ -1706,12 +1751,20 @@ public class DataAccess { * @param option Optional parameters * @return The list of element requested * @throws Exception */ - public static List query(final Class clazz, final String query, final List parameters, final QueryOption... option) throws Exception { + public static List query( + final Class clazz, + final String query, + final List parameters, + final QueryOption... option) throws Exception { final QueryOptions options = new QueryOptions(option); return query(clazz, query, parameters, options); } - public static List query(final Class clazz, final String queryBase, final List parameters, final QueryOptions options) throws Exception { + public static List query( + final Class clazz, + final String queryBase, + final List parameters, + final QueryOptions options) throws Exception { final List lazyCall = new ArrayList<>(); // TODO ... final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz); final DBEntry entry = DBInterfaceOption.getAutoEntry(options); @@ -1741,7 +1794,8 @@ public class DataAccess { } LOGGER.warn("generate the query: '{}'", query.toString()); // prepare the request: - final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); + final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), + Statement.RETURN_GENERATED_KEYS); final CountInOut iii = new CountInOut(1); if (parameters != null) { for (final Object elem : parameters) { diff --git a/src/org/kar/archidata/dataAccess/DataAccessAddOn.java b/src/org/kar/archidata/dataAccess/DataAccessAddOn.java index 3c849be..1ae46cf 100644 --- a/src/org/kar/archidata/dataAccess/DataAccessAddOn.java +++ b/src/org/kar/archidata/dataAccess/DataAccessAddOn.java @@ -29,7 +29,8 @@ public interface DataAccessAddOn { * @param iii The index of injection * @return the new index of injection in case of multiple value management * @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 * @param field @@ -45,19 +46,24 @@ public interface DataAccessAddOn { return false; } - void generateQuery(// - @NotNull String tableName, // - @NotNull final String primaryKey, // - @NotNull Field field, // - @NotNull final StringBuilder querySelect, // - @NotNull final StringBuilder query, // - @NotNull String name, // - @NotNull CountInOut count, // - QueryOptions options// - ) throws Exception; + void generateQuery( + @NotNull String tableName, + @NotNull final String primaryKey, + @NotNull Field field, + @NotNull final StringBuilder querySelect, + @NotNull final StringBuilder query, + @NotNull String name, + @NotNull CountInOut count, + QueryOptions options) throws Exception; // Return the number of colomn read - void fillFromQuery(ResultSet rs, Field field, Object data, CountInOut count, QueryOptions options, final List lazyCall) + void fillFromQuery( + ResultSet rs, + Field field, + Object data, + CountInOut count, + QueryOptions options, + final List lazyCall) throws Exception, SQLException, IllegalArgumentException, IllegalAccessException; /** Create associated table of the specific element. @@ -69,17 +75,16 @@ public interface DataAccessAddOn { * @param createDrop * @param fieldId * @throws Exception */ - void createTables(// - String tableName, // - final Field primaryField, // - Field field, // - StringBuilder mainTableBuilder, // - List preActionList, // - List postActionList, // - boolean createIfNotExist, // - boolean createDrop, // - int fieldId // - ) throws Exception; + void createTables( + String tableName, + final Field primaryField, + Field field, + StringBuilder mainTableBuilder, + List preActionList, + List postActionList, + boolean createIfNotExist, + boolean createDrop, + int fieldId) throws Exception; /** Some action must be done asynchronously for update or remove element * @param field @@ -94,7 +99,12 @@ public interface DataAccessAddOn { * @param field Field that is updated. * @param data Data that might be inserted. * @param actions Asynchronous action to do after main request. */ - default void asyncInsert(final String tableName, final Object localId, final Field field, final Object data, final List actions) throws Exception { + default void asyncInsert( + final String tableName, + final Object localId, + final Field field, + final Object data, + final List actions) throws Exception { } @@ -111,7 +121,12 @@ public interface DataAccessAddOn { * @param field Field that is updated. * @param data Data that might be inserted. * @param actions Asynchronous action to do after main request. */ - default void asyncUpdate(final String tableName, final Object localId, final Field field, final Object data, final List actions) throws Exception { + default void asyncUpdate( + final String tableName, + final Object localId, + final Field field, + final Object data, + final List actions) throws Exception { } diff --git a/src/org/kar/archidata/dataAccess/DataExport.java b/src/org/kar/archidata/dataAccess/DataExport.java index dea17cb..cca4099 100644 --- a/src/org/kar/archidata/dataAccess/DataExport.java +++ b/src/org/kar/archidata/dataAccess/DataExport.java @@ -37,7 +37,10 @@ public class DataExport { public static final String CSV_TYPE = "text/csv"; @SuppressWarnings("unchecked") - protected static RetreiveFromDB createSetValueFromDbCallbackTable(final int count, final Class type, final int id) throws Exception { + protected static RetreiveFromDB createSetValueFromDbCallbackTable( + final int count, + final Class type, + final int id) throws Exception { if (type == UUID.class) { return (final ResultSet rs, final Object obj) -> { final UUID tmp = rs.getObject(count, UUID.class); @@ -228,7 +231,8 @@ public class DataExport { } - private static int getQueryPropertyId(final List properties, final String name) throws DataAccessException { + private static int getQueryPropertyId(final List properties, final String name) + throws DataAccessException { for (int iii = 0; iii < properties.size(); iii++) { if (properties.get(iii).name.equals(name)) { return iii; @@ -237,12 +241,20 @@ public class DataExport { throw new DataAccessException("Query with unknown field: '" + name + "'"); } - public static TableQuery queryTable(final List headers, final String query, final List parameters, final QueryOption... option) throws Exception { + public static TableQuery queryTable( + final List headers, + final String query, + final List parameters, + final QueryOption... option) throws Exception { final QueryOptions options = new QueryOptions(option); return queryTable(headers, query, parameters, options); } - public static TableQuery queryTable(final List headers, final String queryBase, final List parameters, final QueryOptions options) throws Exception { + public static TableQuery queryTable( + final List headers, + final String queryBase, + final List parameters, + final QueryOptions options) throws Exception { final List lazyCall = new ArrayList<>(); // TODO ... final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz); final DBEntry entry = DBInterfaceOption.getAutoEntry(options); @@ -272,7 +284,8 @@ public class DataExport { } LOGGER.warn("generate the query: '{}'", query.toString()); // prepare the request: - final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); + final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), + Statement.RETURN_GENERATED_KEYS); final CountInOut iii = new CountInOut(1); if (parameters != null) { for (final Object elem : parameters) { @@ -294,7 +307,8 @@ public class DataExport { final String typeName = rsmd.getColumnTypeName(jjj + 1); final int typeId = rsmd.getColumnType(jjj + 1); final int id = getQueryPropertyId(headers, label); - LOGGER.info(" - {}:{} type=[{}] {} REQUEST={}", jjj, label, typeId, typeName, headers.get(id).type.getCanonicalName()); + LOGGER.info(" - {}:{} type=[{}] {} REQUEST={}", jjj, label, typeId, typeName, + headers.get(id).type.getCanonicalName()); // create the callback... final RetreiveFromDB element = createSetValueFromDbCallbackTable(jjj + 1, headers.get(id).type, id); actionToRetreive.add(element); @@ -363,7 +377,8 @@ public class DataExport { return out.toString(); } - public static Response convertInResponse(final TableQuery dataOut, final String accept) throws DataAccessException, IOException { + public static Response convertInResponse(final TableQuery dataOut, final String accept) + throws DataAccessException, IOException { if (CSV_TYPE.equals(accept)) { // CSV serialization String out = null; diff --git a/src/org/kar/archidata/dataAccess/DataFactory.java b/src/org/kar/archidata/dataAccess/DataFactory.java index 6a3ac22..be640bc 100644 --- a/src/org/kar/archidata/dataAccess/DataFactory.java +++ b/src/org/kar/archidata/dataAccess/DataFactory.java @@ -142,8 +142,16 @@ public class DataFactory { 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 preOtherTables, final List postOtherTables, - final boolean createIfNotExist, final boolean createDrop, final int fieldId, final Class classModel) throws Exception { + public static void createTablesSpecificType( + final String tableName, + final Field elem, + final StringBuilder mainTableBuilder, + final List preOtherTables, + final List postOtherTables, + final boolean createIfNotExist, + final boolean createDrop, + final int fieldId, + final Class classModel) throws Exception { final String name = AnnotationTools.getFieldName(elem); final int limitSize = AnnotationTools.getLimitSize(elem); final boolean notNull = AnnotationTools.getColumnNotNull(elem); @@ -372,16 +380,20 @@ public class DataFactory { LOGGER.trace(" + '{}'", elem.getName()); if (DataAccess.isAddOnField(elem)) { final DataAccessAddOn addOn = DataAccess.findAddOnforField(elem); - LOGGER.trace("Create type for: {} ==> {} (ADD-ON)", AnnotationTools.getFieldName(elem), elem.getType()); + LOGGER.trace("Create type for: {} ==> {} (ADD-ON)", AnnotationTools.getFieldName(elem), + elem.getType()); if (addOn != null) { - addOn.createTables(tableName, primaryField, elem, tmpOut, preActionList, postActionList, createIfNotExist, createDrop, fieldId); + addOn.createTables(tableName, primaryField, elem, tmpOut, preActionList, postActionList, + createIfNotExist, createDrop, fieldId); } else { - throw new DataAccessException( - "Element matked as add-on but add-on does not loaded: table:" + tableName + " field name=" + AnnotationTools.getFieldName(elem) + " type=" + elem.getType()); + throw new DataAccessException("Element matked as add-on but add-on does not loaded: table:" + + tableName + " field name=" + AnnotationTools.getFieldName(elem) + " type=" + + elem.getType()); } } else { LOGGER.trace("Create type for: {} ==> {}", AnnotationTools.getFieldName(elem), elem.getType()); - DataFactory.createTablesSpecificType(tableName, elem, tmpOut, preActionList, postActionList, createIfNotExist, createDrop, fieldId, elem.getType()); + DataFactory.createTablesSpecificType(tableName, elem, tmpOut, preActionList, postActionList, + createIfNotExist, createDrop, fieldId, elem.getType()); } fieldId++; } diff --git a/src/org/kar/archidata/dataAccess/DataFactoryTsApi.java b/src/org/kar/archidata/dataAccess/DataFactoryTsApi.java index 3a57345..632376f 100644 --- a/src/org/kar/archidata/dataAccess/DataFactoryTsApi.java +++ b/src/org/kar/archidata/dataAccess/DataFactoryTsApi.java @@ -45,13 +45,17 @@ import jakarta.ws.rs.core.Response; public class DataFactoryTsApi { static final Logger LOGGER = LoggerFactory.getLogger(DataFactoryTsApi.class); - record APIModel(String data, String className) { - } + record APIModel( + String data, + String className) {} /** Request the generation of the TypeScript file for the "Zod" export model * @param classs List of class used in the model * @throws Exception */ - public static List createApi(final List> classs, final GeneratedTypes previous, final String pathPackage) throws Exception { + public static List createApi( + final List> classs, + final GeneratedTypes previous, + final String pathPackage) throws Exception { final List apis = new ArrayList<>(); final String globalheader = """ /** @@ -281,7 +285,11 @@ public class DataFactoryTsApi { return out; } - public static APIModel createSingleApi(final Class clazz, final Set> includeModel, final Set> includeCheckerModel, final GeneratedTypes previous) throws Exception { + public static APIModel createSingleApi( + final Class clazz, + final Set> includeModel, + final Set> includeCheckerModel, + final GeneratedTypes previous) throws Exception { final StringBuilder builder = new StringBuilder(); // the basic path has no specific elements... final String basicPath = apiAnnotationGetPath(clazz); @@ -296,7 +304,8 @@ public class DataFactoryTsApi { final String methodPath = apiAnnotationGetPath(method); final String methodType = apiAnnotationGetTypeRequest(method); if (methodType == null) { - LOGGER.error(" [{}] {} => {}/{} ==> No methode type @PATH, @GET ...", methodType, methodName, basicPath, methodPath); + LOGGER.error(" [{}] {} => {}/{} ==> No methode type @PATH, @GET ...", methodType, methodName, + basicPath, methodPath); continue; } final String methodDescription = apiAnnotationGetOperationDescription(method); @@ -437,7 +446,8 @@ public class DataFactoryTsApi { builder.append("\n\t */"); } if (isUnmanagedReturnType) { - builder.append("\n\t// TODO: unmanaged \"Response\" type: please specify @AsyncType or considered as 'void'."); + builder.append( + "\n\t// TODO: unmanaged \"Response\" type: please specify @AsyncType or considered as 'void'."); } builder.append("\n\texport function "); builder.append(methodName); @@ -601,7 +611,8 @@ public class DataFactoryTsApi { builder.append("\n\t\t\tcallback,"); } builder.append("\n\t\t}"); - if (tmpReturn.size() != 0 && tmpReturn.get(0).tsTypeName != null && !tmpReturn.get(0).tsTypeName.equals("void")) { + if (tmpReturn.size() != 0 && tmpReturn.get(0).tsTypeName != null + && !tmpReturn.get(0).tsTypeName.equals("void")) { builder.append(", "); // TODO: correct this it is really bad ... builder.append(convertInTypeScriptCheckType(tmpReturn)); @@ -613,7 +624,10 @@ public class DataFactoryTsApi { return new APIModel(builder.toString(), classSimpleName); } - public static void generatePackage(final List> classApi, final List> classModel, final String pathPackage) throws Exception { + public static void generatePackage( + final List> classApi, + final List> classModel, + final String pathPackage) throws Exception { final GeneratedTypes previous = DataFactoryZod.createBasicType(); DataFactoryZod.createTable(RestErrorResponse.class, previous); final List listApi = createApi(classApi, previous, pathPackage); diff --git a/src/org/kar/archidata/dataAccess/DataFactoryZod.java b/src/org/kar/archidata/dataAccess/DataFactoryZod.java index b673331..2d44c05 100644 --- a/src/org/kar/archidata/dataAccess/DataFactoryZod.java +++ b/src/org/kar/archidata/dataAccess/DataFactoryZod.java @@ -36,7 +36,8 @@ public class DataFactoryZod { public boolean isEnum = false; public boolean nativeType; - public ClassElement(final Class model[], final String zodName, final String tsTypeName, final String tsCheckType, final String declaration, final boolean nativeType) { + public ClassElement(final Class model[], final String zodName, final String tsTypeName, + final String tsCheckType, final String declaration, final boolean nativeType) { this.model = model; this.zodName = zodName; this.tsTypeName = tsTypeName; @@ -90,7 +91,8 @@ public class DataFactoryZod { } } - public static ClassElement convertTypeZodEnum(final Class clazz, final GeneratedTypes previous) throws Exception { + public static ClassElement convertTypeZodEnum(final Class clazz, final GeneratedTypes previous) + throws Exception { final ClassElement element = new ClassElement(clazz); previous.add(element); final Object[] arr = clazz.getEnumConstants(); @@ -150,7 +152,8 @@ public class DataFactoryZod { return convertTypeZodEnum(type, previous).zodName; } if (type == List.class) { - throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName() + " Unmanaged List of List ... "); + throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName() + + " Unmanaged List of List ... "); } final ClassElement elemCreated = createTable(type, previous); if (elemCreated != null) { @@ -188,7 +191,11 @@ public class DataFactoryZod { return ".optional()"; } - public static void createTablesSpecificType(final Field elem, final int fieldId, final StringBuilder builder, final GeneratedTypes previous) throws Exception { + public static void createTablesSpecificType( + final Field elem, + final int fieldId, + final StringBuilder builder, + final GeneratedTypes previous) throws Exception { final String name = elem.getName(); final Class classModel = elem.getType(); final int limitSize = AnnotationTools.getLimitSize(elem); @@ -240,21 +247,33 @@ public class DataFactoryZod { public static GeneratedTypes createBasicType() throws Exception { final GeneratedTypes previous = new GeneratedTypes(); previous.add(new ClassElement(new Class[] { Void.class, void.class }, "void", "void", null, null, true)); - previous.add(new ClassElement(new Class[] { String.class }, "zod.string()", "string", null, "zod.string()", true)); - previous.add(new ClassElement(new Class[] { InputStream.class, FormDataContentDisposition.class }, "z.instanceof(File)", "File", null, "z.instanceof(File)", true)); - previous.add(new ClassElement(new Class[] { Boolean.class, boolean.class }, "zod.boolean()", "boolean", null, "zod.boolean()", true)); - previous.add(new ClassElement(new Class[] { UUID.class }, "ZodUUID", "UUID", "isUUID", "zod.string().uuid()", false), true); + previous.add(new ClassElement(new Class[] { String.class }, "zod.string()", "string", null, "zod.string()", + true)); + previous.add(new ClassElement(new Class[] { InputStream.class, FormDataContentDisposition.class }, + "z.instanceof(File)", "File", null, "z.instanceof(File)", true)); + previous.add(new ClassElement(new Class[] { Boolean.class, boolean.class }, "zod.boolean()", "boolean", null, + "zod.boolean()", true)); + previous.add(new ClassElement(new Class[] { UUID.class }, "ZodUUID", "UUID", "isUUID", "zod.string().uuid()", + false), true); previous.add(new ClassElement(new Class[] { Long.class, long.class }, "ZodLong", "Long", "isLong", // "zod.bigint()", "zod.number()", false), true); - previous.add(new ClassElement(new Class[] { Integer.class, int.class }, "ZodInteger", "Integer", "isInteger", "zod.number().safe()", false), true); - previous.add(new ClassElement(new Class[] { Double.class, double.class }, "ZodDouble", "Double", "isDouble", "zod.number()", true), true); - previous.add(new ClassElement(new Class[] { Float.class, float.class }, "ZodFloat", "Float", "isFloat", "zod.number()", false), true); - previous.add(new ClassElement(new Class[] { Instant.class }, "ZodInstant", "Instant", "isInstant", "zod.string()", false), true); - previous.add(new ClassElement(new Class[] { Date.class }, "ZodDate", "Date", "isDate", "zod.date()", false), true); - previous.add(new ClassElement(new Class[] { Timestamp.class }, "ZodTimestamp", "Timestamp", "isTimestamp", "zod.date()", false), true); - previous.add(new ClassElement(new Class[] { LocalDate.class }, "ZodLocalDate", "LocalDate", "isLocalDate", "zod.date()", false), true); - previous.add(new ClassElement(new Class[] { LocalTime.class }, "ZodLocalTime", "LocalTime", "isLocalTime", "zod.date()", false), true); + previous.add(new ClassElement(new Class[] { Integer.class, int.class }, "ZodInteger", "Integer", "isInteger", + "zod.number().safe()", false), true); + previous.add(new ClassElement(new Class[] { Double.class, double.class }, "ZodDouble", "Double", "isDouble", + "zod.number()", true), true); + previous.add(new ClassElement(new Class[] { Float.class, float.class }, "ZodFloat", "Float", "isFloat", + "zod.number()", false), true); + previous.add(new ClassElement(new Class[] { Instant.class }, "ZodInstant", "Instant", "isInstant", + "zod.string()", false), true); + previous.add(new ClassElement(new Class[] { Date.class }, "ZodDate", "Date", "isDate", "zod.date()", false), + true); + previous.add(new ClassElement(new Class[] { Timestamp.class }, "ZodTimestamp", "Timestamp", "isTimestamp", + "zod.date()", false), true); + previous.add(new ClassElement(new Class[] { LocalDate.class }, "ZodLocalDate", "LocalDate", "isLocalDate", + "zod.date()", false), true); + previous.add(new ClassElement(new Class[] { LocalTime.class }, "ZodLocalTime", "LocalTime", "isLocalTime", + "zod.date()", false), true); return previous; } @@ -293,7 +312,8 @@ public class DataFactoryZod { return generatedData.toString(); } - public static List createTables(final Class[] classs, final GeneratedTypes previous) throws Exception { + public static List createTables(final Class[] classs, final GeneratedTypes previous) + throws Exception { final List out = new ArrayList<>(); for (final Class clazz : classs) { if (clazz == Response.class) { @@ -344,7 +364,8 @@ public class DataFactoryZod { LOGGER.trace(" + '{}'", elem.getName()); if (false && DataAccess.isAddOnField(elem)) { final DataAccessAddOn addOn = DataAccess.findAddOnforField(elem); - LOGGER.error("Create type for: {} ==> {} (ADD-ON) ==> Not managed now ....", AnnotationTools.getFieldName(elem), elem.getType()); + LOGGER.error("Create type for: {} ==> {} (ADD-ON) ==> Not managed now ....", + AnnotationTools.getFieldName(elem), elem.getType()); /* LOGGER.trace("Create type for: {} ==> {} (ADD-ON)", AnnotationTools.getFieldName(elem), elem.getType()); if (addOn != null) { addOn.createTables(tableName, elem, tmpOut, * preActionList, postActionList, createIfNotExist, createDrop, fieldId); } else { throw new DataAccessException( "Element matked as add-on but add-on does not loaded: table:" + * tableName + " field name=" + AnnotationTools.getFieldName(elem) + " type=" + elem.getType()); } fieldId++; */ diff --git a/src/org/kar/archidata/dataAccess/addOn/AddOnDataJson.java b/src/org/kar/archidata/dataAccess/addOn/AddOnDataJson.java index ad21496..8d5d7ba 100644 --- a/src/org/kar/archidata/dataAccess/addOn/AddOnDataJson.java +++ b/src/org/kar/archidata/dataAccess/addOn/AddOnDataJson.java @@ -52,7 +52,8 @@ public class AddOnDataJson implements DataAccessAddOn { } @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); if (data == null) { ps.setNull(iii.value, Types.VARCHAR); @@ -79,16 +80,15 @@ public class AddOnDataJson implements DataAccessAddOn { } @Override - public void generateQuery(// - @NotNull final String tableName, // - @NotNull final String primaryKey, // - @NotNull final Field field, // - @NotNull final StringBuilder querySelect, // - @NotNull final StringBuilder query, // - @NotNull final String name, // - @NotNull final CountInOut count, // - final QueryOptions options// - ) throws Exception { + public void generateQuery( + @NotNull final String tableName, + @NotNull final String primaryKey, + @NotNull final Field field, + @NotNull final StringBuilder querySelect, + @NotNull final StringBuilder query, + @NotNull final String name, + @NotNull final CountInOut count, + final QueryOptions options) throws Exception { querySelect.append(" "); querySelect.append(tableName); querySelect.append("."); @@ -98,7 +98,13 @@ public class AddOnDataJson implements DataAccessAddOn { } @Override - public void fillFromQuery(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List lazyCall) throws Exception { + public void fillFromQuery( + final ResultSet rs, + final Field field, + final Object data, + final CountInOut count, + final QueryOptions options, + final List lazyCall) throws Exception { final String jsonData = rs.getString(count.value); count.inc(); if (!rs.wasNull()) { @@ -149,23 +155,25 @@ public class AddOnDataJson implements DataAccessAddOn { } @Override - public void createTables(// - final String tableName, // - final Field primaryField, // - final Field field, // - final StringBuilder mainTableBuilder, // - final List preActionList, // - final List postActionList, // - final boolean createIfNotExist, // - final boolean createDrop, // - final int fieldId // - ) throws Exception { - DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, createIfNotExist, createDrop, fieldId, JsonValue.class); + public void createTables( + final String tableName, + final Field primaryField, + final Field field, + final StringBuilder mainTableBuilder, + final List preActionList, + final List postActionList, + final boolean createIfNotExist, + final boolean createDrop, + final int fieldId) throws Exception { + DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, + createIfNotExist, createDrop, fieldId, JsonValue.class); } - public static void addLink(final Class clazz, final Long id, final String column, final Long remoteKey) throws Exception { + public static void addLink(final Class clazz, final Long id, final String column, final Long remoteKey) + throws Exception { final String tableName = AnnotationTools.getTableName(clazz); - final TableCoversLongLong data = DataAccess.get(TableCoversLongLong.class, id, new OverrideTableName(tableName)); + final TableCoversLongLong data = DataAccess.get(TableCoversLongLong.class, id, + new OverrideTableName(tableName)); if (data.covers == null) { data.covers = new ArrayList<>(); } @@ -178,9 +186,11 @@ public class AddOnDataJson implements DataAccessAddOn { DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); } - public static void addLink(final Class clazz, final Long id, final String column, final UUID remoteKey) throws Exception { + public static void addLink(final Class clazz, final Long id, final String column, final UUID remoteKey) + throws Exception { final String tableName = AnnotationTools.getTableName(clazz); - final TableCoversLongUUID data = DataAccess.get(TableCoversLongUUID.class, id, new OverrideTableName(tableName)); + final TableCoversLongUUID data = DataAccess.get(TableCoversLongUUID.class, id, + new OverrideTableName(tableName)); if (data.covers == null) { data.covers = new ArrayList<>(); } @@ -193,9 +203,11 @@ public class AddOnDataJson implements DataAccessAddOn { DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); } - public static void addLink(final Class clazz, final UUID id, final String column, final UUID remoteKey) throws Exception { + public static void addLink(final Class clazz, final UUID id, final String column, final UUID remoteKey) + throws Exception { final String tableName = AnnotationTools.getTableName(clazz); - final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, id, new OverrideTableName(tableName)); + final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, id, + new OverrideTableName(tableName)); if (data.covers == null) { data.covers = new ArrayList<>(); } @@ -208,9 +220,11 @@ public class AddOnDataJson implements DataAccessAddOn { DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); } - public static void addLink(final Class clazz, final UUID id, final String column, final Long remoteKey) throws Exception { + public static void addLink(final Class clazz, final UUID id, final String column, final Long remoteKey) + throws Exception { final String tableName = AnnotationTools.getTableName(clazz); - final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, id, new OverrideTableName(tableName)); + final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, id, + new OverrideTableName(tableName)); if (data.covers == null) { data.covers = new ArrayList<>(); } @@ -223,9 +237,11 @@ public class AddOnDataJson implements DataAccessAddOn { DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); } - public static void removeLink(final Class clazz, final UUID id, final String column, final Long remoteKey) throws Exception { + public static void removeLink(final Class clazz, final UUID id, final String column, final Long remoteKey) + throws Exception { final String tableName = AnnotationTools.getTableName(clazz); - final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, id, new OverrideTableName(tableName)); + final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, id, + new OverrideTableName(tableName)); if (data.covers == null) { return; } @@ -240,9 +256,11 @@ public class AddOnDataJson implements DataAccessAddOn { DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); } - public static void removeLink(final Class clazz, final UUID id, final String column, final UUID remoteKey) throws Exception { + public static void removeLink(final Class clazz, final UUID id, final String column, final UUID remoteKey) + throws Exception { final String tableName = AnnotationTools.getTableName(clazz); - final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, id, new OverrideTableName(tableName)); + final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, id, + new OverrideTableName(tableName)); if (data.covers == null) { return; } @@ -257,9 +275,11 @@ public class AddOnDataJson implements DataAccessAddOn { DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); } - public static void removeLink(final Class clazz, final Long id, final String column, final Long remoteKey) throws Exception { + public static void removeLink(final Class clazz, final Long id, final String column, final Long remoteKey) + throws Exception { final String tableName = AnnotationTools.getTableName(clazz); - final TableCoversLongLong data = DataAccess.get(TableCoversLongLong.class, id, new OverrideTableName(tableName)); + final TableCoversLongLong data = DataAccess.get(TableCoversLongLong.class, id, + new OverrideTableName(tableName)); if (data.covers == null) { return; } @@ -274,9 +294,11 @@ public class AddOnDataJson implements DataAccessAddOn { DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); } - public static void removeLink(final Class clazz, final Long id, final String column, final UUID remoteKey) throws Exception { + public static void removeLink(final Class clazz, final Long id, final String column, final UUID remoteKey) + throws Exception { final String tableName = AnnotationTools.getTableName(clazz); - final TableCoversLongUUID data = DataAccess.get(TableCoversLongUUID.class, id, new OverrideTableName(tableName)); + final TableCoversLongUUID data = DataAccess.get(TableCoversLongUUID.class, id, + new OverrideTableName(tableName)); if (data.covers == null) { return; } diff --git a/src/org/kar/archidata/dataAccess/addOn/AddOnManyToMany.java b/src/org/kar/archidata/dataAccess/addOn/AddOnManyToMany.java index edce660..79ae5ec 100644 --- a/src/org/kar/archidata/dataAccess/addOn/AddOnManyToMany.java +++ b/src/org/kar/archidata/dataAccess/addOn/AddOnManyToMany.java @@ -56,7 +56,8 @@ public class AddOnManyToMany implements DataAccessAddOn { } @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 { } @@ -70,7 +71,8 @@ public class AddOnManyToMany implements DataAccessAddOn { if (field.getType() != List.class) { return false; } - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; if (objectClass == Long.class || objectClass == UUID.class) { return true; } @@ -97,18 +99,18 @@ public class AddOnManyToMany implements DataAccessAddOn { return tableName + "_link_" + localName; } - public void generateConcatQuery(// - @NotNull final String tableName, // - @NotNull final String primaryKey, // - @NotNull final Field field, // - @NotNull final StringBuilder querySelect, // - @NotNull final StringBuilder query, // - @NotNull final String name, // - @NotNull final CountInOut count, // - final QueryOptions options// - ) throws Exception { + public void generateConcatQuery( + @NotNull final String tableName, + @NotNull final String primaryKey, + @NotNull final Field field, + @NotNull final StringBuilder querySelect, + @NotNull final StringBuilder query, + @NotNull final String name, + @NotNull final CountInOut count, + final QueryOptions options) throws Exception { final String linkTableName = generateLinkTableName(tableName, name); - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; final String tmpVariable = "tmp_" + Integer.toString(count.value); querySelect.append(" (SELECT GROUP_CONCAT("); querySelect.append(tmpVariable); @@ -154,20 +156,20 @@ public class AddOnManyToMany implements DataAccessAddOn { } @Override - public void generateQuery(// - @NotNull final String tableName, // - @NotNull final String primaryKey, // - @NotNull final Field field, // - @NotNull final StringBuilder querySelect, // - @NotNull final StringBuilder query, // - @NotNull final String name, // - @NotNull final CountInOut count, // - final QueryOptions options// - ) throws Exception { + public void generateQuery( + @NotNull final String tableName, + @NotNull final String primaryKey, + @NotNull final Field field, + @NotNull final StringBuilder querySelect, + @NotNull final StringBuilder query, + @NotNull final String name, + @NotNull final CountInOut count, + final QueryOptions options) throws Exception { if (field.getType() != List.class) { return; } - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; if (objectClass == Long.class || objectClass == UUID.class) { generateConcatQuery(tableName, primaryKey, field, querySelect, query, name, count, options); } @@ -185,19 +187,19 @@ public class AddOnManyToMany implements DataAccessAddOn { } @Override - public void fillFromQuery( // - final ResultSet rs, // - final Field field, // - final Object data, // - final CountInOut count, // - final QueryOptions options, // - final List lazyCall // - ) throws Exception { + public void fillFromQuery( + final ResultSet rs, + final Field field, + final Object data, + final CountInOut count, + final QueryOptions options, + final List lazyCall) throws Exception { if (field.getType() != List.class) { LOGGER.error("Can not ManyToMany with other than List Model: {}", field.getType().getCanonicalName()); return; } - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; if (objectClass == Long.class) { final List idList = DataAccess.getListOfIds(rs, count.value, SEPARATOR_LONG); field.set(data, idList); @@ -228,7 +230,8 @@ public class AddOnManyToMany implements DataAccessAddOn { final List childs = new ArrayList<>(idList); // TODO: update to have get with abstract types .... @SuppressWarnings("unchecked") - final Object foreignData = DataAccess.getsWhere(decorators.targetEntity(), new Condition(new QueryInList<>(idField, childs))); + final Object foreignData = DataAccess.getsWhere(decorators.targetEntity(), + new Condition(new QueryInList<>(idField, childs))); if (foreignData == null) { return; } @@ -247,7 +250,8 @@ public class AddOnManyToMany implements DataAccessAddOn { final List childs = new ArrayList<>(idList); // TODO: update to have get with abstract types .... @SuppressWarnings("unchecked") - final Object foreignData = DataAccess.getsWhere(decorators.targetEntity(), new Condition(new QueryInList<>(idField, childs))); + final Object foreignData = DataAccess.getsWhere(decorators.targetEntity(), + new Condition(new QueryInList<>(idField, childs))); if (foreignData == null) { return; } @@ -265,14 +269,21 @@ public class AddOnManyToMany implements DataAccessAddOn { } @Override - public void asyncUpdate(final String tableName, final Object localKey, final Field field, final Object data, final List actions) throws Exception { + public void asyncUpdate( + final String tableName, + final Object localKey, + final Field field, + final Object data, + final List actions) throws Exception { if (field.getType() != List.class) { LOGGER.error("Can not ManyToMany with other than List Model: {}", field.getType().getCanonicalName()); return; } - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; if (objectClass != Long.class && objectClass != UUID.class) { - throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + objectClass.getCanonicalName() + ">"); + throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + + objectClass.getCanonicalName() + ">"); } final String columnName = AnnotationTools.getFieldName(field); final String linkTableName = generateLinkTableName(tableName, columnName); @@ -280,24 +291,28 @@ public class AddOnManyToMany implements DataAccessAddOn { if (localKey instanceof final Long localKeyLong) { if (objectClass == Long.class) { actions.add(() -> { - DataAccess.deleteWhere(LinkTableLongLong.class, new OverrideTableName(linkTableName), new Condition(new QueryCondition("object1Id", "=", localKeyLong))); + DataAccess.deleteWhere(LinkTableLongLong.class, new OverrideTableName(linkTableName), + new Condition(new QueryCondition("object1Id", "=", localKeyLong))); }); asyncInsert(tableName, localKey, field, data, actions); } else { actions.add(() -> { - DataAccess.deleteWhere(LinkTableLongUUID.class, new OverrideTableName(linkTableName), new Condition(new QueryCondition("object1Id", "=", localKeyLong))); + DataAccess.deleteWhere(LinkTableLongUUID.class, new OverrideTableName(linkTableName), + new Condition(new QueryCondition("object1Id", "=", localKeyLong))); }); asyncInsert(tableName, localKey, field, data, actions); } } else if (localKey instanceof final UUID localKeyUUID) { if (objectClass == Long.class) { actions.add(() -> { - DataAccess.deleteWhere(LinkTableUUIDLong.class, new OverrideTableName(linkTableName), new Condition(new QueryCondition("object1Id", "=", localKeyUUID))); + DataAccess.deleteWhere(LinkTableUUIDLong.class, new OverrideTableName(linkTableName), + new Condition(new QueryCondition("object1Id", "=", localKeyUUID))); }); asyncInsert(tableName, localKey, field, data, actions); } else { actions.add(() -> { - DataAccess.deleteWhere(LinkTableUUIDUUID.class, new OverrideTableName(linkTableName), new Condition(new QueryCondition("object1Id", "=", localKeyUUID))); + DataAccess.deleteWhere(LinkTableUUIDUUID.class, new OverrideTableName(linkTableName), + new Condition(new QueryCondition("object1Id", "=", localKeyUUID))); }); asyncInsert(tableName, localKey, field, data, actions); } @@ -310,7 +325,12 @@ public class AddOnManyToMany implements DataAccessAddOn { } @Override - public void asyncInsert(final String tableName, final Object localKey, final Field field, final Object data, final List actions) throws Exception { + public void asyncInsert( + final String tableName, + final Object localKey, + final Field field, + final Object data, + final List actions) throws Exception { if (data == null) { return; } @@ -318,9 +338,11 @@ public class AddOnManyToMany implements DataAccessAddOn { LOGGER.error("Can not ManyToMany with other than List Model: {}", field.getType().getCanonicalName()); return; } - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; if (objectClass != Long.class && objectClass != UUID.class) { - throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + objectClass.getCanonicalName() + ">"); + throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + + objectClass.getCanonicalName() + ">"); } final String columnName = AnnotationTools.getFieldName(field); final String linkTableName = generateLinkTableName(tableName, columnName); @@ -421,7 +443,8 @@ public class AddOnManyToMany implements DataAccessAddOn { }); } } else { - throw new DataAccessException("Not manage access of remte key like ManyToMany other than Long or UUID: " + localKey.getClass().getCanonicalName()); + throw new DataAccessException("Not manage access of remte key like ManyToMany other than Long or UUID: " + + localKey.getClass().getCanonicalName()); } } @@ -430,9 +453,11 @@ public class AddOnManyToMany implements DataAccessAddOn { public void drop(final String tableName, final Field field) throws Exception { final String columnName = AnnotationTools.getFieldName(field); final String linkTableName = generateLinkTableName(tableName, columnName); - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; if (objectClass != Long.class && objectClass != UUID.class) { - throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + objectClass.getCanonicalName() + ">"); + throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + + objectClass.getCanonicalName() + ">"); } DataAccess.drop(LinkTableLongLong.class, new OverrideTableName(linkTableName)); } @@ -441,14 +466,17 @@ public class AddOnManyToMany implements DataAccessAddOn { public void cleanAll(final String tableName, final Field field) throws Exception { final String columnName = AnnotationTools.getFieldName(field); final String linkTableName = generateLinkTableName(tableName, columnName); - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; if (objectClass != Long.class && objectClass != UUID.class) { - throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + objectClass.getCanonicalName() + ">"); + throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + + objectClass.getCanonicalName() + ">"); } DataAccess.cleanAll(LinkTableLongLong.class, new OverrideTableName(linkTableName)); } - 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 linkTableName = generateLinkTableName(tableName, column); /* final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; if (objectClass != Long.class && objectClass != UUID.class) { throw new @@ -458,30 +486,33 @@ public class AddOnManyToMany implements DataAccessAddOn { } - 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 linkTableName = generateLinkTableName(tableName, column); return DataAccess.deleteWhere(LinkTableLongLong.class, new OverrideTableName(linkTableName), - new Condition(new QueryAnd(new QueryCondition("object1Id", "=", localKey), new QueryCondition("object2Id", "=", remoteKey)))); + new Condition(new QueryAnd(new QueryCondition("object1Id", "=", localKey), + new QueryCondition("object2Id", "=", remoteKey)))); } @Override - public void createTables( // - final String tableName, // - final Field primaryField, // - final Field field, // - final StringBuilder mainTableBuilder, // - final List preActionList, // - final List postActionList, // - final boolean createIfNotExist, // - final boolean createDrop, // - final int fieldId// - ) throws Exception { + public void createTables( + final String tableName, + final Field primaryField, + final Field field, + final StringBuilder mainTableBuilder, + final List preActionList, + final List postActionList, + final boolean createIfNotExist, + final boolean createDrop, + final int fieldId) throws Exception { final String linkTableName = generateLinkTableNameField(tableName, field); final QueryOptions options = new QueryOptions(new OverrideTableName(linkTableName)); - final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; + final Class objectClass = (Class) ((ParameterizedType) field.getGenericType()) + .getActualTypeArguments()[0]; if (objectClass != Long.class && objectClass != UUID.class) { - throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + objectClass.getCanonicalName() + ">"); + throw new DataAccessException("Can not ManyToMany with other than List or List Model: List<" + + objectClass.getCanonicalName() + ">"); } final Class primaryType = primaryField.getType(); if (primaryType == Long.class) { @@ -502,7 +533,8 @@ public class AddOnManyToMany implements DataAccessAddOn { postActionList.addAll(sqlCommand); } } else { - throw new DataAccessException("Can not ManyToMany with other than primary key type Long or UUID Model: " + primaryType.getCanonicalName()); + throw new DataAccessException("Can not ManyToMany with other than primary key type Long or UUID Model: " + + primaryType.getCanonicalName()); } } } diff --git a/src/org/kar/archidata/dataAccess/addOn/AddOnManyToOne.java b/src/org/kar/archidata/dataAccess/addOn/AddOnManyToOne.java index 0133a29..2b96b64 100644 --- a/src/org/kar/archidata/dataAccess/addOn/AddOnManyToOne.java +++ b/src/org/kar/archidata/dataAccess/addOn/AddOnManyToOne.java @@ -48,7 +48,8 @@ public class AddOnManyToOne implements DataAccessAddOn { } @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); if (data == null) { if (field.getType() == Long.class) { @@ -95,11 +96,8 @@ public class AddOnManyToOne implements DataAccessAddOn { @Override public boolean canInsert(final Field field) { - if (field.getType() == Long.class // - || field.getType() == Integer.class // - || field.getType() == Short.class // - || field.getType() == String.class // - || field.getType() == UUID.class) { + if (field.getType() == Long.class || field.getType() == Integer.class || field.getType() == Short.class + || field.getType() == String.class || field.getType() == UUID.class) { return true; } final ManyToOne decorators = field.getDeclaredAnnotation(ManyToOne.class); @@ -117,11 +115,8 @@ public class AddOnManyToOne implements DataAccessAddOn { @Override public boolean canRetrieve(final Field field) { final Class classType = field.getType(); - if (classType == Long.class // - || classType == Integer.class // - || classType == Short.class // - || classType == String.class // - || classType == UUID.class) { + if (classType == Long.class || classType == Integer.class || classType == Short.class + || classType == String.class || classType == UUID.class) { return true; } final ManyToOne decorators = field.getDeclaredAnnotation(ManyToOne.class); @@ -132,21 +127,17 @@ public class AddOnManyToOne implements DataAccessAddOn { } @Override - public void generateQuery(// - @NotNull final String tableName, // - @NotNull final String primaryKey, // - @NotNull final Field field, // - @NotNull final StringBuilder querySelect, // - @NotNull final StringBuilder query, // - @NotNull final String name, // - @NotNull final CountInOut count, // - final QueryOptions options// - ) throws Exception { - if (field.getType() == Long.class // - || field.getType() == Integer.class // - || field.getType() == Short.class // - || field.getType() == String.class // - || field.getType() == UUID.class) { + public void generateQuery( + @NotNull final String tableName, + @NotNull final String primaryKey, + @NotNull final Field field, + @NotNull final StringBuilder querySelect, + @NotNull final StringBuilder query, + @NotNull final String name, + @NotNull final CountInOut count, + final QueryOptions options) throws Exception { + if (field.getType() == Long.class || field.getType() == Integer.class || field.getType() == Short.class + || field.getType() == String.class || field.getType() == UUID.class) { querySelect.append(" "); querySelect.append(tableName); querySelect.append("."); @@ -186,7 +177,13 @@ public class AddOnManyToOne implements DataAccessAddOn { } @Override - public void fillFromQuery(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List lazyCall) throws Exception { + public void fillFromQuery( + final ResultSet rs, + final Field field, + final Object data, + final CountInOut count, + final QueryOptions options, + final List lazyCall) throws Exception { if (field.getType() == Long.class) { final Long foreignKey = rs.getLong(count.value); count.inc(); @@ -236,7 +233,8 @@ public class AddOnManyToOne implements DataAccessAddOn { if (objectClass == decorators.targetEntity()) { if (decorators.fetch() == FetchType.EAGER) { final CountInOut countNotNull = new CountInOut(0); - final Object dataNew = DataAccess.createObjectFromSQLRequest(rs, objectClass, count, countNotNull, options, lazyCall); + final Object dataNew = DataAccess.createObjectFromSQLRequest(rs, objectClass, count, countNotNull, + options, lazyCall); if (dataNew != null && countNotNull.value != 0) { field.set(data, dataNew); } @@ -262,27 +260,25 @@ public class AddOnManyToOne implements DataAccessAddOn { // TODO : refacto this table to manage a generic table with dynamic name to be serialisable with the default system @Override - public void createTables(// - final String tableName, // - final Field primaryField, // - final Field field, // - final StringBuilder mainTableBuilder, // - final List preActionList, // - final List postActionList, // - final boolean createIfNotExist, // - final boolean createDrop, // - final int fieldId // - ) throws Exception { + public void createTables( + final String tableName, + final Field primaryField, + final Field field, + final StringBuilder mainTableBuilder, + final List preActionList, + final List postActionList, + final boolean createIfNotExist, + final boolean createDrop, + final int fieldId) throws Exception { final Class classType = field.getType(); - if (classType == Long.class // - || classType == Integer.class // - || classType == Short.class // - || classType == String.class // - || classType == UUID.class) { - DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, createIfNotExist, createDrop, fieldId, classType); + if (classType == Long.class || classType == Integer.class || classType == Short.class + || classType == String.class || classType == UUID.class) { + DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, + createIfNotExist, createDrop, fieldId, classType); } else { LOGGER.error("Support only the Long remote field of ecternal primary keys..."); - DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, createIfNotExist, createDrop, fieldId, Long.class); + DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, + createIfNotExist, createDrop, fieldId, Long.class); } } } diff --git a/src/org/kar/archidata/dataAccess/addOn/AddOnOneToMany.java b/src/org/kar/archidata/dataAccess/addOn/AddOnOneToMany.java index 7bbc86c..c4a99d8 100644 --- a/src/org/kar/archidata/dataAccess/addOn/AddOnOneToMany.java +++ b/src/org/kar/archidata/dataAccess/addOn/AddOnOneToMany.java @@ -75,7 +75,8 @@ public class AddOnOneToMany implements DataAccessAddOn { } @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); iii.inc(); if (data == null) { @@ -103,16 +104,15 @@ public class AddOnOneToMany implements DataAccessAddOn { } @Override - public void generateQuery(// - @NotNull final String tableName, // - @NotNull final String primaryKey, // - @NotNull final Field field, // - @NotNull final StringBuilder querySelect, // - @NotNull final StringBuilder query, // - @NotNull final String name, // - @NotNull final CountInOut count, // - final QueryOptions options// - ) { + public void generateQuery( + @NotNull final String tableName, + @NotNull final String primaryKey, + @NotNull final Field field, + @NotNull final StringBuilder querySelect, + @NotNull final StringBuilder query, + @NotNull final String name, + @NotNull final CountInOut count, + final QueryOptions options) { querySelect.append(" "); querySelect.append(tableName); querySelect.append("."); @@ -121,8 +121,13 @@ public class AddOnOneToMany implements DataAccessAddOn { } @Override - public void fillFromQuery(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List lazyCall) - throws SQLException, IllegalArgumentException, IllegalAccessException { + public void fillFromQuery( + final ResultSet rs, + final Field field, + final Object data, + final CountInOut count, + final QueryOptions options, + final List lazyCall) throws SQLException, IllegalArgumentException, IllegalAccessException { final Long foreignKey = rs.getLong(count.value); count.inc(); if (!rs.wasNull()) { @@ -133,17 +138,17 @@ public class AddOnOneToMany implements DataAccessAddOn { // TODO : refacto this table to manage a generic table with dynamic name to be serializable with the default system @Override - public void createTables(// - final String tableName, // - final Field primaryField, // - final Field field, // - final StringBuilder mainTableBuilder, // - final List preActionList, // - final List postActionList, // - final boolean createIfNotExist, // - final boolean createDrop, // - final int fieldId // - ) throws Exception { - DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, createIfNotExist, createDrop, fieldId, Long.class); + public void createTables( + final String tableName, + final Field primaryField, + final Field field, + final StringBuilder mainTableBuilder, + final List preActionList, + final List postActionList, + final boolean createIfNotExist, + final boolean createDrop, + final int fieldId) throws Exception { + DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, + createIfNotExist, createDrop, fieldId, Long.class); } } diff --git a/src/org/kar/archidata/dataAccess/addOn/AddOnSQLTableExternalForeinKeyAsList.java b/src/org/kar/archidata/dataAccess/addOn/AddOnSQLTableExternalForeinKeyAsList.java index 2a2197b..da58902 100644 --- a/src/org/kar/archidata/dataAccess/addOn/AddOnSQLTableExternalForeinKeyAsList.java +++ b/src/org/kar/archidata/dataAccess/addOn/AddOnSQLTableExternalForeinKeyAsList.java @@ -55,12 +55,14 @@ public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn { @Override public boolean isCompatibleField(final Field field) { - final SQLTableExternalForeinKeyAsList decorators = field.getDeclaredAnnotation(SQLTableExternalForeinKeyAsList.class); + final SQLTableExternalForeinKeyAsList decorators = field + .getDeclaredAnnotation(SQLTableExternalForeinKeyAsList.class); return decorators != null; } @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); iii.inc(); if (data == null) { @@ -88,16 +90,15 @@ public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn { } @Override - public void generateQuery(// - @NotNull final String tableName, // - @NotNull final String primaryKey, // - @NotNull final Field field, // - @NotNull final StringBuilder querySelect, // - @NotNull final StringBuilder query, // - @NotNull final String name, // - @NotNull final CountInOut count, // - final QueryOptions options// - ) { + public void generateQuery( + @NotNull final String tableName, + @NotNull final String primaryKey, + @NotNull final Field field, + @NotNull final StringBuilder querySelect, + @NotNull final StringBuilder query, + @NotNull final String name, + @NotNull final CountInOut count, + final QueryOptions options) { count.inc(); querySelect.append(" "); querySelect.append(tableName); @@ -106,27 +107,30 @@ public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn { } @Override - public void fillFromQuery(final ResultSet rs, final Field field, final Object data, final CountInOut count, final QueryOptions options, final List lazyCall) - throws SQLException, IllegalArgumentException, IllegalAccessException { + public void fillFromQuery( + final ResultSet rs, + final Field field, + final Object data, + final CountInOut count, + final QueryOptions options, + final List lazyCall) throws SQLException, IllegalArgumentException, IllegalAccessException { final List idList = DataAccess.getListOfIds(rs, count.value, SEPARATOR); field.set(data, idList); count.inc(); } @Override - public void createTables(// - final String tableName, // - final Field primaryField, // - final Field field, // - final StringBuilder mainTableBuilder, // - final List preActionList, // - final List postActionList, // - final boolean createIfNotExist, // - final boolean createDrop, // - final int fieldId // - ) throws Exception { - // TODO Auto-generated method stub - - DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, createIfNotExist, createDrop, fieldId, String.class); + public void createTables( + final String tableName, + final Field primaryField, + final Field field, + final StringBuilder mainTableBuilder, + final List preActionList, + final List postActionList, + final boolean createIfNotExist, + final boolean createDrop, + final int fieldId) throws Exception { + DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, + createIfNotExist, createDrop, fieldId, String.class); } } diff --git a/src/org/kar/archidata/dataAccess/options/CheckJPA.java b/src/org/kar/archidata/dataAccess/options/CheckJPA.java index f790786..83b4f30 100644 --- a/src/org/kar/archidata/dataAccess/options/CheckJPA.java +++ b/src/org/kar/archidata/dataAccess/options/CheckJPA.java @@ -67,7 +67,8 @@ public class CheckJPA implements CheckFunctionInterface { final String fieldName = field.getName(); // AnnotationTools.getFieldName(field); if (AnnotationTools.isPrimaryKey(field)) { add(fieldName, (final String baseName, final T data) -> { - throw new InputException(baseName + fieldName, "This is a '@Id' (primaryKey) ==> can not be change"); + throw new InputException(baseName + fieldName, + "This is a '@Id' (primaryKey) ==> can not be change"); }); } if (AnnotationTools.getConstraintsNotNull(field)) { @@ -120,7 +121,8 @@ public class CheckJPA implements CheckFunctionInterface { } final long count = DataAccess.count(annotationManyToOne.targetEntity(), elem); if (count == 0) { - throw new InputException(baseName + fieldName, "Foreign element does not exist in the DB:" + elem); + throw new InputException(baseName + fieldName, + "Foreign element does not exist in the DB:" + elem); } }); } @@ -163,7 +165,8 @@ public class CheckJPA implements CheckFunctionInterface { } final long count = DataAccess.count(annotationManyToOne.targetEntity(), elem); if (count == 0) { - throw new InputException(baseName + fieldName, "Foreign element does not exist in the DB:" + elem); + throw new InputException(baseName + fieldName, + "Foreign element does not exist in the DB:" + elem); } }); } @@ -177,7 +180,8 @@ public class CheckJPA implements CheckFunctionInterface { } final long count = DataAccess.count(annotationManyToOne.targetEntity(), elem); if (count == 0) { - throw new InputException(baseName + fieldName, "Foreign element does not exist in the DB:" + elem); + throw new InputException(baseName + fieldName, + "Foreign element does not exist in the DB:" + elem); } }); } @@ -257,7 +261,8 @@ public class CheckJPA implements CheckFunctionInterface { } final String elemTyped = (String) elem; if (elemTyped.length() > maxSizeString) { - throw new InputException(baseName + fieldName, "Too long size must be <= " + maxSizeString); + throw new InputException(baseName + fieldName, + "Too long size must be <= " + maxSizeString); } }); } @@ -270,10 +275,12 @@ public class CheckJPA implements CheckFunctionInterface { } final String elemTyped = (String) elem; if (elemTyped.length() > limitSize.max()) { - throw new InputException(baseName + fieldName, "Too long size (constraints) must be <= " + limitSize.max()); + throw new InputException(baseName + fieldName, + "Too long size (constraints) must be <= " + limitSize.max()); } if (elemTyped.length() < limitSize.min()) { - throw new InputException(baseName + fieldName, "Too small size (constraints) must be >= " + limitSize.max()); + throw new InputException(baseName + fieldName, + "Too small size (constraints) must be >= " + limitSize.max()); } }); } @@ -287,7 +294,9 @@ public class CheckJPA implements CheckFunctionInterface { } final String elemTyped = (String) elem; if (!pattern.matcher(elemTyped).find()) { - throw new InputException(baseName + fieldName, "does not match the required pattern (constraints) must be '" + patternString + "'"); + throw new InputException(baseName + fieldName, + "does not match the required pattern (constraints) must be '" + patternString + + "'"); } }); } @@ -295,7 +304,8 @@ public class CheckJPA implements CheckFunctionInterface { final DataJson jsonAnnotation = AnnotationTools.getDataJson(field); if (jsonAnnotation != null && jsonAnnotation.checker() != CheckFunctionVoid.class) { // Here if we have an error it crash at start and no new instance after creation... - final CheckFunctionInterface instance = jsonAnnotation.checker().getDeclaredConstructor().newInstance(); + final CheckFunctionInterface instance = jsonAnnotation.checker().getDeclaredConstructor() + .newInstance(); add(fieldName, (final String baseName, final T data) -> { instance.checkAll(baseName + fieldName + ".", field.get(data)); }); @@ -307,7 +317,8 @@ public class CheckJPA implements CheckFunctionInterface { if (AnnotationTools.isUnique(field)) { // Create the request ... add(fieldName, (final String baseName, final T data) -> { - final Object other = DataAccess.getWhere(this.clazz, new Condition(new QueryCondition(fieldName, "==", field.get(data)))); + final Object other = DataAccess.getWhere(this.clazz, + new Condition(new QueryCondition(fieldName, "==", field.get(data)))); if (other != null) { throw new InputException(baseName + fieldName, "Name already exist in the DB"); } diff --git a/src/org/kar/archidata/dataAccess/options/Condition.java b/src/org/kar/archidata/dataAccess/options/Condition.java index fcd32d7..b4a7167 100644 --- a/src/org/kar/archidata/dataAccess/options/Condition.java +++ b/src/org/kar/archidata/dataAccess/options/Condition.java @@ -31,7 +31,11 @@ public class Condition extends QueryOption { } } - public void whereAppendQuery(final StringBuilder query, final String tableName, final QueryOptions options, final String deletedFieldName) { + public void whereAppendQuery( + final StringBuilder query, + final String tableName, + final QueryOptions options, + final String deletedFieldName) { boolean exclude_deleted = true; if (options != null) { exclude_deleted = !options.exist(AccessDeletedItems.class); diff --git a/src/org/kar/archidata/db/DBConfig.java b/src/org/kar/archidata/db/DBConfig.java index fa8ad52..46c7a52 100644 --- a/src/org/kar/archidata/db/DBConfig.java +++ b/src/org/kar/archidata/db/DBConfig.java @@ -14,7 +14,8 @@ public class DBConfig { private final String dbName; private final 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) { + 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) { this.type = "mysql"; } else { @@ -38,8 +39,9 @@ public class DBConfig { @Override public String toString() { - return "DBConfig{type='" + this.type + '\'' + ", hostname='" + this.hostname + '\'' + ", port=" + this.port + ", login='" + this.login + '\'' + ", password='" + this.password + '\'' - + ", dbName='" + this.dbName + "' }"; + return "DBConfig{type='" + this.type + '\'' + ", hostname='" + this.hostname + '\'' + ", port=" + this.port + + ", login='" + this.login + '\'' + ", password='" + this.password + '\'' + ", dbName='" + this.dbName + + "' }"; } public String getHostname() { @@ -81,8 +83,10 @@ public class DBConfig { return "jdbc:sqlite:" + this.hostname + ".db"; } if (isRoot) { - return "jdbc:" + this.type + "://" + this.hostname + ":" + this.port + "/?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC"; + return "jdbc:" + this.type + "://" + this.hostname + ":" + this.port + + "/?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC"; } - return "jdbc:" + this.type + "://" + this.hostname + ":" + this.port + "/" + this.dbName + "?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC"; + return "jdbc:" + this.type + "://" + this.hostname + ":" + this.port + "/" + this.dbName + + "?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC"; } } diff --git a/src/org/kar/archidata/db/DBEntry.java b/src/org/kar/archidata/db/DBEntry.java index 3085da9..de51803 100644 --- a/src/org/kar/archidata/db/DBEntry.java +++ b/src/org/kar/archidata/db/DBEntry.java @@ -50,7 +50,8 @@ public class DBEntry implements Closeable { public void connectRoot() throws IOException { 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) { throw new IOException("Connection db fail: " + ex.getMessage() + " On URL: " + this.config.getUrl(true)); } @@ -59,7 +60,8 @@ public class DBEntry implements Closeable { public void connect() throws IOException { 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) { throw new IOException("Connection db fail: " + ex.getMessage() + " On URL: " + this.config.getUrl(true)); } diff --git a/src/org/kar/archidata/exception/RESTErrorResponseExeption.java b/src/org/kar/archidata/exception/RESTErrorResponseExeption.java index 780f7d1..1b88568 100644 --- a/src/org/kar/archidata/exception/RESTErrorResponseExeption.java +++ b/src/org/kar/archidata/exception/RESTErrorResponseExeption.java @@ -19,7 +19,8 @@ public class RESTErrorResponseExeption extends Exception { this.statusMessage = null; } - public RESTErrorResponseExeption(final UUID uuid, final String time, final String name, final String message, final int status, final String statusMessage) { + public RESTErrorResponseExeption(final UUID uuid, final String time, final String name, final String message, + final int status, final String statusMessage) { this.uuid = uuid; this.time = time; this.name = name; @@ -30,8 +31,9 @@ public class RESTErrorResponseExeption extends Exception { @Override public String toString() { - return "RESTErrorResponseExeption [uuid=" + this.uuid + ", time=" + this.time + ", name=" + this.name + ", message=" + this.message + ", status=" + this.status + ", statusMessage=" - + this.statusMessage + "]"; + return "RESTErrorResponseExeption [uuid=" + this.uuid + ", time=" + this.time + ", name=" + this.name + + ", message=" + this.message + ", status=" + this.status + ", statusMessage=" + this.statusMessage + + "]"; } } diff --git a/src/org/kar/archidata/filter/AuthenticationFilter.java b/src/org/kar/archidata/filter/AuthenticationFilter.java index 95be39d..d0b0e6d 100644 --- a/src/org/kar/archidata/filter/AuthenticationFilter.java +++ b/src/org/kar/archidata/filter/AuthenticationFilter.java @@ -82,7 +82,8 @@ public class AuthenticationFilter implements ContainerRequestFilter { if (authorizationHeader == null && apikeyHeader == null && method.isAnnotationPresent(PermitTokenInURI.class)) { final MultivaluedMap quaryparam = requestContext.getUriInfo().getQueryParameters(); for (final Entry> item : quaryparam.entrySet()) { - if ((authorizationHeader == null && HttpHeaders.AUTHORIZATION.equals(item.getKey())) && !item.getValue().isEmpty()) { + if ((authorizationHeader == null && HttpHeaders.AUTHORIZATION.equals(item.getKey())) + && !item.getValue().isEmpty()) { authorizationHeader = item.getValue().get(0); } if ((apikeyHeader == null && APIKEY.equals(item.getKey())) && !item.getValue().isEmpty()) { @@ -148,7 +149,8 @@ public class AuthenticationFilter implements ContainerRequestFilter { // Is user valid? if (!haveRight) { 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()); return; } requestContext.setSecurityContext(userContext); @@ -159,7 +161,8 @@ public class AuthenticationFilter implements ContainerRequestFilter { // Check if the Authorization header is valid // It must not be null and must be prefixed with "Bearer" plus a whitespace // The authentication scheme comparison must be case-insensitive - return authorizationHeader != null && authorizationHeader.toLowerCase().startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " "); + return authorizationHeader != null + && authorizationHeader.toLowerCase().startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " "); } private void abortWithUnauthorized(final ContainerRequestContext requestContext, final String message) { @@ -169,14 +172,17 @@ public class AuthenticationFilter implements ContainerRequestFilter { LOGGER.warn("abortWithUnauthorized:"); final RestErrorResponse ret = new RestErrorResponse(Response.Status.UNAUTHORIZED, "Unauthorized", message); LOGGER.error("Error UUID={}", ret.uuid); - requestContext.abortWith(Response.status(ret.status).header(HttpHeaders.WWW_AUTHENTICATE, AUTHENTICATION_SCHEME + " base64(HEADER).base64(CONTENT).base64(KEY)").entity(ret) - .type(MediaType.APPLICATION_JSON).build()); + requestContext.abortWith(Response.status(ret.status) + .header(HttpHeaders.WWW_AUTHENTICATE, + AUTHENTICATION_SCHEME + " base64(HEADER).base64(CONTENT).base64(KEY)") + .entity(ret).type(MediaType.APPLICATION_JSON).build()); } private void abortWithForbidden(final ContainerRequestContext requestContext, final String message) { final RestErrorResponse ret = new RestErrorResponse(Response.Status.FORBIDDEN, "FORBIDDEN", message); LOGGER.error("Error UUID={}", ret.uuid); - requestContext.abortWith(Response.status(ret.status).header(HttpHeaders.WWW_AUTHENTICATE, message).entity(ret).type(MediaType.APPLICATION_JSON).build()); + requestContext.abortWith(Response.status(ret.status).header(HttpHeaders.WWW_AUTHENTICATE, message).entity(ret) + .type(MediaType.APPLICATION_JSON).build()); } protected UserByToken validateToken(final String authorization) throws Exception { @@ -206,7 +212,8 @@ public class AuthenticationFilter implements ContainerRequestFilter { if (rights.containsKey(this.applicationName)) { user.right = rights.get(this.applicationName); } else { - LOGGER.error("Connect with no right for this application='{}' full Right='{}'", this.applicationName, rights); + LOGGER.error("Connect with no right for this application='{}' full Right='{}'", this.applicationName, + rights); } } // logger.debug("request user: '{}' right: '{}' row='{}'", userUID, user.right, rowRight); diff --git a/src/org/kar/archidata/filter/CORSFilter.java b/src/org/kar/archidata/filter/CORSFilter.java index 5c9de03..1490e4f 100644 --- a/src/org/kar/archidata/filter/CORSFilter.java +++ b/src/org/kar/archidata/filter/CORSFilter.java @@ -11,11 +11,13 @@ import jakarta.ws.rs.ext.Provider; public class CORSFilter implements ContainerResponseFilter { @Override - public void filter(final ContainerRequestContext request, final ContainerResponseContext response) throws IOException { + public void filter(final ContainerRequestContext request, final ContainerResponseContext response) + throws IOException { // System.err.println("filter cors ..." + request.toString()); response.getHeaders().add("Access-Control-Allow-Origin", "*"); - response.getHeaders().add("Access-Control-Allow-Headers", "Origin, content-type, Content-type, Accept, Authorization, mime-type, filename"); + response.getHeaders().add("Access-Control-Allow-Headers", + "Origin, content-type, Content-type, Accept, Authorization, mime-type, filename"); response.getHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD"); } diff --git a/src/org/kar/archidata/migration/MigrationEngine.java b/src/org/kar/archidata/migration/MigrationEngine.java index e694832..544c2ea 100644 --- a/src/org/kar/archidata/migration/MigrationEngine.java +++ b/src/org/kar/archidata/migration/MigrationEngine.java @@ -162,14 +162,16 @@ public class MigrationEngine { sqlQuery = DataFactory.createTable(Migration.class); } catch (final Exception ex) { ex.printStackTrace(); - throw new MigrationException("Fail to create the local DB SQL model for migaration ==> wait administrator interventions"); + throw new MigrationException( + "Fail to create the local DB SQL model for migaration ==> wait administrator interventions"); } LOGGER.info("Create Table with : {}", sqlQuery.get(0)); try { DataAccess.executeQuery(sqlQuery.get(0)); } catch (SQLException | IOException ex) { ex.printStackTrace(); - throw new MigrationException("Fail to create the local DB model for migaration ==> wait administrator interventions"); + throw new MigrationException( + "Fail to create the local DB model for migaration ==> wait administrator interventions"); } } final Migration currentVersion = getCurrentVersion(); @@ -188,7 +190,8 @@ public class MigrationEngine { } } else { if (!currentVersion.terminated) { - throw new MigrationException("An error occured in the last migration: '" + currentVersion.name + "' defect @" + currentVersion.stepId + "/" + currentVersion.count); + throw new MigrationException("An error occured in the last migration: '" + currentVersion.name + + "' defect @" + currentVersion.stepId + "/" + currentVersion.count); } LOGGER.info("Upgrade the system Current version: {}", currentVersion.name); boolean find = this.init != null && this.init.getName().equals(currentVersion.name); @@ -220,7 +223,8 @@ public class MigrationEngine { } } catch (final IOException e) { e.printStackTrace(); - throw new MigrationException("An error occured in the migration (can not access to the DB): '" + currentVersion.name + "' defect @" + currentVersion.stepId + "/" + currentVersion.count); + throw new MigrationException("An error occured in the migration (can not access to the DB): '" + + currentVersion.name + "' defect @" + currentVersion.stepId + "/" + currentVersion.count); } if (needPlaceholder) { if (this.datas.size() == 0) { @@ -246,7 +250,8 @@ public class MigrationEngine { LOGGER.info("Execute migration ... [ END ]"); } - public void migrateSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) throws MigrationException { + public void migrateSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) + throws MigrationException { LOGGER.info("---------------------------------------------------------"); LOGGER.info("-- Migrate: [{}/{}] {} [BEGIN]", id, count, elem.getName()); LOGGER.info("---------------------------------------------------------"); @@ -260,14 +265,16 @@ public class MigrationEngine { migrationResult.count = elem.getNumberOfStep(); } catch (final Exception e) { e.printStackTrace(); - throw new MigrationException("Fail to get number of migration step (maybe generation fail): " + e.getLocalizedMessage()); + throw new MigrationException( + "Fail to get number of migration step (maybe generation fail): " + e.getLocalizedMessage()); } migrationResult.log = log.toString(); try { migrationResult = DataAccess.insert(migrationResult); } catch (final Exception e) { e.printStackTrace(); - throw new MigrationException("Fail to insert migration Log in the migration table: " + e.getLocalizedMessage()); + throw new MigrationException( + "Fail to insert migration Log in the migration table: " + e.getLocalizedMessage()); } boolean ret = true; try { @@ -276,7 +283,8 @@ public class MigrationEngine { log.append("\nFail in the migration apply "); log.append(e.getLocalizedMessage()); e.printStackTrace(); - throw new MigrationException("Migration fail: '" + migrationResult.name + "' defect @" + migrationResult.stepId + "/" + migrationResult.count); + throw new MigrationException("Migration fail: '" + migrationResult.name + "' defect @" + + migrationResult.stepId + "/" + migrationResult.count); } if (ret) { migrationResult.terminated = true; @@ -284,7 +292,8 @@ public class MigrationEngine { DataAccess.update(migrationResult, migrationResult.id, List.of("terminated")); } catch (final Exception e) { e.printStackTrace(); - throw new MigrationException("Fail to update migration Log in the migration table: " + e.getLocalizedMessage()); + throw new MigrationException( + "Fail to update migration Log in the migration table: " + e.getLocalizedMessage()); } } else { try { @@ -293,10 +302,12 @@ public class MigrationEngine { DataAccess.update(migrationResult, migrationResult.id, List.of("log")); } catch (final Exception e) { e.printStackTrace(); - throw new MigrationException("Fail to update migration Log in the migration table: " + e.getLocalizedMessage() + " WITH: An error occured in the migration (OUTSIDE detection): '" + throw new MigrationException("Fail to update migration Log in the migration table: " + + e.getLocalizedMessage() + " WITH: An error occured in the migration (OUTSIDE detection): '" + migrationResult.name + "' defect @" + migrationResult.stepId + "/" + migrationResult.count); } - throw new MigrationException("An error occured in the migration (OUTSIDE detection): '" + migrationResult.name + "' defect @" + migrationResult.stepId + "/" + migrationResult.count); + throw new MigrationException("An error occured in the migration (OUTSIDE detection): '" + + migrationResult.name + "' defect @" + migrationResult.stepId + "/" + migrationResult.count); } LOGGER.info("Migrate: [{}/{}] {} [ END ]", id, count, elem.getName()); } diff --git a/src/org/kar/archidata/migration/MigrationSqlStep.java b/src/org/kar/archidata/migration/MigrationSqlStep.java index 60da0d9..af63f7d 100644 --- a/src/org/kar/archidata/migration/MigrationSqlStep.java +++ b/src/org/kar/archidata/migration/MigrationSqlStep.java @@ -13,7 +13,10 @@ import org.kar.archidata.tools.ConfigBaseVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -record Action(String action, AsyncCall async, List filterDB) { +record Action( + String action, + AsyncCall async, + List filterDB) { public Action(final String action) { this(action, null, List.of()); } @@ -49,9 +52,11 @@ public class MigrationSqlStep implements MigrationInterface { for (int iii = 0; iii < this.actions.size(); iii++) { final Action action = this.actions.get(iii); if (action.action() != null) { - 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()); } else { - LOGGER.info(" >>>> SQL ACTION : {}/{} ==> filter='{}'\nAsync lambda", iii, this.actions.size(), action.filterDB()); + LOGGER.info(" >>>> SQL ACTION : {}/{} ==> filter='{}'\nAsync lambda", iii, this.actions.size(), + action.filterDB()); } } } @@ -65,7 +70,8 @@ public class MigrationSqlStep implements MigrationInterface { } @Override - public boolean applyMigration(final DBEntry entry, final StringBuilder log, final Migration model) throws Exception { + public boolean applyMigration(final DBEntry entry, final StringBuilder log, final Migration model) + throws Exception { if (!this.isGenerated) { this.isGenerated = true; generateStep(); @@ -76,10 +82,12 @@ public class MigrationSqlStep implements MigrationInterface { final Action action = this.actions.get(iii); if (action.action() != null) { - 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"); } else { - LOGGER.info("SQL request: on '{}' current={}", action.filterDB(), ConfigBaseVariable.getDBType()); + LOGGER.info("SQL request: on '{}' current={}", action.filterDB(), + ConfigBaseVariable.getDBType()); log.append("SQL: on " + action.filterDB() + "\n"); } boolean isValid = true; diff --git a/src/org/kar/archidata/model/GetToken.java b/src/org/kar/archidata/model/GetToken.java index 6e356b3..5191d26 100644 --- a/src/org/kar/archidata/model/GetToken.java +++ b/src/org/kar/archidata/model/GetToken.java @@ -3,5 +3,5 @@ package org.kar.archidata.model; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) -public record GetToken(String jwt) { -} +public record GetToken( + String jwt) {} diff --git a/src/org/kar/archidata/model/Token.java b/src/org/kar/archidata/model/Token.java index 926ed11..b0b6465 100644 --- a/src/org/kar/archidata/model/Token.java +++ b/src/org/kar/archidata/model/Token.java @@ -12,7 +12,8 @@ public class Token { public Token() {} - public Token(final long id, final long userId, final String token, final String createTime, final String endValidityTime) { + public Token(final long id, final long userId, final String token, final String createTime, + final String endValidityTime) { this.id = id; this.userId = userId; this.token = token; @@ -35,6 +36,7 @@ public class Token { @Override public String toString() { - return "Token{" + "id=" + this.id + ", userId=" + this.userId + ", token='" + this.token + '\'' + ", createTime=" + this.createTime + ", endValidityTime=" + this.endValidityTime + '}'; + return "Token{" + "id=" + this.id + ", userId=" + this.userId + ", token='" + this.token + '\'' + + ", createTime=" + this.createTime + ", endValidityTime=" + this.endValidityTime + '}'; } } diff --git a/src/org/kar/archidata/tools/ConfigBaseVariable.java b/src/org/kar/archidata/tools/ConfigBaseVariable.java index 8069962..b068e1c 100644 --- a/src/org/kar/archidata/tools/ConfigBaseVariable.java +++ b/src/org/kar/archidata/tools/ConfigBaseVariable.java @@ -127,8 +127,10 @@ public class ConfigBaseVariable { return Boolean.parseBoolean(testMode); } - public record EMailConfig(String from, String login, String password) { - }; + public record EMailConfig( + String from, + String login, + String password) {}; public static EMailConfig getEMailConfig() { if (eMailFrom == null || eMailLogin == null || eMailPassword == null) { diff --git a/src/org/kar/archidata/tools/DataTools.java b/src/org/kar/archidata/tools/DataTools.java index e428579..5915e74 100644 --- a/src/org/kar/archidata/tools/DataTools.java +++ b/src/org/kar/archidata/tools/DataTools.java @@ -69,7 +69,8 @@ public class DataTools { public static Data getWithSha512(final String sha512) { try { - return DataAccess.getWhere(Data.class, new Condition(new QueryCondition("sha512", "=", sha512)), new ReadAllColumn()); + return DataAccess.getWhere(Data.class, new Condition(new QueryCondition("sha512", "=", sha512)), + new ReadAllColumn()); } catch (final Exception e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -79,7 +80,8 @@ public class DataTools { public static Data getWithId(final long id) { try { - return DataAccess.getWhere(Data.class, new Condition(new QueryAnd(List.of(new QueryCondition("deleted", "=", false), new QueryCondition("id", "=", id))))); + return DataAccess.getWhere(Data.class, new Condition(new QueryAnd( + List.of(new QueryCondition("deleted", "=", false), new QueryCondition("id", "=", id))))); } catch (final Exception e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -87,18 +89,19 @@ public class DataTools { return null; } - public static Data createNewData(final long tmpUID, final String originalFileName, final String sha512) throws IOException, SQLException { + public static Data createNewData(final long tmpUID, final String originalFileName, final String sha512) + throws IOException, SQLException { // determine mime type: String mimeType = ""; final String extension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1); mimeType = switch (extension.toLowerCase()) { - case "jpg", "jpeg" -> "image/jpeg"; - case "png" -> "image/png"; - case "webp" -> "image/webp"; - case "mka" -> "audio/x-matroska"; - case "mkv" -> "video/x-matroska"; - case "webm" -> "video/webm"; - default -> throw new IOException("Can not find the mime type of data input: '" + extension + "'"); + case "jpg", "jpeg" -> "image/jpeg"; + case "png" -> "image/png"; + case "webp" -> "image/webp"; + case "mka" -> "audio/x-matroska"; + case "mkv" -> "video/x-matroska"; + case "webm" -> "video/webm"; + default -> throw new IOException("Can not find the mime type of data input: '" + extension + "'"); }; final String tmpPath = getTmpFileInData(tmpUID); final long fileSize = Files.size(Paths.get(tmpPath)); @@ -211,7 +214,11 @@ public class DataTools { return data; } - public static Response uploadCover(final Class clazz, final ID_TYPE id, String fileName, final InputStream fileInputStream, + public static Response uploadCover( + final Class clazz, + final ID_TYPE id, + String fileName, + final InputStream fileInputStream, final FormDataContentDisposition fileMetaData) { try { // correct input string stream : diff --git a/src/org/kar/archidata/tools/JWTWrapper.java b/src/org/kar/archidata/tools/JWTWrapper.java index ad4ac6e..6afe1e7 100644 --- a/src/org/kar/archidata/tools/JWTWrapper.java +++ b/src/org/kar/archidata/tools/JWTWrapper.java @@ -78,7 +78,8 @@ public class JWTWrapper { public PublicKey() {} } - 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: final URL obj = new URL(ssoUri + "public_key"); // LOGGER.debug("Request token from: {}", obj); @@ -169,7 +170,13 @@ public class JWTWrapper { * @param isuer The one who provide the Token * @param timeOutInMunites Expiration of the token. * @return the encoded token */ - public static String generateJWToken(final long userID, final String userLogin, final String isuer, final String application, final Map rights, final int timeOutInMunites) { + public static String generateJWToken( + final long userID, + final String userLogin, + final String isuer, + final String application, + final Map rights, + final int timeOutInMunites) { if (rsaJWK == null) { LOGGER.warn("JWT private key is not present !!!"); return null; @@ -186,7 +193,8 @@ public class JWTWrapper { final Date expiration = new Date(new Date().getTime() - 60 * timeOutInMunites * 1000 /* millisecond */); LOGGER.warn("expiration= {}", expiration); - 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 // add right if needed: if (rights != null && !rights.isEmpty()) { @@ -194,7 +202,8 @@ public class JWTWrapper { } // Prepare JWT with claims set 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 signedJWT.sign(signer); @@ -230,12 +239,15 @@ public class JWTWrapper { return null; } } - if (!ConfigBaseVariable.getTestMode() && !new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) { - LOGGER.error("JWT token is expired now = " + new Date() + " with=" + signedJWT.getJWTClaimsSet().getExpirationTime()); + if (!ConfigBaseVariable.getTestMode() + && !new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) { + LOGGER.error("JWT token is expired now = " + new Date() + " with=" + + signedJWT.getJWTClaimsSet().getExpirationTime()); return null; } if (!isuer.equals(signedJWT.getJWTClaimsSet().getIssuer())) { - LOGGER.error("JWT issuer is wong: '" + isuer + "' != '" + signedJWT.getJWTClaimsSet().getIssuer() + "'"); + LOGGER.error( + "JWT issuer is wong: '" + isuer + "' != '" + signedJWT.getJWTClaimsSet().getIssuer() + "'"); return null; } if (application != null) { @@ -251,7 +263,12 @@ public class JWTWrapper { return null; } - public static String createJwtTestToken(final long userID, final String userLogin, final String isuer, final String application, final Map> rights) { + public static String createJwtTestToken( + final long userID, + final String userLogin, + final String isuer, + final String application, + final Map> rights) { if (!ConfigBaseVariable.getTestMode()) { LOGGER.error("Test mode disable !!!!!"); return null; @@ -262,7 +279,8 @@ public class JWTWrapper { final Date now = new Date(); final Date expiration = new Date(new Date().getTime() + timeOutInMunites * 1000 /* ms */); - 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 // add right if needed: if (rights != null && !rights.isEmpty()) { @@ -270,7 +288,8 @@ public class JWTWrapper { } // Prepare JWT with claims set 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 signedJWT.sign(new TestSigner()); diff --git a/src/org/kar/archidata/tools/RESTApi.java b/src/org/kar/archidata/tools/RESTApi.java index 3cce870..3238392 100644 --- a/src/org/kar/archidata/tools/RESTApi.java +++ b/src/org/kar/archidata/tools/RESTApi.java @@ -36,9 +36,11 @@ public class RESTApi { this.token = token; } - public List gets(final Class clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException { + public List gets(final Class clazz, final String urlOffset) + throws RESTErrorResponseExeption, IOException, InterruptedException { final HttpClient client = HttpClient.newHttpClient(); - Builder requestBuilding = HttpRequest.newBuilder().version(Version.HTTP_1_1).uri(URI.create(this.baseUrl + urlOffset)); + Builder requestBuilding = HttpRequest.newBuilder().version(Version.HTTP_1_1) + .uri(URI.create(this.baseUrl + urlOffset)); if (this.token != null) { requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Bearer " + this.token); } @@ -46,56 +48,69 @@ public class RESTApi { final HttpResponse httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) { try { - final RESTErrorResponseExeption out = this.mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class); + final RESTErrorResponseExeption out = this.mapper.readValue(httpResponse.body(), + RESTErrorResponseExeption.class); throw out; } catch (final MismatchedInputException ex) { - throw new IOException("Fail to get the data [" + httpResponse.statusCode() + "] " + httpResponse.body()); + throw new IOException( + "Fail to get the data [" + httpResponse.statusCode() + "] " + httpResponse.body()); } } return this.mapper.readValue(httpResponse.body(), new TypeReference>() {}); } - public T get(final Class clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T get(final Class clazz, final String urlOffset) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSendJson("GET", clazz, urlOffset, null); } - public T post(final Class clazz, final String urlOffset, final U data) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T post(final Class clazz, final String urlOffset, final U data) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSend("POST", clazz, urlOffset, data); } - public T postJson(final Class clazz, final String urlOffset, final String body) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T postJson(final Class clazz, final String urlOffset, final String body) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSendJson("POST", clazz, urlOffset, body); } - public T postMap(final Class clazz, final String urlOffset, final Map data) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T postMap(final Class clazz, final String urlOffset, final Map data) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSendMap("POST", clazz, urlOffset, data); } - public T put(final Class clazz, final String urlOffset, final U data) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T put(final Class clazz, final String urlOffset, final U data) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSend("PUT", clazz, urlOffset, data); } - public T putJson(final Class clazz, final String urlOffset, final String body) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T putJson(final Class clazz, final String urlOffset, final String body) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSendJson("PUT", clazz, urlOffset, body); } - public T putMap(final Class clazz, final String urlOffset, final Map data) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T putMap(final Class clazz, final String urlOffset, final Map data) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSendMap("PUT", clazz, urlOffset, data); } - public T patch(final Class clazz, final String urlOffset, final U data) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T patch(final Class clazz, final String urlOffset, final U data) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSend("PATCH", clazz, urlOffset, data); } - public T patchJson(final Class clazz, final String urlOffset, final String body) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T patchJson(final Class clazz, final String urlOffset, final String body) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSendJson("PATCH", clazz, urlOffset, body); } - public T patchMap(final Class clazz, final String urlOffset, final Map data) throws RESTErrorResponseExeption, IOException, InterruptedException { + public T patchMap(final Class clazz, final String urlOffset, final Map data) + throws RESTErrorResponseExeption, IOException, InterruptedException { return modelSendMap("PATCH", clazz, urlOffset, data); } - protected T modelSend(final String model, final Class clazz, final String urlOffset, final U data) throws RESTErrorResponseExeption, IOException, InterruptedException { + protected T modelSend(final String model, final Class clazz, final String urlOffset, final U data) + throws RESTErrorResponseExeption, IOException, InterruptedException { if (data == null) { return modelSendJson(model, clazz, urlOffset, null); } else { @@ -104,10 +119,12 @@ public class RESTApi { } } - protected T modelSendJson(final String model, final Class clazz, final String urlOffset, String body) throws RESTErrorResponseExeption, IOException, InterruptedException { + protected T modelSendJson(final String model, final Class clazz, final String urlOffset, String body) + throws RESTErrorResponseExeption, IOException, InterruptedException { final HttpClient client = HttpClient.newHttpClient(); // client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); - Builder requestBuilding = HttpRequest.newBuilder().version(Version.HTTP_1_1).uri(URI.create(this.baseUrl + urlOffset)); + Builder requestBuilding = HttpRequest.newBuilder().version(Version.HTTP_1_1) + .uri(URI.create(this.baseUrl + urlOffset)); LOGGER.trace("call {}: {}", model, URI.create(this.baseUrl + urlOffset)); LOGGER.trace("DATA: {}", body); if (this.token != null) { @@ -123,14 +140,17 @@ public class RESTApi { if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) { LOGGER.trace("Receive Error: {}", httpResponse.body()); try { - final RESTErrorResponseExeption out = this.mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class); + final RESTErrorResponseExeption out = this.mapper.readValue(httpResponse.body(), + RESTErrorResponseExeption.class); throw out; } catch (final MismatchedInputException ex) { - throw new IOException("Fail to get the data [" + httpResponse.statusCode() + "] " + httpResponse.body()); + throw new IOException( + "Fail to get the data [" + httpResponse.statusCode() + "] " + httpResponse.body()); } catch (final JsonParseException ex) { ex.printStackTrace(); LOGGER.error("body: {}", httpResponse.body()); - throw new IOException("Fail to get the ERROR data [" + httpResponse.statusCode() + "] " + httpResponse.body()); + throw new IOException( + "Fail to get the ERROR data [" + httpResponse.statusCode() + "] " + httpResponse.body()); } } if (clazz.equals(String.class)) { @@ -140,10 +160,15 @@ public class RESTApi { return this.mapper.readValue(httpResponse.body(), clazz); } - protected T modelSendMap(final String model, final Class clazz, final String urlOffset, final Map data) throws RESTErrorResponseExeption, IOException, InterruptedException { + protected T modelSendMap( + final String model, + final Class clazz, + final String urlOffset, + final Map data) throws RESTErrorResponseExeption, IOException, InterruptedException { final HttpClient client = HttpClient.newHttpClient(); String body = null; - Builder requestBuilding = HttpRequest.newBuilder().version(Version.HTTP_1_1).uri(URI.create(this.baseUrl + urlOffset)); + Builder requestBuilding = HttpRequest.newBuilder().version(Version.HTTP_1_1) + .uri(URI.create(this.baseUrl + urlOffset)); if (this.token != null) { requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Bearer " + this.token); } @@ -157,10 +182,12 @@ public class RESTApi { final HttpResponse httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) { try { - final RESTErrorResponseExeption out = this.mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class); + final RESTErrorResponseExeption out = this.mapper.readValue(httpResponse.body(), + RESTErrorResponseExeption.class); throw out; } catch (final MismatchedInputException ex) { - throw new IOException("Fail to get the data [" + httpResponse.statusCode() + "] " + httpResponse.body()); + throw new IOException( + "Fail to get the data [" + httpResponse.statusCode() + "] " + httpResponse.body()); } } if (clazz.equals(String.class)) { @@ -169,9 +196,11 @@ public class RESTApi { return this.mapper.readValue(httpResponse.body(), clazz); } - public void delete(final Class clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException { + public void delete(final Class clazz, final String urlOffset) + throws RESTErrorResponseExeption, IOException, InterruptedException { final HttpClient client = HttpClient.newHttpClient(); - Builder requestBuilding = HttpRequest.newBuilder().version(Version.HTTP_1_1).uri(URI.create(this.baseUrl + urlOffset)); + Builder requestBuilding = HttpRequest.newBuilder().version(Version.HTTP_1_1) + .uri(URI.create(this.baseUrl + urlOffset)); if (this.token != null) { requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Bearer " + this.token); } @@ -179,10 +208,12 @@ public class RESTApi { final HttpResponse httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString()); if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) { try { - final RESTErrorResponseExeption out = this.mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class); + final RESTErrorResponseExeption out = this.mapper.readValue(httpResponse.body(), + RESTErrorResponseExeption.class); throw out; } catch (final MismatchedInputException ex) { - throw new IOException("Fail to get the data [" + httpResponse.statusCode() + "] " + httpResponse.body()); + throw new IOException( + "Fail to get the data [" + httpResponse.statusCode() + "] " + httpResponse.body()); } } } diff --git a/test/src/test/kar/archidata/StepwiseExtension.java b/test/src/test/kar/archidata/StepwiseExtension.java index 0ca7566..11b0c4c 100644 --- a/test/src/test/kar/archidata/StepwiseExtension.java +++ b/test/src/test/kar/archidata/StepwiseExtension.java @@ -12,11 +12,13 @@ public class StepwiseExtension implements ExecutionCondition, TestExecutionExcep final ExtensionContext.Store store = storeFor(extensionContext, namespace); final String value = store.get(StepwiseExtension.class, String.class); return value == null ? ConditionEvaluationResult.enabled("No test failures in stepwise tests") - : ConditionEvaluationResult.disabled(String.format("Stepwise test disabled due to previous failure in '%s'", value)); + : ConditionEvaluationResult + .disabled(String.format("Stepwise test disabled due to previous failure in '%s'", value)); } @Override - public void handleTestExecutionException(final ExtensionContext extensionContext, final Throwable throwable) throws Throwable { + public void handleTestExecutionException(final ExtensionContext extensionContext, final Throwable throwable) + throws Throwable { final ExtensionContext.Namespace namespace = namespaceFor(extensionContext); final ExtensionContext.Store store = storeFor(extensionContext, namespace); store.put(StepwiseExtension.class, extensionContext.getDisplayName()); @@ -27,7 +29,9 @@ public class StepwiseExtension implements ExecutionCondition, TestExecutionExcep return ExtensionContext.Namespace.create(StepwiseExtension.class, extensionContext.getParent()); } - private ExtensionContext.Store storeFor(final ExtensionContext extensionContext, final ExtensionContext.Namespace namespace) { + private ExtensionContext.Store storeFor( + final ExtensionContext extensionContext, + final ExtensionContext.Namespace namespace) { return extensionContext.getParent().get().getStore(namespace); } } \ No newline at end of file diff --git a/test/src/test/kar/archidata/TestSimpleTable.java b/test/src/test/kar/archidata/TestSimpleTable.java index 7646d57..ff9d4f3 100644 --- a/test/src/test/kar/archidata/TestSimpleTable.java +++ b/test/src/test/kar/archidata/TestSimpleTable.java @@ -91,7 +91,8 @@ public class TestSimpleTable { @Test public void testReadAllValuesUnreadable() throws Exception { // check the full values - final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, QueryOptions.READ_ALL_COLOMN); + final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, + QueryOptions.READ_ALL_COLOMN); Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve.id); @@ -114,7 +115,8 @@ public class TestSimpleTable { final SimpleTable test = new SimpleTable(); test.data = TestSimpleTable.DATA_INJECTED_2; DataAccess.update(test, TestSimpleTable.idOfTheObject, List.of("data")); - final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, QueryOptions.READ_ALL_COLOMN); + final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, + QueryOptions.READ_ALL_COLOMN); Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve.id); Assertions.assertEquals(TestSimpleTable.idOfTheObject, retrieve.id); @@ -139,7 +141,8 @@ public class TestSimpleTable { public void testReadDeletedObject() throws Exception { // check if we set get deleted element - final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, QueryOptions.ACCESS_DELETED_ITEMS); + final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, + QueryOptions.ACCESS_DELETED_ITEMS); Assertions.assertNull(retrieve); } @@ -148,7 +151,8 @@ public class TestSimpleTable { @Test public void testReadAllValuesUnreadableOfDeletedObject() throws Exception { // check if we set get deleted element with all data - final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, QueryOptions.ACCESS_DELETED_ITEMS, QueryOptions.READ_ALL_COLOMN); + final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, + QueryOptions.ACCESS_DELETED_ITEMS, QueryOptions.READ_ALL_COLOMN); Assertions.assertNull(retrieve); } diff --git a/test/src/test/kar/archidata/TestSimpleTableSoftDelete.java b/test/src/test/kar/archidata/TestSimpleTableSoftDelete.java index 41a3c98..eb411cf 100644 --- a/test/src/test/kar/archidata/TestSimpleTableSoftDelete.java +++ b/test/src/test/kar/archidata/TestSimpleTableSoftDelete.java @@ -92,14 +92,16 @@ public class TestSimpleTableSoftDelete { @Test public void testReadAllValuesUnreadable() throws Exception { // check the full values - final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.READ_ALL_COLOMN); + final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, + TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.READ_ALL_COLOMN); Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.DATA_INJECTED, retrieve.data); Assertions.assertNotNull(retrieve.createdAt); - LOGGER.info("start @ {} create @ {}", retrieve.createdAt.toInstant(), TestSimpleTableSoftDelete.startAction.toInstant()); + LOGGER.info("start @ {} create @ {}", retrieve.createdAt.toInstant(), + TestSimpleTableSoftDelete.startAction.toInstant()); // Gros travail sur les timestamp a faire pour que ce soit correct ... // Assertions.assertTrue(retrieve.createdAt.after(this.startAction)); Assertions.assertNotNull(retrieve.updatedAt); @@ -118,7 +120,9 @@ public class TestSimpleTableSoftDelete { final SimpleTableSoftDelete test = new SimpleTableSoftDelete(); test.data = TestSimpleTableSoftDelete.DATA_INJECTED_2; DataAccess.update(test, TestSimpleTableSoftDelete.idOfTheObject, List.of("data")); - final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.ACCESS_DELETED_ITEMS, QueryOptions.READ_ALL_COLOMN); + final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, + TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.ACCESS_DELETED_ITEMS, + QueryOptions.READ_ALL_COLOMN); Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); @@ -141,7 +145,8 @@ public class TestSimpleTableSoftDelete { } // Delete the entry: DataAccess.delete(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject); - final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject); + final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, + TestSimpleTableSoftDelete.idOfTheObject); Assertions.assertNull(retrieve); } @@ -150,7 +155,8 @@ public class TestSimpleTableSoftDelete { public void testReadDeletedObject() throws Exception { // check if we set get deleted element - final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.ACCESS_DELETED_ITEMS); + final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, + TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.ACCESS_DELETED_ITEMS); Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); @@ -165,7 +171,9 @@ public class TestSimpleTableSoftDelete { @Test public void testReadAllValuesUnreadableOfDeletedObject() throws Exception { // check if we set get deleted element with all data - final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.ACCESS_DELETED_ITEMS, QueryOptions.READ_ALL_COLOMN); + final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, + TestSimpleTableSoftDelete.idOfTheObject, QueryOptions.ACCESS_DELETED_ITEMS, + QueryOptions.READ_ALL_COLOMN); Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); diff --git a/test/src/test/kar/archidata/TestTypes.java b/test/src/test/kar/archidata/TestTypes.java index 2c3cfef..5bb3fcb 100644 --- a/test/src/test/kar/archidata/TestTypes.java +++ b/test/src/test/kar/archidata/TestTypes.java @@ -267,7 +267,8 @@ public class TestTypes { Assertions.assertNotNull(retrieve.timeStampData); // Can not compare the exact timestamp due to aproximation and model of storing data : // 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); }