[DEV] update with archidata refacto

This commit is contained in:
Edouard DUPIN 2023-11-11 10:49:15 +01:00
parent f92b582983
commit c928624734
29 changed files with 613 additions and 440 deletions

View File

@ -27,7 +27,6 @@
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes> <attributes>
<attribute name="module" value="true"/>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>

View File

@ -10,16 +10,6 @@
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand>
<name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
<dictionary>
<key>LaunchConfigHandle</key>
<value>&lt;project&gt;/.externalToolBuilders/org.eclipse.jdt.core.javabuilder.launch</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name> <name>org.eclipse.m2e.core.maven2Builder</name>
<arguments> <arguments>

View File

@ -11,7 +11,7 @@ mvn package
// download all dependency in out/maven/dependency // download all dependency in out/maven/dependency
mvn dependency:copy-dependencies mvn dependency:copy-dependencies
java -cp out/maven/scenarium-karso-0.1.0.jar org.kar.oauth.WebLauncher java -cp out/maven/kar-karso-0.1.0.jar org.kar.karso.WebLauncher
// create a single package jar // create a single package jar

View File

@ -121,21 +121,13 @@
<goals> <goals>
<goal>prepare-agent</goal> <goal>prepare-agent</goal>
</goals> </goals>
<!--<configuration>
<destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
<propertyName>surefireArgLine</propertyName>
</configuration>-->
</execution> </execution>
<execution> <execution>
<id>report</id> <id>report</id>
<phase>test</phase> <phase>test</phase>
<goals> <goals>
<goal>report</goal> <goal>report</goal>
</goals><!-- </goals>
<configuration>
<dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
</configuration>-->
</execution> </execution>
<execution> <execution>
<id>jacoco-check</id> <id>jacoco-check</id>
@ -186,8 +178,49 @@
<mainClass>org.kar.karso.WebLauncher</mainClass> <mainClass>org.kar.karso.WebLauncher</mainClass>
</configuration> </configuration>
</plugin> </plugin>
<!-- Check the style of the code -->
<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<configLocation>CheckStyle.xml</configLocation>
<consoleOutput>true</consoleOutput>
<failOnViolation>true</failOnViolation>
<failsOnError>true</failsOnError>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
</configuration>
</plugin>
<plugin>
<groupId>net.revelc.code.formatter</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<version>2.12.2</version>
<configuration>
<encoding>UTF-8</encoding>
<lineEnding>LF</lineEnding>
<configFile>Formatter.xml</configFile>
<directories>
<directory>src/</directory>
<directory>test/src</directory>
</directories>
<includes>
<include>**/*.java</include>
</includes>
<excludes>
<exclude>module-info.java</exclude>
</excludes>
</configuration>
<executions>
<execution>
<goals>
<goal>validate</goal>
</goals>
</execution>
</executions>
</plugin>
-->
</plugins> </plugins>
</build> </build>
<!-- Generate Java-docs As Part Of Project Reports --> <!-- Generate Java-docs As Part Of Project Reports -->
<reporting> <reporting>

View File

@ -19,7 +19,7 @@ import org.kar.archidata.catcher.SystemExceptionCatcher;
import org.kar.archidata.filter.CORSFilter; import org.kar.archidata.filter.CORSFilter;
import org.kar.archidata.filter.OptionFilter; import org.kar.archidata.filter.OptionFilter;
import org.kar.archidata.migration.MigrationEngine; import org.kar.archidata.migration.MigrationEngine;
import org.kar.archidata.migration.MigrationModel; import org.kar.archidata.migration.model.Migration;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.util.ConfigBaseVariable;
import org.kar.archidata.util.JWTWrapper; import org.kar.archidata.util.JWTWrapper;
import org.kar.karso.api.ApplicationResource; import org.kar.karso.api.ApplicationResource;
@ -54,13 +54,13 @@ public class WebLauncher {
public WebLauncher() { public WebLauncher() {
ConfigBaseVariable.bdDatabase = "karso"; ConfigBaseVariable.bdDatabase = "karso";
backupEngine.addClass(MigrationModel.class); this.backupEngine.addClass(Migration.class);
backupEngine.addClass(Settings.class); this.backupEngine.addClass(Settings.class);
backupEngine.addClass(UserAuth.class); this.backupEngine.addClass(UserAuth.class);
backupEngine.addClass(Application.class); this.backupEngine.addClass(Application.class);
backupEngine.addClass(ApplicationToken.class); this.backupEngine.addClass(ApplicationToken.class);
backupEngine.addClass(RightDescription.class); this.backupEngine.addClass(RightDescription.class);
backupEngine.addClass(Right.class); this.backupEngine.addClass(Right.class);
} }
@ -132,11 +132,12 @@ public class WebLauncher {
//rc.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName()); //rc.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName());
this.server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), this.rc); this.server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), this.rc);
final HttpServer serverLink = this.server;
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
LOGGER.info("Stopping server.."); LOGGER.info("Stopping server..");
WebLauncher.this.server.shutdownNow(); serverLink.shutdownNow();
} }
}, "shutdownHook")); }, "shutdownHook"));
@ -151,4 +152,11 @@ public class WebLauncher {
e.printStackTrace(); e.printStackTrace();
} }
} }
public void stop() {
if (this.server != null) {
this.server.shutdownNow();
this.server = null;
}
}
} }

View File

@ -5,13 +5,12 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.kar.archidata.annotation.security.RolesAllowed; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryAnd;
import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.exception.InputException; import org.kar.archidata.exception.InputException;
import org.kar.archidata.filter.GenericContext; import org.kar.archidata.filter.GenericContext;
import org.kar.archidata.sqlWrapper.QuerryAnd;
import org.kar.archidata.sqlWrapper.QuerryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany;
import org.kar.archidata.util.JWTWrapper; import org.kar.archidata.util.JWTWrapper;
import org.kar.karso.model.Application; import org.kar.karso.model.Application;
import org.kar.karso.model.ApplicationSmall; import org.kar.karso.model.ApplicationSmall;
@ -21,6 +20,7 @@ import org.kar.karso.model.UserLinkApplication;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
@ -46,7 +46,7 @@ public class ApplicationResource {
final List<Long> out = new ArrayList<>(); final List<Long> out = new ArrayList<>();
List<UserLinkApplication> links = null; List<UserLinkApplication> links = null;
try { try {
links = SqlWrapper.getsWhere(UserLinkApplication.class, new QuerryCondition("user_id", "=", userId)); links = DataAccess.getsWhere(UserLinkApplication.class, new QueryCondition("user_id", "=", userId));
} catch (final Exception e) { } catch (final Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@ -64,7 +64,7 @@ public class ApplicationResource {
final List<Long> out = new ArrayList<>(); final List<Long> out = new ArrayList<>();
List<UserLinkApplication> links = null; List<UserLinkApplication> links = null;
try { try {
links = SqlWrapper.getsWhere(UserLinkApplication.class, new QuerryCondition("application_id", "=", applicationId)); links = DataAccess.getsWhere(UserLinkApplication.class, new QueryCondition("application_id", "=", applicationId));
} catch (final Exception e) { } catch (final Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@ -90,7 +90,7 @@ public class ApplicationResource {
final GenericContext gc = (GenericContext) sc.getUserPrincipal(); final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("getApplications"); this.logger.debug("getApplications");
// TODO filter with the list of element available in his authorizations ... // TODO filter with the list of element available in his authorizations ...
final List<Application> tmp = SqlWrapper.gets(Application.class); final List<Application> tmp = DataAccess.gets(Application.class);
if (gc.userByToken.hasRight("ADMIN", true)) { if (gc.userByToken.hasRight("ADMIN", true)) {
return tmp; return tmp;
} }
@ -119,7 +119,7 @@ public class ApplicationResource {
application.createdAt = null; application.createdAt = null;
application.deleted = null; application.deleted = null;
application.updatedAt = null; application.updatedAt = null;
return SqlWrapper.insert(application); return DataAccess.insert(application);
} }
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
@ -132,7 +132,7 @@ public class ApplicationResource {
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public Application get(@PathParam("id") final Long id) throws Exception { public Application get(@PathParam("id") final Long id) throws Exception {
return SqlWrapper.get(Application.class, id); return DataAccess.get(Application.class, id);
} }
@PUT @PUT
@ -140,8 +140,8 @@ public class ApplicationResource {
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public Application put(@PathParam("id") final Long id, final String jsonRequest) throws Exception { public Application put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
SqlWrapper.update(Application.class, id, jsonRequest); DataAccess.updateWithJson(Application.class, id, jsonRequest);
return SqlWrapper.get(Application.class, id); return DataAccess.get(Application.class, id);
} }
@DELETE @DELETE
@ -149,7 +149,7 @@ public class ApplicationResource {
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@Produces(value = MediaType.TEXT_PLAIN) @Produces(value = MediaType.TEXT_PLAIN)
public void remove(@Context final SecurityContext sc, @PathParam("id") final long applicationId) throws Exception { public void remove(@Context final SecurityContext sc, @PathParam("id") final long applicationId) throws Exception {
SqlWrapper.delete(Application.class, applicationId); DataAccess.delete(Application.class, applicationId);
} }
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
@ -180,7 +180,7 @@ public class ApplicationResource {
public List<ApplicationSmall> getApplicationsSmall(@Context final SecurityContext sc) throws Exception { public List<ApplicationSmall> getApplicationsSmall(@Context final SecurityContext sc) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal(); final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("getApplications"); this.logger.debug("getApplications");
final List<Application> tmp = SqlWrapper.gets(Application.class); final List<Application> tmp = DataAccess.gets(Application.class);
final List<Long> regular = getUserListOfApplication(gc.userByToken.id); final List<Long> regular = getUserListOfApplication(gc.userByToken.id);
final List<ApplicationSmall> out = new ArrayList<>(); final List<ApplicationSmall> out = new ArrayList<>();
for (final Application app : tmp) { for (final Application app : tmp) {
@ -220,7 +220,7 @@ public class ApplicationResource {
@RolesAllowed(value = { "ADMIN" }) @RolesAllowed(value = { "ADMIN" })
public List<RightDescription> getRightsDescription(@PathParam("id") final Long applicationId) throws Exception { public List<RightDescription> getRightsDescription(@PathParam("id") final Long applicationId) throws Exception {
this.logger.debug("getApplications rights"); this.logger.debug("getApplications rights");
return SqlWrapper.getsWhere(RightDescription.class, new QuerryCondition("applicationId", "=", applicationId)); return DataAccess.getsWhere(RightDescription.class, new QueryCondition("applicationId", "=", applicationId));
} }
@GET @GET
@ -246,7 +246,7 @@ public class ApplicationResource {
Application appl = null; Application appl = null;
try { try {
appl = SqlWrapper.getWhere(Application.class, new QuerryCondition("name", "=", applicationName)); appl = DataAccess.getWhere(Application.class, new QueryCondition("name", "=", applicationName));
} catch (final Exception e) { } catch (final Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@ -262,8 +262,8 @@ public class ApplicationResource {
} }
UserLinkApplication links = null; UserLinkApplication links = null;
try { try {
links = SqlWrapper.getWhere(UserLinkApplication.class, links = DataAccess.getWhere(UserLinkApplication.class,
new QuerryAnd(new QuerryCondition("user_id", "=", gc.userByToken.id), new QuerryCondition("deleted", "=", 0), new QuerryCondition("application_id", "=", appl.id))); new QueryAnd(new QueryCondition("user_id", "=", gc.userByToken.id), new QueryCondition("deleted", "=", 0), new QueryCondition("application_id", "=", appl.id)));
} catch (final Exception e) { } catch (final Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@ -319,7 +319,7 @@ public class ApplicationResource {
Application appl = null; Application appl = null;
try { try {
appl = SqlWrapper.getWhere(Application.class, new QuerryCondition("name", "=", applicationName)); appl = DataAccess.getWhere(Application.class, new QueryCondition("name", "=", applicationName));
} catch (final Exception e) { } catch (final Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();

View File

@ -5,15 +5,15 @@ import java.time.OffsetDateTime;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.util.List; import java.util.List;
import org.kar.archidata.annotation.security.RolesAllowed; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryAnd;
import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.exception.InputException; import org.kar.archidata.exception.InputException;
import org.kar.archidata.sqlWrapper.QuerryAnd;
import org.kar.archidata.sqlWrapper.QuerryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.karso.model.ApplicationToken; import org.kar.karso.model.ApplicationToken;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST; import jakarta.ws.rs.POST;
@ -42,7 +42,7 @@ public class ApplicationTokenResource {
@Path("{applicationId}") @Path("{applicationId}")
@RolesAllowed(value = { "ADMIN" }) @RolesAllowed(value = { "ADMIN" })
public List<ApplicationToken> gets(@Context final SecurityContext sc, @PathParam("applicationId") final Long applicationId) throws Exception { public List<ApplicationToken> gets(@Context final SecurityContext sc, @PathParam("applicationId") final Long applicationId) throws Exception {
final List<ApplicationToken> values = SqlWrapper.getsWhere(ApplicationToken.class, new QuerryCondition("parentId", "=", applicationId)); final List<ApplicationToken> values = DataAccess.getsWhere(ApplicationToken.class, new QueryCondition("parentId", "=", applicationId));
// clean all tokens this is a secret: // clean all tokens this is a secret:
for (final ApplicationToken elem : values) { for (final ApplicationToken elem : values) {
elem.token = null; elem.token = null;
@ -54,7 +54,7 @@ public class ApplicationTokenResource {
@Path("{applicationId}/{tokenId}") @Path("{applicationId}/{tokenId}")
@RolesAllowed(value = { "ADMIN" }) @RolesAllowed(value = { "ADMIN" })
public Response delete(@Context final SecurityContext sc, @PathParam("applicationId") final Long applicationId, @PathParam("tokenId") final Integer tokenId) throws Exception { public Response delete(@Context final SecurityContext sc, @PathParam("applicationId") final Long applicationId, @PathParam("tokenId") final Integer tokenId) throws Exception {
final int nbRemoved = SqlWrapper.setDeleteWhere(ApplicationToken.class, new QuerryAnd(new QuerryCondition("parentId", "=", applicationId), new QuerryCondition("id", "=", tokenId))); final int nbRemoved = DataAccess.deleteWhere(ApplicationToken.class, new QueryAnd(new QueryCondition("parentId", "=", applicationId), new QueryCondition("id", "=", tokenId)), null);
if (nbRemoved == 0) { if (nbRemoved == 0) {
return Response.notModified("{}").build(); return Response.notModified("{}").build();
} }
@ -126,7 +126,7 @@ public class ApplicationTokenResource {
this.logger.warn("token.endValidityTime = {}", token.endValidityTime); this.logger.warn("token.endValidityTime = {}", token.endValidityTime);
// insert in the BDD // insert in the BDD
token = SqlWrapper.insert(token); token = DataAccess.insert(token);
// here we return the token to permit to the user to see it to set it in the application. // here we return the token to permit to the user to see it to set it in the application.
return token; return token;
} }

View File

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

View File

@ -1,5 +1,8 @@
package org.kar.karso.api; package org.kar.karso.api;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import org.kar.archidata.util.JWTWrapper; import org.kar.archidata.util.JWTWrapper;
import org.kar.archidata.util.JWTWrapper.PublicKey; import org.kar.archidata.util.JWTWrapper.PublicKey;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -7,12 +10,10 @@ import org.slf4j.LoggerFactory;
import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JOSEException;
import org.kar.archidata.annotation.security.RolesAllowed; import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import java.security.interfaces.RSAPublicKey; import jakarta.ws.rs.Path;
import java.util.Base64; import jakarta.ws.rs.Produces;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
@Path("/public_key") @Path("/public_key")
@ -23,6 +24,7 @@ public class PublicKeyResource {
public PublicKeyResource() { public PublicKeyResource() {
} }
// This is for java server that use the same implementation // This is for java server that use the same implementation
// curl http://localhost:9993/public_key // curl http://localhost:9993/public_key
@GET @GET
@ -37,10 +39,9 @@ public class PublicKeyResource {
@Path("/pem") @Path("/pem")
@RolesAllowed(value = { "APPLICATION" }) @RolesAllowed(value = { "APPLICATION" })
public String getKeyPem() throws JOSEException { public String getKeyPem() throws JOSEException {
RSAPublicKey keyPub = JWTWrapper.getPublicKeyJava(); final RSAPublicKey keyPub = JWTWrapper.getPublicKeyJava();
byte[] data = keyPub.getEncoded(); final byte[] data = keyPub.getEncoded();
String base64encoded = new String(Base64.getEncoder().encode(data)); final String base64encoded = new String(Base64.getEncoder().encode(data));
return "-----BEGIN PUBLIC KEY-----\n" + base64encoded + "\n-----END PUBLIC KEY-----\n"; return "-----BEGIN PUBLIC KEY-----\n" + base64encoded + "\n-----END PUBLIC KEY-----\n";
} }
} }

View File

@ -4,16 +4,16 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.kar.archidata.annotation.security.RolesAllowed; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.sqlWrapper.QuerryAnd; import org.kar.archidata.dataAccess.QueryAnd;
import org.kar.archidata.sqlWrapper.QuerryCondition; import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.karso.model.Right; import org.kar.karso.model.Right;
import org.kar.karso.model.RightDescription; import org.kar.karso.model.RightDescription;
import org.kar.karso.util.Transform; import org.kar.karso.util.Transform;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
@ -31,11 +31,11 @@ public class RightResource {
final static Logger logger = LoggerFactory.getLogger(RightResource.class); final static Logger logger = LoggerFactory.getLogger(RightResource.class);
public static List<RightDescription> getApplicationRightDecription(final long applicationId) throws Exception { public static List<RightDescription> getApplicationRightDecription(final long applicationId) throws Exception {
return SqlWrapper.getsWhere(RightDescription.class, new QuerryCondition("applicationId", "=", applicationId)); return DataAccess.getsWhere(RightDescription.class, new QueryCondition("applicationId", "=", applicationId));
} }
public static List<Right> getRawUserRight(final long userId, final long applicationId) throws Exception { public static List<Right> getRawUserRight(final long userId, final long applicationId) throws Exception {
return SqlWrapper.getsWhere(Right.class, new QuerryAnd(new QuerryCondition("applicationId", "=", applicationId), new QuerryCondition("userId", "=", userId))); return DataAccess.getsWhere(Right.class, new QueryAnd(new QueryCondition("applicationId", "=", applicationId), new QueryCondition("userId", "=", userId)));
} }
public static Map<String, Object> getUserRight(final long userId, final long applicationId) throws Exception { public static Map<String, Object> getUserRight(final long userId, final long applicationId) throws Exception {
@ -102,7 +102,7 @@ public class RightResource {
// The value exist, we need to update it // The value exist, we need to update it
logger.debug("Request update a knonwn parameter: {} with {}", description.key, newValue); logger.debug("Request update a knonwn parameter: {} with {}", description.key, newValue);
right.value = convertedValue; right.value = convertedValue;
SqlWrapper.update(right, right.id, List.of("value")); DataAccess.update(right, right.id, List.of("value"));
} else { } else {
// we need to create it // we need to create it
logger.debug("Request create parameter: {} with {}", description.key, newValue); logger.debug("Request create parameter: {} with {}", description.key, newValue);
@ -111,7 +111,7 @@ public class RightResource {
right.userId = userId; right.userId = userId;
right.rightDescriptionId = description.id; right.rightDescriptionId = description.id;
right.value = convertedValue; right.value = convertedValue;
SqlWrapper.insert(right); DataAccess.insert(right);
} }
} }
} }
@ -119,21 +119,21 @@ public class RightResource {
@GET @GET
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public List<Right> get() throws Exception { public List<Right> get() throws Exception {
return SqlWrapper.gets(Right.class); return DataAccess.gets(Right.class);
} }
@POST @POST
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public Right post(final String jsonRequest) throws Exception { public Right post(final String jsonRequest) throws Exception {
return SqlWrapper.insertWithJson(Right.class, jsonRequest); return DataAccess.insertWithJson(Right.class, jsonRequest);
} }
@GET @GET
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public static Right getWithId(@PathParam("id") final Long id) throws Exception { public static Right getWithId(@PathParam("id") final Long id) throws Exception {
return SqlWrapper.get(Right.class, id); return DataAccess.get(Right.class, id);
} }
@PUT @PUT
@ -141,15 +141,15 @@ public class RightResource {
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public Right put(@PathParam("id") final Long id, final String jsonRequest) throws Exception { public Right put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
SqlWrapper.update(Right.class, id, jsonRequest); DataAccess.updateWithJson(Right.class, id, jsonRequest);
return SqlWrapper.get(Right.class, id); return DataAccess.get(Right.class, id);
} }
@DELETE @DELETE
@Path("{id}") @Path("{id}")
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public Response delete(@PathParam("id") final Long id) throws Exception { public Response delete(@PathParam("id") final Long id) throws Exception {
SqlWrapper.delete(Right.class, id); DataAccess.delete(Right.class, id);
return Response.ok().build(); return Response.ok().build();
} }

View File

@ -2,11 +2,9 @@ package org.kar.karso.api;
import java.util.List; import java.util.List;
import org.kar.archidata.annotation.security.PermitAll; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.annotation.security.RolesAllowed; import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.exception.NotFoundException; import org.kar.archidata.exception.NotFoundException;
import org.kar.archidata.sqlWrapper.QuerryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.karso.model.Settings; import org.kar.karso.model.Settings;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -14,6 +12,8 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT; import jakarta.ws.rs.PUT;
@ -40,7 +40,6 @@ public class SystemConfigResource {
public GetSignUpAvaillable() { public GetSignUpAvaillable() {
this.signup = false; this.signup = false;
} }
} }
public SystemConfigResource() {} public SystemConfigResource() {}
@ -49,7 +48,7 @@ public class SystemConfigResource {
@Path("is_sign_up_availlable") @Path("is_sign_up_availlable")
@PermitAll @PermitAll
public GetSignUpAvaillable isSignUpAvaillable() throws Exception { public GetSignUpAvaillable isSignUpAvaillable() throws Exception {
final Settings set = SqlWrapper.getWhere(Settings.class, new QuerryCondition("key", "=", "SIGN_UP_ENABLE")); final Settings set = DataAccess.getWhere(Settings.class, new QueryCondition("key", "=", "SIGN_UP_ENABLE"));
if (set == null) { if (set == null) {
throw new NotFoundException("Value does not exist"); throw new NotFoundException("Value does not exist");
} }
@ -63,7 +62,7 @@ public class SystemConfigResource {
@Path("key/{key}") @Path("key/{key}")
@RolesAllowed(value = { "USER", "ADMIN" }) @RolesAllowed(value = { "USER", "ADMIN" })
public Response getKey(@Context final SecurityContext sc, @PathParam("key") final String key) throws Exception { public Response getKey(@Context final SecurityContext sc, @PathParam("key") final String key) throws Exception {
final Settings set = SqlWrapper.getWhere(Settings.class, new QuerryCondition("key", "=", key)); final Settings set = DataAccess.getWhere(Settings.class, new QueryCondition("key", "=", key));
if (set == null) { if (set == null) {
throw new NotFoundException("Value does not exist"); throw new NotFoundException("Value does not exist");
} }
@ -85,7 +84,7 @@ public class SystemConfigResource {
public Response setKey(@Context final SecurityContext sc, @PathParam("key") final String key, final String jsonRequest) throws Exception { public Response setKey(@Context final SecurityContext sc, @PathParam("key") final String key, final String jsonRequest) throws Exception {
Settings res = null; Settings res = null;
try { try {
res = SqlWrapper.getWhere(Settings.class, new QuerryCondition("key", "=", key)); res = DataAccess.getWhere(Settings.class, new QueryCondition("key", "=", key));
} catch (final Exception e) { } catch (final Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@ -99,7 +98,7 @@ public class SystemConfigResource {
res.value = value.asText(); res.value = value.asText();
this.logger.debug("Update value : {}", res.value); this.logger.debug("Update value : {}", res.value);
SqlWrapper.update(res, res.id, List.of("value")); DataAccess.update(res, res.id, List.of("value"));
return Response.status(201).entity("{ \"value\":\"" + res.value + "\"}").build(); return Response.status(201).entity("{ \"value\":\"" + res.value + "\"}").build();
} }

View File

@ -9,16 +9,14 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.kar.archidata.annotation.security.PermitAll; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.annotation.security.RolesAllowed; import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.exception.FailException; import org.kar.archidata.exception.FailException;
import org.kar.archidata.exception.InputException; import org.kar.archidata.exception.InputException;
import org.kar.archidata.exception.SystemException; import org.kar.archidata.exception.SystemException;
import org.kar.archidata.filter.GenericContext; import org.kar.archidata.filter.GenericContext;
import org.kar.archidata.model.GetToken; import org.kar.archidata.model.GetToken;
import org.kar.archidata.sqlWrapper.QuerryCondition;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany;
import org.kar.archidata.util.JWTWrapper; import org.kar.archidata.util.JWTWrapper;
import org.kar.karso.migration.Initialization; import org.kar.karso.migration.Initialization;
import org.kar.karso.model.ChangePassword; import org.kar.karso.model.ChangePassword;
@ -32,6 +30,8 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET; import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException; import jakarta.ws.rs.NotFoundException;
@ -60,7 +60,6 @@ public class UserResource {
this.id = id; this.id = id;
this.login = login; this.login = login;
} }
} }
public UserResource() {} public UserResource() {}
@ -68,7 +67,7 @@ public class UserResource {
@GET @GET
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public List<UserAuthGet> getUsers() throws Exception { public List<UserAuthGet> getUsers() throws Exception {
return SqlWrapper.gets(UserAuthGet.class); return DataAccess.gets(UserAuthGet.class);
} }
@GET @GET
@ -76,7 +75,7 @@ public class UserResource {
@RolesAllowed("ADMIN") @RolesAllowed("ADMIN")
public UserAuthGet getUser(@Context final SecurityContext sc, @PathParam("id") final long userId) throws Exception { public UserAuthGet getUser(@Context final SecurityContext sc, @PathParam("id") final long userId) throws Exception {
//GenericContext gc = (GenericContext) sc.getUserPrincipal(); //GenericContext gc = (GenericContext) sc.getUserPrincipal();
return SqlWrapper.get(UserAuthGet.class, userId); return DataAccess.get(UserAuthGet.class, userId);
} }
@POST @POST
@ -90,7 +89,7 @@ public class UserResource {
} else { } else {
AddOnManyToMany.removeLink(UserAuth.class, userId, "application", applicationId); AddOnManyToMany.removeLink(UserAuth.class, userId, "application", applicationId);
} }
return SqlWrapper.get(UserAuth.class, userId); return DataAccess.get(UserAuth.class, userId);
} }
@GET @GET
@ -117,7 +116,7 @@ public class UserResource {
public Response setAdmin(@Context final SecurityContext sc, @PathParam("id") final long userId, final boolean data) throws Exception { public Response setAdmin(@Context final SecurityContext sc, @PathParam("id") final long userId, final boolean data) throws Exception {
final UserAuth user = new UserAuth(); final UserAuth user = new UserAuth();
user.admin = data; user.admin = data;
final int ret = SqlWrapper.update(user, userId, List.of("admin")); final int ret = DataAccess.update(user, userId, List.of("admin"));
if (ret == 0) { if (ret == 0) {
return Response.notModified("{}").build(); return Response.notModified("{}").build();
} }
@ -130,7 +129,7 @@ public class UserResource {
public Response setBlocked(@Context final SecurityContext sc, @PathParam("id") final long userId, final boolean data) throws Exception { public Response setBlocked(@Context final SecurityContext sc, @PathParam("id") final long userId, final boolean data) throws Exception {
final UserAuth user = new UserAuth(); final UserAuth user = new UserAuth();
user.blocked = data; user.blocked = data;
final int ret = SqlWrapper.update(user, userId, List.of("blocked")); final int ret = DataAccess.update(user, userId, List.of("blocked"));
if (ret == 0) { if (ret == 0) {
return Response.notModified("{}").build(); return Response.notModified("{}").build();
} }
@ -159,12 +158,12 @@ public class UserResource {
// TODO: verify if the data are a hash ... // TODO: verify if the data are a hash ...
// Check login does not exist // Check login does not exist
List<UserAuth> out = SqlWrapper.getsWhere(UserAuth.class, new QuerryCondition("login", "=", user.login)); List<UserAuth> out = DataAccess.getsWhere(UserAuth.class, new QueryCondition("login", "=", user.login));
if (out.size() >= 1) { if (out.size() >= 1) {
throw new FailException(Response.Status.BAD_REQUEST, "Login already used !!!"); throw new FailException(Response.Status.BAD_REQUEST, "Login already used !!!");
} }
// Check email does not exist // Check email does not exist
out = SqlWrapper.getsWhere(UserAuth.class, new QuerryCondition("email", "=", user.email)); out = DataAccess.getsWhere(UserAuth.class, new QueryCondition("email", "=", user.email));
if (out.size() >= 1) { if (out.size() >= 1) {
throw new FailException(Response.Status.BAD_REQUEST, "e-mail already used !!!"); throw new FailException(Response.Status.BAD_REQUEST, "e-mail already used !!!");
} }
@ -179,9 +178,9 @@ public class UserResource {
newUser.password = user.password; newUser.password = user.password;
newUser.email = user.email; newUser.email = user.email;
newUser.lastConnection = Timestamp.valueOf(LocalDateTime.now()); newUser.lastConnection = Timestamp.valueOf(LocalDateTime.now());
final UserAuth tmp = SqlWrapper.insert(newUser); final UserAuth tmp = DataAccess.insert(newUser);
this.logger.debug("create new user done with id=={}", tmp.id); this.logger.debug("create new user done with id=={}", tmp.id);
return SqlWrapper.get(UserAuthGet.class, tmp.id); return DataAccess.get(UserAuthGet.class, tmp.id);
} }
@GET @GET
@ -214,7 +213,7 @@ public class UserResource {
} }
// Process the update: // Process the update:
user.password = data.newPassword; user.password = data.newPassword;
SqlWrapper.update(user, user.id, List.of("password")); DataAccess.update(user, user.id, List.of("password"));
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} }
@ -240,7 +239,7 @@ public class UserResource {
@PermitAll @PermitAll
public Response checkLogin(@QueryParam("login") final String login) throws Exception { public Response checkLogin(@QueryParam("login") final String login) throws Exception {
this.logger.debug("checkLogin: '{}'", login); this.logger.debug("checkLogin: '{}'", login);
final List<UserAuth> out = SqlWrapper.getsWhere(UserAuth.class, new QuerryCondition("login", "=", login)); final List<UserAuth> out = DataAccess.getsWhere(UserAuth.class, new QueryCondition("login", "=", login));
if (out.size() >= 1) { if (out.size() >= 1) {
return Response.ok().build(); return Response.ok().build();
} }
@ -253,7 +252,7 @@ public class UserResource {
@PermitAll @PermitAll
public Response checkEmail(@QueryParam("email") final String email) throws Exception { public Response checkEmail(@QueryParam("email") final String email) throws Exception {
this.logger.debug("checkEmail: {}", email); this.logger.debug("checkEmail: {}", email);
final List<UserAuth> out = SqlWrapper.getsWhere(UserAuth.class, new QuerryCondition("email", "=", email)); final List<UserAuth> out = DataAccess.getsWhere(UserAuth.class, new QueryCondition("email", "=", email));
if (out.size() >= 1) { if (out.size() >= 1) {
return Response.ok().build(); return Response.ok().build();
} }
@ -277,7 +276,7 @@ public class UserResource {
if (login.contains("@")) { if (login.contains("@")) {
query = "email"; query = "email";
} }
final UserAuth user = SqlWrapper.getWhere(UserAuth.class, new QuerryCondition(query, "=", login)); final UserAuth user = DataAccess.getWhere(UserAuth.class, new QueryCondition(query, "=", login));
if (user == null) { if (user == null) {
throw new FailException(Response.Status.PRECONDITION_FAILED, "FAIL Authentiocate-wrong email/login '" + login + "')"); throw new FailException(Response.Status.PRECONDITION_FAILED, "FAIL Authentiocate-wrong email/login '" + login + "')");
@ -322,7 +321,7 @@ public class UserResource {
// Update last connection: // Update last connection:
final UserAuth newUser = new UserAuth(); final UserAuth newUser = new UserAuth();
newUser.lastConnection = Timestamp.valueOf(LocalDateTime.now()); newUser.lastConnection = Timestamp.valueOf(LocalDateTime.now());
SqlWrapper.update(newUser, user.id, List.of("lastConnection")); DataAccess.update(newUser, user.id, List.of("lastConnection"));
//logger.debug(" ==> generate token: {}", ret); //logger.debug(" ==> generate token: {}", ret);
return new GetToken(ret); return new GetToken(ret);

View File

@ -3,9 +3,9 @@ package org.kar.karso.filter;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.time.Instant; import java.time.Instant;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.filter.AuthenticationFilter; import org.kar.archidata.filter.AuthenticationFilter;
import org.kar.archidata.model.UserByToken; import org.kar.archidata.model.UserByToken;
import org.kar.archidata.sqlWrapper.SqlWrapper;
import org.kar.karso.model.ApplicationToken; import org.kar.karso.model.ApplicationToken;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,7 +39,7 @@ public class KarsoAuthenticationFilter extends AuthenticationFilter {
} }
final Long indexToken = Long.parseLong(elems[0]); final Long indexToken = Long.parseLong(elems[0]);
final ApplicationToken value = SqlWrapper.get(ApplicationToken.class, indexToken); final ApplicationToken value = DataAccess.get(ApplicationToken.class, indexToken);
if (value == null) { if (value == null) {
System.out.println("Application authentication can not find id '" + authorization + "'"); System.out.println("Application authentication can not find id '" + authorization + "'");
return null; return null;

View File

@ -36,7 +36,7 @@ public class Initialization extends MigrationSqlStep {
'admin@admin.ZZZ', 1); 'admin@admin.ZZZ', 1);
"""); """);
addAction(""" addAction("""
INSERT INTO `user_link_application` (`user_id`, `application_id`) INSERT INTO `user_link_application` (`object1Id`, `object2Id`)
VALUES ('1', '1'); VALUES ('1', '1');
"""); """);
addAction(""" addAction("""

View File

@ -10,10 +10,10 @@ CREATE TABLE `application` (
*/ */
import org.kar.archidata.annotation.SQLComment; import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.SQLDefault; import org.kar.archidata.annotation.DataDefault;
import org.kar.archidata.annotation.SQLIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.GenericTableSoftDelete; import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
@ -21,9 +21,9 @@ import jakarta.persistence.Column;
import jakarta.persistence.Table; import jakarta.persistence.Table;
@Table(name = "application") @Table(name = "application")
@SQLIfNotExists @DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class Application extends GenericTableSoftDelete { public class Application extends GenericDataSoftDelete {
@Column(length = 256) @Column(length = 256)
public String name; public String name;
@Column(length = 2048) @Column(length = 2048)
@ -31,18 +31,18 @@ public class Application extends GenericTableSoftDelete {
@Column(length = 2048, nullable = false) @Column(length = 2048, nullable = false)
public String redirect; public String redirect;
@Column(length = 2048) @Column(length = 2048)
@SQLDefault("'http://localhost:4200/sso/'") @DataDefault("'http://localhost:4200/sso/'")
public String redirectDev; public String redirectDev;
@Column(length = 2048) @Column(length = 2048)
@SQLDefault("'http://localhost:4200/sso/notification'") @DataDefault("'http://localhost:4200/sso/notification'")
public String notification; public String notification;
@Column(nullable = false) @Column(nullable = false)
@SQLComment("Expiration time ") @DataComment("Expiration time ")
@SQLDefault("666") @DataDefault("666")
public Integer ttl; public Integer ttl;
@Column(nullable = false) @Column(nullable = false)
@SQLComment("Right is manage with Karso") @DataComment("Right is manage with Karso")
@SQLDefault("0") @DataDefault("0")
public Boolean manageRight; public Boolean manageRight;
public Application() {} public Application() {}

View File

@ -1,6 +1,6 @@
package org.kar.karso.model; package org.kar.karso.model;
import org.kar.archidata.annotation.SQLIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.GenericToken; import org.kar.archidata.model.GenericToken;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
@ -8,7 +8,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.persistence.Table; import jakarta.persistence.Table;
@Table(name = "applicationToken") @Table(name = "applicationToken")
@SQLIfNotExists @DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class ApplicationToken extends GenericToken { public class ApplicationToken extends GenericToken {

View File

@ -1,8 +1,8 @@
package org.kar.karso.model; package org.kar.karso.model;
import org.kar.archidata.annotation.SQLComment; import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.SQLIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.GenericTableSoftDelete; import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
@ -12,23 +12,23 @@ import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table; import jakarta.persistence.Table;
@Table(name = "right") @Table(name = "right")
@SQLIfNotExists @DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class Right extends GenericTableSoftDelete { public class Right extends GenericDataSoftDelete {
@Column(nullable = false) @Column(nullable = false)
@SQLComment("application-ID that have the reference of the right") @DataComment("application-ID that have the reference of the right")
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Application.class) @ManyToOne(fetch = FetchType.LAZY, targetEntity = Application.class)
public long applicationId; public Long applicationId;
@Column(nullable = false) @Column(nullable = false)
@SQLComment("user-ID ") @DataComment("user-ID ")
@ManyToOne(fetch = FetchType.LAZY, targetEntity = UserAuth.class) @ManyToOne(fetch = FetchType.LAZY, targetEntity = UserAuth.class)
public long userId; public Long userId;
@Column(nullable = false) @Column(nullable = false)
@SQLComment("rightDescription-ID of the right description") @DataComment("rightDescription-ID of the right description")
@ManyToOne(fetch = FetchType.LAZY, targetEntity = RightDescription.class) @ManyToOne(fetch = FetchType.LAZY, targetEntity = RightDescription.class)
public long rightDescriptionId; public Long rightDescriptionId;
@Column(length = 1024, nullable = false) @Column(length = 1024, nullable = false)
@SQLComment("Value of the right") @DataComment("Value of the right")
public String value; public String value;
} }

View File

@ -1,9 +1,9 @@
package org.kar.karso.model; package org.kar.karso.model;
import org.kar.archidata.annotation.SQLComment; import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.SQLDefault; import org.kar.archidata.annotation.DataDefault;
import org.kar.archidata.annotation.SQLIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.GenericTableSoftDelete; import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
@ -13,27 +13,27 @@ import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table; import jakarta.persistence.Table;
@Table(name = "rightDescription") @Table(name = "rightDescription")
@SQLIfNotExists @DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class RightDescription extends GenericTableSoftDelete { public class RightDescription extends GenericDataSoftDelete {
@Column(nullable = false) @Column(nullable = false)
@SQLComment("Application id that have the reference of the right") @DataComment("Application id that have the reference of the right")
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Application.class) @ManyToOne(fetch = FetchType.LAZY, targetEntity = Application.class)
public long applicationId; public Long applicationId;
@Column(length = 64, nullable = false) @Column(length = 64, nullable = false)
@SQLComment("Key of the property") @DataComment("Key of the property")
public String key; public String key;
@Column(length = 1024, nullable = false) @Column(length = 1024, nullable = false)
@SQLComment("Title of the right") @DataComment("Title of the right")
public String title; public String title;
@Column(length = 1024, nullable = false) @Column(length = 1024, nullable = false)
@SQLComment("Description of the right") @DataComment("Description of the right")
public String description; public String description;
@Column(length = 1024) @Column(length = 1024)
@SQLComment("default value if Never set") @DataComment("default value if Never set")
public String defaultValue; public String defaultValue;
@Column(length = 16, nullable = false) @Column(length = 16, nullable = false)
@SQLComment("Type of the property") @DataComment("Type of the property")
@SQLDefault("\"BOOLEAN\"") @DataDefault("\"BOOLEAN\"")
public String type = "BOOLEAN"; // this is a place-holder (current type supported BOOLEAN) public String type = "BOOLEAN"; // this is a place-holder (current type supported BOOLEAN)
} }

View File

@ -10,10 +10,10 @@ CREATE TABLE `application` (
*/ */
import org.kar.archidata.annotation.SQLComment; import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.SQLDefault; import org.kar.archidata.annotation.DataDefault;
import org.kar.archidata.annotation.SQLIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.GenericTableSoftDelete; import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
@ -25,19 +25,19 @@ enum PropertyType {
} }
@Table(name = "settings") @Table(name = "settings")
@SQLIfNotExists @DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class Settings extends GenericTableSoftDelete { public class Settings extends GenericDataSoftDelete {
@Column(length = 512, nullable = false) @Column(length = 512, nullable = false)
public String key; public String key;
@SQLComment("Right for the specific element(ADMIN [rw] USER [rw] other [rw])") @DataComment("Right for the specific element(ADMIN [rw] USER [rw] other [rw])")
@Column(length = 6, nullable = false) @Column(length = 6, nullable = false)
@SQLDefault("\"rw----\"") @DataDefault("\"rw----\"")
public String right; public String right;
@SQLComment("Type Of the data") @DataComment("Type Of the data")
@Column(length = 10, nullable = false) @Column(length = 10, nullable = false)
public String type; public String type;
@SQLComment("Value of the configuration") @DataComment("Value of the configuration")
@Column(nullable = false) @Column(nullable = false)
public String value; public String value;

View File

@ -3,9 +3,9 @@ package org.kar.karso.model;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List; import java.util.List;
import org.kar.archidata.annotation.SQLComment; import org.kar.archidata.annotation.DataComment;
import org.kar.archidata.annotation.SQLDefault; import org.kar.archidata.annotation.DataDefault;
import org.kar.archidata.annotation.SQLIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.User; import org.kar.archidata.model.User;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
@ -15,7 +15,7 @@ import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table; import jakarta.persistence.Table;
@Table(name = "user") @Table(name = "user")
@SQLIfNotExists @DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class UserAuth extends User { public class UserAuth extends User {
@Column(length = 128, nullable = false) @Column(length = 128, nullable = false)
@ -31,10 +31,10 @@ public class UserAuth extends User {
public Timestamp emailValidate; // time of validation public Timestamp emailValidate; // time of validation
@Column(length = 512) @Column(length = 512)
public String newEmail; public String newEmail;
@SQLDefault("'0'") @DataDefault("'0'")
@Column(nullable = false) @Column(nullable = false)
public boolean avatar = false; public Boolean avatar = false;
@SQLComment("List of accessible application (if not set the application is not available)") @DataComment("List of accessible application (if not set the application is not available)")
@ManyToMany(targetEntity = Application.class) @ManyToMany(targetEntity = Application.class)
public List<Long> applications = null; public List<Long> applications = null;

View File

@ -1,7 +1,7 @@
package org.kar.karso.model; package org.kar.karso.model;
import org.kar.archidata.annotation.SQLDefault; import org.kar.archidata.annotation.DataDefault;
import org.kar.archidata.annotation.SQLIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.User; import org.kar.archidata.model.User;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
@ -10,12 +10,12 @@ import jakarta.persistence.Column;
import jakarta.persistence.Table; import jakarta.persistence.Table;
@Table(name = "user") @Table(name = "user")
@SQLIfNotExists @DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class UserAuthGet extends User { public class UserAuthGet extends User {
@Column(length = 512, nullable = false) @Column(length = 512, nullable = false)
public String email; public String email;
@SQLDefault("'0'") @DataDefault("'0'")
@Column(nullable = false) @Column(nullable = false)
public boolean avatar = false; public Boolean avatar = false;
} }

View File

@ -10,18 +10,18 @@ CREATE TABLE `application` (
*/ */
import org.kar.archidata.annotation.SQLIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.model.GenericTableSoftDelete; import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.persistence.Table; import jakarta.persistence.Table;
// TODO: reùmove this, it must be generated instead of manually create /// // TODO: remove this, it must be generated instead of manually create ///
@Table(name = "user_link_application") @Table(name = "user_link_application")
@SQLIfNotExists @DataIfNotExists
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public class UserLinkApplication extends GenericTableSoftDelete { public class UserLinkApplication extends GenericDataSoftDelete {
public long user_id; public Long user_id;
public long application_id; public Long application_id;
} }

View File

@ -3,7 +3,7 @@
# Default logging detail level for all instances of SimpleLogger. # Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error"). # Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info". # If not specified, defaults to "info".
org.slf4j.simpleLogger.defaultLogLevel=trace org.slf4j.simpleLogger.defaultLogLevel=debug
# Logging detail level for a SimpleLogger instance named "xxxxx". # Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error"). # Must be one of ("trace", "debug", "info", "warn", or "error").

View File

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

View File

@ -1,5 +1,6 @@
package test.kar.karso; package test.kar.karso;
import java.io.IOException;
import java.util.Map; import java.util.Map;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
@ -9,17 +10,12 @@ import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext; import org.kar.archidata.db.DBEntry;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.kar.archidata.exception.RESTErrorResponseExeption;
import org.kar.archidata.model.GetToken; import org.kar.archidata.model.GetToken;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.util.ConfigBaseVariable;
import org.kar.archidata.util.JWTWrapper; import org.kar.archidata.util.JWTWrapper;
import org.kar.archidata.util.RESTApi; import org.kar.archidata.util.RESTApi;
import org.kar.karso.api.HealthCheck.HealthResult;
import org.kar.karso.model.DataGetToken; import org.kar.karso.model.DataGetToken;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -65,24 +61,14 @@ public class TestBase {
} }
@AfterAll @AfterAll
public static void stopWebServer() throws InterruptedException { public static void stopWebServer() throws InterruptedException, IOException {
LOGGER.info("Kill the web server"); LOGGER.info("Kill the web server");
webInterface.stop();
webInterface = null; webInterface = null;
// TODO: do it better... LOGGER.info("Remove the test db");
} DBEntry.closeAllForceMode();
ConfigBaseVariable.clearAllValue();
@Order(1) Thread.sleep(1000);
@Test
//@RepeatedTest(10)
public void checkHealthCheck() throws Exception {
final HealthResult result = api.get(HealthResult.class, "health_check");
Assertions.assertEquals(result.value(), "alive and kicking");
}
@Order(2)
@Test
public void checkHealthCheckWrongAPI() throws Exception {
Assertions.assertThrows(RESTErrorResponseExeption.class, () -> api.get(HealthResult.class, "health_checks"));
} }
@Order(3) @Order(3)
@ -125,124 +111,6 @@ public class TestBase {
// TODO ... Assertions.assertEquals("????", splitted[2]); // TODO ... Assertions.assertEquals("????", splitted[2]);
} }
public void checkFail(final String type, final String urlOffset, final int errorStatus) {
checkFail(type, urlOffset, errorStatus, null);
}
public void checkFail(final String type, final String urlOffset, final int errorStatus, final String data) {
LOGGER.info("Test API: url={} urlOffset={}", type, urlOffset);
try {
if ("GET".equals(type)) {
api.get(String.class, urlOffset);
} else if ("POST".equals(type)) {
api.post(String.class, urlOffset, data);
} else if ("PUT".equals(type)) {
api.put(String.class, urlOffset, data);
} else if ("DELETE".equals(type)) {
api.delete(String.class, urlOffset);
}
Assertions.fail("Request on URL does not fail as expected: '" + type + "' url='" + urlOffset + "'");
} catch (final RESTErrorResponseExeption ex) {
if (errorStatus != ex.status) {
LOGGER.error("Fail in test with the wrong return errors: {}", ex.toString());
}
Assertions.assertEquals(errorStatus, ex.status);
} catch (final Exception ex) {
LOGGER.error("Unexpected throw error: {}", ex);
Assertions.fail("Unexpected throws...");
}
}
public void checkWork(final String type, final String urlOffset) {
checkWork(type, urlOffset, null);
}
public void checkWork(final String type, final String urlOffset, final String data) {
LOGGER.info("Test API: url={} urlOffset={}", type, urlOffset);
try {
if ("GET".equals(type)) {
api.get(String.class, urlOffset);
} else if ("POST".equals(type)) {
api.post(String.class, urlOffset, data);
} else if ("PUT".equals(type)) {
api.put(String.class, urlOffset, data);
} else if ("DELETE".equals(type)) {
api.delete(String.class, urlOffset);
}
//Assertions.fail("Request on URL does not fail as expected: '" + type + "' url='" + urlOffset + "'");
} catch (final RESTErrorResponseExeption ex) {
Assertions.fail("Must not fail ... " + ex.toString());
} catch (final Exception ex) {
LOGGER.error("Unexpected throw error: {}", ex);
Assertions.fail("Unexpected throws...");
}
}
@Order(4)
@Test
public void checkUnAuthorizedAPI() throws Exception {
// /application/
checkFail("GET", "application/", 401);
checkFail("POST", "application/", 401, "{}");
checkFail("PUT", "application/", 405, "{}"); // does not exist
checkFail("DELETE", "application/", 405); // does not exist
// /application/{id}
checkFail("GET", "application/0", 401);
checkFail("PUT", "application/0", 401, "{}");
checkFail("POST", "application/0", 405, "{}");
checkFail("DELETE", "application/0", 401);
// /application/{id}/*
checkFail("GET", "application/0/users", 401);
// /application/*
checkFail("GET", "application/small", 401);
checkFail("GET", "application/get_token", 401);
checkFail("GET", "application/return", 401);
// /application_token/ section:
checkFail("GET", "application_token/0", 401);
checkFail("DELETE", "application_token/0/5", 401);
checkFail("DELETE", "application_token/0/create", 401);
// /front/*
checkFail("GET", "front", 404); // no index in test section
// health check
checkWork("GET", "health_check");
// public_key (only application)
checkFail("GET", "public_key", 401);
checkFail("GET", "public_key/pem", 401);
// /right
checkFail("GET", "right", 401);
checkFail("POST", "right", 401, "{}");
checkFail("GET", "right/0", 401);
checkFail("PUT", "right/0", 401, "{}");
checkFail("DELETE", "right/0", 401);
// /system_config
checkWork("GET", "system_config/is_sign_up_availlable");
checkFail("GET", "system_config/key/skjdfhkjsdhfkjsh", 401);
checkFail("PUT", "system_config/key/skjdfhkjsdhfkjsh", 401, "{}");
// /users
checkFail("GET", "users", 401);
checkFail("GET", "users/0", 401);
checkFail("POST", "users/0/application/0/link", 401, "{}");
checkFail("POST", "users/0/set_admin", 401, "{}");
checkFail("POST", "users/0/set_blocked", 401, "{}");
checkFail("POST", "users/create_new_user", 401, "{}");
checkFail("GET", "users/me", 401, "{}");
checkFail("POST", "users/password", 401, "{}");
checkWork("GET", "users/check_login?login=karadmin");
checkFail("GET", "users/check_login?login=jhkjhkjh", 404);
checkWork("GET", "users/check_email?email=admin@admin.ZZZ");
checkFail("GET", "users/check_email?email=ksjhdkjfhskjdh", 404);
// not testable : get_token
}
@Order(5) @Order(5)
@Test @Test
public void testMeWithToken() throws Exception { public void testMeWithToken() throws Exception {
@ -253,30 +121,3 @@ public class TestBase {
} }
} }
class StepwiseExtension implements ExecutionCondition, TestExecutionExceptionHandler {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(final ExtensionContext extensionContext) {
final ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
final ExtensionContext.Store store = storeFor(extensionContext, namespace);
final String value = store.get(StepwiseExtension.class, String.class);
return value == null ? ConditionEvaluationResult.enabled("No test failures in stepwise tests")
: ConditionEvaluationResult.disabled(String.format("Stepwise test disabled due to previous failure in '%s'", value));
}
@Override
public void handleTestExecutionException(final ExtensionContext extensionContext, final Throwable throwable) throws Throwable {
final ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
final ExtensionContext.Store store = storeFor(extensionContext, namespace);
store.put(StepwiseExtension.class, extensionContext.getDisplayName());
throw throwable;
}
private ExtensionContext.Namespace namespaceFor(final ExtensionContext extensionContext) {
return ExtensionContext.Namespace.create(StepwiseExtension.class, extensionContext.getParent());
}
private ExtensionContext.Store storeFor(final ExtensionContext extensionContext, final ExtensionContext.Namespace namespace) {
return extensionContext.getParent().get().getStore(namespace);
}
}

View File

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

View File

@ -0,0 +1,187 @@
package test.kar.karso;
import java.io.IOException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.kar.archidata.db.DBEntry;
import org.kar.archidata.exception.RESTErrorResponseExeption;
import org.kar.archidata.model.GetToken;
import org.kar.archidata.util.ConfigBaseVariable;
import org.kar.archidata.util.RESTApi;
import org.kar.karso.model.DataGetToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class TestUnAuthorizedAPI {
private final static Logger LOGGER = LoggerFactory.getLogger(TestUnAuthorizedAPI.class);
static WebLauncherTest webInterface = null;
static RESTApi api = null;
public void login(final String login, final String password) {
try {
final GetToken token = api.post(GetToken.class, "users/get_token", DataGetToken.generate(login, "v1", "202515252", password));
api.setToken(token.jwt());
} catch (final Exception ex) {
Assertions.fail("Can not get Authentication for '" + login + "' ==> " + ex.getMessage());
}
}
public void loginAdmin() {
login("karadmin", "adminA@666");
}
@BeforeAll
public static void configureWebServer() throws Exception {
LOGGER.info("configure server ...");
webInterface = new WebLauncherTest();
LOGGER.info("Create DB");
try {
webInterface.migrateDB();
} catch (final Exception ex) {
ex.printStackTrace();
LOGGER.error("Detect an error: {}", ex.getMessage());
}
LOGGER.info("Start REST (BEGIN)");
webInterface.process();
LOGGER.info("Start REST (DONE)");
api = new RESTApi(ConfigBaseVariable.apiAdress);
}
@AfterAll
public static void stopWebServer() throws InterruptedException, IOException {
LOGGER.info("Kill the web server");
webInterface.stop();
webInterface = null;
LOGGER.info("Remove the test db");
DBEntry.closeAllForceMode();
ConfigBaseVariable.clearAllValue();
Thread.sleep(1000);
}
public void checkFail(final String type, final String urlOffset, final int errorStatus) {
checkFail(type, urlOffset, errorStatus, null);
}
public void checkFail(final String type, final String urlOffset, final int errorStatus, final String data) {
LOGGER.info("Test API: url={} urlOffset={}", type, urlOffset);
try {
if ("GET".equals(type)) {
api.get(String.class, urlOffset);
} else if ("POST".equals(type)) {
api.post(String.class, urlOffset, data);
} else if ("PUT".equals(type)) {
api.put(String.class, urlOffset, data);
} else if ("DELETE".equals(type)) {
api.delete(String.class, urlOffset);
}
Assertions.fail("Request on URL does not fail as expected: '" + type + "' url='" + urlOffset + "'");
} catch (final RESTErrorResponseExeption ex) {
if (errorStatus != ex.status) {
LOGGER.error("Fail in test with the wrong return errors: {}", ex.toString());
}
Assertions.assertEquals(errorStatus, ex.status);
} catch (final Exception ex) {
LOGGER.error("Unexpected throw error: {}", ex);
Assertions.fail("Unexpected throws...");
}
}
public void checkWork(final String type, final String urlOffset) {
checkWork(type, urlOffset, null);
}
public void checkWork(final String type, final String urlOffset, final String data) {
LOGGER.info("Test API: url={} urlOffset={}", type, urlOffset);
try {
if ("GET".equals(type)) {
api.get(String.class, urlOffset);
} else if ("POST".equals(type)) {
api.post(String.class, urlOffset, data);
} else if ("PUT".equals(type)) {
api.put(String.class, urlOffset, data);
} else if ("DELETE".equals(type)) {
api.delete(String.class, urlOffset);
}
//Assertions.fail("Request on URL does not fail as expected: '" + type + "' url='" + urlOffset + "'");
} catch (final RESTErrorResponseExeption ex) {
Assertions.fail("Must not fail ... " + ex.toString());
} catch (final Exception ex) {
LOGGER.error("Unexpected throw error: {}", ex);
Assertions.fail("Unexpected throws...");
}
}
@Order(1)
@Test
public void checkUnAuthorizedAPI() throws Exception {
// /application/
checkFail("GET", "application/", 401);
checkFail("POST", "application/", 401, "{}");
checkFail("PUT", "application/", 405, "{}"); // does not exist
checkFail("DELETE", "application/", 405); // does not exist
// /application/{id}
checkFail("GET", "application/0", 401);
checkFail("PUT", "application/0", 401, "{}");
checkFail("POST", "application/0", 405, "{}");
checkFail("DELETE", "application/0", 401);
// /application/{id}/*
checkFail("GET", "application/0/users", 401);
// /application/*
checkFail("GET", "application/small", 401);
checkFail("GET", "application/get_token", 401);
checkFail("GET", "application/return", 401);
// /application_token/ section:
checkFail("GET", "application_token/0", 401);
checkFail("DELETE", "application_token/0/5", 401);
checkFail("DELETE", "application_token/0/create", 401);
// /front/*
checkFail("GET", "front", 404); // no index in test section
// health check
checkWork("GET", "health_check");
// public_key (only application)
checkFail("GET", "public_key", 401);
checkFail("GET", "public_key/pem", 401);
// /right
checkFail("GET", "right", 401);
checkFail("POST", "right", 401, "{}");
checkFail("GET", "right/0", 401);
checkFail("PUT", "right/0", 401, "{}");
checkFail("DELETE", "right/0", 401);
// /system_config
checkWork("GET", "system_config/is_sign_up_availlable");
checkFail("GET", "system_config/key/skjdfhkjsdhfkjsh", 401);
checkFail("PUT", "system_config/key/skjdfhkjsdhfkjsh", 401, "{}");
// /users
checkFail("GET", "users", 401);
checkFail("GET", "users/0", 401);
checkFail("POST", "users/0/application/0/link", 401, "{}");
checkFail("POST", "users/0/set_admin", 401, "{}");
checkFail("POST", "users/0/set_blocked", 401, "{}");
checkFail("POST", "users/create_new_user", 401, "{}");
checkFail("GET", "users/me", 401, "{}");
checkFail("POST", "users/password", 401, "{}");
checkWork("GET", "users/check_login?login=karadmin");
checkFail("GET", "users/check_login?login=jhkjhkjh", 404);
checkWork("GET", "users/check_email?email=admin@admin.ZZZ");
checkFail("GET", "users/check_email?email=ksjhdkjfhskjdh", 404);
// not testable : get_token
}
}

View File

@ -8,14 +8,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class WebLauncherTest extends WebLauncher { public class WebLauncherTest extends WebLauncher {
final Logger logger = LoggerFactory.getLogger(WebLauncherTest.class); final private static Logger LOGGER = LoggerFactory.getLogger(WebLauncherTest.class);
public WebLauncherTest() { public WebLauncherTest() {
this.logger.debug("Configure REST system"); LOGGER.debug("Configure REST system");
// for local test: // for local test:
ConfigBaseVariable.apiAdress = "http://127.0.0.1:12345/test/api/"; ConfigBaseVariable.apiAdress = "http://127.0.0.1:12345/test/api/";
ConfigBaseVariable.dbPort = "3306"; //ConfigBaseVariable.dbPort = "3306";
// create a unique key for test ==> not retrieve the token every load... // create a unique key for test ==> not retrieve the token every load...
ConfigVariable.uuid_for_key_generation = "lkjlkjlkjlmkjqmwlsdkjqfsdlkf,nmQLSDK,NFMQLKSdjmlKQJSDMLQK,S;ndmLQKZNERMA,ÉL"; ConfigVariable.uuid_for_key_generation = "lkjlkjlkjlmkjqmwlsdkjqfsdlkf,nmQLSDK,NFMQLKSdjmlKQJSDMLQK,S;ndmLQKZNERMA,ÉL";
// for the test we a in memory sqlite.. // for the test we a in memory sqlite..
@ -24,8 +24,8 @@ public class WebLauncherTest extends WebLauncher {
// for test we need to connect all time the DB // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true"; ConfigBaseVariable.dbKeepConnected = "true";
ConfigBaseVariable.dbHost = "localhost"; //ConfigBaseVariable.dbHost = "localhost";
ConfigBaseVariable.dbUser = "root"; //ConfigBaseVariable.dbUser = "root";
ConfigBaseVariable.dbPassword = "ZERTYSDGFVHSDFGHJYZSDFGSQxfgsqdfgsqdrf4564654"; //ConfigBaseVariable.dbPassword = "ZERTYSDGFVHSDFGHJYZSDFGSQxfgsqdfgsqdrf4564654";
} }
} }

@ -1 +1 @@
Subproject commit ea5a4f6b7537eb707916f4610bf79fbe86c6296f Subproject commit 9fc25b4feaeba509ff39f70b24d97be47f4b30e1