[DEV] start add hooks
This commit is contained in:
parent
b48916be07
commit
49480bc0aa
@ -27,7 +27,6 @@
|
||||
</classpathentry>
|
||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
|
||||
<attributes>
|
||||
<attribute name="module" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
|
16
README.md
16
README.md
@ -14,12 +14,28 @@ mvn clean compile assembly:single
|
||||
generic interface for all KAR web application
|
||||
|
||||
|
||||
|
||||
Somes tools:
|
||||
============
|
||||
|
||||
Auto-update dependency:
|
||||
-----------------------
|
||||
|
||||
auto-update to the last version dependency:
|
||||
|
||||
```bash
|
||||
mvn versions:use-latest-versions
|
||||
```
|
||||
|
||||
Format the code
|
||||
---------------
|
||||
|
||||
Simply run the cmd-line:
|
||||
|
||||
```bash
|
||||
mvn formatter:format
|
||||
```
|
||||
|
||||
|
||||
Add Gitea in the dependency for the registry:
|
||||
=============================================
|
||||
|
40
pom.xml
40
pom.xml
@ -223,6 +223,46 @@
|
||||
<nohelp>true</nohelp>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- Check the style of the code -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<configuration>
|
||||
<configLocation>CheckStyle.xml</configLocation>
|
||||
<consoleOutput>true</consoleOutput>
|
||||
<failOnViolation>true</failOnViolation>
|
||||
<failsOnError>true</failsOnError>
|
||||
<includeTestSourceDirectory>true</includeTestSourceDirectory>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>net.revelc.code.formatter</groupId>
|
||||
<artifactId>formatter-maven-plugin</artifactId>
|
||||
<version>2.12.2</version>
|
||||
<configuration>
|
||||
<encoding>UTF-8</encoding>
|
||||
<lineEnding>LF</lineEnding>
|
||||
<configFile>Formatter.xml</configFile>
|
||||
<directories>
|
||||
<directory>src/</directory>
|
||||
<directory>test/src</directory>
|
||||
</directories>
|
||||
<includes>
|
||||
<include>**/*.java</include>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>module-info.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>validate</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<!-- Generate Java-docs As Part Of Project Reports -->
|
||||
|
@ -6,14 +6,8 @@ import org.kar.archidata.util.ConfigBaseVariable;
|
||||
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());
|
||||
}
|
||||
static {
|
||||
dbConfig = new DBConfig(ConfigBaseVariable.getDBType(), ConfigBaseVariable.getDBHost(), Integer.parseInt(ConfigBaseVariable.getDBPort()), ConfigBaseVariable.getDBLogin(),
|
||||
ConfigBaseVariable.getDBPassword(), ConfigBaseVariable.getDBName(), ConfigBaseVariable.getDBKeepConnected());
|
||||
}
|
||||
}
|
||||
|
@ -6,17 +6,18 @@ import org.kar.archidata.util.JWTWrapper;
|
||||
public class UpdateJwtPublicKey extends Thread {
|
||||
boolean kill = false;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (ConfigBaseVariable.getSSOAddress() == null) {
|
||||
System.out.println("SSO INTERFACE is not provided ==> work alone.");
|
||||
// No SO provided, kill the thread.
|
||||
return;
|
||||
}
|
||||
while (this.kill == false) {
|
||||
while (!this.kill) {
|
||||
// need to upgrade when server call us...
|
||||
try {
|
||||
JWTWrapper.initLocalTokenRemote(ConfigBaseVariable.getSSOAddress(), "archidata");
|
||||
} catch (Exception e1) {
|
||||
} catch (final Exception e1) {
|
||||
e1.printStackTrace();
|
||||
System.out.println("Can not retreive the basic tocken");
|
||||
return;
|
||||
@ -24,7 +25,7 @@ public class UpdateJwtPublicKey extends Thread {
|
||||
try {
|
||||
// update every 5 minutes the master token
|
||||
Thread.sleep(1000 * 60 * 5, 0);
|
||||
} catch (InterruptedException e) {
|
||||
} catch (final InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
@ -12,12 +12,12 @@ public class UserDB {
|
||||
|
||||
public UserDB() {}
|
||||
|
||||
public static User getUsers(long userId) throws Exception {
|
||||
public static User getUsers(final long userId) throws Exception {
|
||||
return DataAccess.get(User.class, userId);
|
||||
}
|
||||
|
||||
public static User getUserOrCreate(long userId, String userLogin) throws Exception {
|
||||
User user = getUsers(userId);
|
||||
public static User getUserOrCreate(final long userId, final String userLogin) throws Exception {
|
||||
final User user = getUsers(userId);
|
||||
if (user != null) {
|
||||
return user;
|
||||
}
|
||||
@ -25,19 +25,18 @@ public class UserDB {
|
||||
return getUsers(userId);
|
||||
}
|
||||
|
||||
private static void createUsersInfoFromOAuth(long userId, String login) throws IOException {
|
||||
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||
String query = "INSERT INTO `user` (`id`, `login`, `lastConnection`, `admin`, `blocked`, `removed`) VALUE (?,?,now(3),'0','0','0')";
|
||||
private static void createUsersInfoFromOAuth(final long userId, final String login) throws IOException {
|
||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||
final String query = "INSERT INTO `user` (`id`, `login`, `lastConnection`, `admin`, `blocked`, `removed`) VALUE (?,?,now(3),'0','0','0')";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
final PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
ps.setLong(1, userId);
|
||||
ps.setString(2, login);
|
||||
ps.executeUpdate();
|
||||
} catch (SQLException throwables) {
|
||||
} catch (final SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
} finally {
|
||||
entry.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -57,14 +57,12 @@ public class DataResource {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(MediaType.class);
|
||||
private final static int CHUNK_SIZE = 1024 * 1024; // 1MB chunks
|
||||
private final static int CHUNK_SIZE_IN = 50 * 1024 * 1024; // 1MB chunks
|
||||
/**
|
||||
* Upload some datas
|
||||
*/
|
||||
/** Upload some datas */
|
||||
private static long tmpFolderId = 1;
|
||||
|
||||
private static void createFolder(final String path) throws IOException {
|
||||
if (!Files.exists(java.nio.file.Path.of(path))) {
|
||||
//Log.print("Create folder: " + path);
|
||||
// Log.print("Create folder: " + path);
|
||||
Files.createDirectories(java.nio.file.Path.of(path));
|
||||
}
|
||||
}
|
||||
@ -121,13 +119,13 @@ public class DataResource {
|
||||
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;
|
||||
@ -176,7 +174,7 @@ public class DataResource {
|
||||
|
||||
outpuStream = new FileOutputStream(new File(serverLocation));
|
||||
while ((read = uploadedInputStream.read(bytes)) != -1) {
|
||||
//logger.info("write {}", read);
|
||||
// logger.info("write {}", read);
|
||||
md.update(bytes, 0, read);
|
||||
outpuStream.write(bytes, 0, read);
|
||||
}
|
||||
@ -226,7 +224,7 @@ public class DataResource {
|
||||
LOGGER.info("===================================================");
|
||||
LOGGER.info("== DATA uploadFile {}", (gc == null ? "null" : gc.userByToken));
|
||||
LOGGER.info("===================================================");
|
||||
//public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||
// public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||
LOGGER.info("Upload file: ");
|
||||
final String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
||||
try {
|
||||
@ -236,7 +234,7 @@ public class DataResource {
|
||||
}
|
||||
saveFile(fileInputStream, filePath);
|
||||
return Response.ok("Data uploaded successfully !!").build();
|
||||
//return null;
|
||||
// return null;
|
||||
}
|
||||
|
||||
@GET
|
||||
@ -247,9 +245,9 @@ public class DataResource {
|
||||
public Response retriveDataId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
||||
@PathParam("id") final Long id) throws Exception {
|
||||
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
||||
//logger.info("===================================================");
|
||||
// logger.info("===================================================");
|
||||
LOGGER.info("== DATA retriveDataId ? id={} user={}", id, (gc == null ? "null" : gc.userByToken));
|
||||
//logger.info("===================================================");
|
||||
// logger.info("===================================================");
|
||||
final Data value = getSmall(id);
|
||||
if (value == null) {
|
||||
Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
||||
@ -262,13 +260,13 @@ public class DataResource {
|
||||
@RolesAllowed("USER")
|
||||
@PermitTokenInURI
|
||||
@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
//@CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
||||
// @CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
||||
public Response retriveDataThumbnailId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
||||
@PathParam("id") final Long id) throws Exception {
|
||||
//GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
||||
//logger.info("===================================================");
|
||||
//logger.info("== DATA retriveDataThumbnailId ? {}", (gc==null?"null":gc.user));
|
||||
//logger.info("===================================================");
|
||||
// GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
||||
// logger.info("===================================================");
|
||||
// logger.info("== DATA retriveDataThumbnailId ? {}", (gc==null?"null":gc.user));
|
||||
// logger.info("===================================================");
|
||||
final Data value = getSmall(id);
|
||||
if (value == null) {
|
||||
return Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
||||
@ -279,7 +277,7 @@ public class DataResource {
|
||||
return Response.status(404).entity("{\"error\":\"media Does not exist: " + id + "\"}").type("application/json").build();
|
||||
}
|
||||
if (value.mimeType.contentEquals("image/jpeg") || value.mimeType.contentEquals("image/png")
|
||||
// || value.mimeType.contentEquals("image/webp")
|
||||
// || value.mimeType.contentEquals("image/webp")
|
||||
) {
|
||||
// reads input image
|
||||
final BufferedImage inputImage = ImageIO.read(inputFile);
|
||||
@ -302,7 +300,7 @@ public class DataResource {
|
||||
return Response.status(500).entity("Internal Error: resize fail: " + e.getMessage()).type("text/plain").build();
|
||||
}
|
||||
final byte[] imageData = baos.toByteArray();
|
||||
//Response.ok(new ByteArrayInputStream(imageData)).build();
|
||||
// Response.ok(new ByteArrayInputStream(imageData)).build();
|
||||
final Response.ResponseBuilder out = Response.ok(imageData).header(HttpHeaders.CONTENT_LENGTH, imageData.length);
|
||||
out.type("image/jpeg");
|
||||
// TODO: move this in a decorator !!!
|
||||
@ -315,7 +313,7 @@ public class DataResource {
|
||||
return buildStream(filePathName, range, value.mimeType);
|
||||
}
|
||||
|
||||
//@Secured
|
||||
// @Secured
|
||||
@GET
|
||||
@Path("{id}/{name}")
|
||||
@PermitTokenInURI
|
||||
@ -324,9 +322,9 @@ public class DataResource {
|
||||
public Response retriveDataFull(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
|
||||
@PathParam("id") final Long id, @PathParam("name") final String name) throws Exception {
|
||||
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
||||
//logger.info("===================================================");
|
||||
// logger.info("===================================================");
|
||||
LOGGER.info("== DATA retriveDataFull ? id={} user={}", id, (gc == null ? "null" : gc.userByToken));
|
||||
//logger.info("===================================================");
|
||||
// logger.info("===================================================");
|
||||
final Data value = getSmall(id);
|
||||
if (value == null) {
|
||||
Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
|
||||
@ -334,16 +332,14 @@ public class DataResource {
|
||||
return buildStream(ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adapted from http://stackoverflow.com/questions/12768812/video-streaming-to-ipad-does-not-work-with-tapestry5/12829541#12829541
|
||||
/** Adapted from http://stackoverflow.com/questions/12768812/video-streaming-to-ipad-does-not-work-with-tapestry5/12829541#12829541
|
||||
*
|
||||
* @param range range header
|
||||
* @return Streaming output
|
||||
* @throws Exception IOException if an error occurs in streaming.
|
||||
*/
|
||||
* @throws Exception IOException if an error occurs in streaming. */
|
||||
private Response buildStream(final String filename, final String range, final String mimeType) throws Exception {
|
||||
final File file = new File(filename);
|
||||
//logger.info("request range : {}", range);
|
||||
// logger.info("request range : {}", range);
|
||||
// range not requested : Firefox does not send range headers
|
||||
if (range == null) {
|
||||
final StreamingOutput output = new StreamingOutput() {
|
||||
@ -356,7 +352,7 @@ public class DataResource {
|
||||
try {
|
||||
out.write(buf, 0, len);
|
||||
out.flush();
|
||||
//logger.info("---- wrote {} bytes file ----", len);
|
||||
// logger.info("---- wrote {} bytes file ----", len);
|
||||
} catch (final IOException ex) {
|
||||
LOGGER.info("remote close connection");
|
||||
break;
|
||||
@ -378,8 +374,8 @@ public class DataResource {
|
||||
final String[] ranges = range.split("=")[1].split("-");
|
||||
final long from = Long.parseLong(ranges[0]);
|
||||
|
||||
//logger.info("request range : {}", ranges.length);
|
||||
//Chunk media if the range upper bound is unspecified. Chrome, Opera sends "bytes=0-"
|
||||
// logger.info("request range : {}", ranges.length);
|
||||
// Chunk media if the range upper bound is unspecified. Chrome, Opera sends "bytes=0-"
|
||||
long to = CHUNK_SIZE + from;
|
||||
if (ranges.length == 1) {
|
||||
to = file.length() - 1;
|
||||
@ -387,7 +383,7 @@ public class DataResource {
|
||||
to = file.length() - 1;
|
||||
}
|
||||
final String responseRange = String.format("bytes %d-%d/%d", from, to, file.length());
|
||||
//logger.info("responseRange: {}", responseRange);
|
||||
// logger.info("responseRange: {}", responseRange);
|
||||
final RandomAccessFile raf = new RandomAccessFile(file, "r");
|
||||
raf.seek(from);
|
||||
|
||||
|
@ -76,7 +76,7 @@ public class FrontGeneric {
|
||||
}
|
||||
final ResponseBuilder response = Response.ok(download);
|
||||
// use this if I want to download the file:
|
||||
//response.header("Content-Disposition", "attachment; filename=" + fileName);
|
||||
// response.header("Content-Disposition", "attachment; filename=" + fileName);
|
||||
final CacheControl cc = new CacheControl();
|
||||
cc.setMaxAge(60);
|
||||
cc.setNoCache(false);
|
||||
@ -88,8 +88,8 @@ public class FrontGeneric {
|
||||
|
||||
@GET
|
||||
@PermitAll()
|
||||
//@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
//@CacheMaxAge(time = 1, unit = TimeUnit.DAYS)
|
||||
// @Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
// @CacheMaxAge(time = 1, unit = TimeUnit.DAYS)
|
||||
public Response retrive0() throws Exception {
|
||||
return retrive("index.html");
|
||||
}
|
||||
@ -97,8 +97,8 @@ public class FrontGeneric {
|
||||
@GET
|
||||
@Path("{any: .*}")
|
||||
@PermitAll()
|
||||
//@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
//@CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
||||
// @Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
// @CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
||||
public Response retrive1(@PathParam("any") final List<PathSegment> segments) throws Exception {
|
||||
String filename = "";
|
||||
for (final PathSegment elem : segments) {
|
||||
|
@ -19,7 +19,7 @@ public class MediaStreamer implements StreamingOutput {
|
||||
private final RandomAccessFile raf;
|
||||
|
||||
public MediaStreamer(final long length, final RandomAccessFile raf) throws IOException {
|
||||
//logger.info("request stream of {} data", length / 1024);
|
||||
// logger.info("request stream of {} data", length / 1024);
|
||||
if (length < 0) {
|
||||
throw new IOException("Wrong size of the file to stream: " + length);
|
||||
}
|
||||
|
@ -11,15 +11,15 @@ public class BackupEngine {
|
||||
|
||||
private final String pathStore;
|
||||
private final StoreMode mode;
|
||||
private List<Class<?>> classes = new ArrayList<>();
|
||||
private final List<Class<?>> classes = new ArrayList<>();
|
||||
|
||||
public BackupEngine(String pathToStoreDB, StoreMode mode) {
|
||||
public BackupEngine(final String pathToStoreDB, final StoreMode mode) {
|
||||
this.pathStore = pathToStoreDB;
|
||||
this.mode = mode;
|
||||
}
|
||||
|
||||
public void addClass(Class<?> clazz) {
|
||||
classes.add(clazz);
|
||||
public void addClass(final Class<?> clazz) {
|
||||
this.classes.add(clazz);
|
||||
}
|
||||
|
||||
public void store() {
|
||||
|
@ -11,15 +11,15 @@ public class ExceptionCatcher implements ExceptionMapper<Exception> {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatcher.class);
|
||||
|
||||
@Override
|
||||
public Response toResponse(Exception exception) {
|
||||
public Response toResponse(final Exception exception) {
|
||||
LOGGER.warn("Catch exception (not managed...):");
|
||||
RestErrorResponse ret = build(exception);
|
||||
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();
|
||||
}
|
||||
|
||||
private RestErrorResponse build(Exception exception) {
|
||||
private RestErrorResponse build(final Exception exception) {
|
||||
return new RestErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Catch Unknown Exception", exception.getMessage());
|
||||
}
|
||||
|
||||
|
@ -12,15 +12,15 @@ public class FailExceptionCatcher implements ExceptionMapper<FailException> {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FailExceptionCatcher.class);
|
||||
|
||||
@Override
|
||||
public Response toResponse(FailException exception) {
|
||||
RestErrorResponse ret = build(exception);
|
||||
public Response toResponse(final FailException exception) {
|
||||
final RestErrorResponse ret = build(exception);
|
||||
LOGGER.error("Error UUID={}", ret.uuid);
|
||||
// Not display backtrace ==> this may be a normal case ...
|
||||
//exception.printStackTrace();
|
||||
// exception.printStackTrace();
|
||||
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private RestErrorResponse build(FailException exception) {
|
||||
private RestErrorResponse build(final FailException exception) {
|
||||
return new RestErrorResponse(exception.status, "Request Fail", exception.getMessage());
|
||||
}
|
||||
|
||||
|
@ -12,14 +12,14 @@ public class InputExceptionCatcher implements ExceptionMapper<InputException> {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(InputExceptionCatcher.class);
|
||||
|
||||
@Override
|
||||
public Response toResponse(InputException exception) {
|
||||
RestErrorResponse ret = build(exception);
|
||||
public Response toResponse(final InputException exception) {
|
||||
final RestErrorResponse ret = build(exception);
|
||||
LOGGER.error("Error UUID={}", ret.uuid);
|
||||
exception.printStackTrace();
|
||||
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private RestErrorResponse build(InputException exception) {
|
||||
private RestErrorResponse build(final InputException exception) {
|
||||
return new RestErrorResponse(exception.status, "Error on input='" + exception.missingVariable + "'", exception.getMessage());
|
||||
}
|
||||
|
||||
|
@ -13,7 +13,7 @@ public class RestErrorResponse {
|
||||
final public int status;
|
||||
final public String statusMessage;
|
||||
|
||||
public RestErrorResponse(Response.Status status, String time, String error, String message) {
|
||||
public RestErrorResponse(final Response.Status status, final String time, final String error, final String message) {
|
||||
this.time = time;
|
||||
this.error = error;
|
||||
this.message = message;
|
||||
@ -21,7 +21,7 @@ public class RestErrorResponse {
|
||||
this.statusMessage = status.getReasonPhrase();
|
||||
}
|
||||
|
||||
public RestErrorResponse(Response.Status status, String error, String message) {
|
||||
public RestErrorResponse(final Response.Status status, final String error, final String message) {
|
||||
this.time = Instant.now().toString();
|
||||
this.error = error;
|
||||
this.message = message;
|
||||
@ -29,7 +29,7 @@ public class RestErrorResponse {
|
||||
this.statusMessage = status.getReasonPhrase();
|
||||
}
|
||||
|
||||
public RestErrorResponse(Response.Status status) {
|
||||
public RestErrorResponse(final Response.Status status) {
|
||||
this.time = Instant.now().toString();
|
||||
this.status = status.getStatusCode();
|
||||
this.statusMessage = status.getReasonPhrase();
|
||||
|
@ -12,14 +12,14 @@ public class SystemExceptionCatcher implements ExceptionMapper<SystemException>
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SystemExceptionCatcher.class);
|
||||
|
||||
@Override
|
||||
public Response toResponse(SystemException exception) {
|
||||
RestErrorResponse ret = build(exception);
|
||||
public Response toResponse(final SystemException exception) {
|
||||
final RestErrorResponse ret = build(exception);
|
||||
LOGGER.error("Error UUID={}", ret.uuid);
|
||||
exception.printStackTrace();
|
||||
return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private RestErrorResponse build(SystemException exception) {
|
||||
private RestErrorResponse build(final SystemException exception) {
|
||||
return new RestErrorResponse(exception.status, "System error", exception.getMessage());
|
||||
}
|
||||
|
||||
|
@ -84,10 +84,10 @@ public class DataAccess {
|
||||
// TODO : Maybe connect with a temporary not specified connection interface to a db ...
|
||||
final PreparedStatement ps = entry.connection.prepareStatement("show databases");
|
||||
final ResultSet rs = ps.executeQuery();
|
||||
//LOGGER.info("List all tables: equals? '{}'", name);
|
||||
// LOGGER.info("List all tables: equals? '{}'", name);
|
||||
while (rs.next()) {
|
||||
final String data = rs.getString(1);
|
||||
//LOGGER.info(" - '{}'", data);
|
||||
// LOGGER.info(" - '{}'", data);
|
||||
if (name.equals(data)) {
|
||||
return true;
|
||||
}
|
||||
@ -132,7 +132,7 @@ public class DataAccess {
|
||||
WHERE type = 'table'
|
||||
AND name = ?;
|
||||
""";
|
||||
// PreparedStatement ps = entry.connection.prepareStatement("show tables");
|
||||
// PreparedStatement ps = entry.connection.prepareStatement("show tables");
|
||||
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||
final PreparedStatement ps = entry.connection.prepareStatement(request);
|
||||
ps.setString(1, name);
|
||||
@ -144,10 +144,10 @@ public class DataAccess {
|
||||
// TODO : Maybe connect with a temporary not specified connection interface to a db ...
|
||||
final PreparedStatement ps = entry.connection.prepareStatement("show tables");
|
||||
final ResultSet rs = ps.executeQuery();
|
||||
//LOGGER.info("List all tables: equals? '{}'", name);
|
||||
// LOGGER.info("List all tables: equals? '{}'", name);
|
||||
while (rs.next()) {
|
||||
final String data = rs.getString(1);
|
||||
//LOGGER.info(" - '{}'", data);
|
||||
// LOGGER.info(" - '{}'", data);
|
||||
if (name.equals(data)) {
|
||||
return true;
|
||||
}
|
||||
@ -162,13 +162,11 @@ public class DataAccess {
|
||||
throw new InternalServerErrorException("Can Not manage the DB-access");
|
||||
}
|
||||
|
||||
/**
|
||||
* extract a list of "-" separated element from a SQL input data.
|
||||
/** extract a list of "-" separated element from a SQL input data.
|
||||
* @param rs Result Set of the BDD
|
||||
* @param iii Id in the result set
|
||||
* @return The list of Long value
|
||||
* @throws SQLException if an error is generated in the sql request.
|
||||
*/
|
||||
* @return The list of Long value
|
||||
* @throws SQLException if an error is generated in the sql request. */
|
||||
public static List<Long> getListOfIds(final ResultSet rs, final int iii, final String separator) throws SQLException {
|
||||
final String trackString = rs.getString(iii);
|
||||
if (rs.wasNull()) {
|
||||
@ -287,14 +285,14 @@ public class DataAccess {
|
||||
if (rs.wasNull()) {
|
||||
field.set(data, null);
|
||||
} else {
|
||||
//logger.debug(" ==> {}", tmp);
|
||||
// logger.debug(" ==> {}", tmp);
|
||||
field.set(data, tmp);
|
||||
countNotNull.inc();
|
||||
}
|
||||
} else if (type == long.class) {
|
||||
final Long tmp = rs.getLong(count.value);
|
||||
if (rs.wasNull()) {
|
||||
//field.set(data, null);
|
||||
// field.set(data, null);
|
||||
} else {
|
||||
field.setLong(data, tmp);
|
||||
countNotNull.inc();
|
||||
@ -310,7 +308,7 @@ public class DataAccess {
|
||||
} else if (type == int.class) {
|
||||
final Integer tmp = rs.getInt(count.value);
|
||||
if (rs.wasNull()) {
|
||||
//field.set(data, null);
|
||||
// field.set(data, null);
|
||||
} else {
|
||||
field.setInt(data, tmp);
|
||||
countNotNull.inc();
|
||||
@ -326,7 +324,7 @@ public class DataAccess {
|
||||
} else if (type == float.class) {
|
||||
final Float tmp = rs.getFloat(count.value);
|
||||
if (rs.wasNull()) {
|
||||
//field.set(data, null);
|
||||
// field.set(data, null);
|
||||
} else {
|
||||
field.setFloat(data, tmp);
|
||||
countNotNull.inc();
|
||||
@ -342,7 +340,7 @@ public class DataAccess {
|
||||
} else if (type == double.class) {
|
||||
final Double tmp = rs.getDouble(count.value);
|
||||
if (rs.wasNull()) {
|
||||
//field.set(data, null);
|
||||
// field.set(data, null);
|
||||
} else {
|
||||
field.setDouble(data, tmp);
|
||||
countNotNull.inc();
|
||||
@ -358,7 +356,7 @@ public class DataAccess {
|
||||
} else if (type == boolean.class) {
|
||||
final Boolean tmp = rs.getBoolean(count.value);
|
||||
if (rs.wasNull()) {
|
||||
//field.set(data, null);
|
||||
// field.set(data, null);
|
||||
} else {
|
||||
field.setBoolean(data, tmp);
|
||||
countNotNull.inc();
|
||||
@ -469,7 +467,7 @@ public class DataAccess {
|
||||
// real add in the BDD:
|
||||
try {
|
||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||
//boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
|
||||
// boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
|
||||
final StringBuilder query = new StringBuilder();
|
||||
query.append("INSERT INTO `");
|
||||
query.append(tableName);
|
||||
@ -594,7 +592,7 @@ public class DataAccess {
|
||||
LOGGER.error("Can not manage the primary filed !!!");
|
||||
}
|
||||
}
|
||||
//ps.execute();
|
||||
// ps.execute();
|
||||
} catch (final SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
} finally {
|
||||
@ -627,17 +625,15 @@ public class DataAccess {
|
||||
return new QueryCondition(AnnotationTools.getFieldName(idField), "=", idKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an object with the inserted json data
|
||||
/** Update an object with the inserted json data
|
||||
*
|
||||
* @param <T> Type of the object to insert
|
||||
* @param <ID_TYPE> Master key on the object manage with @Id
|
||||
* @param clazz Class reference of the insertion model
|
||||
* @param id Key to insert data
|
||||
* @param jsonData Json data (partial) values to update
|
||||
* @param jsonData Json data (partial) values to update
|
||||
* @return the number of object updated
|
||||
* @throws Exception
|
||||
*/
|
||||
* @throws Exception */
|
||||
public static <T, ID_TYPE> int updateWithJson(final Class<T> clazz, final ID_TYPE id, final String jsonData) throws Exception {
|
||||
return updateWhereWithJson(clazz, getTableIdCondition(clazz, id), jsonData);
|
||||
}
|
||||
@ -662,28 +658,25 @@ public class DataAccess {
|
||||
return updateWhere(data, condition, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param <T>
|
||||
/** @param <T>
|
||||
* @param data
|
||||
* @param id
|
||||
* @param filterValue
|
||||
* @return the affected rows.
|
||||
* @throws Exception
|
||||
*/
|
||||
* @throws Exception */
|
||||
public static <T, ID_TYPE> int update(final T data, final ID_TYPE id, final List<String> filterValue) throws Exception {
|
||||
return updateWhere(data, getTableIdCondition(data.getClass(), id), null, filterValue);
|
||||
}
|
||||
|
||||
public static <T> int updateWhere(final T data, final QueryItem condition, final QueryOptions options, final List<String> filterValue) throws Exception {
|
||||
final Class<?> clazz = data.getClass();
|
||||
//public static NodeSmall createNode(String typeInNode, String name, String description, Long parentId) {
|
||||
// public static NodeSmall createNode(String typeInNode, String name, String description, Long parentId) {
|
||||
|
||||
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||
// real add in the BDD:
|
||||
try {
|
||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||
//boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
|
||||
// boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
|
||||
final StringBuilder query = new StringBuilder();
|
||||
query.append("UPDATE `");
|
||||
query.append(tableName);
|
||||
@ -1101,12 +1094,7 @@ public class DataAccess {
|
||||
public static int deleteSoftWhere(final Class<?> clazz, final QueryItem condition, final QueryOptions options) throws Exception {
|
||||
final String tableName = AnnotationTools.getTableName(clazz, options);
|
||||
final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
|
||||
/*
|
||||
String updateFieldName = null;
|
||||
if ("sqlite".equalsIgnoreCase(ConfigBaseVariable.getDBType())) {
|
||||
updateFieldName = AnnotationTools.getUpdatedFieldName(clazz);
|
||||
}
|
||||
*/
|
||||
/* String updateFieldName = null; if ("sqlite".equalsIgnoreCase(ConfigBaseVariable.getDBType())) { updateFieldName = AnnotationTools.getUpdatedFieldName(clazz); } */
|
||||
// find the deleted field
|
||||
|
||||
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
|
||||
@ -1116,15 +1104,8 @@ public class DataAccess {
|
||||
query.append("` SET `");
|
||||
query.append(deletedFieldName);
|
||||
query.append("`=true ");
|
||||
/*
|
||||
* The trigger work well, but the timestamp is store @ seconds...
|
||||
if (updateFieldName != null) {
|
||||
// done only in SQLite (the trigger does not work...
|
||||
query.append(", `");
|
||||
query.append(updateFieldName);
|
||||
query.append("`=DATE()");
|
||||
}
|
||||
*/
|
||||
/* The trigger work well, but the timestamp is store @ seconds... if (updateFieldName != null) { // done only in SQLite (the trigger does not work... query.append(", `");
|
||||
* query.append(updateFieldName); query.append("`=DATE()"); } */
|
||||
whereAppendQuery(query, tableName, condition, null, deletedFieldName);
|
||||
try {
|
||||
LOGGER.debug("APPLY UPDATE: {}", query.toString());
|
||||
@ -1159,12 +1140,7 @@ public class DataAccess {
|
||||
query.append("` SET `");
|
||||
query.append(deletedFieldName);
|
||||
query.append("`=false ");
|
||||
/*
|
||||
* is is needed only for SQLite ???
|
||||
query.append("`modify_date`=");
|
||||
query.append(getDBNow());
|
||||
query.append(", ");
|
||||
*/
|
||||
/* is is needed only for SQLite ??? query.append("`modify_date`="); query.append(getDBNow()); query.append(", "); */
|
||||
// need to disable the deleted false because the model must be unselected to be updated.
|
||||
options.put(QueryOptions.SQL_DELETED_DISABLE, true);
|
||||
whereAppendQuery(query, tableName, condition, options, deletedFieldName);
|
||||
|
@ -9,34 +9,26 @@ import java.util.List;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public interface DataAccessAddOn {
|
||||
/**
|
||||
* Get the Class of the declaration annotation
|
||||
* @return The annotation class
|
||||
*/
|
||||
/** Get the Class of the declaration annotation
|
||||
* @return The annotation class */
|
||||
Class<?> getAnnotationClass();
|
||||
|
||||
/**
|
||||
* Get the SQL type that is needed to declare for the specific Field Type.
|
||||
/** Get the SQL type that is needed to declare for the specific Field Type.
|
||||
* @param elem Field to declare.
|
||||
* @return SQL type to create.
|
||||
*/
|
||||
* @return SQL type to create. */
|
||||
String getSQLFieldType(Field elem) throws Exception;
|
||||
|
||||
/**
|
||||
* Check if the field is manage by the local add-on
|
||||
/** Check if the field is manage by the local add-on
|
||||
* @param elem Field to inspect.
|
||||
* @return True of the field is manage by the current Add-on.
|
||||
*/
|
||||
* @return True of the field is manage by the current Add-on. */
|
||||
boolean isCompatibleField(Field elem);
|
||||
|
||||
/**
|
||||
* Insert data in the specific field (the field must be in the current db, otherwiise it does not work at all.
|
||||
/** Insert data in the specific field (the field must be in the current db, otherwiise it does not work at all.
|
||||
* @param ps DB statement interface.
|
||||
* @param data The date to inject.
|
||||
* @param iii The index of injection
|
||||
* @return the new index of injection in case of multiple value management
|
||||
* @throws SQLException
|
||||
*/
|
||||
* @throws SQLException */
|
||||
void insertData(PreparedStatement ps, final Field field, Object data, CountInOut iii) throws Exception, SQLException, IllegalArgumentException, IllegalAccessException;
|
||||
|
||||
// Element can insert in the single request
|
||||
@ -52,8 +44,7 @@ public interface DataAccessAddOn {
|
||||
void fillFromQuerry(ResultSet rs, Field field, Object data, CountInOut count, QueryOptions options, final List<LazyGetter> lazyCall)
|
||||
throws Exception, SQLException, IllegalArgumentException, IllegalAccessException;
|
||||
|
||||
/**
|
||||
* Create associated table of the specific element.
|
||||
/** Create associated table of the specific element.
|
||||
* @param tableName
|
||||
* @param elem
|
||||
* @param mainTableBuilder
|
||||
@ -61,8 +52,7 @@ public interface DataAccessAddOn {
|
||||
* @param createIfNotExist
|
||||
* @param createDrop
|
||||
* @param fieldId
|
||||
* @throws Exception
|
||||
*/
|
||||
* @throws Exception */
|
||||
void createTables(String tableName, Field field, StringBuilder mainTableBuilder, List<String> preActionList, List<String> postActionList, boolean createIfNotExist, boolean createDrop, int fieldId)
|
||||
throws Exception;
|
||||
|
||||
|
@ -183,12 +183,7 @@ public class DataFactory {
|
||||
mainTableBuilder.append("(3)");
|
||||
} else {
|
||||
// TODO: add trigger:
|
||||
/*
|
||||
CREATE TRIGGER your_table_trig AFTER UPDATE ON your_table
|
||||
BEGIN
|
||||
update your_table SET updated_on = datetime('now') WHERE user_id = NEW.user_id;
|
||||
END;
|
||||
*/
|
||||
/* CREATE TRIGGER your_table_trig AFTER UPDATE ON your_table BEGIN update your_table SET updated_on = datetime('now') WHERE user_id = NEW.user_id; END; */
|
||||
final StringBuilder triggerBuilder = new StringBuilder();
|
||||
triggerBuilder.append("CREATE TRIGGER ");
|
||||
triggerBuilder.append(tableName);
|
||||
|
@ -112,13 +112,8 @@ public class AddOnManyToMany implements DataAccessAddOn {
|
||||
querrySelect.append(") AS ");
|
||||
querrySelect.append(name);
|
||||
querrySelect.append(" ");
|
||||
/*
|
||||
" (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" +
|
||||
" FROM cover_link_node tmp" +
|
||||
" WHERE tmp.deleted = false" +
|
||||
" AND node.id = tmp.node_id" +
|
||||
" GROUP BY tmp.node_id) AS covers" +
|
||||
*/
|
||||
/* " (SELECT GROUP_CONCAT(tmp.data_id SEPARATOR '-')" + " FROM cover_link_node tmp" + " WHERE tmp.deleted = false" +
|
||||
* " AND node.id = tmp.node_id" + " GROUP BY tmp.node_id) AS covers" + */
|
||||
elemCount.inc();
|
||||
}
|
||||
|
||||
@ -165,7 +160,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
|
||||
throw new DataAccessException("EAGER is not supported for list of element...");
|
||||
} else {
|
||||
final List<Long> idList = DataAccess.getListOfIds(rs, count.value, SEPARATOR);
|
||||
//field.set(data, idList);
|
||||
// field.set(data, idList);
|
||||
count.inc();
|
||||
if (idList != null && idList.size() > 0) {
|
||||
final String idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass));
|
||||
|
@ -132,11 +132,7 @@ public class AddOnManyToOne implements DataAccessAddOn {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
SELECT k.id, r.id
|
||||
FROM `right` k
|
||||
LEFT OUTER JOIN `rightDescription` r ON k.rightDescriptionId=r.id
|
||||
*/
|
||||
/* SELECT k.id, r.id FROM `right` k LEFT OUTER JOIN `rightDescription` r ON k.rightDescriptionId=r.id */
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -24,23 +24,19 @@ import jakarta.validation.constraints.NotNull;
|
||||
public class AddOnOneToMany implements DataAccessAddOn {
|
||||
static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class);
|
||||
|
||||
/**
|
||||
* Convert the list if external id in a string '-' separated
|
||||
/** Convert the list if external id in a string '-' separated
|
||||
* @param ids List of value (null are removed)
|
||||
* @return '-' string separated
|
||||
*/
|
||||
* @return '-' string separated */
|
||||
protected static String getStringOfIds(final List<Long> ids) {
|
||||
final List<Long> tmp = new ArrayList<>(ids);
|
||||
return tmp.stream().map(String::valueOf).collect(Collectors.joining("-"));
|
||||
}
|
||||
|
||||
/**
|
||||
* extract a list of "-" separated element from a SQL input data.
|
||||
/** extract a list of "-" separated element from a SQL input data.
|
||||
* @param rs Result Set of the BDD
|
||||
* @param iii Id in the result set
|
||||
* @return The list of Long value
|
||||
* @throws SQLException if an error is generated in the sql request.
|
||||
*/
|
||||
* @return The list of Long value
|
||||
* @throws SQLException if an error is generated in the sql request. */
|
||||
protected static List<Long> getListOfIds(final ResultSet rs, final int iii) throws SQLException {
|
||||
final String trackString = rs.getString(iii);
|
||||
if (rs.wasNull()) {
|
||||
|
@ -26,11 +26,9 @@ public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn {
|
||||
static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class);
|
||||
static final String SEPARATOR = "-";
|
||||
|
||||
/**
|
||||
* Convert the list if external id in a string '-' separated
|
||||
/** Convert the list if external id in a string '-' separated
|
||||
* @param ids List of value (null are removed)
|
||||
* @return '-' string separated
|
||||
*/
|
||||
* @return '-' string separated */
|
||||
protected static String getStringOfIds(final List<Long> ids) {
|
||||
final List<Long> tmp = new ArrayList<>(ids);
|
||||
return tmp.stream().map(String::valueOf).collect(Collectors.joining(SEPARATOR));
|
||||
|
@ -14,7 +14,7 @@ public class DBConfig {
|
||||
private final String dbName;
|
||||
private final boolean keepConnected;
|
||||
|
||||
public DBConfig(String type, String hostname, Integer port, String login, String password, String dbName, boolean keepConnected) {
|
||||
public DBConfig(final String type, final String hostname, final Integer port, final String login, final String password, final String dbName, final boolean keepConnected) {
|
||||
if (type == null) {
|
||||
this.type = "mysql";
|
||||
} else {
|
||||
@ -38,40 +38,41 @@ public class DBConfig {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DBConfig{type='" + type + '\'' + ", hostname='" + hostname + '\'' + ", port=" + port + ", login='" + login + '\'' + ", password='" + password + '\'' + ", dbName='" + dbName + "' }";
|
||||
return "DBConfig{type='" + this.type + '\'' + ", hostname='" + this.hostname + '\'' + ", port=" + this.port + ", login='" + this.login + '\'' + ", password='" + this.password + '\''
|
||||
+ ", dbName='" + this.dbName + "' }";
|
||||
}
|
||||
|
||||
public String getHostname() {
|
||||
return hostname;
|
||||
return this.hostname;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
return this.port;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
return this.login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
return this.password;
|
||||
}
|
||||
|
||||
public String getDbName() {
|
||||
return dbName;
|
||||
return this.dbName;
|
||||
}
|
||||
|
||||
public boolean getKeepConnected() {
|
||||
return keepConnected;
|
||||
return this.keepConnected;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return getUrl(false);
|
||||
}
|
||||
|
||||
public String getUrl(boolean isRoot) {
|
||||
if (type.equals("sqlite")) {
|
||||
if (isRoot == true) {
|
||||
public String getUrl(final boolean isRoot) {
|
||||
if (this.type.equals("sqlite")) {
|
||||
if (isRoot) {
|
||||
LOGGER.error("Can not manage root connection on SQLite...");
|
||||
}
|
||||
if (this.hostname.equals("memory")) {
|
||||
|
@ -76,7 +76,7 @@ public class DBEntry implements Closeable {
|
||||
|
||||
public void closeForce() throws IOException {
|
||||
try {
|
||||
//connection.commit();
|
||||
// connection.commit();
|
||||
this.connection.close();
|
||||
} catch (final SQLException ex) {
|
||||
throw new IOException("Dis-connection db fail: " + ex.getMessage());
|
||||
|
@ -6,12 +6,12 @@ public class FailException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final Response.Status status;
|
||||
|
||||
public FailException(Response.Status status, String message) {
|
||||
public FailException(final Response.Status status, final String message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public FailException(String message) {
|
||||
public FailException(final String message) {
|
||||
super(message);
|
||||
this.status = Response.Status.BAD_REQUEST;
|
||||
|
||||
|
@ -7,13 +7,13 @@ public class InputException extends Exception {
|
||||
public final String missingVariable;
|
||||
public final Response.Status status;
|
||||
|
||||
public InputException(Response.Status status, String variable, String message) {
|
||||
public InputException(final Response.Status status, final String variable, final String message) {
|
||||
super(message);
|
||||
this.missingVariable = variable;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public InputException(String variable, String message) {
|
||||
public InputException(final String variable, final String message) {
|
||||
super(message);
|
||||
this.missingVariable = variable;
|
||||
this.status = Response.Status.NOT_ACCEPTABLE;
|
||||
|
@ -5,7 +5,7 @@ import jakarta.ws.rs.core.Response;
|
||||
public class NotFoundException extends FailException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public NotFoundException(String message) {
|
||||
public NotFoundException(final String message) {
|
||||
super(Response.Status.NOT_FOUND, message);
|
||||
}
|
||||
}
|
||||
|
@ -11,7 +11,6 @@ public class RESTErrorResponseExeption extends Exception {
|
||||
public String statusMessage;
|
||||
|
||||
public RESTErrorResponseExeption() {
|
||||
super();
|
||||
this.uuid = null;
|
||||
this.time = null;
|
||||
this.error = null;
|
||||
@ -20,8 +19,7 @@ public class RESTErrorResponseExeption extends Exception {
|
||||
this.statusMessage = null;
|
||||
}
|
||||
|
||||
public RESTErrorResponseExeption(UUID uuid, String time, String error, String message, int status, String statusMessage) {
|
||||
super();
|
||||
public RESTErrorResponseExeption(final UUID uuid, final String time, final String error, final String message, final int status, final String statusMessage) {
|
||||
this.uuid = uuid;
|
||||
this.time = time;
|
||||
this.error = error;
|
||||
@ -32,7 +30,8 @@ public class RESTErrorResponseExeption extends Exception {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RESTErrorResponseExeption [uuid=" + uuid + ", time=" + time + ", error=" + error + ", message=" + message + ", status=" + status + ", statusMessage=" + statusMessage + "]";
|
||||
return "RESTErrorResponseExeption [uuid=" + this.uuid + ", time=" + this.time + ", error=" + this.error + ", message=" + this.message + ", status=" + this.status + ", statusMessage="
|
||||
+ this.statusMessage + "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -6,12 +6,12 @@ public class SystemException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final Response.Status status;
|
||||
|
||||
public SystemException(Response.Status status, String message) {
|
||||
public SystemException(final Response.Status status, final String message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public SystemException(String message) {
|
||||
public SystemException(final String message) {
|
||||
super(message);
|
||||
this.status = Response.Status.INTERNAL_SERVER_ERROR;
|
||||
}
|
||||
|
@ -5,7 +5,7 @@ import jakarta.ws.rs.core.Response;
|
||||
public class UnAuthorizedException extends FailException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public UnAuthorizedException(String message) {
|
||||
public UnAuthorizedException(final String message) {
|
||||
super(Response.Status.UNAUTHORIZED, message);
|
||||
}
|
||||
}
|
||||
|
@ -52,12 +52,8 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
|
||||
@Override
|
||||
public void filter(final ContainerRequestContext requestContext) throws IOException {
|
||||
/*
|
||||
logger.debug("-----------------------------------------------------");
|
||||
logger.debug("---- Check if have authorization ----");
|
||||
logger.debug("-----------------------------------------------------");
|
||||
logger.debug(" for:{}", requestContext.getUriInfo().getPath());
|
||||
*/
|
||||
/* logger.debug("-----------------------------------------------------"); logger.debug("---- Check if have authorization ----");
|
||||
* logger.debug("-----------------------------------------------------"); logger.debug(" for:{}", requestContext.getUriInfo().getPath()); */
|
||||
final Method method = this.resourceInfo.getResourceMethod();
|
||||
// Access denied for all
|
||||
if (method.isAnnotationPresent(DenyAll.class)) {
|
||||
@ -66,9 +62,9 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
return;
|
||||
}
|
||||
|
||||
//Access allowed for all
|
||||
// Access allowed for all
|
||||
if (method.isAnnotationPresent(PermitAll.class)) {
|
||||
//logger.debug(" ==> permit all " + requestContext.getUriInfo().getPath());
|
||||
// logger.debug(" ==> permit all " + requestContext.getUriInfo().getPath());
|
||||
// no control ...
|
||||
return;
|
||||
}
|
||||
@ -81,7 +77,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
|
||||
// Get the Authorization header from the request
|
||||
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
|
||||
//logger.debug("authorizationHeader: {}", authorizationHeader);
|
||||
// logger.debug("authorizationHeader: {}", authorizationHeader);
|
||||
if (authorizationHeader == null && method.isAnnotationPresent(PermitTokenInURI.class)) {
|
||||
final MultivaluedMap<String, String> quaryparam = requestContext.getUriInfo().getQueryParameters();
|
||||
for (final Entry<String, List<String>> item : quaryparam.entrySet()) {
|
||||
@ -106,7 +102,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
if (isJwtToken) {
|
||||
// Extract the token from the Authorization header (Remove "Yota ")
|
||||
final String token = authorizationHeader.substring(AUTHENTICATION_SCHEME.length()).trim();
|
||||
//logger.debug("token: {}", token);
|
||||
// logger.debug("token: {}", token);
|
||||
try {
|
||||
userByToken = validateJwtToken(token);
|
||||
} catch (final Exception e) {
|
||||
@ -122,7 +118,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
} else {
|
||||
// Extract the token from the Authorization header (Remove "Zota ")
|
||||
final String token = authorizationHeader.substring(AUTHENTICATION_TOKEN_SCHEME.length()).trim();
|
||||
//logger.debug("token: {}", token);
|
||||
// logger.debug("token: {}", token);
|
||||
try {
|
||||
userByToken = validateToken(token);
|
||||
} catch (final Exception e) {
|
||||
@ -151,7 +147,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
break;
|
||||
}
|
||||
}
|
||||
//Is user valid?
|
||||
// Is user valid?
|
||||
if (!haveRight) {
|
||||
this.logger.error("REJECTED not enought right : {} require: {}", requestContext.getUriInfo().getPath(), roles);
|
||||
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity("Not enought RIGHT !!!").build());
|
||||
@ -193,7 +189,7 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
|
||||
// must be override to be good implementation
|
||||
protected UserByToken validateJwtToken(final String authorization) throws Exception {
|
||||
//logger.debug(" validate token : " + authorization);
|
||||
// logger.debug(" validate token : " + authorization);
|
||||
final JWTClaimsSet ret = JWTWrapper.validateToken(authorization, "KarAuth", null);
|
||||
// check the token is valid !!! (signed and coherent issuer...
|
||||
if (ret == null) {
|
||||
@ -216,8 +212,8 @@ public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
this.logger.error("Connect with no right for this application='{}' full Right='{}'", this.applicationName, rights);
|
||||
}
|
||||
}
|
||||
//logger.debug("request user: '{}' right: '{}' row='{}'", userUID, user.right, rowRight);
|
||||
// logger.debug("request user: '{}' right: '{}' row='{}'", userUID, user.right, rowRight);
|
||||
return user;
|
||||
//return UserDB.getUserOrCreate(id, (String)ret.getClaim("login") );
|
||||
// return UserDB.getUserOrCreate(id, (String)ret.getClaim("login") );
|
||||
}
|
||||
}
|
||||
|
@ -11,12 +11,12 @@ import jakarta.ws.rs.ext.Provider;
|
||||
public class CORSFilter implements ContainerResponseFilter {
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
|
||||
//System.err.println("filter cors ..." + request.toString());
|
||||
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");
|
||||
// "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, DELETE, OPTIONS, HEAD");
|
||||
}
|
||||
|
@ -8,7 +8,7 @@ public class GenericContext implements Principal {
|
||||
|
||||
public UserByToken userByToken;
|
||||
|
||||
public GenericContext(UserByToken userByToken) {
|
||||
public GenericContext(final UserByToken userByToken) {
|
||||
this.userByToken = userByToken;
|
||||
}
|
||||
|
||||
|
@ -12,21 +12,21 @@ class MySecurityContext implements SecurityContext {
|
||||
private final GenericContext contextPrincipale;
|
||||
private final String sheme;
|
||||
|
||||
public MySecurityContext(UserByToken userByToken, String sheme) {
|
||||
public MySecurityContext(final UserByToken userByToken, final String sheme) {
|
||||
this.contextPrincipale = new GenericContext(userByToken);
|
||||
this.sheme = sheme;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Principal getUserPrincipal() {
|
||||
return contextPrincipale;
|
||||
return this.contextPrincipale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserInRole(String role) {
|
||||
if (contextPrincipale.userByToken != null) {
|
||||
Object value = this.contextPrincipale.userByToken.right.get(role);
|
||||
if (value instanceof Boolean ret) {
|
||||
public boolean isUserInRole(final String role) {
|
||||
if (this.contextPrincipale.userByToken != null) {
|
||||
final Object value = this.contextPrincipale.userByToken.right.get(role);
|
||||
if (value instanceof final Boolean ret) {
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
@ -35,12 +35,12 @@ class MySecurityContext implements SecurityContext {
|
||||
|
||||
@Override
|
||||
public boolean isSecure() {
|
||||
return sheme.equalsIgnoreCase("https");
|
||||
return this.sheme.equalsIgnoreCase("https");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthenticationScheme() {
|
||||
if (contextPrincipale.userByToken != null) {
|
||||
if (this.contextPrincipale.userByToken != null) {
|
||||
return "Zota";
|
||||
}
|
||||
return null;
|
||||
|
@ -12,7 +12,7 @@ import jakarta.ws.rs.ext.Provider;
|
||||
@PreMatching
|
||||
public class OptionFilter implements ContainerRequestFilter {
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext) throws IOException {
|
||||
public void filter(final ContainerRequestContext requestContext) throws IOException {
|
||||
if (requestContext.getMethod().contentEquals("OPTIONS")) {
|
||||
requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build());
|
||||
}
|
||||
|
@ -22,43 +22,33 @@ public class MigrationEngine {
|
||||
// initialization of the migration if the DB is not present...
|
||||
private MigrationInterface init;
|
||||
|
||||
/**
|
||||
* Migration engine constructor (empty).
|
||||
*/
|
||||
/** Migration engine constructor (empty). */
|
||||
public MigrationEngine() {
|
||||
this(new ArrayList<>(), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Migration engine constructor (specific mode).
|
||||
/** Migration engine constructor (specific mode).
|
||||
* @param datas All the migration ordered.
|
||||
* @param init Initialization migration model.
|
||||
*/
|
||||
* @param init Initialization migration model. */
|
||||
public MigrationEngine(final List<MigrationInterface> datas, final MigrationInterface init) {
|
||||
this.datas = datas;
|
||||
this.init = init;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a Migration in the list
|
||||
* @param migration Migration to add.
|
||||
*/
|
||||
/** Add a Migration in the list
|
||||
* @param migration Migration to add. */
|
||||
public void add(final MigrationInterface migration) {
|
||||
this.datas.add(migration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set first initialization class
|
||||
* @param migration migration class for first init.
|
||||
*/
|
||||
/** Set first initialization class
|
||||
* @param migration migration class for first init. */
|
||||
public void setInit(final MigrationInterface migration) {
|
||||
this.init = migration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current version/migration name
|
||||
* @return Model represent the last migration. If null then no migration has been done.
|
||||
*/
|
||||
/** Get the current version/migration name
|
||||
* @return Model represent the last migration. If null then no migration has been done. */
|
||||
public Migration getCurrentVersion() {
|
||||
if (!DataAccess.isTableExist("KAR_migration")) {
|
||||
return null;
|
||||
@ -85,12 +75,10 @@ public class MigrationEngine {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the automatic migration of the system
|
||||
/** Process the automatic migration of the system
|
||||
* @param config SQL connection for the migration
|
||||
* @throws InterruptedException user interrupt the migration
|
||||
* @throws IOException Error if access on the DB
|
||||
*/
|
||||
* @throws IOException Error if access on the DB */
|
||||
public void migrate(final DBConfig config) throws InterruptedException, IOException {
|
||||
LOGGER.info("Execute migration ... [BEGIN]");
|
||||
|
||||
@ -140,7 +128,7 @@ public class MigrationEngine {
|
||||
final Migration currentVersion = getCurrentVersion();
|
||||
List<MigrationInterface> toApply = new ArrayList<>();
|
||||
if (currentVersion == null) {
|
||||
//This is a first migration
|
||||
// This is a first migration
|
||||
LOGGER.info("First installation of the system ==> Create the DB");
|
||||
if (this.init == null) {
|
||||
toApply = this.datas;
|
||||
|
@ -4,32 +4,24 @@ import org.kar.archidata.db.DBEntry;
|
||||
import org.kar.archidata.migration.model.Migration;
|
||||
|
||||
public interface MigrationInterface {
|
||||
/**
|
||||
* Get Name of the migration
|
||||
* @return Migration name
|
||||
*/
|
||||
/** Get Name of the migration
|
||||
* @return Migration name */
|
||||
String getName();
|
||||
|
||||
/**
|
||||
* Migrate the system to a new version.
|
||||
/** Migrate the system to a new version.
|
||||
* @param entry DB interface for the migration.
|
||||
* @param log Stored data in the BDD for the migration progression.
|
||||
* @param migration Migration post data on each step...
|
||||
* @return true if migration is finished.
|
||||
*/
|
||||
* @return true if migration is finished. */
|
||||
boolean applyMigration(DBEntry entry, StringBuilder log, Migration model);
|
||||
|
||||
/**
|
||||
* Remove a migration the system to the previous version.
|
||||
/** Remove a migration the system to the previous version.
|
||||
* @param entry DB interface for the migration.
|
||||
* @param log Stored data in the BDD for the migration progression.
|
||||
* @return true if migration is finished.
|
||||
*/
|
||||
* @return true if migration is finished. */
|
||||
boolean revertMigration(DBEntry entry, StringBuilder log);
|
||||
|
||||
/**
|
||||
* Get the number of step in the migration process.
|
||||
* @return count of SQL access.
|
||||
*/
|
||||
/** Get the number of step in the migration process.
|
||||
* @return count of SQL access. */
|
||||
int getNumberOfStep();
|
||||
}
|
||||
|
@ -13,9 +13,7 @@ import org.kar.archidata.util.ConfigBaseVariable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
record Action(
|
||||
String action,
|
||||
List<String> filterDB) {
|
||||
record Action(String action, List<String> filterDB) {
|
||||
public Action(final String action) {
|
||||
this(action, List.of());
|
||||
}
|
||||
|
@ -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) {
|
||||
}
|
||||
|
@ -12,7 +12,7 @@ public class Token {
|
||||
|
||||
public Token() {}
|
||||
|
||||
public Token(long id, long userId, String token, String createTime, String endValidityTime) {
|
||||
public Token(final long id, final long userId, final String token, final String createTime, final String endValidityTime) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.token = token;
|
||||
@ -20,7 +20,7 @@ public class Token {
|
||||
this.endValidityTime = endValidityTime;
|
||||
}
|
||||
|
||||
public Token(ResultSet rs) {
|
||||
public Token(final ResultSet rs) {
|
||||
int iii = 1;
|
||||
try {
|
||||
this.id = rs.getLong(iii++);
|
||||
@ -28,13 +28,13 @@ public class Token {
|
||||
this.token = rs.getString(iii++);
|
||||
this.createTime = rs.getString(iii++);
|
||||
this.endValidityTime = rs.getString(iii++);
|
||||
} catch (SQLException ex) {
|
||||
} catch (final SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Token{" + "id=" + id + ", userId=" + userId + ", token='" + token + '\'' + ", createTime=" + createTime + ", endValidityTime=" + endValidityTime + '}';
|
||||
return "Token{" + "id=" + this.id + ", userId=" + this.userId + ", token='" + this.token + '\'' + ", createTime=" + this.createTime + ", endValidityTime=" + this.endValidityTime + '}';
|
||||
}
|
||||
}
|
||||
|
@ -50,7 +50,7 @@ public class User extends GenericDataSoftDelete {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User [login=" + login + ", last=" + lastConnection + ", admin=" + admin + "]";
|
||||
return "User [login=" + this.login + ", last=" + this.lastConnection + ", admin=" + this.admin + "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -15,37 +15,37 @@ public class UserByToken {
|
||||
// Right map
|
||||
public Map<String, Object> right = new HashMap<>();
|
||||
|
||||
public boolean hasRight(String key, Object value) {
|
||||
public boolean hasRight(final String key, final Object value) {
|
||||
if (!this.right.containsKey(key)) {
|
||||
return false;
|
||||
}
|
||||
Object data = this.right.get(key);
|
||||
if (data instanceof Boolean elem) {
|
||||
if (value instanceof Boolean castVal) {
|
||||
final Object data = this.right.get(key);
|
||||
if (data instanceof final Boolean elem) {
|
||||
if (value instanceof final Boolean castVal) {
|
||||
if (elem == castVal) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (data instanceof String elem) {
|
||||
if (value instanceof String castVal) {
|
||||
if (data instanceof final String elem) {
|
||||
if (value instanceof final String castVal) {
|
||||
if (elem.equals(castVal)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (data instanceof Long elem) {
|
||||
if (value instanceof Long castVal) {
|
||||
if (data instanceof final Long elem) {
|
||||
if (value instanceof final Long castVal) {
|
||||
if (elem == castVal) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (data instanceof Double elem) {
|
||||
if (value instanceof Double castVal) {
|
||||
if (data instanceof final Double elem) {
|
||||
if (value instanceof final Double castVal) {
|
||||
if (elem == castVal) {
|
||||
return true;
|
||||
}
|
||||
|
@ -14,9 +14,9 @@ import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.kar.archidata.dataAccess.DataAccess;
|
||||
import org.kar.archidata.dataAccess.QueryAnd;
|
||||
import org.kar.archidata.dataAccess.QueryCondition;
|
||||
import org.kar.archidata.dataAccess.DataAccess;
|
||||
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
|
||||
import org.kar.archidata.model.Data;
|
||||
import org.slf4j.Logger;
|
||||
@ -29,12 +29,10 @@ public class DataTools {
|
||||
|
||||
public final static int CHUNK_SIZE = 1024 * 1024; // 1MB chunks
|
||||
public final static int CHUNK_SIZE_IN = 50 * 1024 * 1024; // 1MB chunks
|
||||
/**
|
||||
* Upload some data
|
||||
*/
|
||||
/** Upload some data */
|
||||
private static long tmpFolderId = 1;
|
||||
|
||||
public static void createFolder(String path) throws IOException {
|
||||
public static void createFolder(final String path) throws IOException {
|
||||
if (!Files.exists(java.nio.file.Path.of(path))) {
|
||||
LOGGER.info("Create folder: " + path);
|
||||
Files.createDirectories(java.nio.file.Path.of(path));
|
||||
@ -45,85 +43,71 @@ public class DataTools {
|
||||
return tmpFolderId++;
|
||||
}
|
||||
|
||||
public static String getTmpFileInData(long tmpFolderId) {
|
||||
String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId;
|
||||
public static String getTmpFileInData(final long tmpFolderId) {
|
||||
final String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId;
|
||||
try {
|
||||
createFolder(ConfigBaseVariable.getTmpDataFolder() + File.separator);
|
||||
} catch (IOException e) {
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public static String getTmpFolder() {
|
||||
String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
||||
final String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
||||
try {
|
||||
createFolder(ConfigBaseVariable.getTmpDataFolder() + File.separator);
|
||||
} catch (IOException e) {
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public static String getFileData(long tmpFolderId) {
|
||||
String filePath = ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + "data";
|
||||
public static String getFileData(final long tmpFolderId) {
|
||||
final String filePath = ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + "data";
|
||||
try {
|
||||
createFolder(ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator);
|
||||
} catch (IOException e) {
|
||||
} catch (final IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public static Data getWithSha512(String sha512) {
|
||||
public static Data getWithSha512(final String sha512) {
|
||||
try {
|
||||
return DataAccess.getWhere(Data.class, new QueryCondition("sha512", "=", sha512));
|
||||
} catch (Exception e) {
|
||||
} catch (final Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Data getWithId(long id) {
|
||||
public static Data getWithId(final long id) {
|
||||
try {
|
||||
return DataAccess.getWhere(Data.class, new QueryAnd(List.of(new QueryCondition("deleted", "=", false), new QueryCondition("id", "=", id))));
|
||||
} catch (Exception e) {
|
||||
} catch (final Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Data createNewData(long tmpUID, String originalFileName, String sha512) throws IOException, SQLException {
|
||||
public static Data createNewData(final long tmpUID, final String originalFileName, final String sha512) throws IOException, SQLException {
|
||||
// determine mime type:
|
||||
String mimeType = "";
|
||||
String extension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1);
|
||||
switch (extension.toLowerCase()) {
|
||||
case "jpg":
|
||||
case "jpeg":
|
||||
mimeType = "image/jpeg";
|
||||
break;
|
||||
case "png":
|
||||
mimeType = "image/png";
|
||||
break;
|
||||
case "webp":
|
||||
mimeType = "image/webp";
|
||||
break;
|
||||
case "mka":
|
||||
mimeType = "audio/x-matroska";
|
||||
break;
|
||||
case "mkv":
|
||||
mimeType = "video/x-matroska";
|
||||
break;
|
||||
case "webm":
|
||||
mimeType = "video/webm";
|
||||
break;
|
||||
default:
|
||||
throw new IOException("Can not find the mime type of data input: '" + extension + "'");
|
||||
}
|
||||
String tmpPath = getTmpFileInData(tmpUID);
|
||||
long fileSize = Files.size(Paths.get(tmpPath));
|
||||
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 + "'");
|
||||
};
|
||||
final String tmpPath = getTmpFileInData(tmpUID);
|
||||
final long fileSize = Files.size(Paths.get(tmpPath));
|
||||
Data out = new Data();
|
||||
;
|
||||
try {
|
||||
@ -131,16 +115,16 @@ public class DataTools {
|
||||
out.mimeType = mimeType;
|
||||
out.size = fileSize;
|
||||
out = DataAccess.insert(out);
|
||||
} catch (SQLException ex) {
|
||||
} catch (final SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
} catch (final Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
String mediaPath = getFileData(out.id);
|
||||
final String mediaPath = getFileData(out.id);
|
||||
LOGGER.info("src = {}", tmpPath);
|
||||
LOGGER.info("dst = {}", mediaPath);
|
||||
Files.move(Paths.get(tmpPath), Paths.get(mediaPath), StandardCopyOption.ATOMIC_MOVE);
|
||||
@ -150,25 +134,25 @@ public class DataTools {
|
||||
return out;
|
||||
}
|
||||
|
||||
public static void undelete(Long id) {
|
||||
public static void undelete(final Long id) {
|
||||
try {
|
||||
DataAccess.unsetDelete(Data.class, id);
|
||||
} catch (Exception e) {
|
||||
} catch (final Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static String saveTemporaryFile(InputStream uploadedInputStream, long idData) {
|
||||
public static String saveTemporaryFile(final InputStream uploadedInputStream, final long idData) {
|
||||
return saveFile(uploadedInputStream, getTmpFileInData(idData));
|
||||
}
|
||||
|
||||
public static void removeTemporaryFile(long idData) {
|
||||
String filepath = getTmpFileInData(idData);
|
||||
public static void removeTemporaryFile(final long idData) {
|
||||
final String filepath = getTmpFileInData(idData);
|
||||
if (Files.exists(Paths.get(filepath))) {
|
||||
try {
|
||||
Files.delete(Paths.get(filepath));
|
||||
} catch (IOException e) {
|
||||
} catch (final IOException e) {
|
||||
LOGGER.info("can not delete temporary file : {}", Paths.get(filepath));
|
||||
e.printStackTrace();
|
||||
}
|
||||
@ -176,17 +160,17 @@ public class DataTools {
|
||||
}
|
||||
|
||||
// save uploaded file to a defined location on the server
|
||||
public static String saveFile(InputStream uploadedInputStream, String serverLocation) {
|
||||
public static String saveFile(final InputStream uploadedInputStream, final String serverLocation) {
|
||||
String out = "";
|
||||
try {
|
||||
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
|
||||
int read = 0;
|
||||
byte[] bytes = new byte[CHUNK_SIZE_IN];
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-512");
|
||||
final byte[] bytes = new byte[CHUNK_SIZE_IN];
|
||||
final MessageDigest md = MessageDigest.getInstance("SHA-512");
|
||||
|
||||
outpuStream = new FileOutputStream(new File(serverLocation));
|
||||
while ((read = uploadedInputStream.read(bytes)) != -1) {
|
||||
//logger.debug("write {}", read);
|
||||
// logger.debug("write {}", read);
|
||||
md.update(bytes, 0, read);
|
||||
outpuStream.write(bytes, 0, read);
|
||||
}
|
||||
@ -194,14 +178,14 @@ public class DataTools {
|
||||
outpuStream.flush();
|
||||
outpuStream.close();
|
||||
// create the end of sha512
|
||||
byte[] sha512Digest = md.digest();
|
||||
final byte[] sha512Digest = md.digest();
|
||||
// convert in hexadecimal
|
||||
out = bytesToHex(sha512Digest);
|
||||
uploadedInputStream.close();
|
||||
} catch (IOException ex) {
|
||||
} catch (final IOException ex) {
|
||||
LOGGER.error("Can not write in temporary file ... ");
|
||||
ex.printStackTrace();
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
} catch (final NoSuchAlgorithmException ex) {
|
||||
LOGGER.error("Can not find sha512 algorithms");
|
||||
ex.printStackTrace();
|
||||
}
|
||||
@ -209,26 +193,21 @@ public class DataTools {
|
||||
}
|
||||
|
||||
// curl http://localhost:9993/api/users/3
|
||||
//@Secured
|
||||
/*
|
||||
@GET
|
||||
@Path("{id}")
|
||||
//@RolesAllowed("GUEST")
|
||||
@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
public Response retriveData(@HeaderParam("Range") String range, @PathParam("id") Long id) throws Exception {
|
||||
return retriveDataFull(range, id, "no-name");
|
||||
}
|
||||
*/
|
||||
// @Secured
|
||||
/* @GET
|
||||
* @Path("{id}") //@RolesAllowed("GUEST")
|
||||
* @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response retriveData(@HeaderParam("Range") String range, @PathParam("id") Long id) throws Exception { return retriveDataFull(range, id,
|
||||
* "no-name"); } */
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
public static String bytesToHex(final byte[] bytes) {
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
for (final byte b : bytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String multipartCorrection(String data) {
|
||||
public static String multipartCorrection(final String data) {
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
@ -241,39 +220,39 @@ public class DataTools {
|
||||
return data;
|
||||
}
|
||||
|
||||
public static <T> Response uploadCover(Class<T> clazz, Long id, String fileName, InputStream fileInputStream, FormDataContentDisposition fileMetaData) {
|
||||
public static <T> Response uploadCover(final Class<T> clazz, final Long id, String fileName, final InputStream fileInputStream, final FormDataContentDisposition fileMetaData) {
|
||||
try {
|
||||
// correct input string stream :
|
||||
fileName = multipartCorrection(fileName);
|
||||
|
||||
//public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||
// public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||
LOGGER.info("Upload media file: {}", fileMetaData);
|
||||
LOGGER.info(" - id: {}", id);
|
||||
LOGGER.info(" - file_name: ", fileName);
|
||||
LOGGER.info(" - fileInputStream: {}", fileInputStream);
|
||||
LOGGER.info(" - fileMetaData: {}", fileMetaData);
|
||||
T media = DataAccess.get(clazz, id);
|
||||
final T media = DataAccess.get(clazz, id);
|
||||
if (media == null) {
|
||||
return Response.notModified("Media Id does not exist or removed...").build();
|
||||
}
|
||||
|
||||
long tmpUID = getTmpDataId();
|
||||
String sha512 = saveTemporaryFile(fileInputStream, tmpUID);
|
||||
final long tmpUID = getTmpDataId();
|
||||
final String sha512 = saveTemporaryFile(fileInputStream, tmpUID);
|
||||
Data data = getWithSha512(sha512);
|
||||
if (data == null) {
|
||||
LOGGER.info("Need to add the data in the BDD ... ");
|
||||
try {
|
||||
data = createNewData(tmpUID, fileName, sha512);
|
||||
} catch (IOException ex) {
|
||||
} catch (final IOException ex) {
|
||||
removeTemporaryFile(tmpUID);
|
||||
ex.printStackTrace();
|
||||
return Response.notModified("can not create input media").build();
|
||||
} catch (SQLException ex) {
|
||||
} catch (final SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
removeTemporaryFile(tmpUID);
|
||||
return Response.notModified("Error in SQL insertion ...").build();
|
||||
}
|
||||
} else if (data.deleted == true) {
|
||||
} else if (data.deleted) {
|
||||
LOGGER.error("Data already exist but deleted");
|
||||
undelete(data.id);
|
||||
data.deleted = false;
|
||||
@ -284,7 +263,7 @@ public class DataTools {
|
||||
LOGGER.info("Find typeNode");
|
||||
AddOnManyToMany.addLink(clazz, id, "cover", data.id);
|
||||
return Response.ok(DataAccess.get(clazz, id)).build();
|
||||
} catch (Exception ex) {
|
||||
} catch (final Exception ex) {
|
||||
System.out.println("Cat ann unexpected error ... ");
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
@ -34,22 +34,15 @@ import com.nimbusds.jwt.SignedJWT;
|
||||
class TestSigner implements JWSSigner {
|
||||
public static String test_signature = "TEST_SIGNATURE_FOR_LOCAL_TEST_AND_TEST_E2E";
|
||||
|
||||
/**
|
||||
* Signs the specified {@link JWSObject#getSigningInput input} of a
|
||||
* {@link JWSObject JWS object}.
|
||||
/** Signs the specified {@link JWSObject#getSigningInput input} of a {@link JWSObject JWS object}.
|
||||
*
|
||||
* @param header The JSON Web Signature (JWS) header. Must
|
||||
* specify a supported JWS algorithm and must not
|
||||
* be {@code null}.
|
||||
* @param header The JSON Web Signature (JWS) header. Must specify a supported JWS algorithm and must not be {@code null}.
|
||||
* @param signingInput The input to sign. Must not be {@code null}.
|
||||
*
|
||||
* @return The resulting signature part (third part) of the JWS object.
|
||||
*
|
||||
* @throws JOSEException If the JWS algorithm is not supported, if a
|
||||
* critical header parameter is not supported or
|
||||
* marked for deferral to the application, or if
|
||||
* signing failed for some other internal reason.
|
||||
*/
|
||||
* @throws JOSEException If the JWS algorithm is not supported, if a critical header parameter is not supported or marked for deferral to the application, or if signing failed for some other
|
||||
* internal reason. */
|
||||
@Override
|
||||
public Base64URL sign(final JWSHeader header, final byte[] signingInput) throws JOSEException {
|
||||
return new Base64URL(test_signature);
|
||||
@ -87,7 +80,7 @@ public class JWTWrapper {
|
||||
public static void initLocalTokenRemote(final String ssoUri, final String application) throws IOException, ParseException {
|
||||
// check Token:
|
||||
final URL obj = new URL(ssoUri + "public_key");
|
||||
//LOGGER.debug("Request token from: {}", obj);
|
||||
// LOGGER.debug("Request token from: {}", obj);
|
||||
final HttpURLConnection con = (HttpURLConnection) obj.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
con.setRequestProperty("User-Agent", application);
|
||||
@ -100,7 +93,7 @@ public class JWTWrapper {
|
||||
}
|
||||
final int responseCode = con.getResponseCode();
|
||||
|
||||
//LOGGER.debug("GET Response Code :: {}", responseCode);
|
||||
// LOGGER.debug("GET Response Code :: {}", responseCode);
|
||||
if (responseCode == HttpURLConnection.HTTP_OK) { // success
|
||||
final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
||||
|
||||
@ -111,7 +104,7 @@ public class JWTWrapper {
|
||||
}
|
||||
in.close();
|
||||
// print result
|
||||
//LOGGER.debug(response.toString());
|
||||
// LOGGER.debug(response.toString());
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final PublicKey values = mapper.readValue(response.toString(), PublicKey.class);
|
||||
rsaPublicJWK = RSAKey.parse(values.key);
|
||||
@ -169,25 +162,19 @@ public class JWTWrapper {
|
||||
return rsaPublicJWK.toRSAPublicKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a token with the provided elements
|
||||
/** Create a token with the provided elements
|
||||
* @param userID UniqueId of the USER (global unique ID)
|
||||
* @param userLogin Login of the user (never change)
|
||||
* @param isuer The one who provide the Token
|
||||
* @param timeOutInMunites Expiration of the token.
|
||||
* @return the encoded token
|
||||
*/
|
||||
* @return the encoded token */
|
||||
public static String generateJWToken(final long userID, final String userLogin, final String isuer, final String application, final Map<String, Object> rights, final int timeOutInMunites) {
|
||||
if (rsaJWK == null) {
|
||||
LOGGER.warn("JWT private key is not present !!!");
|
||||
return null;
|
||||
}
|
||||
/*
|
||||
LOGGER.debug(" ===> expire in : " + timeOutInMunites);
|
||||
LOGGER.debug(" ===>" + new Date().getTime());
|
||||
LOGGER.debug(" ===>" + new Date(new Date().getTime()));
|
||||
LOGGER.debug(" ===>" + new Date(new Date().getTime() - 60 * timeOutInMunites * 1000));
|
||||
*/
|
||||
/* LOGGER.debug(" ===> expire in : " + timeOutInMunites); LOGGER.debug(" ===>" + new Date().getTime()); LOGGER.debug(" ===>" + new Date(new Date().getTime())); LOGGER.debug(" ===>" + new
|
||||
* Date(new Date().getTime() - 60 * timeOutInMunites * 1000)); */
|
||||
try {
|
||||
// Create RSA-signer with the private key
|
||||
final JWSSigner signer = new RSASSASigner(rsaJWK);
|
||||
@ -206,7 +193,7 @@ 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);
|
||||
@ -253,8 +240,8 @@ public class JWTWrapper {
|
||||
// TODO: verify the token is used for the correct application.
|
||||
}
|
||||
// the element must be validated outside ...
|
||||
//LOGGER.debug("JWT token is verified 'alice' =?= '" + signedJWT.getJWTClaimsSet().getSubject() + "'");
|
||||
//LOGGER.debug("JWT token isuer 'https://c2id.com' =?= '" + signedJWT.getJWTClaimsSet().getIssuer() + "'");
|
||||
// LOGGER.debug("JWT token is verified 'alice' =?= '" + signedJWT.getJWTClaimsSet().getSubject() + "'");
|
||||
// LOGGER.debug("JWT token isuer 'https://c2id.com' =?= '" + signedJWT.getJWTClaimsSet().getIssuer() + "'");
|
||||
return signedJWT.getJWTClaimsSet();
|
||||
} catch (final JOSEException ex) {
|
||||
ex.printStackTrace();
|
||||
@ -283,7 +270,7 @@ 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());
|
||||
|
@ -3,7 +3,7 @@ package org.kar.archidata.util;
|
||||
public class PublicKey {
|
||||
public String key;
|
||||
|
||||
public PublicKey(String key) {
|
||||
public PublicKey(final String key) {
|
||||
this.key = key;
|
||||
}
|
||||
}
|
@ -24,161 +24,161 @@ public class RESTApi {
|
||||
final String baseUrl;
|
||||
private String token = null;
|
||||
|
||||
public RESTApi(String baseUrl) {
|
||||
public RESTApi(final String baseUrl) {
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
public void setToken(final String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public <T> List<T> gets(Class<T> clazz, String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
public <T> List<T> gets(final Class<T> clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final HttpClient client = HttpClient.newHttpClient();
|
||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||
if (token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
||||
if (this.token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||
}
|
||||
HttpRequest request = requestBuilding.GET().build();
|
||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final HttpRequest request = requestBuilding.GET().build();
|
||||
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
throw out;
|
||||
}
|
||||
List<T> out = mapper.readValue(httpResponse.body(), new TypeReference<List<T>>() {});
|
||||
final List<T> out = mapper.readValue(httpResponse.body(), new TypeReference<List<T>>() {});
|
||||
return out;
|
||||
}
|
||||
|
||||
public <T> T get(Class<T> clazz, String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
public <T> T get(final Class<T> clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final HttpClient client = HttpClient.newHttpClient();
|
||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||
if (token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
||||
if (this.token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||
}
|
||||
HttpRequest request = requestBuilding.GET().build();
|
||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final HttpRequest request = requestBuilding.GET().build();
|
||||
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||
//LOGGER.error("catch error from REST API: {}", httpResponse.body());
|
||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
// LOGGER.error("catch error from REST API: {}", httpResponse.body());
|
||||
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
throw new RESTErrorResponseExeption(out.uuid, out.time, out.error, out.message, out.status, out.statusMessage);
|
||||
}
|
||||
//LOGGER.error("status code: {}", httpResponse.statusCode());
|
||||
//LOGGER.error("data: {}", httpResponse.body());
|
||||
// LOGGER.error("status code: {}", httpResponse.statusCode());
|
||||
// LOGGER.error("data: {}", httpResponse.body());
|
||||
if (clazz.equals(String.class)) {
|
||||
return (T) httpResponse.body();
|
||||
}
|
||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
return out;
|
||||
}
|
||||
|
||||
public <T, U> T post(Class<T> clazz, String urlOffset, U data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
String body = mapper.writeValueAsString(data);
|
||||
public <T, U> T post(final Class<T> clazz, final String urlOffset, final U data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final HttpClient client = HttpClient.newHttpClient();
|
||||
final String body = mapper.writeValueAsString(data);
|
||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||
if (token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
||||
if (this.token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||
}
|
||||
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
||||
HttpRequest request = requestBuilding.POST(BodyPublishers.ofString(body)).build();
|
||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final HttpRequest request = requestBuilding.POST(BodyPublishers.ofString(body)).build();
|
||||
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||
LOGGER.error("status code: {}", httpResponse.statusCode());
|
||||
LOGGER.error("data: {}", httpResponse.body());
|
||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
throw out;
|
||||
}
|
||||
if (clazz.equals(String.class)) {
|
||||
return (T) httpResponse.body();
|
||||
}
|
||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
return out;
|
||||
}
|
||||
|
||||
public <T> T postMap(Class<T> clazz, String urlOffset, Map<String, Object> data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
String body = mapper.writeValueAsString(data);
|
||||
public <T> T postMap(final Class<T> clazz, final String urlOffset, final Map<String, Object> data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final HttpClient client = HttpClient.newHttpClient();
|
||||
final String body = mapper.writeValueAsString(data);
|
||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||
if (token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
||||
if (this.token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||
}
|
||||
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
||||
HttpRequest request = requestBuilding.POST(BodyPublishers.ofString(body)).build();
|
||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final HttpRequest request = requestBuilding.POST(BodyPublishers.ofString(body)).build();
|
||||
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
throw out;
|
||||
}
|
||||
if (clazz.equals(String.class)) {
|
||||
return (T) httpResponse.body();
|
||||
}
|
||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
return out;
|
||||
}
|
||||
|
||||
public <T, U> T put(Class<T> clazz, String urlOffset, U data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
String body = mapper.writeValueAsString(data);
|
||||
public <T, U> T put(final Class<T> clazz, final String urlOffset, final U data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final HttpClient client = HttpClient.newHttpClient();
|
||||
final String body = mapper.writeValueAsString(data);
|
||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||
if (token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
||||
if (this.token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||
}
|
||||
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
||||
HttpRequest request = requestBuilding.PUT(BodyPublishers.ofString(body)).build();
|
||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final HttpRequest request = requestBuilding.PUT(BodyPublishers.ofString(body)).build();
|
||||
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
throw out;
|
||||
}
|
||||
if (clazz.equals(String.class)) {
|
||||
return (T) httpResponse.body();
|
||||
}
|
||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
return out;
|
||||
}
|
||||
|
||||
public <T> T putMap(Class<T> clazz, String urlOffset, Map<String, Object> data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
String body = mapper.writeValueAsString(data);
|
||||
public <T> T putMap(final Class<T> clazz, final String urlOffset, final Map<String, Object> data) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final HttpClient client = HttpClient.newHttpClient();
|
||||
final String body = mapper.writeValueAsString(data);
|
||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||
if (token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
||||
if (this.token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||
}
|
||||
requestBuilding = requestBuilding.header("Content-Type", "application/json");
|
||||
HttpRequest request = requestBuilding.PUT(BodyPublishers.ofString(body)).build();
|
||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final HttpRequest request = requestBuilding.PUT(BodyPublishers.ofString(body)).build();
|
||||
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
throw out;
|
||||
}
|
||||
if (clazz.equals(String.class)) {
|
||||
return (T) httpResponse.body();
|
||||
}
|
||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
return out;
|
||||
}
|
||||
|
||||
public <T, U> T delete(Class<T> clazz, String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
public <T, U> T delete(final Class<T> clazz, final String urlOffset) throws RESTErrorResponseExeption, IOException, InterruptedException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final HttpClient client = HttpClient.newHttpClient();
|
||||
Builder requestBuilding = HttpRequest.newBuilder().uri(URI.create(this.baseUrl + urlOffset));
|
||||
if (token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + token);
|
||||
if (this.token != null) {
|
||||
requestBuilding = requestBuilding.header(HttpHeaders.AUTHORIZATION, "Yota " + this.token);
|
||||
}
|
||||
HttpRequest request = requestBuilding.DELETE().build();
|
||||
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final HttpRequest request = requestBuilding.DELETE().build();
|
||||
final HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (httpResponse.statusCode() < 200 || httpResponse.statusCode() >= 300) {
|
||||
RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
final RESTErrorResponseExeption out = mapper.readValue(httpResponse.body(), RESTErrorResponseExeption.class);
|
||||
throw out;
|
||||
}
|
||||
if (clazz.equals(String.class)) {
|
||||
return (T) httpResponse.body();
|
||||
}
|
||||
T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
final T out = mapper.readValue(httpResponse.body(), clazz);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
@ -175,11 +175,6 @@ public class TestManyToMany {
|
||||
DataAccess.delete(TypeManyToManyRoot.class, insertedData.id);
|
||||
}
|
||||
|
||||
/*
|
||||
API TODO:
|
||||
- Replace list (permet de les ordonnées)
|
||||
- remove all links
|
||||
- delete en cascade .... (compliqué...)
|
||||
*/
|
||||
/* API TODO: - Replace list (permet de les ordonnées) - remove all links - delete en cascade .... (compliqué...) */
|
||||
|
||||
}
|
@ -265,7 +265,7 @@ public class TestTypes {
|
||||
LOGGER.debug("Retreive Timestamp = {}", retrieve.timeStampData);
|
||||
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, retrieve.timeStampData);
|
||||
Assertions.assertEquals(insertedData.timeStampData.toInstant().toEpochMilli(), retrieve.timeStampData.toInstant().toEpochMilli());
|
||||
|
||||
DataAccess.delete(TypesTable.class, insertedData.id);
|
||||
|
9
tools/configure_precommit.bash
Executable file
9
tools/configure_precommit.bash
Executable file
@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
set +e
|
||||
ln -sf ../../tools/pre-commit-hook .git/hooks/pre-commit
|
||||
if [[ 0 != $? ]]; then
|
||||
echo "pre-commit hooks: [ERROR] Cannot configure"
|
||||
exit 1
|
||||
else
|
||||
echo "pre-commit hooks: [OK]"
|
||||
fi
|
27
tools/pre-commit
Executable file
27
tools/pre-commit
Executable file
@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# get bash colors and styles here:
|
||||
# http://misc.flogisoft.com/bash/tip_colors_and_formatting
|
||||
C_RESET='\e[0m'
|
||||
C_RED='\e[31m'
|
||||
C_GREEN='\e[32m'
|
||||
C_YELLOW='\e[33m'
|
||||
|
||||
function __run() #(step, name, cmd)
|
||||
{
|
||||
local color output exitcode
|
||||
|
||||
printf "${C_YELLOW}[%s]${C_RESET} %-20s" "$1" "$2"
|
||||
output=$(eval "$3" 2>&1)
|
||||
exitcode=$?
|
||||
|
||||
if [[ 0 == $exitcode ]]; then
|
||||
echo -e "${C_GREEN}OK!${C_RESET}"
|
||||
else
|
||||
echo -e "${C_RED}NOK! (${exitcode})${C_RESET}\n\n$output"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
__run "1/1" "Check JAVA code format" "mvn formatter:verify"
|
||||
|
Loading…
Reference in New Issue
Block a user