diff --git a/annotation-service/Dockerfile b/annotation-service/Dockerfile deleted file mode 100644 index 2752d79a0..000000000 --- a/annotation-service/Dockerfile +++ /dev/null @@ -1,38 +0,0 @@ -####################################### Build stage ####################################### -FROM maven:3.9-eclipse-temurin-21-alpine AS build-stage - -ARG MAVEN_ACCOUNT_USR -ARG MAVEN_ACCOUNT_PSW -ARG REVISION -ARG PROFILE -ENV server_username=$MAVEN_ACCOUNT_USR -ENV server_password=$MAVEN_ACCOUNT_PSW -ARG CITE_MAVEN_REPO_URL - -COPY pom.xml /build/ -COPY annotation /build/annotation/ -COPY annotation-web /build/annotation-web/ -COPY settings.xml /root/.m2/settings.xml -RUN rm -f /build/annotation-web/src/main/resources/config/app.env -RUN rm -f /build/annotation-web/src/main/resources/config/*-devel.yml -RUN rm -f /build/annotation-web/src/main/resources/logging/*.xml -RUN rm -f /build/annotation-web/src/main/resources/certificates/*.crt - -WORKDIR /build/ - -RUN mvn -Drevision=${REVISION} -DciteMavenRepoUrl=${CITE_MAVEN_REPO_URL} -P${PROFILE} clean -RUN mvn -Drevision=${REVISION} -DciteMavenRepoUrl=${CITE_MAVEN_REPO_URL} -P${PROFILE} install -# Build project -RUN mvn -Drevision=${REVISION} -DciteMavenRepoUrl=${CITE_MAVEN_REPO_URL} -P${PROFILE} package - -######################################## Run Stage ######################################## -FROM eclipse-temurin:21-jre-ubi9-minimal - -ARG PROFILE -ARG REVISION -ENV SERVER_PORT=8080 -EXPOSE ${SERVER_PORT} - -COPY --from=build-stage /build/annotation-web/target/annotation-web-${REVISION}.jar /app/annotation-web.jar - -ENTRYPOINT ["java","-Dspring.config.additional-location=file:/config/","-Dspring.profiles.active=${PROFILE}","-Djava.security.egd=file:/dev/./urandom","-jar","/app/annotation-web.jar"] \ No newline at end of file diff --git a/annotation-service/Dockerfile.Sonar b/annotation-service/Dockerfile.Sonar deleted file mode 100644 index b9697d569..000000000 --- a/annotation-service/Dockerfile.Sonar +++ /dev/null @@ -1,30 +0,0 @@ -####################################### Build stage ####################################### -FROM maven:3.9-eclipse-temurin-21-alpine - -ARG MAVEN_ACCOUNT_USR -ARG MAVEN_ACCOUNT_PSW -ARG REVISION -ARG PROFILE -ARG ORACLE_URL -ARG ORACLE_TOKEN -ENV server_username=$MAVEN_ACCOUNT_USR -ENV server_password=$MAVEN_ACCOUNT_PSW -ARG CITE_MAVEN_REPO_URL - -COPY pom.xml /build/ -COPY annotation /build/annotation/ -COPY annotation-web /build/annotation-web/ -COPY settings.xml /root/.m2/settings.xml -RUN rm -f /build/annotation-web/src/main/resources/config/app.env -RUN rm -f /build/annotation-web/src/main/resources/config/*-devel.yml -RUN rm -f /build/annotation-web/src/main/resources/logging/*.xml -RUN rm -f /build/annotation-web/src/main/resources/certificates/*.crt - -COPY oracle.local.cite.gr.crt $JAVA_HOME/conf/security -RUN cd "$JAVA_HOME"/conf/security && keytool -cacerts -storepass changeit -noprompt -trustcacerts -importcert -alias oraclecert -file oracle.local.cite.gr.crt - -WORKDIR /build/ -RUN mvn -Drevision=${REVISION} -DciteMavenRepoUrl=${CITE_MAVEN_REPO_URL} -P${PROFILE} clean -RUN mvn -Drevision=${REVISION} -DciteMavenRepoUrl=${CITE_MAVEN_REPO_URL} -P${PROFILE} install -RUN mvn -Drevision=${REVISION} -DciteMavenRepoUrl=${CITE_MAVEN_REPO_URL} -P${PROFILE} package -RUN mvn sonar:sonar -Drevision=${REVISION} -DciteMavenRepoUrl=${CITE_MAVEN_REPO_URL} -P${PROFILE} -Dsonar.projectKey=OpenDMP:annotation-api -Dsonar.login=${ORACLE_TOKEN} -Dsonar.host.url=${ORACLE_URL} -Dsonar.projectName='OpenDMP Annotation API' \ No newline at end of file diff --git a/annotation-service/annotation-web/.gitignore b/annotation-service/annotation-web/.gitignore deleted file mode 100644 index 5eac309eb..000000000 --- a/annotation-service/annotation-web/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ \ No newline at end of file diff --git a/annotation-service/annotation-web/pom.xml b/annotation-service/annotation-web/pom.xml deleted file mode 100644 index 9e2b1e0f0..000000000 --- a/annotation-service/annotation-web/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - 4.0.0 - - - gr.cite - annotation-service-parent - ${revision} - ../pom.xml - - - annotation-web - ${revision} - jar - - - 21 - 21 - 21 - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-webflux - - - - org.springframework.boot - spring-boot-starter-validation - - - - org.postgresql - postgresql - - - org.hibernate.orm - hibernate-core - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - gr.cite - annotation - ${revision} - - - - gr.cite - oidc-authz - 2.1.0 - - - gr.cite - cache - 2.2.0 - - - gr.cite - exceptions-web - 2.1.0 - - - gr.cite - cors-web - 2.1.0 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/AnnotationApplication.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/AnnotationApplication.java deleted file mode 100644 index b7f47cf41..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/AnnotationApplication.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.annotation.web; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.scheduling.annotation.EnableAsync; - -@SpringBootApplication( - scanBasePackages = { - "gr.cite.annotation.*", - "gr.cite", - "gr.cite.queueoutbox", - "gr.cite.queueinbox", - "gr.cite.annotation.integrationevent", - "gr.cite.tools", - "gr.cite.commons"}) -@EntityScan({ - "gr.cite.annotation.data"}) -@EnableAsync -public class AnnotationApplication { - - public static void main(String[] args) { - SpringApplication.run(AnnotationApplication.class, args); - } - -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/WebConfiguration.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/WebConfiguration.java deleted file mode 100644 index 775930c70..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/WebConfiguration.java +++ /dev/null @@ -1,40 +0,0 @@ -package gr.cite.annotation.web; - -import gr.cite.annotation.web.scope.tenant.TenantInterceptor; -import gr.cite.annotation.web.scope.tenant.TenantScopeClaimInterceptor; -import gr.cite.annotation.web.scope.tenant.TenantScopeHeaderInterceptor; -import gr.cite.annotation.web.scope.user.UserInterceptor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebConfiguration implements WebMvcConfigurer { - private final TenantInterceptor tenantInterceptor; - private final TenantScopeHeaderInterceptor scopeHeaderInterceptor; - private final TenantScopeClaimInterceptor scopeClaimInterceptor; - private final UserInterceptor userInterceptor; - - @Autowired - public WebConfiguration( - TenantInterceptor tenantInterceptor, - TenantScopeHeaderInterceptor scopeHeaderInterceptor, - TenantScopeClaimInterceptor scopeClaimInterceptor, - UserInterceptor userInterceptor - ) { - this.tenantInterceptor = tenantInterceptor; - this.scopeHeaderInterceptor = scopeHeaderInterceptor; - this.scopeClaimInterceptor = scopeClaimInterceptor; - this.userInterceptor = userInterceptor; - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - int order = 1; - registry.addWebRequestInterceptor(scopeHeaderInterceptor).order(order++); - registry.addWebRequestInterceptor(scopeClaimInterceptor).order(order++); - registry.addWebRequestInterceptor(userInterceptor).order(order++); - registry.addWebRequestInterceptor(tenantInterceptor).order(order++); - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/AffiliatedAuthorizationHandler.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/AffiliatedAuthorizationHandler.java deleted file mode 100644 index e1f93182b..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/AffiliatedAuthorizationHandler.java +++ /dev/null @@ -1,56 +0,0 @@ -package gr.cite.annotation.web.authorization; - -import gr.cite.annotation.authorization.AffiliatedAuthorizationRequirement; -import gr.cite.annotation.authorization.AffiliatedResource; -import gr.cite.commons.web.authz.handler.AuthorizationHandler; -import gr.cite.commons.web.authz.handler.AuthorizationHandlerContext; -import gr.cite.commons.web.authz.policy.AuthorizationRequirement; -import gr.cite.commons.web.oidc.principal.MyPrincipal; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component("affiliatedAuthorizationHandler") -public class AffiliatedAuthorizationHandler extends AuthorizationHandler { - - private final CustomPermissionAttributesConfiguration myConfiguration; - - @Autowired - public AffiliatedAuthorizationHandler(CustomPermissionAttributesConfiguration myConfiguration) { - this.myConfiguration = myConfiguration; - } - - @Override - public int handleRequirement(AuthorizationHandlerContext context, Object resource, AuthorizationRequirement requirement) { - AffiliatedAuthorizationRequirement req = (AffiliatedAuthorizationRequirement) requirement; - if (req.getRequiredPermissions() == null) - return ACCESS_NOT_DETERMINED; - - AffiliatedResource rs = (AffiliatedResource) resource; - - boolean isAuthenticated = ((MyPrincipal) context.getPrincipal()).isAuthenticated(); - if (!isAuthenticated) - return ACCESS_NOT_DETERMINED; - - if (myConfiguration.getMyPolicies() == null) - return ACCESS_NOT_DETERMINED; - - int hits = 0; - Boolean entityAffiliated = rs != null && rs.getAffiliated() != null ? rs.getAffiliated() : null; - - for (String permission : req.getRequiredPermissions()) { - CustomPermissionAttributesProperties.MyPermission policy = myConfiguration.getMyPolicies().get(permission); - boolean hasPermission = policy != null && policy.getEntityAffiliated() != null && policy.getEntityAffiliated() && entityAffiliated != null && entityAffiliated; - if (hasPermission) hits += 1; - } - if ((req.getMatchAll() && req.getRequiredPermissions().size() == hits) || (!req.getMatchAll() && hits > 0)) - return ACCESS_GRANTED; - - return ACCESS_NOT_DETERMINED; - } - - @Override - public Class supporting() { - return AffiliatedAuthorizationRequirement.class; - } - -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/CustomPermissionAttributesConfiguration.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/CustomPermissionAttributesConfiguration.java deleted file mode 100644 index 4767d4ea3..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/CustomPermissionAttributesConfiguration.java +++ /dev/null @@ -1,24 +0,0 @@ -package gr.cite.annotation.web.authorization; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -import java.util.HashMap; - -@Configuration -@EnableConfigurationProperties(CustomPermissionAttributesProperties.class) -public class CustomPermissionAttributesConfiguration { - - private final CustomPermissionAttributesProperties properties; - - @Autowired - public CustomPermissionAttributesConfiguration(CustomPermissionAttributesProperties properties) { - this.properties = properties; - } - - public HashMap getMyPolicies() { - return properties.getPolicies(); - } - -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/CustomPermissionAttributesProperties.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/CustomPermissionAttributesProperties.java deleted file mode 100644 index 13d0614aa..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/CustomPermissionAttributesProperties.java +++ /dev/null @@ -1,38 +0,0 @@ -package gr.cite.annotation.web.authorization; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.ConstructorBinding; - -import java.util.HashMap; - -@ConfigurationProperties(prefix = "permissions") -@ConditionalOnProperty(prefix = "permissions", name = "enabled", havingValue = "true") -public class CustomPermissionAttributesProperties { - - private final HashMap policies; - - @ConstructorBinding - public CustomPermissionAttributesProperties(HashMap policies) { - this.policies = policies; - } - - public HashMap getPolicies() { - return policies; - } - - public static class MyPermission { - - private final Boolean entityAffiliated; - - @ConstructorBinding - public MyPermission(Boolean entityAffiliated) { - this.entityAffiliated = entityAffiliated; - } - - public Boolean getEntityAffiliated() { - return entityAffiliated; - } - } - -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/OwnedAuthorizationHandler.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/OwnedAuthorizationHandler.java deleted file mode 100644 index 922dc5266..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/authorization/OwnedAuthorizationHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -package gr.cite.annotation.web.authorization; - -import gr.cite.commons.web.authz.handler.AuthorizationHandler; -import gr.cite.commons.web.authz.handler.AuthorizationHandlerContext; -import gr.cite.commons.web.authz.policy.AuthorizationRequirement; -import gr.cite.commons.web.oidc.principal.MyPrincipal; -import gr.cite.annotation.authorization.OwnedAuthorizationRequirement; -import gr.cite.annotation.authorization.OwnedResource; -import gr.cite.annotation.common.scope.user.UserScope; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component("ownedAuthorizationHandler") -public class OwnedAuthorizationHandler extends AuthorizationHandler { - - private final UserScope userScope; - - @Autowired - public OwnedAuthorizationHandler(UserScope userScope) { - this.userScope = userScope; - } - - @Override - public int handleRequirement(AuthorizationHandlerContext context, Object resource, AuthorizationRequirement requirement) { - OwnedAuthorizationRequirement req = (OwnedAuthorizationRequirement) requirement; - - OwnedResource rs = (OwnedResource) resource; - - boolean isAuthenticated = ((MyPrincipal) context.getPrincipal()).isAuthenticated(); - if (!isAuthenticated) return ACCESS_NOT_DETERMINED; - - if (this.userScope.getUserIdSafe() == null) return ACCESS_NOT_DETERMINED; - - if (rs != null && rs.getUserIds() != null && rs.getUserIds().contains(this.userScope.getUserIdSafe())) return ACCESS_GRANTED; - - return ACCESS_NOT_DETERMINED; - } - - @Override - public Class supporting() { - return OwnedAuthorizationRequirement.class; - } - -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/config/AppMessageSourceConfiguration.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/config/AppMessageSourceConfiguration.java deleted file mode 100644 index 971e1eb3c..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/config/AppMessageSourceConfiguration.java +++ /dev/null @@ -1,25 +0,0 @@ -package gr.cite.annotation.web.config; - -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.ReloadableResourceBundleMessageSource; -import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; - -@Configuration -public class AppMessageSourceConfiguration { - @Bean - public MessageSource messageSource() { - ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); - messageSource.setBasename("classpath:messages/messages"); - messageSource.setDefaultEncoding("UTF-8"); - return messageSource; - } - - @Bean - public LocalValidatorFactoryBean getValidator() { - LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean(); - bean.setValidationMessageSource(messageSource()); - return bean; - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/config/SecurityConfiguration.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/config/SecurityConfiguration.java deleted file mode 100644 index a52e25875..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/config/SecurityConfiguration.java +++ /dev/null @@ -1,152 +0,0 @@ -package gr.cite.annotation.web.config; - -import gr.cite.annotation.authorization.AffiliatedAuthorizationRequirement; -import gr.cite.annotation.authorization.AffiliatedResource; -import gr.cite.annotation.web.authorization.AffiliatedAuthorizationHandler; -import gr.cite.commons.web.authz.handler.AuthorizationHandler; -import gr.cite.commons.web.authz.handler.PermissionClientAuthorizationHandler; -import gr.cite.commons.web.authz.policy.AuthorizationRequirement; -import gr.cite.commons.web.authz.policy.AuthorizationRequirementMapper; -import gr.cite.commons.web.authz.policy.AuthorizationResource; -import gr.cite.commons.web.authz.policy.resolver.AuthorizationPolicyConfigurer; -import gr.cite.commons.web.authz.policy.resolver.AuthorizationPolicyResolverStrategy; -import gr.cite.commons.web.oidc.configuration.WebSecurityProperties; -import gr.cite.annotation.authorization.OwnedAuthorizationRequirement; -import gr.cite.annotation.authorization.OwnedResource; -import gr.cite.annotation.web.authorization.OwnedAuthorizationHandler; -import jakarta.servlet.Filter; -import jakarta.servlet.http.HttpServletRequest; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManagerResolver; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; -import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -@Configuration -@EnableWebSecurity -public class SecurityConfiguration { - - private final WebSecurityProperties webSecurityProperties; - private final AuthenticationManagerResolver authenticationManagerResolver; - private final Filter apiKeyFilter; - private final OwnedAuthorizationHandler ownedAuthorizationHandler; - private final AffiliatedAuthorizationHandler affiliatedAuthorizationHandler; - - @Autowired - public SecurityConfiguration(WebSecurityProperties webSecurityProperties, - @Qualifier("tokenAuthenticationResolver") AuthenticationManagerResolver authenticationManagerResolver, - @Qualifier("apiKeyFilter") Filter apiKeyFilter, - @Qualifier("ownedAuthorizationHandler") OwnedAuthorizationHandler ownedAuthorizationHandler, - @Qualifier("affiliatedAuthorizationHandler") AffiliatedAuthorizationHandler affiliatedAuthorizationHandler) { - this.webSecurityProperties = webSecurityProperties; - this.authenticationManagerResolver = authenticationManagerResolver; - this.apiKeyFilter = apiKeyFilter; - this.ownedAuthorizationHandler = ownedAuthorizationHandler; - this.affiliatedAuthorizationHandler = affiliatedAuthorizationHandler; - } - - @Bean - public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - HttpSecurity tempHttp = http - .csrf(AbstractHttpConfigurer::disable) - .cors(httpSecurityCorsConfigurer -> {}) - .headers(httpSecurityHeadersConfigurer -> httpSecurityHeadersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) - .addFilterBefore(apiKeyFilter, AbstractPreAuthenticatedProcessingFilter.class) - .authorizeHttpRequests(authRequest -> - authRequest.requestMatchers(buildAntPatterns(webSecurityProperties.getAllowedEndpoints())).anonymous() - .requestMatchers(buildAntPatterns(webSecurityProperties.getAuthorizedEndpoints())).authenticated()) - .sessionManagement( sessionManagementConfigurer-> sessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.NEVER)) - .oauth2ResourceServer(oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver)); - return tempHttp.build(); - } - - @Bean - AuthorizationPolicyConfigurer authorizationPolicyConfigurer() { - return new AuthorizationPolicyConfigurer() { - - @Override - public AuthorizationPolicyResolverStrategy strategy() { - return AuthorizationPolicyResolverStrategy.STRICT_CONSENSUS_BASED; - } - - //Here you can register your custom authorization handlers, which will get used as well as the existing ones - //This is optional and can be omitted - //If not set / set to null, only the default authorization handlers will be used - @Override - public List> addCustomHandlers() { - return List.of(affiliatedAuthorizationHandler, ownedAuthorizationHandler); - } - - //Here you can register your custom authorization requirements (if any) - //This is optional and can be omitted - //If not set / set to null, only the default authorization requirements will be used - @Override - public List extendRequirements() { - return List.of( -// new TimeOfDayAuthorizationRequirement(new TimeOfDay("08:00","16:00"), true) - ); - } - - //Here you can select handlers you want to disable by providing the classes they are implemented by - //You can disable any handler (including any custom one) - //This is optional and can be omitted - //If not set / set to null, all the handlers will be invoked, based on their requirement support - //In the example below, the default client handler will be ignored by the resolver - @Override - public List>> disableHandlers() { - return new ArrayList<>(); - } - }; - } - - @Bean - AuthorizationRequirementMapper authorizationRequirementMapper() { - return new AuthorizationRequirementMapper() { - @Override - public AuthorizationRequirement map(AuthorizationResource resource, boolean matchAll, String[] permissions) { - Class type = resource.getClass(); - if (!AuthorizationResource.class.isAssignableFrom(type)) throw new IllegalArgumentException("resource"); - - if (OwnedResource.class.equals(type)) { - return new OwnedAuthorizationRequirement(); - } - if (AffiliatedResource.class.equals(type)) { - return new AffiliatedAuthorizationRequirement(matchAll, permissions); - } - throw new IllegalArgumentException("resource"); - } - }; - } - - private String[] buildAntPatterns(Set endpoints) { - if (endpoints == null) { - return new String[0]; - } - return endpoints.stream() - .filter(endpoint -> endpoint != null && !endpoint.isBlank()) - .map(endpoint -> "/" + stripUnnecessaryCharacters(endpoint) + "/**") - .toArray(String[]::new); - } - - private String stripUnnecessaryCharacters(String endpoint) { - endpoint = endpoint.strip(); - if (endpoint.startsWith("/")) { - endpoint = endpoint.substring(1); - } - if (endpoint.endsWith("/")) { - endpoint = endpoint.substring(0, endpoint.length() - 1); - } - return endpoint; - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllerhandler/GlobalExceptionHandler.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllerhandler/GlobalExceptionHandler.java deleted file mode 100644 index ebefb8eff..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllerhandler/GlobalExceptionHandler.java +++ /dev/null @@ -1,193 +0,0 @@ -package gr.cite.annotation.web.controllerhandler; - -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.tools.exception.*; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.context.request.WebRequest; - -import java.text.MessageFormat; -import java.util.Map; - -@RestControllerAdvice -@ControllerAdvice -public class GlobalExceptionHandler { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(GlobalExceptionHandler.class)); - - private final JsonHandlingService jsonHandlingService; - - public GlobalExceptionHandler(JsonHandlingService jsonHandlingService) { - this.jsonHandlingService = jsonHandlingService; - } - - - @ExceptionHandler(Exception.class) - public ResponseEntity handleUnexpectedErrors(Exception exception, WebRequest request) throws Exception { - HandledException handled = this.handleException(exception, request); - this.log(handled.getLevel(), exception, MessageFormat.format("returning code {0} and payload {1}", handled.getStatusCode(), handled.getMessage())); - return new ResponseEntity<>(handled.getMessage(), handled.getStatusCode()); - } - - public void log(System.Logger.Level level, Exception e, String message) { - if (level != null) { - switch (level) { - case TRACE: - logger.trace(message, e); - break; - case DEBUG: - logger.debug(message, e); - break; - case INFO: - logger.info(message, e); - break; - case WARNING: - logger.warn(message, e); - break; - case ERROR: - logger.error(message, e); - break; - } - } - } - - public HandledException handleException(Exception exception, WebRequest request) throws Exception { - HttpStatus statusCode; - Map result; - System.Logger.Level logLevel; - - switch (exception){ - case MyNotFoundException myNotFoundException -> { - logLevel = System.Logger.Level.DEBUG; - statusCode = HttpStatus.NOT_FOUND; - int code = myNotFoundException.getCode(); - if (code > 0) { - result = Map.ofEntries( - Map.entry("code", code), - Map.entry("error", myNotFoundException.getMessage()) - ); - } - else { - result = Map.ofEntries( - Map.entry("error", myNotFoundException.getMessage()) - ); - } - } - case MyUnauthorizedException myUnauthorizedException -> { - logLevel = System.Logger.Level.DEBUG; - statusCode = HttpStatus.UNAUTHORIZED; - int code = myUnauthorizedException.getCode(); - if (code > 0) { - result = Map.ofEntries( - Map.entry("code", code), - Map.entry("error", myUnauthorizedException.getMessage()) - ); - } - else { - result = Map.ofEntries( - Map.entry("error", myUnauthorizedException.getMessage()) - ); - } - } - case MyForbiddenException myForbiddenException -> { - logLevel = System.Logger.Level.DEBUG; - statusCode = HttpStatus.FORBIDDEN; - int code = myForbiddenException.getCode(); - if (code > 0) { - result = Map.ofEntries( - Map.entry("code", code), - Map.entry("error", myForbiddenException.getMessage()) - ); - } - else { - result = Map.ofEntries( - Map.entry("error", myForbiddenException.getMessage()) - ); - } - } - case MyValidationException myValidationException -> { - logLevel = System.Logger.Level.DEBUG; - statusCode = HttpStatus.BAD_REQUEST; - int code = myValidationException.getCode(); - if (code > 0) { - result = Map.ofEntries( - Map.entry("code", code), - Map.entry("error", myValidationException.getMessage()), - Map.entry("message", myValidationException.getErrors()) - ); - } - else { - result = Map.ofEntries( - Map.entry("error", myValidationException.getMessage()), - Map.entry("message", myValidationException.getErrors()) - ); - } - } - case MyApplicationException myApplicationException -> { - logLevel = System.Logger.Level.ERROR; - statusCode = HttpStatus.INTERNAL_SERVER_ERROR; - int code = myApplicationException.getCode(); - if (code > 0) { - result = Map.ofEntries( - Map.entry("code", code), - Map.entry("error", myApplicationException.getMessage()) - ); - } - else { - result = Map.ofEntries( - Map.entry("error", myApplicationException.getMessage()) - ); - } - } - default -> { - logLevel = System.Logger.Level.ERROR; - statusCode = HttpStatus.INTERNAL_SERVER_ERROR; - result = Map.ofEntries( - Map.entry("error", "System error") - ); - } - } - String serialization = this.jsonHandlingService.toJsonSafe(result); - return new HandledException(statusCode, serialization, logLevel); - } - - public static class HandledException{ - public HttpStatus statusCode; - public String message; - public System.Logger.Level level; - - public HandledException(HttpStatus statusCode, String message, System.Logger.Level level) { - this.statusCode = statusCode; - this.message = message; - this.level = level; - } - - public HttpStatus getStatusCode() { - return statusCode; - } - - public void setStatusCode(HttpStatus statusCode) { - this.statusCode = statusCode; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public System.Logger.Level getLevel() { - return level; - } - - public void setLevel(System.Logger.Level level) { - this.level = level; - } - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllers/AnnotationController.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllers/AnnotationController.java deleted file mode 100644 index a318ad8e2..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllers/AnnotationController.java +++ /dev/null @@ -1,132 +0,0 @@ -package gr.cite.annotation.web.controllers; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.annotation.audit.AuditableAction; -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.data.AnnotationEntity; -import gr.cite.annotation.model.Annotation; -import gr.cite.annotation.model.builder.AnnotationBuilder; -import gr.cite.annotation.model.censorship.AnnotationCensor; -import gr.cite.annotation.model.persist.AnnotationPersist; -import gr.cite.annotation.query.AnnotationQuery; -import gr.cite.annotation.query.lookup.AnnotationLookup; -import gr.cite.annotation.service.annotation.AnnotationService; -import gr.cite.annotation.web.model.QueryResult; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.censor.CensorFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.exception.MyNotFoundException; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import gr.cite.tools.validation.ValidationFilterAnnotation; -import jakarta.transaction.Transactional; -import jakarta.xml.bind.JAXBException; -import org.slf4j.LoggerFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.*; - -import javax.management.InvalidApplicationException; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerException; -import java.util.AbstractMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -@RestController -@RequestMapping(path = "api/annotation", produces = MediaType.APPLICATION_JSON_VALUE) -public class AnnotationController { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AnnotationController.class)); - - private final CensorFactory censorFactory; - - private final QueryFactory queryFactory; - - private final BuilderFactory builderFactory; - - private final AuditService auditService; - - private final MessageSource messageSource; - - private final AnnotationService annotationService; - - public AnnotationController(CensorFactory censorFactory, QueryFactory queryFactory, BuilderFactory builderFactory, AuditService auditService, MessageSource messageSource, AnnotationService annotationService) { - this.censorFactory = censorFactory; - this.queryFactory = queryFactory; - this.builderFactory = builderFactory; - this.auditService = auditService; - this.messageSource = messageSource; - this.annotationService = annotationService; - } - - @PostMapping("query") - public QueryResult query(@RequestBody AnnotationLookup lookup) { - logger.debug("querying {}", Annotation.class.getSimpleName()); - - this.censorFactory.censor(AnnotationCensor.class).censor(lookup.getProject(), null); - - AnnotationQuery query = lookup.enrich(this.queryFactory).disableTracking().authorize(AuthorizationFlags.OwnerOrPermissionAssociated); - List data = query.collect(); - List models = this.builderFactory.builder(AnnotationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermissionAssociated).build(lookup.getProject(), data); - long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size(); - - this.auditService.track(AuditableAction.Annotation_Query, "lookup", lookup); - - return new QueryResult<>(models, count); - } - - @GetMapping("{id}") - public Annotation get(@PathVariable("id") UUID id, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException { - logger.debug(new MapLogEntry("retrieving" + Annotation.class.getSimpleName()).And("id", id).And("fields", fieldSet)); - - this.censorFactory.censor(AnnotationCensor.class).censor(fieldSet, null); - - AnnotationQuery query = this.queryFactory.query(AnnotationQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrPermissionAssociated).ids(id); - Annotation model = this.builderFactory.builder(AnnotationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermissionAssociated).build(fieldSet, query.firstAs(fieldSet)); - if (model == null) - throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, Annotation.class.getSimpleName()}, LocaleContextHolder.getLocale())); - - this.auditService.track(AuditableAction.Annotation_Lookup, Map.ofEntries( - new AbstractMap.SimpleEntry("id", id), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - - return model; - } - - @PostMapping("persist") - @Transactional - @ValidationFilterAnnotation(validator = AnnotationPersist.AnnotationPersistValidator.ValidatorName, argumentName = "model") - public Annotation persist(@RequestBody AnnotationPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException { - logger.debug(new MapLogEntry("persisting" + Annotation.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); - - this.censorFactory.censor(AnnotationCensor.class).censor(fieldSet, null); - - Annotation persisted = this.annotationService.persist(model, fieldSet); - - this.auditService.track(AuditableAction.Annotation_Persist, Map.ofEntries( - new AbstractMap.SimpleEntry("model", model), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - - return persisted; - } - - @DeleteMapping("{id}") - @Transactional - public void delete(@PathVariable("id") UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug(new MapLogEntry("retrieving" + Annotation.class.getSimpleName()).And("id", id)); - - this.annotationService.deleteAndSave(id); - - this.auditService.track(AuditableAction.Annotation_Delete, "id", id); - } - -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllers/PrincipalController.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllers/PrincipalController.java deleted file mode 100644 index 4850e8641..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/controllers/PrincipalController.java +++ /dev/null @@ -1,76 +0,0 @@ -package gr.cite.annotation.web.controllers; - -import gr.cite.annotation.authorization.ClaimNames; -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.MyPrincipal; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; -import gr.cite.annotation.audit.AuditableAction; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.web.model.Account; -import gr.cite.annotation.web.model.AccountBuilder; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; -import java.util.stream.Collectors; - -@RestController -@RequestMapping(path = "api/annotation/principal", produces = MediaType.APPLICATION_JSON_VALUE) -public class PrincipalController { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(PrincipalController.class)); - private final AuditService auditService; - - private final CurrentPrincipalResolver currentPrincipalResolver; - private final AccountBuilder accountBuilder; - - @Autowired - public PrincipalController( - CurrentPrincipalResolver currentPrincipalResolver, - AccountBuilder accountBuilder, - AuditService auditService) { - this.currentPrincipalResolver = currentPrincipalResolver; - this.accountBuilder = accountBuilder; - this.auditService = auditService; - } - - @GetMapping("me") - public Account me(FieldSet fieldSet) { - logger.debug("me"); - - - if (fieldSet == null || fieldSet.isEmpty()) { - fieldSet = new BaseFieldSet( - Account._isAuthenticated, - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._subject), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._userId), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._name), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._scope), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._client), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._issuedAt), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._notBefore), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._authenticatedAt), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._expiresAt), - BaseFieldSet.asIndexer(Account._principal, Account.PrincipalInfo._more), - Account._permissions); - } - - MyPrincipal principal = this.currentPrincipalResolver.currentPrincipal(); - - Account me = this.accountBuilder.build(fieldSet, principal); - - this.auditService.track(AuditableAction.Principal_Lookup); - //auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return me; - - } - -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/Account.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/Account.java deleted file mode 100644 index d92dcf6d2..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/Account.java +++ /dev/null @@ -1,160 +0,0 @@ -package gr.cite.annotation.web.model; - -import gr.cite.tools.logging.annotation.LogSensitive; - -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class Account { - - public static class PrincipalInfo { - - public static final String _userId = "userId"; - public UUID userId; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public static final String _subject = "subject"; - public UUID subject; - - public UUID getSubject() { - return subject; - } - - public void setSubject(UUID subject) { - this.subject = subject; - } - - public static final String _name = "name"; - @LogSensitive - public String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public static final String _scope = "scope"; - public List scope; - - public List getScope() { - return scope; - } - - public void setScope(List scope) { - this.scope = scope; - } - - public static final String _client = "client"; - public String client; - - public String getClient() { - return client; - } - - public void setClient(String client) { - this.client = client; - } - - public static final String _notBefore = "notBefore"; - public Instant notBefore; - - public Instant getNotBefore() { - return notBefore; - } - - public void setNotBefore(Instant notBefore) { - this.notBefore = notBefore; - } - - public static final String _issuedAt = "issuedAt"; - public Instant issuedAt; - - public Instant getIssuedAt() { - return issuedAt; - } - - public void setIssuedAt(Instant issuedAt) { - this.issuedAt = issuedAt; - } - - public static final String _authenticatedAt = "authenticatedAt"; - public Instant authenticatedAt; - - public Instant getAuthenticatedAt() { - return authenticatedAt; - } - - public void setAuthenticatedAt(Instant authenticatedAt) { - this.authenticatedAt = authenticatedAt; - } - - public static final String _expiresAt = "expiresAt"; - public Instant expiresAt; - - public Instant getExpiresAt() { - return expiresAt; - } - - public void setExpiresAt(Instant expiresAt) { - this.expiresAt = expiresAt; - } - - public static final String _more = "more"; - @LogSensitive - public Map> more; - - public Map> getMore() { - return more; - } - - public void setMore(Map> more) { - this.more = more; - } - } - - - public static final String _isAuthenticated = "isAuthenticated"; - private Boolean isAuthenticated; - - public Boolean getIsAuthenticated() { - return isAuthenticated; - } - - public void setIsAuthenticated(Boolean authenticated) { - isAuthenticated = authenticated; - } - - public static final String _principal = "principal"; - private PrincipalInfo principal; - - public PrincipalInfo getPrincipal() { - return principal; - } - - public void setPrincipal(PrincipalInfo principal) { - this.principal = principal; - } - - public static final String _permissions = "permissions"; - private List permissions; - - public List getPermissions() { - return permissions; - } - - public void setPermissions(List permissions) { - this.permissions = permissions; - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/AccountBuilder.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/AccountBuilder.java deleted file mode 100644 index de36df03c..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/AccountBuilder.java +++ /dev/null @@ -1,86 +0,0 @@ -package gr.cite.annotation.web.model; - -import gr.cite.commons.web.authz.configuration.AuthorizationConfiguration; -import gr.cite.commons.web.authz.configuration.Permission; -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.MyPrincipal; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorKeys; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.fieldset.FieldSet; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.*; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class AccountBuilder { - - private final ClaimExtractor claimExtractor; - private final Set excludeMoreClaim; - private final AuthorizationConfiguration authorizationConfiguration; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final UserScope userScope; - - public AccountBuilder(ClaimExtractor claimExtractor, AuthorizationConfiguration authorizationConfiguration, CurrentPrincipalResolver currentPrincipalResolver, UserScope userScope) { - this.claimExtractor = claimExtractor; - this.authorizationConfiguration = authorizationConfiguration; - this.currentPrincipalResolver = currentPrincipalResolver; - this.userScope = userScope; - this.excludeMoreClaim = Set.of( - ClaimExtractorKeys.Subject, - ClaimExtractorKeys.Name, - ClaimExtractorKeys.Scope, - ClaimExtractorKeys.Client, - ClaimExtractorKeys.IssuedAt, - ClaimExtractorKeys.NotBefore, - ClaimExtractorKeys.AuthenticatedAt, - ClaimExtractorKeys.ExpiresAt); - } - - public Account build(FieldSet fields, MyPrincipal principal) { - Account model = new Account(); - if (principal == null || !principal.isAuthenticated()) { - model.setIsAuthenticated(false); - return model; - } - model.setIsAuthenticated(true); - - FieldSet principalFields = fields.extractPrefixed(BaseFieldSet.asIndexerPrefix(Account._principal)); - if (!principalFields.isEmpty()) model.setPrincipal(new Account.PrincipalInfo()); - if (principalFields.hasField(Account.PrincipalInfo._subject)) model.getPrincipal().setSubject(this.claimExtractor.subjectUUID(principal)); - if (principalFields.hasField(Account.PrincipalInfo._userId)) model.getPrincipal().setUserId(this.userScope.getUserIdSafe()); - if (principalFields.hasField(Account.PrincipalInfo._name)) model.getPrincipal().setName(this.claimExtractor.name(principal)); - if (principalFields.hasField(Account.PrincipalInfo._scope)) model.getPrincipal().setScope(this.claimExtractor.scope(principal)); - if (principalFields.hasField(Account.PrincipalInfo._client)) model.getPrincipal().setClient(this.claimExtractor.client(principal)); - if (principalFields.hasField(Account.PrincipalInfo._issuedAt)) model.getPrincipal().setIssuedAt(this.claimExtractor.issuedAt(principal)); - if (principalFields.hasField(Account.PrincipalInfo._notBefore)) model.getPrincipal().setNotBefore(this.claimExtractor.notBefore(principal)); - if (principalFields.hasField(Account.PrincipalInfo._authenticatedAt)) model.getPrincipal().setAuthenticatedAt(this.claimExtractor.authenticatedAt(principal)); - if (principalFields.hasField(Account.PrincipalInfo._expiresAt)) model.getPrincipal().setExpiresAt(this.claimExtractor.expiresAt(principal)); - if (principalFields.hasField(Account.PrincipalInfo._more)) { - model.getPrincipal().setMore(new HashMap<>()); - for (String key : this.claimExtractor.knownPublicKeys()) { - if (this.excludeMoreClaim.contains(key)) continue; - List values = this.claimExtractor.asStrings(principal, key); - if (values == null || values.size() == 0) continue; - if (!model.getPrincipal().getMore().containsKey(key)) model.getPrincipal().getMore().put(key, new ArrayList<>()); - model.getPrincipal().getMore().get(key).addAll(values); - } - } - - if (fields.hasField(Account._permissions)) { - List roles = claimExtractor.roles(currentPrincipalResolver.currentPrincipal()); - Set permissions = authorizationConfiguration.permissionsOfRoles(roles); - for (Map.Entry permissionEntry : authorizationConfiguration.getRawPolicies().entrySet()){ - if (permissionEntry.getValue().getAllowAuthenticated()){ - permissions.add(permissionEntry.getKey()); - } - } - model.setPermissions(new ArrayList<>(permissions)); - } - return model; - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/QueryResult.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/QueryResult.java deleted file mode 100644 index 13ccd82b5..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/model/QueryResult.java +++ /dev/null @@ -1,37 +0,0 @@ -package gr.cite.annotation.web.model; - -import java.util.ArrayList; -import java.util.List; - -public class QueryResult { - public QueryResult() { } - public QueryResult(List items, long count) - { - this.items = items; - this.count = count; - } - - public List items; - public long count; - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } - - public long getCount() { - return count; - } - - public void setCount(long count) { - this.count = count; - } - - public static QueryResult Empty() - { - return new QueryResult<>(new ArrayList<>(), 0L); - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByCodeCacheOptions.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByCodeCacheOptions.java deleted file mode 100644 index 3836bd8b3..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByCodeCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - -import gr.cite.tools.cache.CacheOptions; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "cache.tenant-by-code") -public class TenantByCodeCacheOptions extends CacheOptions { -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByCodeCacheService.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByCodeCacheService.java deleted file mode 100644 index 45d7fdc1f..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByCodeCacheService.java +++ /dev/null @@ -1,76 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.event.TenantTouchedEvent; -import gr.cite.tools.cache.CacheService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.UUID; - -@Service -public class TenantByCodeCacheService extends CacheService { - - public static class TenantByCodeCacheValue { - - public TenantByCodeCacheValue() { - } - - public TenantByCodeCacheValue(String tenantCode, UUID tenantId) { - this.tenantCode = tenantCode; - this.tenantId = tenantId; - } - - private String tenantCode; - - public String getTenantCode() { - return tenantCode; - } - - public void setTenantCode(String tenantCode) { - this.tenantCode = tenantCode; - } - - private UUID tenantId; - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - } - - private final ConventionService conventionService; - - @Autowired - public TenantByCodeCacheService(TenantByCodeCacheOptions options, ConventionService conventionService) { - super(options); - this.conventionService = conventionService; - } - - @EventListener - public void handleTenantTouchedEvent(TenantTouchedEvent event) { - if (!this.conventionService.isNullOrEmpty(event.getTenantCode())) - this.evict(this.buildKey(event.getTenantCode())); - } - - @Override - protected Class valueClass() { - return TenantByCodeCacheValue.class; - } - - @Override - public String keyOf(TenantByCodeCacheValue value) { - return this.buildKey(value.getTenantCode()); - } - - public String buildKey(String code) { - HashMap keyParts = new HashMap<>(); - keyParts.put("$code$", code); - return this.generateKey(keyParts); - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByIdCacheOptions.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByIdCacheOptions.java deleted file mode 100644 index 9de5b4803..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByIdCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - -import gr.cite.tools.cache.CacheOptions; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "cache.tenant-by-id") -public class TenantByIdCacheOptions extends CacheOptions { -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByIdCacheService.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByIdCacheService.java deleted file mode 100644 index e6f7c8469..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantByIdCacheService.java +++ /dev/null @@ -1,75 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.event.TenantTouchedEvent; -import gr.cite.tools.cache.CacheService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.Locale; -import java.util.UUID; - -@Service -public class TenantByIdCacheService extends CacheService { - - public static class TenantByIdCacheValue { - - public TenantByIdCacheValue() { - } - - public TenantByIdCacheValue(String tenantCode, UUID tenantId) { - this.tenantCode = tenantCode; - this.tenantId = tenantId; - } - - private String tenantCode; - - public String getTenantCode() { - return tenantCode; - } - - public void setTenantCode(String tenantCode) { - this.tenantCode = tenantCode; - } - - private UUID tenantId; - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - } - - - @Autowired - public TenantByIdCacheService(TenantByIdCacheOptions options) { - super(options); - } - - @EventListener - public void handleTenantTouchedEvent(TenantTouchedEvent event) { - if (event.getTenantId() != null) - this.evict(this.buildKey(event.getTenantId())); - } - - @Override - protected Class valueClass() { - return TenantByIdCacheValue.class; - } - - @Override - public String keyOf(TenantByIdCacheValue value) { - return this.buildKey(value.getTenantId()); - } - - public String buildKey(UUID id) { - HashMap keyParts = new HashMap<>(); - keyParts.put("$tenantId$", id.toString().toLowerCase(Locale.ROOT)); - return this.generateKey(keyParts); - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantInterceptor.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantInterceptor.java deleted file mode 100644 index 70dc50be4..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantInterceptor.java +++ /dev/null @@ -1,183 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - - -import gr.cite.annotation.authorization.ClaimNames; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.data.TenantUserEntity; -import gr.cite.annotation.data.UserEntity; -import gr.cite.annotation.data.tenant.TenantScopedBaseEntity; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.annotation.query.utils.BuildSubQueryInput; -import gr.cite.annotation.query.utils.QueryUtilsService; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; -import org.hibernate.Session; -import org.jetbrains.annotations.NotNull; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Component; -import org.springframework.ui.ModelMap; -import org.springframework.web.context.request.ServletWebRequest; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.WebRequestInterceptor; - -import javax.management.InvalidApplicationException; -import java.util.List; -import java.util.Locale; -import java.util.UUID; - -@Component -public class TenantInterceptor implements WebRequestInterceptor { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantInterceptor.class)); - private final TenantScope tenantScope; - private final UserScope userScope; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractor claimExtractor; - private final ApplicationContext applicationContext; - private final TenantScopeProperties tenantScopeProperties; - private final UserAllowedTenantCacheService userAllowedTenantCacheService; - private final ErrorThesaurusProperties errors; - private final QueryUtilsService queryUtilsService; - public final TenantEntityManager tenantEntityManager; - @PersistenceContext - public EntityManager entityManager; - - @Autowired - public TenantInterceptor( - TenantScope tenantScope, - UserScope userScope, - CurrentPrincipalResolver currentPrincipalResolver, - ClaimExtractor claimExtractor, - ApplicationContext applicationContext, - TenantScopeProperties tenantScopeProperties, - UserAllowedTenantCacheService userAllowedTenantCacheService, - ErrorThesaurusProperties errors, QueryUtilsService queryUtilsService, TenantEntityManager tenantEntityManager) { - this.tenantScope = tenantScope; - this.userScope = userScope; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractor = claimExtractor; - this.applicationContext = applicationContext; - this.tenantScopeProperties = tenantScopeProperties; - this.userAllowedTenantCacheService = userAllowedTenantCacheService; - this.errors = errors; - this.queryUtilsService = queryUtilsService; - this.tenantEntityManager = tenantEntityManager; - } - - @Override - public void preHandle(@NotNull WebRequest request) throws InvalidApplicationException, InterruptedException { - if (!this.currentPrincipalResolver.currentPrincipal().isAuthenticated()) return; - if (!this.tenantScope.isMultitenant()) return; - - boolean isAllowedNoTenant = this.applicationContext.getBean(AuthorizationService.class).authorize(Permission.AllowNoTenant); - if (tenantScope.isSet() && this.entityManager != null) { - List currentPrincipalTenantCodes = this.claimExtractor.asStrings(this.currentPrincipalResolver.currentPrincipal(), ClaimNames.TenantCodesClaimName); - if ((currentPrincipalTenantCodes == null || !currentPrincipalTenantCodes.contains(tenantScope.getTenantCode())) && !isAllowedNoTenant) { - logger.warn("tenant not allowed {}", this.tenantScope.getTenant()); - throw new MyForbiddenException(this.errors.getTenantNotAllowed().getCode(), this.errors.getTenantNotAllowed().getMessage()); - } - - boolean isUserAllowedTenant = false; - if (this.tenantScope.isDefaultTenant()){ - isUserAllowedTenant = true; - } else { - UserAllowedTenantCacheService.UserAllowedTenantCacheValue cacheValue = this.userAllowedTenantCacheService.lookup(this.userAllowedTenantCacheService.buildKey(this.userScope.getUserId(), this.tenantScope.getTenant())); - if (cacheValue != null) { - isUserAllowedTenant = cacheValue.isAllowed(); - } else { - isUserAllowedTenant = this.isUserAllowedTenant(); - this.userAllowedTenantCacheService.put(new UserAllowedTenantCacheService.UserAllowedTenantCacheValue(this.userScope.getUserId(), this.tenantScope.getTenant(), isUserAllowedTenant)); - } - } - - if (isUserAllowedTenant) { - this.tenantEntityManager.reloadTenantFilters(); - } else { - if (isAllowedNoTenant || this.isWhiteListedEndpoint(request)) { - tenantScope.setTenant(null, null); - } else { - logger.warn("tenant not allowed {}", this.tenantScope.getTenant()); - throw new MyForbiddenException(this.errors.getTenantNotAllowed().getCode(), this.errors.getTenantNotAllowed().getMessage()); - } - } - } else { - if (!isAllowedNoTenant) { - if (!this.isWhiteListedEndpoint(request)) { - logger.warn("tenant scope not provided"); - throw new MyForbiddenException(this.errors.getMissingTenant().getCode(), this.errors.getMissingTenant().getMessage()); - } - } - } - } - - private boolean isWhiteListedEndpoint(WebRequest request) { - String servletPath = ((ServletWebRequest) request).getRequest().getServletPath(); - if (this.tenantScopeProperties.getWhiteListedEndpoints() != null) { - for (String whiteListedEndpoint : this.tenantScopeProperties.getWhiteListedEndpoints()) { - if (servletPath.toLowerCase(Locale.ROOT).startsWith(whiteListedEndpoint.toLowerCase(Locale.ROOT))) { - return true; - } - } - } - return false; - } - - private boolean isUserAllowedTenant() throws InvalidApplicationException, InterruptedException { - if (userScope.isSet()) { - CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); - CriteriaQuery query = criteriaBuilder.createQuery(UserEntity.class); - Root root = query.from(UserEntity.class); - query.where(criteriaBuilder.and( - criteriaBuilder.equal(root.get(UserEntity._isActive), IsActive.Active), - criteriaBuilder.in(root.get(UserEntity._id)).value(queryUtilsService.buildSubQuery(new BuildSubQueryInput<>(new BuildSubQueryInput.Builder<>(TenantUserEntity.class, UUID.class) - .query(query) - .criteriaBuilder(criteriaBuilder) - .keyPathFunc((subQueryRoot) -> subQueryRoot.get(TenantUserEntity._userId)) - .filterFunc((subQueryRoot, cb) -> - { - try { - return cb.and( - criteriaBuilder.equal(subQueryRoot.get(TenantUserEntity._tenantId), this.tenantScope.getTenant()), - criteriaBuilder.equal(subQueryRoot.get(TenantUserEntity._userId), this.userScope.getUserId()), - criteriaBuilder.equal(subQueryRoot.get(TenantUserEntity._isActive), IsActive.Active) - ); - } catch (InvalidApplicationException e) { - throw new RuntimeException(e); - } - } - ) - )) - ) - )); - query.multiselect(root.get(UserEntity._id).alias(UserEntity._id)); - List results = this.entityManager.createQuery(query).getResultList(); - return !results.isEmpty(); - } - - return false; - } - - @Override - public void postHandle(@NonNull WebRequest request, ModelMap model) { - this.tenantScope.setTenant(null, null); - this.tenantEntityManager.disableTenantFilters(); - } - @Override - public void afterCompletion(@NonNull WebRequest request, Exception ex) { - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeClaimInterceptor.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeClaimInterceptor.java deleted file mode 100644 index ca58331e6..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeClaimInterceptor.java +++ /dev/null @@ -1,184 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - - -import gr.cite.annotation.authorization.ClaimNames; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.data.TenantEntity; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.MyPrincipal; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorContext; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; -import org.jetbrains.annotations.NotNull; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Component; -import org.springframework.ui.ModelMap; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.WebRequestInterceptor; - -import javax.management.InvalidApplicationException; -import java.util.List; -import java.util.UUID; - -@Component -public class TenantScopeClaimInterceptor implements WebRequestInterceptor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantScopeClaimInterceptor.class)); - private final TenantScope tenantScope; - private final ConventionService conventionService; - private final TenantScopeProperties tenantScopeProperties; - private final ErrorThesaurusProperties errorThesaurusProperties; - private final ClaimExtractor claimExtractor; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final String clientTenantClaimName; - private final ClaimExtractorContext claimExtractorContext; - private final TenantByCodeCacheService tenantByCodeCacheService; - private final TenantByIdCacheService tenantByIdCacheService; - @PersistenceContext - public EntityManager entityManager; - - @Autowired - public TenantScopeClaimInterceptor( - TenantScope tenantScope, - ConventionService conventionService, - ClaimExtractor claimExtractor, - CurrentPrincipalResolver currentPrincipalResolver, - ErrorThesaurusProperties errorThesaurusProperties, - TenantScopeProperties tenantScopeProperties, - ClaimExtractorContext claimExtractorContext, - TenantByCodeCacheService tenantByCodeCacheService, - TenantByIdCacheService tenantByIdCacheService - ) { - this.tenantScope = tenantScope; - this.conventionService = conventionService; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractor = claimExtractor; - this.errorThesaurusProperties = errorThesaurusProperties; - this.tenantScopeProperties = tenantScopeProperties; - this.claimExtractorContext = claimExtractorContext; - this.tenantByCodeCacheService = tenantByCodeCacheService; - this.tenantByIdCacheService = tenantByIdCacheService; - this.clientTenantClaimName = this.tenantScopeProperties.getClientClaimsPrefix() + ClaimNames.TenantClaimName; - } - - @Override - public void preHandle(@NotNull WebRequest request) throws InvalidApplicationException { - if (!this.currentPrincipalResolver.currentPrincipal().isAuthenticated()) return; - if (!this.tenantScope.isMultitenant()) return; - - MyPrincipal principal = this.currentPrincipalResolver.currentPrincipal(); - if (principal != null && principal.isAuthenticated() /* principal.Claims.Any() */) { - boolean scoped = this.scopeByPrincipal(principal); - if (!scoped) scoped = this.scopeByClient(principal); - if (!scoped && this.tenantScope.isSet() && this.tenantScopeProperties.getEnforceTrustedTenant()) - throw new MyForbiddenException(this.errorThesaurusProperties.getMissingTenant().getCode(), this.errorThesaurusProperties.getMissingTenant().getMessage()); - } - } - - private boolean scopeByPrincipal(MyPrincipal principal) { - String tenantCode = this.claimExtractor.tenantString(principal); - if (this.conventionService.isNullOrEmpty(tenantCode)) tenantCode = this.claimExtractor.asString(principal, this.clientTenantClaimName); - if (tenantCode == null || this.conventionService.isNullOrEmpty(tenantCode)) return false; - - if (tenantCode.equalsIgnoreCase(this.tenantScope.getDefaultTenantCode())){ - logger.debug("parsed tenant header and set tenant to default tenant"); - this.tenantScope.setTenant(null, tenantCode); - this.claimExtractorContext.putReplaceParameter(TenantScope.TenantReplaceParameter, tenantCode); - return true; - } - - UUID tenantId = this.conventionService.parseUUIDSafe(tenantCode); - if (tenantId == null) { - TenantByCodeCacheService.TenantByCodeCacheValue cacheValue = this.tenantByCodeCacheService.lookup(this.tenantByCodeCacheService.buildKey(tenantCode)); - if (cacheValue != null) { - tenantId = cacheValue.getTenantId(); - } else { - tenantId = this.getTenantIdFromDatabase(tenantCode); - this.tenantByCodeCacheService.put(new TenantByCodeCacheService.TenantByCodeCacheValue(tenantCode, tenantId)); - this.tenantByIdCacheService.put(new TenantByIdCacheService.TenantByIdCacheValue(tenantCode, tenantId)); - } - } else { - logger.debug("tenant claim was set to {}", tenantId); - TenantByIdCacheService.TenantByIdCacheValue cacheValue = this.tenantByIdCacheService.lookup(this.tenantByIdCacheService.buildKey(tenantId)); - - if (cacheValue != null) { - tenantCode = cacheValue.getTenantCode(); - } else { - tenantCode = this.getTenantCodeFromDatabase(tenantId); - this.tenantByCodeCacheService.put(new TenantByCodeCacheService.TenantByCodeCacheValue(tenantCode, tenantId)); - this.tenantByIdCacheService.put(new TenantByIdCacheService.TenantByIdCacheValue(tenantCode, tenantId)); - } - } - - if (tenantId != null) { - logger.debug("parsed tenant header and set tenant id to {}", tenantId); - this.tenantScope.setTenant(tenantId, tenantCode); - this.claimExtractorContext.putReplaceParameter(TenantScope.TenantReplaceParameter, tenantCode); - return true; - } - return false; - } - - private boolean scopeByClient(MyPrincipal principal) throws InvalidApplicationException { - String client = this.claimExtractor.client(principal); - - Boolean isWhiteListed = this.tenantScopeProperties.getWhiteListedClients() != null && !this.conventionService.isNullOrEmpty(client) && this.tenantScopeProperties.getWhiteListedClients().contains(client); - logger.debug("client is whitelisted : {}, scope is set: {}, with value {}", isWhiteListed, this.tenantScope.isSet(), (this.tenantScope.isSet() ? this.tenantScope.getTenant() : null)); - - return isWhiteListed && this.tenantScope.isSet(); - } - - private UUID getTenantIdFromDatabase(String tenantCode) { - CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); - CriteriaQuery query = criteriaBuilder.createQuery(TenantEntity.class); - Root root = query.from(TenantEntity.class); - query = query.where( - criteriaBuilder.and( - criteriaBuilder.equal(root.get(TenantEntity._code), tenantCode), - criteriaBuilder.equal(root.get(TenantEntity._isActive), IsActive.Active) - ) - ).multiselect(root.get(TenantEntity._id).alias(TenantEntity._id)); - List results = this.entityManager.createQuery(query).getResultList(); - if (results.size() == 1) { - return results.getFirst().getId(); - } - return null; - } - - private String getTenantCodeFromDatabase(UUID tenantId) { - CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); - CriteriaQuery query = criteriaBuilder.createQuery(TenantEntity.class); - Root root = query.from(TenantEntity.class); - query = query.where( - criteriaBuilder.and( - criteriaBuilder.equal(root.get(TenantEntity._id), tenantId), - criteriaBuilder.equal(root.get(TenantEntity._isActive), IsActive.Active) - ) - ).multiselect(root.get(TenantEntity._code).alias(TenantEntity._code)); - List results = this.entityManager.createQuery(query).getResultList(); - if (results.size() == 1) { - return results.getFirst().getCode(); - } - return null; - } - - @Override - public void postHandle(@NonNull WebRequest request, ModelMap model) { - this.tenantScope.setTenant(null, null); - this.claimExtractorContext.removeReplaceParameter(TenantScope.TenantReplaceParameter); - } - - @Override - public void afterCompletion(@NonNull WebRequest request, Exception ex) { - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeConfiguration.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeConfiguration.java deleted file mode 100644 index 5a1d50b06..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties(TenantScopeProperties.class) -public class TenantScopeConfiguration { -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeHeaderInterceptor.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeHeaderInterceptor.java deleted file mode 100644 index cce792db8..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeHeaderInterceptor.java +++ /dev/null @@ -1,146 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - - -import gr.cite.annotation.authorization.ClaimNames; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.data.TenantEntity; -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorContext; -import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; -import org.jetbrains.annotations.NotNull; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Component; -import org.springframework.ui.ModelMap; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.WebRequestInterceptor; - -import java.util.List; -import java.util.UUID; - -@Component -public class TenantScopeHeaderInterceptor implements WebRequestInterceptor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantScopeHeaderInterceptor.class)); - private final TenantScope tenantScope; - private final ConventionService conventionService; - private final TenantByCodeCacheService tenantByCodeCacheService; - private final TenantByIdCacheService tenantByIdCacheService; - private final ClaimExtractorContext claimExtractorContext; - private final CurrentPrincipalResolver currentPrincipalResolver; - @PersistenceContext - public EntityManager entityManager; - - @Autowired - public TenantScopeHeaderInterceptor( - TenantScope tenantScope, - ConventionService conventionService, - TenantByCodeCacheService tenantByCodeCacheService, - TenantByIdCacheService tenantByIdCacheService, - ClaimExtractorContext claimExtractorContext, - CurrentPrincipalResolver currentPrincipalResolver - ) { - this.tenantScope = tenantScope; - this.conventionService = conventionService; - this.tenantByCodeCacheService = tenantByCodeCacheService; - this.tenantByIdCacheService = tenantByIdCacheService; - this.claimExtractorContext = claimExtractorContext; - this.currentPrincipalResolver = currentPrincipalResolver; - } - - @Override - public void preHandle(@NotNull WebRequest request) { - if (!this.currentPrincipalResolver.currentPrincipal().isAuthenticated()) return; - if (!this.tenantScope.isMultitenant()) return; - - String tenantCode = request.getHeader(ClaimNames.TenantClaimName); - logger.debug("retrieved request tenant header is: {}", tenantCode); - if (tenantCode == null || this.conventionService.isNullOrEmpty(tenantCode)) return; - - if (tenantCode.equalsIgnoreCase(this.tenantScope.getDefaultTenantCode())){ - logger.debug("parsed tenant header and set tenant to default tenant"); - this.tenantScope.setTenant(null, tenantCode); - this.claimExtractorContext.putReplaceParameter(TenantScope.TenantReplaceParameter, tenantCode); - return; - } - - UUID tenantId = this.conventionService.parseUUIDSafe(tenantCode); - if (tenantId == null) { - TenantByCodeCacheService.TenantByCodeCacheValue cacheValue = this.tenantByCodeCacheService.lookup(this.tenantByCodeCacheService.buildKey(tenantCode)); - if (cacheValue != null) { - tenantId = cacheValue.getTenantId(); - } else { - tenantId = this.getTenantIdFromDatabase(tenantCode); - this.tenantByCodeCacheService.put(new TenantByCodeCacheService.TenantByCodeCacheValue(tenantCode, tenantId)); - this.tenantByIdCacheService.put(new TenantByIdCacheService.TenantByIdCacheValue(tenantCode, tenantId)); - } - } else { - TenantByIdCacheService.TenantByIdCacheValue cacheValue = this.tenantByIdCacheService.lookup(this.tenantByIdCacheService.buildKey(tenantId)); - if (cacheValue != null) { - tenantCode = cacheValue.getTenantCode(); - } else { - tenantCode = this.getTenantCodeFromDatabase(tenantId); - this.tenantByCodeCacheService.put(new TenantByCodeCacheService.TenantByCodeCacheValue(tenantCode, tenantId)); - this.tenantByIdCacheService.put(new TenantByIdCacheService.TenantByIdCacheValue(tenantCode, tenantId)); - } - } - - if (tenantId != null) { - logger.debug("parsed tenant header and set tenant id to {}", tenantId); - this.tenantScope.setTenant(tenantId, tenantCode); - this.claimExtractorContext.putReplaceParameter(TenantScope.TenantReplaceParameter, tenantCode); - } - } - - private UUID getTenantIdFromDatabase(String tenantCode) { - CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); - CriteriaQuery query = criteriaBuilder.createQuery(TenantEntity.class); - Root root = query.from(TenantEntity.class); - query = query.where( - criteriaBuilder.and( - criteriaBuilder.equal(root.get(TenantEntity._code), tenantCode), - criteriaBuilder.equal(root.get(TenantEntity._isActive), IsActive.Active) - ) - ).multiselect(root.get(TenantEntity._id).alias(TenantEntity._id)); - List results = this.entityManager.createQuery(query).getResultList(); - if (results.size() == 1) { - return results.getFirst().getId(); - } - return null; - } - - private String getTenantCodeFromDatabase(UUID tenantId) { - CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); - CriteriaQuery query = criteriaBuilder.createQuery(TenantEntity.class); - Root root = query.from(TenantEntity.class); - query = query.where( - criteriaBuilder.and( - criteriaBuilder.equal(root.get(TenantEntity._id), tenantId), - criteriaBuilder.equal(root.get(TenantEntity._isActive), IsActive.Active) - ) - ).multiselect(root.get(TenantEntity._code).alias(TenantEntity._code)); - List results = this.entityManager.createQuery(query).getResultList(); - if (results.size() == 1) { - return results.getFirst().getCode(); - } - return null; - } - - @Override - public void postHandle(@NonNull WebRequest request, ModelMap model) { - - this.tenantScope.setTenant(null, null); - this.claimExtractorContext.removeReplaceParameter(TenantScope.TenantReplaceParameter); - } - - @Override - public void afterCompletion(@NonNull WebRequest request, Exception ex) { - } -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeProperties.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeProperties.java deleted file mode 100644 index 53e8e649f..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/TenantScopeProperties.java +++ /dev/null @@ -1,44 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.HashSet; -import java.util.List; - -@ConfigurationProperties(prefix = "tenant.interceptor") -public class TenantScopeProperties { - - private String clientClaimsPrefix; - public String getClientClaimsPrefix() { - return clientClaimsPrefix; - } - public void setClientClaimsPrefix(String clientClaimsPrefix) { - this.clientClaimsPrefix = clientClaimsPrefix; - } - - private HashSet whiteListedClients; - public HashSet getWhiteListedClients() { - return whiteListedClients; - } - public void setWhiteListedClients(HashSet whiteListedClients) { - this.whiteListedClients = whiteListedClients; - } - - private List whiteListedEndpoints; - public List getWhiteListedEndpoints() { - return whiteListedEndpoints; - } - public void setWhiteListedEndpoints(List whiteListedEndpoints) { - this.whiteListedEndpoints = whiteListedEndpoints; - } - - private Boolean enforceTrustedTenant; - public Boolean getEnforceTrustedTenant() { - return enforceTrustedTenant; - } - public void setEnforceTrustedTenant(Boolean enforceTrustedTenant) { - this.enforceTrustedTenant = enforceTrustedTenant; - } - -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/UserAllowedTenantCacheOptions.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/UserAllowedTenantCacheOptions.java deleted file mode 100644 index d6787db90..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/UserAllowedTenantCacheOptions.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - -import gr.cite.tools.cache.CacheOptions; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "cache.user-allowed-tenant") -public class UserAllowedTenantCacheOptions extends CacheOptions { -} - - diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/UserAllowedTenantCacheService.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/UserAllowedTenantCacheService.java deleted file mode 100644 index 8f32190ab..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/tenant/UserAllowedTenantCacheService.java +++ /dev/null @@ -1,91 +0,0 @@ -package gr.cite.annotation.web.scope.tenant; - -import gr.cite.annotation.event.UserAddedToTenantEvent; -import gr.cite.annotation.event.UserRemovedFromTenantEvent; -import gr.cite.tools.cache.CacheService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.Locale; -import java.util.UUID; - -@Service -public class UserAllowedTenantCacheService extends CacheService { - - public static class UserAllowedTenantCacheValue { - - public UserAllowedTenantCacheValue() { - } - - public UserAllowedTenantCacheValue(UUID userId, UUID tenantId, boolean isAllowed) { - this.userId = userId; - this.tenantId = tenantId; - this.isAllowed = isAllowed; - } - - private UUID userId; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - private UUID tenantId; - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - - private boolean isAllowed; - - public boolean isAllowed() { - return isAllowed; - } - - public void setAllowed(boolean allowed) { - isAllowed = allowed; - } - } - - @Autowired - public UserAllowedTenantCacheService(UserAllowedTenantCacheOptions options) { - super(options); - } - - @EventListener - public void handleUserRemovedFromTenantEvent(UserRemovedFromTenantEvent event) { - this.evict(this.buildKey(event.getUserId(), event.getTenantId())); - } - - @EventListener - public void handleUserAddedToTenantEvent(UserAddedToTenantEvent event) { - this.evict(this.buildKey(event.getUserId(), event.getTenantId())); - } - - @Override - protected Class valueClass() { - return UserAllowedTenantCacheValue.class; - } - - @Override - public String keyOf(UserAllowedTenantCacheValue value) { - return this.buildKey(value.getUserId(), value.getTenantId()); - } - - public String buildKey(UUID userId, UUID tenantId) { - HashMap keyParts = new HashMap<>(); - keyParts.put("$user_id$", userId.toString().toLowerCase(Locale.ROOT)); - keyParts.put("$tenant_id$", tenantId.toString().toLowerCase(Locale.ROOT)); - return this.generateKey(keyParts); - } -} - diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptor.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptor.java deleted file mode 100644 index 36e86189d..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptor.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.annotation.web.scope.user; - - -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.UserCredentialEntity; -import gr.cite.annotation.model.UserCredential; -import gr.cite.annotation.query.UserCredentialQuery; -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.fieldset.BaseFieldSet; -import org.jetbrains.annotations.NotNull; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Component; -import org.springframework.ui.ModelMap; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.WebRequestInterceptor; - -import java.util.UUID; - -@Component -public class UserInterceptor implements WebRequestInterceptor { - private final UserScope userScope; - private final ClaimExtractor claimExtractor; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final UserInterceptorCacheService userInterceptorCacheService; - private final QueryFactory queryFactory; - - @Autowired - public UserInterceptor( - UserScope userScope, - ClaimExtractor claimExtractor, - CurrentPrincipalResolver currentPrincipalResolver, - UserInterceptorCacheService userInterceptorCacheService, - QueryFactory queryFactory) { - this.userScope = userScope; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractor = claimExtractor; - this.userInterceptorCacheService = userInterceptorCacheService; - this.queryFactory = queryFactory; - } - - @Override - public void preHandle(@NotNull WebRequest request) { - UUID userId = null; - if (this.currentPrincipalResolver.currentPrincipal().isAuthenticated()) { - String subjectId = this.claimExtractor.subjectString(this.currentPrincipalResolver.currentPrincipal()); - if (subjectId == null || subjectId.isBlank()) throw new MyForbiddenException("Empty subjects not allowed"); - - UserInterceptorCacheService.UserInterceptorCacheValue cacheValue = this.userInterceptorCacheService.lookup(this.userInterceptorCacheService.buildKey(subjectId)); - if (cacheValue != null) { - userId = cacheValue.getUserId(); - } else { - userId = this.findExistingUserFromDb(subjectId); - if (userId != null) { - cacheValue = new UserInterceptorCacheService.UserInterceptorCacheValue(subjectId, userId); - this.userInterceptorCacheService.put(cacheValue); - } - } - } - this.userScope.setUserId(userId); - } - private UUID findExistingUserFromDb(String subjectId) { - UserCredentialEntity userCredential = this.queryFactory.query(UserCredentialQuery.class).disableTracking().externalIds(subjectId).firstAs(new BaseFieldSet().ensure(UserCredential._user)); - if (userCredential != null) { - return userCredential.getUserId(); - } - return null; - } - @Override - public void postHandle(@NonNull WebRequest request, ModelMap model) { - this.userScope.setUserId(null); - } - - @Override - public void afterCompletion(@NonNull WebRequest request, Exception ex) { - } -} - diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptorCacheOptions.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptorCacheOptions.java deleted file mode 100644 index d1e503a67..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptorCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.annotation.web.scope.user; - -import gr.cite.tools.cache.CacheOptions; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "cache.user-by-subject-id") -public class UserInterceptorCacheOptions extends CacheOptions { -} diff --git a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptorCacheService.java b/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptorCacheService.java deleted file mode 100644 index c3601fefe..000000000 --- a/annotation-service/annotation-web/src/main/java/gr/cite/annotation/web/scope/user/UserInterceptorCacheService.java +++ /dev/null @@ -1,77 +0,0 @@ -package gr.cite.annotation.web.scope.user; - -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.event.UserCredentialTouchedEvent; -import gr.cite.tools.cache.CacheService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.UUID; - -@Service -public class UserInterceptorCacheService extends CacheService { - private final ConventionService conventionService; - - public static class UserInterceptorCacheValue { - - public UserInterceptorCacheValue() { - } - - public UserInterceptorCacheValue(String subjectId, UUID userId) { - this.subjectId = subjectId; - this.userId = userId; - } - - - public String getSubjectId() { - return subjectId; - } - - public void setSubjectId(String subjectId) { - this.subjectId = subjectId; - } - - private String subjectId; - private UUID userId; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - } - - - - @EventListener - public void handleTenantTouchedEvent(UserCredentialTouchedEvent event) { - if (!this.conventionService.isNullOrEmpty(event.getSubjectId())) - this.evict(this.buildKey(event.getSubjectId())); - } - @Autowired - public UserInterceptorCacheService(UserInterceptorCacheOptions options, ConventionService conventionService){ - super(options); - this.conventionService = conventionService; - } - - @Override - protected Class valueClass() { - return UserInterceptorCacheValue.class; - } - - @Override - public String keyOf(UserInterceptorCacheValue value) { - return this.buildKey(value.getSubjectId()); - } - - - public String buildKey(String subject) { - HashMap keyParts = new HashMap<>(); - keyParts.put("$subject$", subject); - return this.generateKey(keyParts); - } -} diff --git a/annotation-service/annotation-web/src/main/resources/config/application.yml b/annotation-service/annotation-web/src/main/resources/config/application.yml deleted file mode 100644 index 8ed82b873..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/application.yml +++ /dev/null @@ -1,18 +0,0 @@ -spring: - jackson: - default-property-inclusion: non_null - config: - import: optional:classpath:config/app.env[.properties], optional:file:../config/app.env[.properties], - optional:classpath:config/db.yml[.yml], optional:classpath:config/db-${spring.profiles.active}.yml[.yml], optional:file:../config/db-${spring.profiles.active}.yml[.yml], - optional:classpath:config/permissions.yml[.yml], optional:classpath:config/permissions-${spring.profiles.active}.yml[.yml], optional:file:../config/permissions-${spring.profiles.active}.yml[.yml], - optional:classpath:config/errors.yml[.yml], optional:classpath:config/errors-${spring.profiles.active}.yml[.yml], optional:file:../config/errors-${spring.profiles.active}.yml[.yml], - optional:classpath:config/security.yml[.yml], optional:classpath:config/security-${spring.profiles.active}.yml[.yml], optional:file:../config/security-${spring.profiles.active}.yml[.yml], - optional:classpath:config/server.yml[.yml], optional:classpath:config/server-${spring.profiles.active}.yml[.yml], optional:file:../config/server-${spring.profiles.active}.yml[.yml], - optional:classpath:config/logging.yml[.yml], optional:classpath:config/logging-${spring.profiles.active}.yml[.yml], optional:file:../config/logging-${spring.profiles.active}.yml[.yml], - optional:classpath:config/idpclaims.yml[.yml], optional:classpath:config/idpclaims-${spring.profiles.active}.yml[.yml], optional:file:../config/idpclaims-${spring.profiles.active}.yml[.yml], - optional:classpath:config/cache.yml[.yml], optional:classpath:config/cache-${spring.profiles.active}.yml[.yml], optional:file:../config/cache-${spring.profiles.active}.yml[.yml], - optional:classpath:config/tenant.yml[.yml], optional:classpath:config/tenant-${spring.profiles.active}.yml[.yml], optional:file:../config/tenant-${spring.profiles.active}.yml[.yml], - optional:classpath:config/locale.yml[.yml], optional:classpath:config/locale-${spring.profiles.active}.yml[.yml], optional:file:../config/locale-${spring.profiles.active}.yml[.yml], - optional:classpath:config/cors.yml[.yml], optional:classpath:config/cors-${spring.profiles.active}.yml[.yml], optional:file:../config/cors-${spring.profiles.active}.yml[.yml], - optional:classpath:config/queue.yml[.yml], optional:classpath:config/queue-${spring.profiles.active}.yml[.yml], optional:file:../config/queue-${spring.profiles.active}.yml[.yml], - optional:classpath:config/cipher.yml[.yml], optional:classpath:config/cipher-${spring.profiles.active}.yml[.yml], optional:file:../config/cipher-${spring.profiles.active}.yml[.yml] diff --git a/annotation-service/annotation-web/src/main/resources/config/cache.yml b/annotation-service/annotation-web/src/main/resources/config/cache.yml deleted file mode 100644 index 3a935a5f1..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/cache.yml +++ /dev/null @@ -1,59 +0,0 @@ -cache: - manager: - fallbackToNoOpCache: true - caffeineCaches: - - names: [ apikey ] - allowNullValues: true - initialCapacity: 100 - maximumSize: 500 - enableRecordStats: false - expireAfterWriteSeconds: 600 - - names: [ tenantByCode ] - allowNullValues: true - initialCapacity: 100 - maximumSize: 500 - enableRecordStats: false - expireAfterWriteSeconds: 20 - - names: [ tenantById ] - allowNullValues: true - initialCapacity: 100 - maximumSize: 500 - enableRecordStats: false - expireAfterWriteSeconds: 20 - - names: [ userBySubjectId ] - allowNullValues: true - initialCapacity: 100 - maximumSize: 500 - enableRecordStats: false - expireAfterWriteSeconds: 20 - - names: [ userAccessTenant ] - allowNullValues: true - initialCapacity: 100 - maximumSize: 500 - enableRecordStats: false - expireAfterWriteSeconds: 20 - - names: [ "affiliation" ] - allowNullValues: true - initialCapacity: 100 - maximumSize: 5000 - enableRecordStats: false - expireAfterWriteSeconds: 20 - mapCaches: - apiKey: - name: apikey - keyPattern: ant_resolve_$keyhash$:v0 - userBySubjectId: - name: userBySubjectId - keyPattern: ant_user_by_subject_$subject$:v0 - tenantByCode: - name: tenantByCode - keyPattern: ant_tenant_by_code_$code$:v0 - tenantById: - name: tenantById - keyPattern: ant_tenant_by_id_$tenantId$:v0 - userAllowedTenant: - name: userAccessTenant - keyPattern: ant_user_access_tenant_$user_id$_$tenant_id$:v0 - affiliation: - name: affiliation - keyPattern: ant_affiliation_$entity$_$user$_$type$:v0 diff --git a/annotation-service/annotation-web/src/main/resources/config/cipher.yml b/annotation-service/annotation-web/src/main/resources/config/cipher.yml deleted file mode 100644 index caa559296..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/cipher.yml +++ /dev/null @@ -1,35 +0,0 @@ -cipher-profiles: - profile-map: - configuration-profile-name: "configuration" - queue-profile-name: "queue" - notification-profile-name: "queue" - -cipher: -# salted-hash: -# default-o: null -# options: null - symetric-encryption: - default-o: null - options: - configuration: - aes: - key: ${CIPHER_SYMETRIC_ENCRYPTION_CONFIGURATION_AES_KEY:} - iv: ${CIPHER_SYMETRIC_ENCRYPTION_CONFIGURATION_AES_IV:} - queue: - aes: - key: ${CIPHER_SYMETRIC_ENCRYPTION_QUEUE_AES_KEY:} - iv: ${CIPHER_SYMETRIC_ENCRYPTION_QUEUE_AES_IV:} - masking: - default: null - options: - configuration: - character: "*" - clear-begining: 2 - clear-ending: 4 - at-least-percentage: 70 - digital-signature: - default: null - options: - configuration: - certificate-path: null - certificate-password: null \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/cors-devel.yml b/annotation-service/annotation-web/src/main/resources/config/cors-devel.yml deleted file mode 100644 index 3e9227ef3..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/cors-devel.yml +++ /dev/null @@ -1,3 +0,0 @@ -web: - cors: - allowed-origins: [ http://localhost, http://localhost:4200 ] diff --git a/annotation-service/annotation-web/src/main/resources/config/cors.yml b/annotation-service/annotation-web/src/main/resources/config/cors.yml deleted file mode 100644 index 3774f14d4..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/cors.yml +++ /dev/null @@ -1,7 +0,0 @@ -web: - cors: - enabled: true - allowed-methods: [ HEAD, GET, POST, PUT, DELETE, PATCH ] - allowed-headers: [ Authorization, Cache-Control, Content-Type, Content-Disposition, x-tenant ] - exposed-headers: [ Authorization, Cache-Control, Content-Type, Content-Disposition ] - allow-credentials: false diff --git a/annotation-service/annotation-web/src/main/resources/config/db-devel.yml b/annotation-service/annotation-web/src/main/resources/config/db-devel.yml deleted file mode 100644 index e5299bb04..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/db-devel.yml +++ /dev/null @@ -1,10 +0,0 @@ -spring: - datasource: - maxIdle: 10 - minIdle: 5 - maxActive: 10 - jpa: - show-sql: true - properties: - hibernate: - format_sql: false \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/db.yml b/annotation-service/annotation-web/src/main/resources/config/db.yml deleted file mode 100644 index 163ff2f80..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/db.yml +++ /dev/null @@ -1,28 +0,0 @@ -spring: - jpa: - properties: - org: - hibernate: - flushMode: MANUAL - hibernate: - globally_quoted_identifiers: true - ddl-auto: validate - dialect: org.hibernate.dialect.PostgreSQLDialect - hibernate: - naming: - physical-strategy: gr.cite.annotation.data.namingstrategy.PrefixPhysicalNamingStrategy - implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy - datasource: - url: ${DB_CONNECTION_STRING} - username: ${DB_USER} - password: ${DB_PASSWORD} - driver-class-name: org.postgresql.Driver - hikari: - connection-timeout: 30000 - minimum-idle: 3 - maximum-pool-size: 10 - idle-timeout: 600000 - max-lifetime: 1800000 - -naming-strategy: - prefix: ant_ diff --git a/annotation-service/annotation-web/src/main/resources/config/errors.yml b/annotation-service/annotation-web/src/main/resources/config/errors.yml deleted file mode 100644 index 12a48ea12..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/errors.yml +++ /dev/null @@ -1,52 +0,0 @@ -error-thesaurus: -# common errors start with 1.. - hash-conflict: - code: 100 - message: there is a hash conflict for the item modified. please reload to get the latest changes - forbidden: - code: 101 - message: insufficient rights - system-error: - code: 102 - message: an unexpected system error occurred - missing-tenant: - code: 103 - message: tenant scope not provided - model-validation: - code: 106 - message: validation error - tenant-not-allowed: - code: 112 - message: tenant not allowed - tenant-tampering: - code: 127 - message: Tenant tampering - -# annotations¬ification errors start with 2.. - invalid-api-key: - code: 200 - message: provided APIKey not valid - stale-api-key: - code: 201 - message: there was a problem authorizing you with your API key. Please try again. Contact the system administrator if the problem persists - sensitive-info: - code: 202 - message: you are attempting to access sensitive information. please don't do that - non-person-principal: - code: 203 - message: the operation is available only to person users - blocking-consent: - code: 204 - message: user consents are not sufficient to complete the operation - single-tenant-configuration-per-type-supported: - code: 205 - message: a single tenant configuration entry per config type is supported - incompatible-tenant-configuration-types: - code: 206 - message: the provided tenant configuration type is incompatible - missing-totp-token: - code: 207 - message: totp token not provided - overlapping-tenant-configuration-notifier-list: - code: 208 - message: Overlapping Tenant Configuration Notifier List diff --git a/annotation-service/annotation-web/src/main/resources/config/idpclaims.yml b/annotation-service/annotation-web/src/main/resources/config/idpclaims.yml deleted file mode 100644 index 26e00f2a1..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/idpclaims.yml +++ /dev/null @@ -1,58 +0,0 @@ -idpclient: - claims: - mapping: - Subject: - - type: sub - Name: - - type: name - Client: - - type: client_id - AuthenticationMethod: - - type: amr - NotBefore: - - type: nbf - AuthenticatedAt: - - type: auth_time - ExpiresAt: - - type: exp - Email: - - type: email - Roles: - - type: resource_access - path: dmp_web.roles - - type: tenant_roles - filterBy: "(.*):::TenantCode::" - extractByExpression: "(.*):(.*)" - extractExpressionValue: "[[g1]]" - GlobalRoles: - - type: resource_access - path: dmp_web.roles - TenantRoles: - - type: tenant_roles - filterBy: "(.*):::TenantCode::" - extractByExpression: "(.*):(.*)" - extractExpressionValue: "[[g1]]" - Scope: - - type: scope - AccessToken: - - type: x-access-token - visibility: SENSITIVE - Tenant: - - type: x-tenant - IssuedAt: - - type: iat - Issuer: - - type: iss - Audience: - - type: aud - TokenType: - - type: typ - AuthorizedParty: - - type: azp - Authorities: - - type: authorities - TenantCodes: - - type: tenant_roles - filterBy: "(.*):(.*)" - extractByExpression: "(.*):(.*)" - extractExpressionValue: "[[g2]]" \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/locale.yml b/annotation-service/annotation-web/src/main/resources/config/locale.yml deleted file mode 100644 index b09c59e53..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/locale.yml +++ /dev/null @@ -1,4 +0,0 @@ -locale: - timezone: UTC - language: en - culture: en-US diff --git a/annotation-service/annotation-web/src/main/resources/config/logging-devel.yml b/annotation-service/annotation-web/src/main/resources/config/logging-devel.yml deleted file mode 100644 index 2f565c0d7..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/logging-devel.yml +++ /dev/null @@ -1,2 +0,0 @@ -logging: - config: classpath:logging/logback-dev.xml diff --git a/annotation-service/annotation-web/src/main/resources/config/logging.yml b/annotation-service/annotation-web/src/main/resources/config/logging.yml deleted file mode 100644 index 56e152d3f..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/logging.yml +++ /dev/null @@ -1,35 +0,0 @@ -logging: - context: - request: - requestIdKey: req.id - requestRemoteHostKey: req.remoteHost - requestUriKey: req.requestURI - requestQueryStringKey: req.queryString - requestUrlKey : req.requestURL - requestMethodKey: req.method - requestUserAgentKey: req.userAgent - requestForwardedForKey: req.xForwardedFor - requestSchemeKey: req.scheme - requestRemoteAddressKey: req.remoteAddr - requestRemotePortKey: req.remotePort - requestRemoteUserKey: req.remoteUser - principal: - subjectKey: usr.subject - nameKey: usr.name - clientKey: usr.client -audit: - enable: true - requestRemoteHostKey: req.remoteHost - requestUriKey: req.requestURI - requestQueryStringKey: req.queryString - requestUrlKey : req.requestURL - requestMethodKey: req.method - requestUserAgentKey: req.userAgent - requestForwardedForKey: req.xForwardedFor - requestSchemeKey: req.scheme - requestRemoteAddressKey: req.remoteAddr - requestRemotePortKey: req.remotePort - requestRemoteUserKey: req.remoteUser - principalSubjectKey: usr.subject - principalNameKey: usr.name - principalClientKey: usr.client diff --git a/annotation-service/annotation-web/src/main/resources/config/permissions.yml b/annotation-service/annotation-web/src/main/resources/config/permissions.yml deleted file mode 100644 index 37cb3d25e..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/permissions.yml +++ /dev/null @@ -1,101 +0,0 @@ -permissions: - policies: - DeferredAffiliation: - roles: - - TenantAdmin - - TenantUser - - TenantPlanManager - - TenantConfigManager - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - # Tenants - BrowseTenant: - roles: [ ] - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - EditTenant: - roles: [ ] - clients: [ "opencdmp-api-dev" ] - allowAnonymous: false - allowAuthenticated: false - DeleteTenant: - roles: [ ] - claims: [ ] - clients: [ "opencdmp-api-dev" ] - allowAnonymous: false - allowAuthenticated: false - AllowNoTenant: - roles: - - Admin - - InstallationAdmin - claims: [ ] - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - # Users - BrowseUser: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - EditUser: - roles: [ ] - clients: [ "opencdmp-api-dev" ] - allowAnonymous: false - allowAuthenticated: false - DeleteUser: - roles: [ ] - claims: [ ] - clients: [ "opencdmp-api-dev" ] - allowAnonymous: false - allowAuthenticated: false - #Annotation - BrowseAnnotation: - roles: - - Admin - - TenantAdmin - entityAffiliated: true - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - NewAnnotation: - roles: - - Admin - - TenantAdmin - entityAffiliated: true - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - EditAnnotation: - roles: - - Admin - - TenantAdmin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - DeleteAnnotation: - roles: - - Admin - - TenantAdmin - entityAffiliated: false - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - #Tenant Configuration - BrowseTenantConfiguration: - roles: - - Admin - - TenantAdmin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - EditTenantConfiguration: - roles: - - Admin - - TenantAdmin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/queue-devel.yml b/annotation-service/annotation-web/src/main/resources/config/queue-devel.yml deleted file mode 100644 index dc60ed5a7..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/queue-devel.yml +++ /dev/null @@ -1,21 +0,0 @@ -queue: - rabbitmq: - enable: true - durable: true - queue: cite_dmp_devel_annotation_inbox_queue - exchange: cite_dmp_devel_queue - listenerEnabled: true - publisherEnabled: true - task: - publisher: - enable: true - options: - exchange: cite_dmp_devel_queue - rabbitmq: - enable: true - listener: - enable: true - options: - exchange: cite_dmp_devel_queue - rabbitmq: - enable: true diff --git a/annotation-service/annotation-web/src/main/resources/config/queue.yml b/annotation-service/annotation-web/src/main/resources/config/queue.yml deleted file mode 100644 index 18cf14d5f..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/queue.yml +++ /dev/null @@ -1,55 +0,0 @@ -spring: - rabbitmq: - host: ${RABBIT_HOST} - port: ${RABBIT_PORT} - username: ${RABBIT_USER} - password: ${RABBIT_PASS} - ssl: - enabled: false -queue: - rabbitmq: - enable: false - appId: ${QUEUE_APP_ID} - durable: null - queue: null - exchange: null - listenerEnabled: true - publisherEnabled: true - #TODO - connection-recovery: - enable: true - network-recovery-interval: 5000 - unreachable-recovery-interval: 5000 - task: - publisher: - enable: false - options: - exchange: null - annotation-created-topic: annotation.created - rabbitmq: - enable: false - interval-seconds: 3 - options: - retry-threashold: 100 - retry-delay-step-seconds: 300 - max-retry-delay-seconds: 10800 - too-old-to-send-seconds: 604800 - confirm-timeout-seconds: 30 - listener: - enable: false - options: - exchange: null - tenant-removal-topic: tenant.remove - tenant-touch-topic: tenant.touch - user-removal-topic: user.remove - user-touch-topic: user.touch - annotation-entities-touch-topic: annotation.entities.touch - annotation-entities-removal-topic: annotation.entities.remove - rabbitmq: - enable: false - interval-seconds: 3 - options: - retry-threashold: 100 - retry-delay-step-seconds: 300 - max-retry-delay-seconds: 10800 - too-old-to-send-seconds: 604800 \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/security-devel.yml b/annotation-service/annotation-web/src/main/resources/config/security-devel.yml deleted file mode 100644 index 7692e66d9..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/security-devel.yml +++ /dev/null @@ -1,6 +0,0 @@ -web: - security: - idp: - resource: - jwt: - audiences: [ "dmp_annotation" ] \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/security.yml b/annotation-service/annotation-web/src/main/resources/config/security.yml deleted file mode 100644 index 8f41034ac..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/security.yml +++ /dev/null @@ -1,14 +0,0 @@ -web: - security: - enabled: true - authorized-endpoints: [ api ] - allowed-endpoints: [ public ] - idp: - api-key: - enabled: false - resource: - token-type: JWT #| opaque - jwt: - claims: [ role, x-role ] - issuer-uri: ${IDP_ISSUER_URI} - validIssuer: ${IDP_ISSUER_URI} \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/server-devel.yml b/annotation-service/annotation-web/src/main/resources/config/server-devel.yml deleted file mode 100644 index 2a628f82f..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/server-devel.yml +++ /dev/null @@ -1,2 +0,0 @@ -server: - forward-headers-strategy: FRAMEWORK \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/server.yml b/annotation-service/annotation-web/src/main/resources/config/server.yml deleted file mode 100644 index 9a4a97cbc..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/server.yml +++ /dev/null @@ -1,13 +0,0 @@ -server: - port: ${WEB_PORT} - forward-headers-strategy: NONE - tomcat: - threads: - max: 20 - max-connections: 10000 - - spring: - servlet: - multipart: - max-file-size: 10MB - max-request-size: 10MB \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/tenant-devel.yml b/annotation-service/annotation-web/src/main/resources/config/tenant-devel.yml deleted file mode 100644 index f2149021a..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/tenant-devel.yml +++ /dev/null @@ -1,7 +0,0 @@ -tenant: - multitenancy: - is-multitenant: true - default-tenant-code: default - interceptor: - client-claims-prefix: client_ - enforce-trusted-tenant: false \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/config/tenant.yml b/annotation-service/annotation-web/src/main/resources/config/tenant.yml deleted file mode 100644 index 5325de856..000000000 --- a/annotation-service/annotation-web/src/main/resources/config/tenant.yml +++ /dev/null @@ -1,7 +0,0 @@ -tenant: - multitenancy: - is-multitenant: false - interceptor: - white-listed-clients: [ ] - enforce-trusted-tenant: false - white-listed-endpoints: [ '/api/annotation/principal/me' ] \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/logging/logback-dev.xml b/annotation-service/annotation-web/src/main/resources/logging/logback-dev.xml deleted file mode 100644 index e304c45df..000000000 --- a/annotation-service/annotation-web/src/main/resources/logging/logback-dev.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - %date{ISO8601} [%thread] %-5level %logger{36} [%X{req.id}] - %message%n - - - - - logs/logging.log - - logs/logging.%d{yyyy-MM-dd}.%i.log - - 100MB - - 15 - - - %date{ISO8601} [%thread] %-5level %logger{36} [%X{req.id}] - %message%n - - - - - logs/auditing.log - - logs/auditing.%d{yyyy-MM-dd}.%i.log - - 100MB - - 15 - - - %date{ISO8601} - %X{req.id} - %message%n - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/annotation-service/annotation-web/src/main/resources/messages/messages.properties b/annotation-service/annotation-web/src/main/resources/messages/messages.properties deleted file mode 100644 index 93d6cd27a..000000000 --- a/annotation-service/annotation-web/src/main/resources/messages/messages.properties +++ /dev/null @@ -1,10 +0,0 @@ -validation.empty=Value cannot be empty -validation.hashempty=Hash must be set -validation.lowerthanmin=Value must be larger than {value} -validation.largerthanmax=Value must be less than {value} -validation.invalidid=Not valid id -General_ItemNotFound=Item {0} of type {1} not found -Validation_Required={0} is required -Validation_OverPosting=Too much info -Validation_MaxLength={0} too long -Validation_UnexpectedValue=Unexpected value in field {0} \ No newline at end of file diff --git a/annotation-service/annotation-web/src/main/resources/messages/messages_el.properties b/annotation-service/annotation-web/src/main/resources/messages/messages_el.properties deleted file mode 100644 index 4d060cc58..000000000 --- a/annotation-service/annotation-web/src/main/resources/messages/messages_el.properties +++ /dev/null @@ -1,6 +0,0 @@ -validation.empty=el-Value cannot be empty -validation.hashempty=el-Hash must be set -validation.lowerthanmin=el-Value must be larger than {value} -validation.largerthanmax=el-Value must be less than {value} -validation.invalidid=el-Not valid id -General_ItemNotFound=el-Item {0} of type {1} not found \ No newline at end of file diff --git a/annotation-service/annotation/.gitignore b/annotation-service/annotation/.gitignore deleted file mode 100644 index 549e00a2a..000000000 --- a/annotation-service/annotation/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/annotation-service/annotation/pom.xml b/annotation-service/annotation/pom.xml deleted file mode 100644 index 21f9e9d62..000000000 --- a/annotation-service/annotation/pom.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - 4.0.0 - - - gr.cite - annotation-service-parent - ${revision} - ../pom.xml - - - annotation - ${revision} - - - 21 - 21 - 21 - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-mail - - - org.apache.poi - poi - 5.2.2 - - - org.apache.poi - poi-ooxml - 5.2.2 - - - - gr.cite - data-tools - 2.1.5 - - - gr.cite - field-set - 2.1.0 - - - gr.cite - oidc-authn - 2.2.2 - - - gr.cite - logging - 1.0.0 - - - gr.cite - oidc-authz - 2.1.0 - - - gr.cite - exceptions - 2.1.0 - - - gr.cite - validation - 3.0.3 - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - - - - gr.cite - cipher - 2.1.0 - compile - - - - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/audit/AuditableAction.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/audit/AuditableAction.java deleted file mode 100644 index 14f1c57a6..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/audit/AuditableAction.java +++ /dev/null @@ -1,59 +0,0 @@ -package gr.cite.annotation.audit; - -import gr.cite.tools.logging.EventId; - -public class AuditableAction { -// public static final EventId Tenant_Available_Notifiers_Query = new EventId(2006, "Tenant_Available_Notifiers_Query"); - public static final EventId Principal_Lookup = new EventId(6000, "Principal_Lookup"); - public static final EventId Tenants_Lookup = new EventId(6001, "Tenants_Lookup"); - -// public static final EventId User_Available_Notifiers_Query = new EventId(10004, "User_Available_Notifiers_Query"); - - public static final EventId User_Query = new EventId(11000, "User_Query"); - public static final EventId User_Lookup = new EventId(11001, "User_Lookup"); - public static final EventId User_Persist = new EventId(11002, "User_Persist"); - public static final EventId User_Delete = new EventId(11003, "User_Delete"); - - public static final EventId Tenant_Query = new EventId(12000, "Tenant_Query"); - public static final EventId Tenant_Lookup = new EventId(12001, "Tenant_Lookup"); - public static final EventId Tenant_Persist = new EventId(12002, "Tenant_Persist"); - public static final EventId Tenant_Delete = new EventId(12003, "Tenant_Delete"); - -// public static final EventId Notification_Query = new EventId(19000, "Notification_Query"); -// public static final EventId Notification_Lookup = new EventId(19001, "Notification_Lookup"); -// public static final EventId Notification_Persist = new EventId(19002, "Notification_Persist"); -// public static final EventId Notification_Delete = new EventId(19003, "Notification_Delete"); - -// public static final EventId InApp_Notification_Query = new EventId(20000, "InApp_Notification_Query"); -// public static final EventId InApp_Notification_Lookup = new EventId(20001, "InApp_Notification_Lookup"); -// public static final EventId InApp_Notification_Persist = new EventId(20002, "InApp_Notification_Persist"); -// public static final EventId InApp_Notification_Delete = new EventId(20003, "InApp_Notification_Delete"); -// public static final EventId InApp_Notification_Read = new EventId(20003, "InApp_Notification_Read"); -// public static final EventId InApp_Notification_Read_All = new EventId(20003, "InApp_Notification_Read_All"); - - public static final EventId Tenant_Configuration_Query = new EventId(21000, "Tenant_Configuration_Query"); - public static final EventId Tenant_Configuration_Lookup = new EventId(21001, "Tenant_Configuration_Lookup"); - public static final EventId Tenant_Configuration_Persist = new EventId(21002, "Tenant_Configuration_Persist"); - public static final EventId Tenant_Configuration_Delete = new EventId(21003, "Tenant_Configuration_Delete"); - -// public static final EventId User_Notification_Preference_Query = new EventId(22000, "User_Notification_Preference_Query"); -// public static final EventId User_Notification_Preference_Lookup = new EventId(22001, "User_Notification_Preference_Lookup"); -// public static final EventId User_Notification_Preference_Persist = new EventId(22002, "User_Notification_Preference_Persist"); -// public static final EventId User_Notification_Preference_Delete = new EventId(22003, "User_Notification_Preference_Delete"); -// -// public static final EventId Notification_Template_Query = new EventId(23000, "Notification_Template_Query"); -// public static final EventId Notification_Template_Lookup = new EventId(23001, "Notification_Template_Lookup"); -// public static final EventId Notification_Template_Persist = new EventId(23002, "Notification_Template_Persist"); -// public static final EventId Notification_Template_Delete = new EventId(23003, "Notification_Template_Delete"); - - public static final EventId Annotation_Query = new EventId(24000, "Annotation_Query"); - public static final EventId Annotation_Lookup = new EventId(24001, "Annotation_Lookup"); - public static final EventId Annotation_Persist = new EventId(24002, "Annotation_Persist"); - public static final EventId Annotation_Delete = new EventId(24003, "Annotation_Delete"); - - public static final EventId Entity_User_Query = new EventId(25000, "Entity_User_Query"); - public static final EventId Entity_User_Lookup = new EventId(25001, "Entity_User_Lookup"); - public static final EventId Entity_User_Persist = new EventId(25002, "Entity_User_Persist"); - public static final EventId Entity_User_Delete = new EventId(25003, "Entity_User_Delete"); - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AffiliatedAuthorizationRequirement.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AffiliatedAuthorizationRequirement.java deleted file mode 100644 index c15d5cff2..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AffiliatedAuthorizationRequirement.java +++ /dev/null @@ -1,40 +0,0 @@ -package gr.cite.annotation.authorization; - -import gr.cite.commons.web.authz.policy.AuthorizationRequirement; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class AffiliatedAuthorizationRequirement implements AuthorizationRequirement { - private final Set requiredPermissions; - private final boolean matchAll; - - public AffiliatedAuthorizationRequirement(Set requiredPermissions) { - this(false, requiredPermissions); - } - - public AffiliatedAuthorizationRequirement(String... requiredPermissions) { - this(false, requiredPermissions); - - } - - public AffiliatedAuthorizationRequirement(boolean matchAll, Set requiredPermissions) { - this.matchAll = matchAll; - this.requiredPermissions = requiredPermissions; - } - - public AffiliatedAuthorizationRequirement(boolean matchAll, String... requiredPermissions) { - this.requiredPermissions = new HashSet<>(); - this.matchAll = matchAll; - this.requiredPermissions.addAll(Arrays.stream(requiredPermissions).distinct().toList()); - } - - public Set getRequiredPermissions() { - return requiredPermissions; - } - - public boolean getMatchAll() { - return matchAll; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AffiliatedResource.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AffiliatedResource.java deleted file mode 100644 index dc5e6ede9..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AffiliatedResource.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.annotation.authorization; - -import gr.cite.commons.web.authz.policy.AuthorizationResource; - -public class AffiliatedResource extends AuthorizationResource { - private Boolean isAffiliated; - - public AffiliatedResource() { - } - - public AffiliatedResource(Boolean isAffiliated) { - this.isAffiliated = isAffiliated; - } - - public Boolean getAffiliated() { - return isAffiliated; - } - - public void setAffiliated(Boolean affiliated) { - isAffiliated = affiliated; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AuthorizationFlags.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AuthorizationFlags.java deleted file mode 100644 index 33ce8fc17..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/AuthorizationFlags.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.annotation.authorization; - -import java.util.EnumSet; - -public enum AuthorizationFlags { - None, Permission, Associated, Owner; - public static final EnumSet OwnerOrPermissionAssociated = EnumSet.of(Owner, Permission, Associated); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/ClaimNames.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/ClaimNames.java deleted file mode 100644 index a28967fb9..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/ClaimNames.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.annotation.authorization; - -public class ClaimNames { - public static final String ExternalProviderName = "ExternalProviderName"; - public static final String TenantCodesClaimName = "TenantCodes"; - public static final String TenantClaimName = "x-tenant"; - public static final String GlobalRolesClaimName = "GlobalRoles"; - public static final String TenantRolesClaimName = "TenantRoles"; -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/OwnedAuthorizationRequirement.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/OwnedAuthorizationRequirement.java deleted file mode 100644 index 553104fc7..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/OwnedAuthorizationRequirement.java +++ /dev/null @@ -1,6 +0,0 @@ -package gr.cite.annotation.authorization; - -import gr.cite.commons.web.authz.policy.AuthorizationRequirement; - -public class OwnedAuthorizationRequirement implements AuthorizationRequirement { -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/OwnedResource.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/OwnedResource.java deleted file mode 100644 index 83018ff3e..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/OwnedResource.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.annotation.authorization; - -import gr.cite.commons.web.authz.policy.AuthorizationResource; - -import java.util.List; -import java.util.UUID; - -public class OwnedResource extends AuthorizationResource { - private List userIds; - - public OwnedResource(UUID userId) { - this(List.of(userId)); - } - - public OwnedResource(List userIds) { - this.userIds = userIds; - } - - public List getUserIds() { - return userIds; - } - - public void setUserIds(List userIds) { - this.userIds = userIds; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/Permission.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/Permission.java deleted file mode 100644 index 665736cbe..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/Permission.java +++ /dev/null @@ -1,27 +0,0 @@ -package gr.cite.annotation.authorization; - -public final class Permission { - public static String DeferredAffiliation = "DeferredAffiliation"; - //User - public static String BrowseUser = "BrowseUser"; - public static String EditUser = "EditUser"; - public static String DeleteUser = "DeleteUser"; - - - //Tenant - public static String BrowseTenant = "BrowseTenant"; - public static String EditTenant = "EditTenant"; - public static String DeleteTenant = "DeleteTenant"; - public static String AllowNoTenant = "AllowNoTenant"; - - //Annotation - public static final String BrowseAnnotation = "BrowseAnnotation"; - public static String NewAnnotation = "NewAnnotation"; - public static String EditAnnotation = "EditAnnotation"; - public static String DeleteAnnotation = "DeleteAnnotation"; - - public static final String BrowseTenantConfiguration = "BrowseTenantConfiguration"; - public static final String EditTenantConfiguration = "EditTenantConfiguration"; - - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/PermissionNameProvider.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/PermissionNameProvider.java deleted file mode 100644 index cd1d92d8a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/PermissionNameProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -package gr.cite.annotation.authorization; - -import gr.cite.annotation.convention.ConventionService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Service; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.List; - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) -public class PermissionNameProvider { - private static final Logger logger = LoggerFactory.getLogger(PermissionNameProvider.class); - private final List permissions; - - public PermissionNameProvider(ConventionService conventionService) { - this.permissions = new ArrayList<>(); - Class clazz = Permission.class; - for (Field f : clazz.getDeclaredFields()) { - if (Modifier.isStatic(f.getModifiers())) { - try { - Object value = f.get(null); - if (value != null && !conventionService.isNullOrEmpty((String)value)) this.permissions.add((String)value); - } catch (Exception e) { - logger.error("Can not load permission " + f.getName() + " " + e.getMessage()); - } - } - } - } - - public List getPermissions() { - return permissions; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AffiliationCacheOptions.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AffiliationCacheOptions.java deleted file mode 100644 index b39f5ee08..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AffiliationCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.annotation.authorization.authorizationcontentresolver; - -import gr.cite.tools.cache.CacheOptions; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "cache.affiliation") -public class AffiliationCacheOptions extends CacheOptions { -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AffiliationCacheService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AffiliationCacheService.java deleted file mode 100644 index 4d468b495..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AffiliationCacheService.java +++ /dev/null @@ -1,95 +0,0 @@ -package gr.cite.annotation.authorization.authorizationcontentresolver; - -import gr.cite.annotation.authorization.AffiliatedResource; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.tools.cache.CacheService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.Locale; -import java.util.UUID; - -@Service -public class AffiliationCacheService extends CacheService { - - public static class AffiliationCacheValue { - - public AffiliationCacheValue() { - } - - public AffiliationCacheValue(UUID userId, UUID entityId, String entityType, AffiliatedResource affiliatedResource) { - this.userId = userId; - this.entityId = entityId; - this.entityType = entityType; - this.affiliatedResource = affiliatedResource; - } - - private UUID userId; - private UUID entityId; - private String entityType; - private AffiliatedResource affiliatedResource; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public UUID getEntityId() { - return entityId; - } - - public void setEntityId(UUID entityId) { - this.entityId = entityId; - } - - public String getEntityType() { - return entityType; - } - - public void setEntityType(String entityType) { - this.entityType = entityType; - } - - public AffiliatedResource getAffiliatedResource() { - return affiliatedResource; - } - - public void setAffiliatedResource(AffiliatedResource affiliatedResource) { - this.affiliatedResource = affiliatedResource; - } - } - - private final ConventionService conventionService; - @Autowired - public AffiliationCacheService(AffiliationCacheOptions options, ConventionService conventionService) { - super(options); - this.conventionService = conventionService; - } - - @Override - protected Class valueClass() { - return AffiliationCacheValue.class; - } - - @Override - public String keyOf(AffiliationCacheValue value) { - return this.buildKey(value.getUserId(), value.getEntityId(), value.getEntityType()); - } - - - public String buildKey(UUID userId, UUID entityId, String entityType) { - if (userId == null) throw new IllegalArgumentException("userId id is required"); - if (entityId == null) throw new IllegalArgumentException("entityId id is required"); - if (this.conventionService.isNullOrEmpty(entityType)) throw new IllegalArgumentException("entityType id is required"); - - HashMap keyParts = new HashMap<>(); - keyParts.put("$user$", userId.toString().replace("-", "").toLowerCase(Locale.ROOT)); - keyParts.put("$entity$", entityId.toString().replace("-", "").toLowerCase(Locale.ROOT)); - keyParts.put("$type$", entityType); - return this.generateKey(keyParts); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AuthorizationContentResolver.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AuthorizationContentResolver.java deleted file mode 100644 index ea3e8b408..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AuthorizationContentResolver.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.annotation.authorization.authorizationcontentresolver; - - -import gr.cite.annotation.authorization.AffiliatedResource; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public interface AuthorizationContentResolver { - AffiliatedResource entityAffiliation(UUID id); - - Map entitiesAffiliation(List ids); - - List getPermissionNames(); - - AffiliatedResource annotationAffiliation(UUID id); - - Map annotationsAffiliation(List ids); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AuthorizationContentResolverImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AuthorizationContentResolverImpl.java deleted file mode 100644 index 73e477e8d..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/authorization/authorizationcontentresolver/AuthorizationContentResolverImpl.java +++ /dev/null @@ -1,118 +0,0 @@ -package gr.cite.annotation.authorization.authorizationcontentresolver; - -import gr.cite.annotation.authorization.AffiliatedResource; -import gr.cite.annotation.authorization.PermissionNameProvider; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.AnnotationEntity; -import gr.cite.annotation.data.EntityUserEntity; -import gr.cite.annotation.model.Annotation; -import gr.cite.annotation.model.EntityUser; -import gr.cite.annotation.query.AnnotationQuery; -import gr.cite.annotation.query.EntityUserQuery; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.fieldset.BaseFieldSet; -import org.springframework.stereotype.Service; -import org.springframework.web.context.annotation.RequestScope; - -import java.util.*; -import java.util.stream.Collectors; - -@Service -@RequestScope -public class AuthorizationContentResolverImpl implements AuthorizationContentResolver { - private final QueryFactory queryFactory; - private final UserScope userScope; - private final AffiliationCacheService affiliationCacheService; - private final PermissionNameProvider permissionNameProvider; - public AuthorizationContentResolverImpl(QueryFactory queryFactory, UserScope userScope, AffiliationCacheService affiliationCacheService, PermissionNameProvider permissionNameProvider) { - this.queryFactory = queryFactory; - this.userScope = userScope; - this.affiliationCacheService = affiliationCacheService; - this.permissionNameProvider = permissionNameProvider; - } - - @Override - public AffiliatedResource entityAffiliation(UUID id) { - return this.entitiesAffiliation(List.of(id)).getOrDefault(id, new AffiliatedResource()); - } - @Override - public Map entitiesAffiliation(List ids){ - UUID userId = this.userScope.getUserIdSafe(); - Map affiliatedResources = new HashMap<>(); - for (UUID id : ids){ - affiliatedResources.put(id, new AffiliatedResource()); - } - if (userId == null || !userScope.isSet()) return affiliatedResources; - - List idsToResolve = this.getAffiliatedFromCache(ids, userId, affiliatedResources, AnnotationEntity._entityId); - if (idsToResolve.isEmpty()) return affiliatedResources; - - List entityUsers = this.queryFactory.query(EntityUserQuery.class).disableTracking().entityIds(ids).userIds(userId).isActive(IsActive.Active).collectAs(new BaseFieldSet().ensure(EntityUser._id).ensure(EntityUser._entityId)); - - for (UUID entityId : entityUsers.stream().map(EntityUserEntity::getEntityId).distinct().toList()){ - affiliatedResources.get(entityId).setAffiliated(true); - } - - this.ensureAffiliatedInCache(idsToResolve, userId, affiliatedResources, AnnotationEntity._entityId); - return affiliatedResources; - } - - @Override - public List getPermissionNames() { - return permissionNameProvider.getPermissions(); - } - - @Override - public AffiliatedResource annotationAffiliation(UUID id) { - return this.annotationsAffiliation(List.of(id)).getOrDefault(id, new AffiliatedResource()); - } - @Override - public Map annotationsAffiliation(List ids){ - UUID userId = this.userScope.getUserIdSafe(); - Map affiliatedResources = new HashMap<>(); - for (UUID id : ids){ - affiliatedResources.put(id, new AffiliatedResource()); - } - if (userId == null || !userScope.isSet()) return affiliatedResources; - - List idsToResolve = this.getAffiliatedFromCache(ids, userId, affiliatedResources, AnnotationEntity.class.getSimpleName()); - if (idsToResolve.isEmpty()) return affiliatedResources; - - List annotationEntities = this.queryFactory.query(AnnotationQuery.class).disableTracking().ids(ids).collectAs(new BaseFieldSet().ensure(Annotation._id).ensure(Annotation._entityId).ensure(Annotation._id)); - List entityUsers = this.queryFactory.query(EntityUserQuery.class).disableTracking().entityIds(annotationEntities.stream().map(AnnotationEntity::getEntityId).distinct().toList()).userIds(userId).isActive(IsActive.Active).collectAs(new BaseFieldSet().ensure(EntityUser._id).ensure(EntityUser._entityId)); - Map> entityUsersMap = entityUsers.stream().collect(Collectors.groupingBy(EntityUserEntity::getEntityId)); - - for (AnnotationEntity annotation : annotationEntities){ - List annotationEntityUsers = entityUsersMap.getOrDefault(annotation.getEntityId(), new ArrayList<>()); - if (!annotationEntityUsers.isEmpty()) { - affiliatedResources.get(annotation.getId()).setAffiliated(true); - } - } - - this.ensureAffiliatedInCache(idsToResolve, userId, affiliatedResources, AnnotationEntity.class.getSimpleName()); - return affiliatedResources; - } - - - - private List getAffiliatedFromCache(List ids, UUID userId, Map affiliatedResources, String entityType){ - List idsToResolve = new ArrayList<>(); - for (UUID id : ids){ - AffiliationCacheService.AffiliationCacheValue cacheValue = this.affiliationCacheService.lookup(this.affiliationCacheService.buildKey(userId, id, entityType)); - if (cacheValue != null) affiliatedResources.put(id, cacheValue.getAffiliatedResource()); - else idsToResolve.add(id); - } - return idsToResolve; - } - - private void ensureAffiliatedInCache(List idsToResolve, UUID userId, Map affiliatedResources, String entityType){ - for (UUID id : idsToResolve){ - AffiliatedResource affiliatedResource = affiliatedResources.getOrDefault(id, null); - if (affiliatedResource != null) { - AffiliationCacheService.AffiliationCacheValue cacheValue = new AffiliationCacheService.AffiliationCacheValue(userId, id, entityType, affiliatedResource); - this.affiliationCacheService.put(cacheValue); - } - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/JsonHandlingService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/JsonHandlingService.java deleted file mode 100644 index 0ff1467bc..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/JsonHandlingService.java +++ /dev/null @@ -1,58 +0,0 @@ -package gr.cite.annotation.common; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) -public class JsonHandlingService { - private final ObjectMapper objectMapper; - - public JsonHandlingService() { - this.objectMapper = new ObjectMapper(); - this.objectMapper.registerModule(new JavaTimeModule()); - } - - public String toJson(Object item) throws JsonProcessingException { - if (item == null) return null; - return this.objectMapper.writeValueAsString(item); - } - - public String toJsonSafe(Object item) { - if (item == null) return null; - try { - return this.objectMapper.writeValueAsString(item); - } catch (Exception ex) { - return null; - } - } - - public T fromJson(Class type, String json) throws JsonProcessingException { - if (json == null) return null; - return this.objectMapper.readValue(json, type); - } - - public HashMap mapFromJson(String json) throws JsonProcessingException { - ObjectReader reader = this.objectMapper.readerFor(Map.class); - return reader.readValue(json); - } - - public T fromJsonSafe(Class type, String json) { - if (json == null) return null; - try { - return this.objectMapper.readValue(json, type); - } catch (Exception ex) { - return null; - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/StringUtils.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/StringUtils.java deleted file mode 100644 index 804747d1a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/StringUtils.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.annotation.common; - -public class StringUtils { - - public static Boolean isNullOrEmpty(String string) { - return string == null || string.isEmpty(); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/XmlHandlingService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/XmlHandlingService.java deleted file mode 100644 index 71ece3a73..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/XmlHandlingService.java +++ /dev/null @@ -1,117 +0,0 @@ -package gr.cite.annotation.common; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.annotation.common.types.xml.XmlSerializable; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Marshaller; -import jakarta.xml.bind.Unmarshaller; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import javax.management.InvalidApplicationException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) -public class XmlHandlingService { - - public String generateXml(Document doc) throws TransformerException { - TransformerFactory tFact = TransformerFactory.newInstance(); - Transformer trans = tFact.newTransformer(); - StringWriter writer = new StringWriter(); - StreamResult result = new StreamResult(writer); - DOMSource source = new DOMSource(doc); - trans.setOutputProperty(OutputKeys.INDENT, "yes"); - trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - trans.transform(source, result); - return writer.toString(); - } - - public String toXml(Object item) throws JsonProcessingException, JAXBException, ParserConfigurationException, InvalidApplicationException, TransformerException { - if (XmlSerializable.class.isAssignableFrom(item.getClass())){ - Document document = this.getDocument(); - if (document == null) throw new InvalidApplicationException("Can not create document"); - document.appendChild(((XmlSerializable)item).toXml(document)); - return this.generateXml(document); - } - - JAXBContext context = JAXBContext.newInstance(item.getClass()); - Marshaller marshaller = context.createMarshaller(); - StringWriter out = new StringWriter(); - marshaller.marshal(item, out); - return out.toString(); - } - - public String toXmlSafe(Object item) { - if (item == null) return null; - try { - return this.toXml(item); - } catch (Exception ex) { - return null; - } - } - - public T fromXml(Class type, String xmlString) throws JAXBException, InstantiationException, IllegalAccessException, ParserConfigurationException, IOException, SAXException { - if (XmlSerializable.class.isAssignableFrom(type)){ - XmlSerializable object = (XmlSerializable)type.newInstance(); - return object.fromXml(this.getDocument(xmlString).getDocumentElement()); - } else { - JAXBContext jaxbContext = JAXBContext.newInstance(type); - Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - - return (T) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); - } - } - - public T fromXmlSafe(Class type, String xmlString) { - if (xmlString == null) return null; - try { - return this.fromXml(type, xmlString); - } catch (Exception ex) { - return null; - } - } - -// public > T xmlSerializableFromXml(Class type, String xmlString) throws JAXBException, InstantiationException, IllegalAccessException, ParserConfigurationException, IOException, SAXException { -// T object = type.newInstance(); -// return (T) object.fromXml(this.getDocument(xmlString).getDocumentElement()); -// } -// -// public > T xmlSerializableFromXmlSafe(Class type, String xmlString) { -// if (xmlString == null) return null; -// try { -// return this.xmlSerializableFromXml(type, xmlString); -// } catch (Exception ex) { -// return null; -// } -// } - - public Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - InputSource inputStream = new InputSource(new StringReader(xml)); - return docBuilder.parse(inputStream); - } - - public Document getDocument() throws ParserConfigurationException { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - return docBuilder.newDocument(); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/AnnotationProtectionType.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/AnnotationProtectionType.java deleted file mode 100644 index d864ed8a9..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/AnnotationProtectionType.java +++ /dev/null @@ -1,30 +0,0 @@ -package gr.cite.annotation.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.annotation.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum AnnotationProtectionType implements DatabaseEnum { - - Private((short) 0), - EntityAccessors((short) 1); - - private final Short value; - - AnnotationProtectionType(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(AnnotationProtectionType.class); - - public static AnnotationProtectionType of(Short i) { - return map.get(i); - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/ContactInfoType.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/ContactInfoType.java deleted file mode 100644 index a15c9b41c..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/ContactInfoType.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.annotation.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.annotation.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum ContactInfoType implements DatabaseEnum { - Email((short) 0), - MobilePhone((short) 1), - LandLinePhone((short) 2); - private final Short value; - - ContactInfoType(Short value) { - this.value = value; - } - - @Override - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(ContactInfoType.class); - - public static ContactInfoType of(Short i) { - return map.get(i); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/EnumUtils.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/EnumUtils.java deleted file mode 100644 index 630bab33e..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/EnumUtils.java +++ /dev/null @@ -1,16 +0,0 @@ -package gr.cite.annotation.common.enums; - -import gr.cite.annotation.data.conventers.DatabaseEnum; - -import java.util.HashMap; -import java.util.Map; - -public class EnumUtils { - public static & DatabaseEnum, EnumValue> Map getEnumValueMap(Class enumType){ - HashMap map = new HashMap<>(); - for (EnumType v : enumType.getEnumConstants()) { - map.put(v.getValue(), v); - } - return map; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/IsActive.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/IsActive.java deleted file mode 100644 index ca0fac96d..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/IsActive.java +++ /dev/null @@ -1,28 +0,0 @@ -package gr.cite.annotation.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.annotation.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum IsActive implements DatabaseEnum { - Inactive((short) 0), - Active((short) 1); - - private final Short value; - - IsActive(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(IsActive.class); - - public static IsActive of(Short i) { - return map.get(i); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/TenantConfigurationType.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/TenantConfigurationType.java deleted file mode 100644 index 0b93bb7c6..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/enums/TenantConfigurationType.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.annotation.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.annotation.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum TenantConfigurationType implements DatabaseEnum { - EMAIL_CLIENT_CONFIGURATION((short)1), - DEFAULT_USER_LOCALE((short)3), - NOTIFIER_LIST((short)4); - - private final Short value; - - TenantConfigurationType(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(TenantConfigurationType.class); - - public static TenantConfigurationType of(Short i) { - return map.get(i); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/lock/LockByKeyManager.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/lock/LockByKeyManager.java deleted file mode 100644 index 5976e526b..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/lock/LockByKeyManager.java +++ /dev/null @@ -1,58 +0,0 @@ -package gr.cite.annotation.common.lock; - -import org.springframework.stereotype.Service; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReentrantLock; - -@Service -public class LockByKeyManager { - - private static class LockWrapper { - private final ReentrantLock lock = new ReentrantLock(); - private final AtomicInteger numberOfThreadsInQueue = new AtomicInteger(1); - - private LockWrapper addThreadInQueue() { - numberOfThreadsInQueue.incrementAndGet(); - return this; - } - - private int removeThreadFromQueue() { - return numberOfThreadsInQueue.decrementAndGet(); - } - - } - - private static final ConcurrentHashMap locks = new ConcurrentHashMap(); - - public void lock(String key) { - LockWrapper lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue()); - lockWrapper.lock.lock(); - } - - public boolean tryLock(String key, long timeout, TimeUnit unit) throws InterruptedException { - LockWrapper lockWrapper = null; - try { - lockWrapper = locks.compute(key, (k, v) -> v == null ? new LockWrapper() : v.addThreadInQueue()); - return lockWrapper.lock.tryLock(timeout, unit); - } catch (Exception ex){ - if (lockWrapper != null && lockWrapper.removeThreadFromQueue() == 0) { - // NB : We pass in the specific value to remove to handle the case where another thread would queue right before the removal - locks.remove(key, lockWrapper); - } - throw ex; - } - } - - public void unlock(String key) { - LockWrapper lockWrapper = locks.get(key); - lockWrapper.lock.unlock(); - if (lockWrapper.removeThreadFromQueue() == 0) { - // NB : We pass in the specific value to remove to handle the case where another thread would queue right before the removal - locks.remove(key, lockWrapper); - } - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/fake/FakeRequestAttributes.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/fake/FakeRequestAttributes.java deleted file mode 100644 index 51fb71fff..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/fake/FakeRequestAttributes.java +++ /dev/null @@ -1,125 +0,0 @@ -package gr.cite.annotation.common.scope.fake; - -import org.springframework.util.Assert; -import org.springframework.web.context.request.RequestAttributes; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -public class FakeRequestAttributes implements RequestAttributes { - private final Map requestAttributeMap = new HashMap<>(); - private final Map requestDestructionCallbacks = new LinkedHashMap<>(8); - private volatile boolean requestActive = true; - - @Override - public Object getAttribute(String name, int scope) { - if (scope == RequestAttributes.SCOPE_REQUEST) { - if (!isRequestActive()) { - throw new IllegalStateException("Cannot ask for request attribute - request is not active anymore!"); - } - return this.requestAttributeMap.get(name); - } else { - throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); - } - } - - @Override - public void setAttribute(String name, Object value, int scope) { - if (scope == RequestAttributes.SCOPE_REQUEST) { - if (!isRequestActive()) { - throw new IllegalStateException("Cannot set request attribute - request is not active anymore!"); - } - this.requestAttributeMap.put(name, value); - } else { - throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); - } - } - - @Override - public void removeAttribute(String name, int scope) { - if (scope == RequestAttributes.SCOPE_REQUEST) { - if (isRequestActive()) { - removeRequestDestructionCallback(name); - this.requestAttributeMap.remove(name); - } - } else { - throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); - } - } - - @Override - public String[] getAttributeNames(int scope) { - if (scope == RequestAttributes.SCOPE_REQUEST) { - if (!isRequestActive()) { - throw new IllegalStateException("Cannot ask for request attributes - request is not active anymore!"); - } - return this.requestAttributeMap.keySet().toArray(new String[0]); - } else { - throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); - } - //return new String[0]; - } - - @Override - public void registerDestructionCallback(String name, Runnable callback, int scope) { - if (scope == SCOPE_REQUEST) { - registerRequestDestructionCallback(name, callback); - } else { - throw new IllegalStateException("Only " + RequestAttributes.SCOPE_REQUEST + " allowed for " + FakeRequestAttributes.class.getSimpleName()); - } - } - - protected final void registerRequestDestructionCallback(String name, Runnable callback) { - Assert.notNull(name, "Name must not be null"); - Assert.notNull(callback, "Callback must not be null"); - synchronized (this.requestDestructionCallbacks) { - this.requestDestructionCallbacks.put(name, callback); - } - } - - @Override - public Object resolveReference(String key) { - // Not supported - return null; - } - - @Override - public String getSessionId() { - return null; - } - - @Override - public Object getSessionMutex() { - return null; - } - - public void requestCompleted() { - executeRequestDestructionCallbacks(); - for (String name : getAttributeNames(RequestAttributes.SCOPE_REQUEST)) { - this.removeAttribute(name, RequestAttributes.SCOPE_REQUEST); - } - this.requestActive = false; - } - - private final boolean isRequestActive() { - return this.requestActive; - } - - - private final void removeRequestDestructionCallback(String name) { - Assert.notNull(name, "Name must not be null"); - synchronized (this.requestDestructionCallbacks) { - this.requestDestructionCallbacks.remove(name); - } - } - - private void executeRequestDestructionCallbacks() { - synchronized (this.requestDestructionCallbacks) { - for (Runnable runnable : this.requestDestructionCallbacks.values()) { - runnable.run(); - } - this.requestDestructionCallbacks.clear(); - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/fake/FakeRequestScope.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/fake/FakeRequestScope.java deleted file mode 100644 index d39057662..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/fake/FakeRequestScope.java +++ /dev/null @@ -1,40 +0,0 @@ -package gr.cite.annotation.common.scope.fake; - -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; - -import java.io.Closeable; - -public class FakeRequestScope implements Closeable { - private RequestAttributes initialRequestAttributes = null; - private FakeRequestAttributes currentRequestAttributes = null; - boolean isInUse = false; - - public FakeRequestScope() { - this.reset(); - } - - public void reset() { - this.close(); - this.isInUse = true; - - this.initialRequestAttributes = RequestContextHolder.getRequestAttributes(); - this.currentRequestAttributes = new FakeRequestAttributes(); - RequestContextHolder.setRequestAttributes(this.currentRequestAttributes); - } - - @Override - public void close() { - if (!this.isInUse) return; - this.isInUse = false; - - if (initialRequestAttributes != null) RequestContextHolder.setRequestAttributes(initialRequestAttributes); - else RequestContextHolder.resetRequestAttributes(); - - if (currentRequestAttributes != null) currentRequestAttributes.requestCompleted(); - - this.initialRequestAttributes = null; - this.currentRequestAttributes = null; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/MultitenancyConfiguration.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/MultitenancyConfiguration.java deleted file mode 100644 index da3e14576..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/MultitenancyConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.annotation.common.scope.tenant; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties(MultitenancyProperties.class) -public class MultitenancyConfiguration { -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/MultitenancyProperties.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/MultitenancyProperties.java deleted file mode 100644 index 258e6bdfe..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/MultitenancyProperties.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.annotation.common.scope.tenant; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "tenant.multitenancy") -public class MultitenancyProperties { - private boolean isMultitenant; - private String defaultTenantCode; - - public boolean isMultitenant() { - return isMultitenant; - } - - public void setIsMultitenant(boolean multitenant) { - isMultitenant = multitenant; - } - - public void setMultitenant(boolean multitenant) { - isMultitenant = multitenant; - } - - public String getDefaultTenantCode() { - return defaultTenantCode; - } - - public void setDefaultTenantCode(String defaultTenantCode) { - this.defaultTenantCode = defaultTenantCode; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/TenantScope.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/TenantScope.java deleted file mode 100644 index f91403fc3..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/TenantScope.java +++ /dev/null @@ -1,88 +0,0 @@ -package gr.cite.annotation.common.scope.tenant; - -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.EntityManager; -import org.hibernate.Session; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; - -@Component -@RequestScope -public class TenantScope { - public static final String TenantReplaceParameter = "::TenantCode::"; - private final MultitenancyProperties multitenancy; - private final AtomicReference tenant = new AtomicReference<>(); - private final AtomicReference tenantCode = new AtomicReference<>(); - private final AtomicReference initialTenant = new AtomicReference<>(); - private final AtomicReference initialTenantCode = new AtomicReference<>(); - - @Autowired - public TenantScope(MultitenancyProperties multitenancy) { - this.multitenancy = multitenancy; - } - - public Boolean isMultitenant() { - return this.multitenancy.isMultitenant(); - } - - public String getDefaultTenantCode() { - return this.multitenancy.getDefaultTenantCode(); - } - - public Boolean isSet() { - if (!this.isMultitenant()) - return Boolean.TRUE; - return this.tenant.get() != null || this.isDefaultTenant(); - } - - public Boolean isDefaultTenant() { - if (!this.isMultitenant()) - return Boolean.TRUE; - return this.multitenancy.getDefaultTenantCode().equalsIgnoreCase(this.tenantCode.get()); - } - - public UUID getTenant() throws InvalidApplicationException { - if (!this.isMultitenant()) - return null; - if (this.tenant.get() == null && !this.isDefaultTenant()) - throw new InvalidApplicationException("tenant not set"); - return this.isDefaultTenant() ? null : this.tenant.get(); - } - - public String getTenantCode() throws InvalidApplicationException { - if (!this.isMultitenant()) - return null; - if (this.tenantCode.get() == null) - throw new InvalidApplicationException("tenant not set"); - return this.tenantCode.get(); - } - - public void setTempTenant(TenantEntityManager entityManager, UUID tenant, String tenantCode) throws InvalidApplicationException { - this.tenant.set(tenant); - this.tenantCode.set(tenantCode); - - entityManager.reloadTenantFilters(); - } - - public void removeTempTenant(TenantEntityManager entityManager) throws InvalidApplicationException { - this.tenant.set(this.initialTenant.get()); - this.tenantCode.set(this.initialTenantCode.get()); - - entityManager.reloadTenantFilters(); - } - - public void setTenant(UUID tenant, String tenantCode) { - if (this.isMultitenant()) { - this.tenant.set(tenant); - this.initialTenant.set(tenant); - this.tenantCode.set(tenantCode); - this.initialTenantCode.set(tenantCode); - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/TenantScoped.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/TenantScoped.java deleted file mode 100644 index ac36b0022..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/tenant/TenantScoped.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.annotation.common.scope.tenant; - -import java.util.UUID; - -public interface TenantScoped { - void setTenantId(UUID tenantId); - UUID getTenantId(); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/user/UserScope.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/user/UserScope.java deleted file mode 100644 index a027aefcb..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/scope/user/UserScope.java +++ /dev/null @@ -1,34 +0,0 @@ -package gr.cite.annotation.common.scope.user; - -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.util.UUID; - -@Component -@RequestScope -public class UserScope { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserScope.class)); - private UUID userId = null; - - public Boolean isSet(){ - return this.userId != null; - } - - public UUID getUserId() throws InvalidApplicationException { - if (this.userId == null) throw new InvalidApplicationException("user not set"); - return this.userId; - } - - public UUID getUserIdSafe() { - return this.userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } -} - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/user/AdditionalInfoEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/user/AdditionalInfoEntity.java deleted file mode 100644 index 17af7cf93..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/user/AdditionalInfoEntity.java +++ /dev/null @@ -1,60 +0,0 @@ -package gr.cite.annotation.common.types.user; - -import java.util.UUID; - -public class AdditionalInfoEntity { - private String avatarUrl; - private String timezone; - private String culture; - private String language; - private String roleOrganization; - private UUID organizationId; - - public String getAvatarUrl() { - return avatarUrl; - } - - public void setAvatarUrl(String avatarUrl) { - this.avatarUrl = avatarUrl; - } - - public String getTimezone() { - return timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public String getCulture() { - return culture; - } - - public void setCulture(String culture) { - this.culture = culture; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public UUID getOrganizationId() { - return organizationId; - } - - public void setOrganizationId(UUID organizationId) { - this.organizationId = organizationId; - } - - public String getRoleOrganization() { - return roleOrganization; - } - - public void setRoleOrganization(String roleOrganization) { - this.roleOrganization = roleOrganization; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/xml/XmlBuilder.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/xml/XmlBuilder.java deleted file mode 100644 index 405501d23..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/xml/XmlBuilder.java +++ /dev/null @@ -1,87 +0,0 @@ -package gr.cite.annotation.common.types.xml; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; - - -public class XmlBuilder { - private static final Logger logger = LoggerFactory.getLogger(XmlBuilder.class); - - public static Document getDocument() { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder; - try { - docBuilder = docFactory.newDocumentBuilder(); - Document doc = docBuilder.newDocument(); - return doc; - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - logger.error(e.getMessage(), e); - return null; - } - } - - public static String generateXml(Document doc) { - TransformerFactory tFact = TransformerFactory.newInstance(); - Transformer trans; - try { - trans = tFact.newTransformer(); - StringWriter writer = new StringWriter(); - StreamResult result = new StreamResult(writer); - DOMSource source = new DOMSource(doc); - trans.setOutputProperty(OutputKeys.INDENT, "yes"); - trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - trans.transform(source, result); - return writer.toString(); - } catch (TransformerException e) { - // TODO Auto-generated catch block - logger.error(e.getMessage(), e); - return null; - } - } - - public static Document fromXml(String xml) { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder; - try { - docBuilder = docFactory.newDocumentBuilder(); - InputSource inputStream = new InputSource(new StringReader(xml)); - Document doc = docBuilder.parse(inputStream); - return doc; - } catch (ParserConfigurationException | SAXException | IOException e) { - // TODO Auto-generated catch block - logger.error(e.getMessage(), e); - return null; - } - } - - - public static Element getNodeFromListByTagName(NodeList list, String tagName) { - for (int temp = 0; temp < list.getLength(); temp++) { - Node element = list.item(temp); - if (element.getNodeType() == Node.ELEMENT_NODE) { - if (element.getNodeName().equals(tagName)) return (Element) element; - } - } - return null; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/xml/XmlSerializable.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/xml/XmlSerializable.java deleted file mode 100644 index b9712f9b5..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/types/xml/XmlSerializable.java +++ /dev/null @@ -1,11 +0,0 @@ -package gr.cite.annotation.common.types.xml; - - -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -public interface XmlSerializable { - Element toXml(Document doc); - - T fromXml(Element item); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/validation/BaseValidator.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/validation/BaseValidator.java deleted file mode 100644 index 9c83f55ac..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/validation/BaseValidator.java +++ /dev/null @@ -1,63 +0,0 @@ -package gr.cite.annotation.common.validation; - -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.validation.AbstractValidator; -import gr.cite.tools.validation.ValidationResult; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public abstract class BaseValidator extends AbstractValidator { - protected final ConventionService conventionService; - protected final ErrorThesaurusProperties errors; - - protected BaseValidator(ConventionService conventionService, ErrorThesaurusProperties errors) { - this.conventionService = conventionService; - this.errors = errors; - } - - @Override - public void validateForce(Object target) { - this.validate(target); - ValidationResult result = result(); - if (!result.isValid()) { - List>> errorsMap = this.flattenValidationResult(); - throw new MyValidationException(this.errors.getModelValidation().getCode(), errorsMap); - } - } - - protected Boolean isValidGuid(UUID guid) { - return this.conventionService.isValidGuid(guid); - } - - protected Boolean isValidHash(String hash) { - return this.conventionService.isValidHash(hash); - } - - protected Boolean isEmpty(String value) { - return this.conventionService.isNullOrEmpty(value); - } - protected Boolean isListNullOrEmpty(List value) { - return this.conventionService.isListNullOrEmpty(value); - } - protected Boolean isNull(Object value) { - return value == null; - } - - protected Boolean isNull(Collection value) { - return value == null; - } - - protected Boolean lessEqualLength(String value, int size) { - return value.length() <= size; - } - - protected Boolean lessEqual(Integer value, int target) { - return value <= target; - } -} - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/validation/UuidValidator.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/common/validation/UuidValidator.java deleted file mode 100644 index ffc1a90a1..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/common/validation/UuidValidator.java +++ /dev/null @@ -1,43 +0,0 @@ -package gr.cite.annotation.common.validation; - -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.tools.validation.specification.Specification; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -@Component(UuidValidator.ValidatorName) -@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UuidValidator extends BaseValidator { - - public static final String ValidatorName = "UuidValidator"; - - private final MessageSource messageSource; - - protected UuidValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return UUID.class; - } - - @Override - protected List specifications(UUID item) { - return Collections.singletonList( - this.spec() - .must(() -> this.isValidGuid(item)) - .failOn("uuid").failWith(messageSource.getMessage("Validation_Required", new Object[]{"uuid"}, LocaleContextHolder.getLocale())) - ); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/convention/ConventionService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/convention/ConventionService.java deleted file mode 100644 index 8821066d5..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/convention/ConventionService.java +++ /dev/null @@ -1,41 +0,0 @@ -package gr.cite.annotation.convention; - -import gr.cite.tools.exception.MyApplicationException; - -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.function.Function; - -public interface ConventionService { - Boolean isValidId(Integer id); - - Boolean isValidGuid(UUID guid); - - Boolean isValidUUID(String str); - UUID parseUUIDSafe(String str); - - Boolean isValidHash(String hash); - - String hashValue(Object value) throws MyApplicationException; - - String limit(String text, int maxLength); - - String truncate(String text, int maxLength); - - UUID getEmptyUUID(); - - boolean isNullOrEmpty(String value); - - boolean isListNullOrEmpty(List value); - - String stringEmpty(); - - String asPrefix(String name); - - String asIndexerPrefix(String part); - - String asIndexer(String... names); - - Map> toDictionaryOfList(List items, Function keySelector); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/convention/ConventionServiceImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/convention/ConventionServiceImpl.java deleted file mode 100644 index 03b10882e..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/convention/ConventionServiceImpl.java +++ /dev/null @@ -1,150 +0,0 @@ -package gr.cite.annotation.convention; - -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) -public class ConventionServiceImpl implements ConventionService { - private final static Pattern UUID_REGEX_PATTERN = Pattern.compile("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"); - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(ConventionServiceImpl.class)); - private final ErrorThesaurusProperties errors; - - @Autowired - public ConventionServiceImpl(ErrorThesaurusProperties errors) { - this.errors = errors; - } - - @Override - public Boolean isValidId(Integer id) { - return id != null && id > 0; - } - - @Override - public Boolean isValidGuid(UUID guid) { - return guid != null && !guid.equals(this.getEmptyUUID()); - } - - @Override - public Boolean isValidUUID(String str) { - if (this.isNullOrEmpty(str)) { - return false; - } - return UUID_REGEX_PATTERN.matcher(str).matches(); - } - - @Override - public UUID parseUUIDSafe(String str) { - if (!this.isValidUUID(str)) { - return null; - } - try { - return UUID.fromString(str); - } catch (Exception ex){ - logger.warn("invalid uuid" + str, ex); - return null; - } - } - - @Override - public Boolean isValidHash(String hash) { - return !this.isNullOrEmpty(hash); - } - - @Override - public String hashValue(Object value) throws MyApplicationException { - if (value == null) return this.stringEmpty(); - if (value instanceof Instant) return String.format("%ts", (Instant) value); - throw new MyApplicationException(this.errors.getSystemError().getCode(), this.errors.getSystemError().getMessage()); - } - - @Override - public String limit(String text, int maxLength) { - if (this.isNullOrEmpty(text)) return text; - if (text.length() > maxLength) return String.format("%s...", text.substring(0, maxLength)); - else return text; - } - - @Override - public String truncate(String text, int maxLength) { - String truncated = text; - if (text.length() < maxLength) return text; - - truncated = truncated.trim(); - truncated = truncated.replaceAll("\\s+", " ");//remove multiple spaces - if (truncated.length() < maxLength) return truncated; - truncated = truncated.replaceAll("([.!@#$%^&-=':;,<>?*\\\"/|])+", "");//remove multiple spaces - if (truncated.length() < maxLength) return truncated; - truncated = truncated.replaceAll("([aeiou])+", "");//remove multiple spaces - if (truncated.length() < maxLength) return truncated; - truncated = truncated.replaceAll("([AEIOU])+", "");//remove multiple spaces - if (truncated.length() < maxLength) return truncated; - - if (text.length() > maxLength) return String.format("%s...", text.substring(0, maxLength)); - return text; - - } - - @Override - public UUID getEmptyUUID() { - return new UUID(0L, 0L); - } - - @Override - public boolean isNullOrEmpty(String value) { - return value == null || value.isBlank(); - } - - @Override - public boolean isListNullOrEmpty(List value) { - if(value == null) return true; - return value.size() <= 0; - } - - @Override - public String stringEmpty() { - return ""; - } - - @Override - public String asPrefix(String name) { - if (name == null) return null; - return name + "."; - } - - @Override - public String asIndexer(String... names) { - if (names == null) return null; - return String.join(".", Arrays.stream(names).filter(x -> !this.isNullOrEmpty(x)).collect(Collectors.toList())); - } - - @Override - public String asIndexerPrefix(String part) { - if (part == null) return null; - return part + "."; - } - - @Override - public Map> toDictionaryOfList(List items, Function keySelector) { - Map> map = new HashMap<>(); - for (V model : items) { - K key = keySelector.apply(model); - if (!map.containsKey(key)) map.put(key, new ArrayList()); - map.get(key).add(model); - } - return map; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/AnnotationEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/AnnotationEntity.java deleted file mode 100644 index 63b076f00..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/AnnotationEntity.java +++ /dev/null @@ -1,188 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.AnnotationProtectionTypeConverter; -import gr.cite.annotation.data.conventers.IsActiveConverter; -import gr.cite.annotation.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"Annotation\"") -public class AnnotationEntity extends TenantScopedBaseEntity { - - @Id - @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "entity_id", columnDefinition = "uuid", nullable = false) - private UUID entityId; - - public static final String _entityId = "entityId"; - - @Column(name = "entity_type", nullable = false) - private String entityType; - - public static final String _entityType = "entityType"; - - @Column(name = "anchor") - private String anchor; - - public static final String _anchor = "anchor"; - - @Column(name = "payload", nullable = false) - private String payload; - - public static final String _payload = "payload"; - - @Column(name = "subject_id", columnDefinition = "uuid", nullable = false) - private UUID subjectId; - - public static final String _subjectId = "subjectId"; - - @Column(name = "thread_id", columnDefinition = "uuid") - private UUID threadId; - - public static final String _threadId = "threadId"; - - @Column(name = "parent_id", columnDefinition = "uuid") - private UUID parentId; - - public static final String _parentId = "parentId"; - - @Column(name = "protection_type", nullable = false) - @Convert(converter = AnnotationProtectionTypeConverter.class) - private AnnotationProtectionType protectionType; - - public static final String _protectionType = "protectionType"; - - @Column(name = "time_stamp", nullable = false) - private Instant timeStamp; - - public static final String _timeStamp = "timeStamp"; - - @Column(name = "\"created_at\"", nullable = false) - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - @Column(name = "\"updated_at\"", nullable = false) - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - @Column(name = "is_active", nullable = false) - @Convert(converter = IsActiveConverter.class) - private IsActive isActive; - - public static final String _isActive = "isActive"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public UUID getEntityId() { - return entityId; - } - - public void setEntityId(UUID entityId) { - this.entityId = entityId; - } - - public String getEntityType() { - return entityType; - } - - public void setEntityType(String entityType) { - this.entityType = entityType; - } - - public String getAnchor() { - return anchor; - } - - public void setAnchor(String anchor) { - this.anchor = anchor; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public UUID getSubjectId() { - return subjectId; - } - - public void setSubjectId(UUID subjectId) { - this.subjectId = subjectId; - } - - public UUID getThreadId() { - return threadId; - } - - public void setThreadId(UUID threadId) { - this.threadId = threadId; - } - - public UUID getParentId() { - return parentId; - } - - public void setParentId(UUID parentId) { - this.parentId = parentId; - } - - public Instant getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(Instant timeStamp) { - this.timeStamp = timeStamp; - } - - public AnnotationProtectionType getProtectionType() { - return protectionType; - } - - public void setProtectionType(AnnotationProtectionType protectionType) { - this.protectionType = protectionType; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/EntityUserEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/EntityUserEntity.java deleted file mode 100644 index 935228cb9..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/EntityUserEntity.java +++ /dev/null @@ -1,94 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.IsActiveConverter; -import gr.cite.annotation.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"EntityUser\"") -public class EntityUserEntity extends TenantScopedBaseEntity { - - @Id - @Column(name = "\"id\"", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "\"entity_id\"", columnDefinition = "uuid", nullable = false) - private UUID entityId; - - public static final String _entityId = "entityId"; - - @Column(name = "\"user_id\"", columnDefinition = "uuid", nullable = false) - private UUID userId; - - public static final String _userId = "userId"; - - @Column(name = "\"created_at\"", nullable = false) - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - @Column(name = "\"updated_at\"", nullable = false) - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - @Column(name = "is_active", nullable = false) - @Convert(converter = IsActiveConverter.class) - private IsActive isActive; - - public static final String _isActive = "isActive"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public UUID getEntityId() { - return entityId; - } - - public void setEntityId(UUID entityId) { - this.entityId = entityId; - } - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/QueueInboxEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/QueueInboxEntity.java deleted file mode 100644 index 4847bc080..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/QueueInboxEntity.java +++ /dev/null @@ -1,195 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.IsActiveConverter; -import gr.cite.annotation.data.conventers.QueueInboxStatusConverter; -import gr.cite.annotation.data.types.JsonSQLType; -import gr.cite.queueinbox.entity.QueueInbox; -import gr.cite.queueinbox.entity.QueueInboxStatus; -import jakarta.persistence.*; -import org.hibernate.annotations.Type; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"QueueInbox\"") -public class QueueInboxEntity implements QueueInbox { - - @Id - @Column(name = "\"id\"", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "\"queue\"", nullable = false, length = 200) - private String queue; - - public static final String _queue = "queue"; - - @Column(name = "\"exchange\"", nullable = false, length = 200) - private String exchange; - - public static final String _exchange = "exchange"; - - @Column(name = "\"route\"", nullable = false, length = 200) - private String route; - - public static final String _route = "route"; - - @Column(name = "\"application_id\"", nullable = false, length = 100) - private String applicationId; - - public static final String _applicationId = "applicationId"; - - @Column(name = "\"message_id\"", columnDefinition = "uuid", nullable = false) - private UUID messageId; - - public static final String _messageId = "messageId"; - - @Type(JsonSQLType.class) - @Column(name = "\"message\"", columnDefinition = "json", nullable = false) - private String message; - - public static final String _message = "message"; - - @Column(name = "\"retry_count\"") - private Integer retryCount; - - public static final String _retryCount = "retryCount"; - - @Column(name = "\"tenant\"", columnDefinition = "uuid") - private UUID tenantId; - - public static final String _tenantId = "tenantId"; - - @Column(name = "\"status\"", nullable = false) - @Convert(converter = QueueInboxStatusConverter.class) - private QueueInboxStatus status; - public final static String _status = "status"; - - - @Column(name = "\"created_at\"", nullable = false) - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - @Column(name = "\"updated_at\"", nullable = false) - @Version - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - @Column(name = "\"is_active\"", nullable = false) - @Convert(converter = IsActiveConverter.class) - private IsActive isActive; - - public static final String _isActive = "isActive"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getQueue() { - return queue; - } - - public void setQueue(String queue) { - this.queue = queue; - } - - public String getExchange() { - return exchange; - } - - public void setExchange(String exchange) { - this.exchange = exchange; - } - - public String getRoute() { - return route; - } - - public void setRoute(String route) { - this.route = route; - } - - public String getApplicationId() { - return applicationId; - } - - public void setApplicationId(String applicationId) { - this.applicationId = applicationId; - } - - public UUID getMessageId() { - return messageId; - } - - public void setMessageId(UUID messageId) { - this.messageId = messageId; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public Integer getRetryCount() { - return retryCount; - } - - public void setRetryCount(Integer retryCount) { - this.retryCount = retryCount; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - - public QueueInboxStatus getStatus() { - return status; - } - - public void setStatus(QueueInboxStatus status) { - this.status = status; - } - - @Override - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } -} - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/QueueOutboxEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/QueueOutboxEntity.java deleted file mode 100644 index 58ac5950d..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/QueueOutboxEntity.java +++ /dev/null @@ -1,206 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.IsActiveConverter; -import gr.cite.annotation.data.conventers.QueueOutboxNotifyStatusConverter; -import gr.cite.queueoutbox.entity.QueueOutbox; -import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"QueueOutbox\"") -public class QueueOutboxEntity implements QueueOutbox { - - @Id - @Column(name = "\"id\"", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "\"exchange\"", nullable = false, length = 200) - private String exchange; - - public static final String _exchange = "exchange"; - - @Column(name = "\"route\"", length = 200) - private String route; - - public static final String _route = "route"; - - @Column(name = "\"message_id\"", columnDefinition = "uuid", nullable = false) - private UUID messageId; - - public static final String _messageId = "messageId"; - - @Column(name = "\"message\"", columnDefinition = "json", nullable = false) - private String message; - - public static final String _message = "message"; - - @Column(name = "\"notify_status\"", nullable = false) - @Convert(converter = QueueOutboxNotifyStatusConverter.class) - private QueueOutboxNotifyStatus notifyStatus; - public final static String _notifyStatus = "notifyStatus"; - - @Column(name = "\"retry_count\"", nullable = false) - private Integer retryCount; - - public static final String _retryCount = "retryCount"; - - @Column(name = "\"published_at\"") - private Instant publishedAt; - - public static final String _publishedAt = "publishedAt"; - - @Column(name = "\"confirmed_at\"") - private Instant confirmedAt; - - public static final String _confirmedAt = "confirmedAt"; - - @Column(name = "\"tenant\"", columnDefinition = "uuid") - private UUID tenantId; - - public static final String _tenantId = "tenantId"; - - @Column(name = "\"created_at\"", nullable = false) - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - @Column(name = "\"updated_at\"", nullable = false) - @Version - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - @Column(name = "\"is_active\"", length = 20, nullable = false) - @Convert(converter = IsActiveConverter.class) - private IsActive isActive; - - public static final String _isActive = "isActive"; - - @Override - public UUID getId() { - return id; - } - - @Override - public void setId(UUID id) { - this.id = id; - } - - public String getExchange() { - return exchange; - } - - public void setExchange(String exchange) { - this.exchange = exchange; - } - - @Override - public String getRoute() { - return route; - } - - @Override - public void setRoute(String route) { - this.route = route; - } - - @Override - public UUID getMessageId() { - return messageId; - } - - @Override - public void setMessageId(UUID messageId) { - this.messageId = messageId; - } - - @Override - public String getMessage() { - return message; - } - - @Override - public void setMessage(String message) { - this.message = message; - } - - @Override - public QueueOutboxNotifyStatus getNotifyStatus() { - return notifyStatus; - } - - @Override - public void setNotifyStatus(QueueOutboxNotifyStatus notifyStatus) { - this.notifyStatus = notifyStatus; - } - - @Override - public Integer getRetryCount() { - return retryCount; - } - - public void setRetryCount(Integer retryCount) { - this.retryCount = retryCount; - } - - @Override - public Instant getPublishedAt() { - return publishedAt; - } - - @Override - public void setPublishedAt(Instant publishedAt) { - this.publishedAt = publishedAt; - } - - @Override - public Instant getConfirmedAt() { - return confirmedAt; - } - - @Override - public void setConfirmedAt(Instant confirmedAt) { - this.confirmedAt = confirmedAt; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - - @Override - public Instant getCreatedAt() { - return createdAt; - } - - @Override - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } -} - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantEntity.java deleted file mode 100644 index bf7ceb77f..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantEntity.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.IsActiveConverter; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"Tenant\"") -public class TenantEntity { - - @Id - @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "code", length = 200, nullable = false) - private String code; - - public static final String _code = "code"; - - @Column(name = "created_at", nullable = false) - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - @Column(name = "updated_at", nullable = false) - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - @Column(name = "is_active", length = 20, nullable = false) - @Convert(converter = IsActiveConverter.class) - private IsActive isActive; - - public static final String _isActive = "isActive"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantEntityManager.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantEntityManager.java deleted file mode 100644 index 5d51df90c..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantEntityManager.java +++ /dev/null @@ -1,165 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.common.scope.tenant.TenantScoped; -import gr.cite.annotation.data.tenant.TenantScopedBaseEntity; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.tools.exception.MyForbiddenException; -import jakarta.persistence.EntityManager; -import jakarta.persistence.FlushModeType; -import jakarta.persistence.PersistenceContext; -import org.hibernate.Session; -import org.springframework.stereotype.Service; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; - -@Service -@RequestScope -public class TenantEntityManager { - @PersistenceContext - private EntityManager entityManager; - private final TenantScope tenantScope; - private final ErrorThesaurusProperties errors; - - boolean tenantFiltersDisabled; - - public TenantEntityManager(TenantScope tenantScope, ErrorThesaurusProperties errors) { - this.tenantScope = tenantScope; - this.errors = errors; - this.tenantFiltersDisabled = false; - } - - - public void persist(Object entity) { - this.entityManager.persist(entity); - } - - public T merge(T entity) throws InvalidApplicationException { - if (!this.tenantFiltersDisabled && this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (!this.tenantScope.isDefaultTenant()) { - if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } else if (tenantScopedEntity.getTenantId() != null) { - throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } - } - return this.entityManager.merge(entity); - } - - public void remove(Object entity) throws InvalidApplicationException { - if (!this.tenantFiltersDisabled && this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (!this.tenantScope.isDefaultTenant()) { - if (tenantScopedEntity.getTenantId() == null || !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } else if (tenantScopedEntity.getTenantId() != null) { - throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } - } - this.entityManager.remove(entity); - } - - public T find(Class entityClass, Object primaryKey) throws InvalidApplicationException { - T entity = this.entityManager.find(entityClass, primaryKey); - - if (!this.tenantFiltersDisabled && this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) return null; - } - return entity; - } - - public T find(Class entityClass, Object primaryKey, boolean disableTracking) throws InvalidApplicationException { - T entity = this.entityManager.find(entityClass, primaryKey); - - if (!this.tenantFiltersDisabled && this.tenantScope.isMultitenant() && (entity instanceof TenantScoped tenantScopedEntity)) { - if (tenantScopedEntity.getTenantId() != null && !tenantScopedEntity.getTenantId().equals(this.tenantScope.getTenant())) return null; - } - if (disableTracking) this.entityManager.detach(entity); - return entity; - } - - public void flush() { - this.entityManager.flush(); - } - - - public void setFlushMode(FlushModeType flushMode) { - this.entityManager.setFlushMode(flushMode); - - } - - public FlushModeType getFlushMode() { - return this.entityManager.getFlushMode(); - } - - public void clear() { - this.entityManager.clear(); - } - - public void reloadTenantFilters() throws InvalidApplicationException { - if (!this.entityManager.isOpen()) return; - - this.disableTenantFilters(); - - if (!this.tenantScope.isSet()) return; - - if (!this.tenantScope.isDefaultTenant()) { - this.entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenantScope.getTenant().toString()); - } else { - this.entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } - this.tenantFiltersDisabled = false; - } - - public void loadExplictTenantFilters() throws InvalidApplicationException { - if (!this.entityManager.isOpen()) return; - - this.disableTenantFilters(); - - if (!this.tenantScope.isSet()) return; - - if (!this.tenantScope.isDefaultTenant()) { - this.entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.TENANT_FILTER_EXPLICT) - .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, this.tenantScope.getTenant().toString()); - } else { - this.entityManager - .unwrap(Session.class) - .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - } - this.tenantFiltersDisabled = false; - } - - public void disableTenantFilters() { - if (!this.entityManager.isOpen()) return; - - this.entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.TENANT_FILTER); - - this.entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); - - this.entityManager - .unwrap(Session.class) - .disableFilter(TenantScopedBaseEntity.TENANT_FILTER_EXPLICT); - this.tenantFiltersDisabled = true; - } - - public boolean isTenantFiltersDisabled() { - return this.tenantFiltersDisabled; - } - - public EntityManager getEntityManager() { - return this.entityManager; - } - - public void setEntityManager(EntityManager entityManager) { - this.entityManager = entityManager; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantUserEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantUserEntity.java deleted file mode 100644 index fd4e79311..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/TenantUserEntity.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.IsActiveConverter; -import gr.cite.annotation.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"TenantUser\"") -public class TenantUserEntity extends TenantScopedBaseEntity { - - @Id - @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "user", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID userId; - - public static final String _userId = "userId"; - - @Column(name = "created_at", nullable = false) - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - @Column(name = "updated_at", nullable = false) - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - @Column(name = "is_active", nullable = false) - @Convert(converter = IsActiveConverter.class) - private IsActive isActive; - - public static final String _isActive = "isActive"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/UserCredentialEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/UserCredentialEntity.java deleted file mode 100644 index 650794344..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/UserCredentialEntity.java +++ /dev/null @@ -1,83 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.IsActiveConverter; -import gr.cite.annotation.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"UserCredential\"") -public class UserCredentialEntity { - - @Id - @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "\"user\"", columnDefinition = "uuid", nullable = false) - private UUID userId; - - public static final String _userId = "userId"; - - @Column(name = "\"external_id\"", length = UserCredentialEntity._externalIdLength, nullable = false) - private String externalId; - - public static final String _externalId = "externalId"; - - public static final int _externalIdLength = 512; - - @Column(name = "created_at", nullable = false) - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - @Column(name = "updated_at", nullable = false) - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public String getExternalId() { - return externalId; - } - - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/UserEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/UserEntity.java deleted file mode 100644 index 8938c1b01..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/UserEntity.java +++ /dev/null @@ -1,96 +0,0 @@ -package gr.cite.annotation.data; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.IsActiveConverter; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"User\"") -public class UserEntity { - - @Id - @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "name", length = UserEntity._nameLength) - private String name = null; - - public static final String _name = "name"; - - public static final int _nameLength = 250; - - @Column(name = "additional_info") - private String additionalInfo; - - public static final String _additionalInfo = "additionalInfo"; - - @Column(name = "created_at", nullable = false) - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - @Column(name = "updated_at", nullable = false) - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - @Column(name = "is_active", nullable = false) - @Convert(converter = IsActiveConverter.class) - private IsActive isActive; - - public static final String _isActive = "isActive"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAdditionalInfo() { - return additionalInfo; - } - - public void setAdditionalInfo(String additionalInfo) { - this.additionalInfo = additionalInfo; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/AnnotationProtectionTypeConverter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/AnnotationProtectionTypeConverter.java deleted file mode 100644 index 16ce5a15c..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/AnnotationProtectionTypeConverter.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.annotation.data.conventers; - -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import jakarta.persistence.Converter; - -@Converter -public class AnnotationProtectionTypeConverter extends DatabaseEnumConverter{ - @Override - protected AnnotationProtectionType of(Short i) { - return AnnotationProtectionType.of(i); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/ContactInfoTypeConverter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/ContactInfoTypeConverter.java deleted file mode 100644 index 66c3a42df..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/ContactInfoTypeConverter.java +++ /dev/null @@ -1,11 +0,0 @@ -package gr.cite.annotation.data.conventers; - -import gr.cite.annotation.common.enums.ContactInfoType; -import jakarta.persistence.Converter; - -@Converter -public class ContactInfoTypeConverter extends DatabaseEnumConverter{ - protected ContactInfoType of(Short i) { - return ContactInfoType.of(i); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/DatabaseEnum.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/DatabaseEnum.java deleted file mode 100644 index 6ba8567f8..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/DatabaseEnum.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.annotation.data.conventers; - -import com.fasterxml.jackson.annotation.JsonValue; - -public interface DatabaseEnum { - @JsonValue - T getValue(); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/DatabaseEnumConverter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/DatabaseEnumConverter.java deleted file mode 100644 index fdba31797..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/DatabaseEnumConverter.java +++ /dev/null @@ -1,21 +0,0 @@ -package gr.cite.annotation.data.conventers; - - -import jakarta.persistence.AttributeConverter; -import jakarta.persistence.Converter; - -@Converter -public abstract class DatabaseEnumConverter, T> implements AttributeConverter { - protected abstract EnumType of(T dbData); - - @Override - public T convertToDatabaseColumn(EnumType value) { - if (value == null) throw new IllegalArgumentException("value"); - return value.getValue(); - } - - @Override - public EnumType convertToEntityAttribute(T dbData) { - return this.of(dbData); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/IsActiveConverter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/IsActiveConverter.java deleted file mode 100644 index 195d7e3c4..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/IsActiveConverter.java +++ /dev/null @@ -1,11 +0,0 @@ -package gr.cite.annotation.data.conventers; - -import gr.cite.annotation.common.enums.IsActive; -import jakarta.persistence.Converter; - -@Converter -public class IsActiveConverter extends DatabaseEnumConverter { - public IsActive of(Short i) { - return IsActive.of(i); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/QueueInboxStatusConverter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/QueueInboxStatusConverter.java deleted file mode 100644 index 2089859d8..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/QueueInboxStatusConverter.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.annotation.data.conventers; - -import gr.cite.queueinbox.entity.QueueInboxStatus; -import jakarta.persistence.AttributeConverter; -import jakarta.persistence.Converter; - -@Converter -public class QueueInboxStatusConverter implements AttributeConverter { - @Override - public Short convertToDatabaseColumn(QueueInboxStatus value) { - if (value == null) throw new IllegalArgumentException("Value could not be null for: " + this.getClass().getSimpleName()); - return value.getValue(); - } - - @Override - public QueueInboxStatus convertToEntityAttribute(Short dbData) { - return QueueInboxStatus.of(dbData); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/QueueOutboxNotifyStatusConverter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/QueueOutboxNotifyStatusConverter.java deleted file mode 100644 index a356181d1..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/QueueOutboxNotifyStatusConverter.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.annotation.data.conventers; - -import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; -import jakarta.persistence.AttributeConverter; -import jakarta.persistence.Converter; - -@Converter -public class QueueOutboxNotifyStatusConverter implements AttributeConverter { - @Override - public Short convertToDatabaseColumn(QueueOutboxNotifyStatus value) { - if (value == null) throw new IllegalArgumentException("Value could not be null for: " + this.getClass().getSimpleName()); - return value.getValue(); - } - - @Override - public QueueOutboxNotifyStatus convertToEntityAttribute(Short dbData) { - return QueueOutboxNotifyStatus.of(dbData); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/TenantConfigurationTypeConverter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/TenantConfigurationTypeConverter.java deleted file mode 100644 index 63623104d..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/conventers/TenantConfigurationTypeConverter.java +++ /dev/null @@ -1,11 +0,0 @@ -package gr.cite.annotation.data.conventers; - -import gr.cite.annotation.common.enums.TenantConfigurationType; -import jakarta.persistence.Converter; - -@Converter -public class TenantConfigurationTypeConverter extends DatabaseEnumConverter { - public TenantConfigurationType of(Short i) { - return TenantConfigurationType.of(i); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/namingstrategy/NamingStrategyProperties.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/namingstrategy/NamingStrategyProperties.java deleted file mode 100644 index a19a24967..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/namingstrategy/NamingStrategyProperties.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.annotation.data.namingstrategy; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.ConstructorBinding; - -@ConfigurationProperties(prefix = "naming-strategy") -public class NamingStrategyProperties { - - private final String prefix; - - @ConstructorBinding - public NamingStrategyProperties(String prefix) { - this.prefix = prefix; - } - - public String getPrefix() { - return prefix; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/namingstrategy/PrefixPhysicalNamingStrategy.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/namingstrategy/PrefixPhysicalNamingStrategy.java deleted file mode 100644 index eccf89595..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/namingstrategy/PrefixPhysicalNamingStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package gr.cite.annotation.data.namingstrategy; - -import gr.cite.annotation.common.StringUtils; -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.stereotype.Component; - -@Component -@EnableConfigurationProperties({NamingStrategyProperties.class}) -public class PrefixPhysicalNamingStrategy extends PhysicalNamingStrategyStandardImpl { - - private final NamingStrategyProperties namingStrategyProperties; - - public PrefixPhysicalNamingStrategy(NamingStrategyProperties namingStrategyProperties) { - this.namingStrategyProperties = namingStrategyProperties; - } - - @Override - public Identifier toPhysicalTableName(Identifier logicalName, JdbcEnvironment context) { - if (StringUtils.isNullOrEmpty(namingStrategyProperties.getPrefix())) - return super.toPhysicalTableName(logicalName, context); - Identifier identifier = new Identifier(namingStrategyProperties.getPrefix() + logicalName.getText(), logicalName.isQuoted()); - return super.toPhysicalTableName(identifier, context); - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantFilterAspect.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantFilterAspect.java deleted file mode 100644 index 32f63706e..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantFilterAspect.java +++ /dev/null @@ -1,44 +0,0 @@ -//package gr.cite.annotation.data.tenant; -// -//import gr.cite.annotation.common.scope.tenant.TenantScope; -//import jakarta.persistence.EntityManager; -//import org.aspectj.lang.JoinPoint; -//import org.aspectj.lang.annotation.AfterReturning; -//import org.aspectj.lang.annotation.Aspect; -//import org.hibernate.Session; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Component; -// -//import javax.management.InvalidApplicationException; -// -//@Aspect -//@Component -//public class TenantFilterAspect { -// -// private final TenantScope tenantScope; -// -// @Autowired -// public TenantFilterAspect( -// TenantScope tenantScope -// ) { -// this.tenantScope = tenantScope; -// } -// -// @AfterReturning( -// pointcut = "bean(entityManagerFactory) && execution(* createEntityManager(..))", -// returning = "retVal") -// public void getSessionAfter(JoinPoint joinPoint, Object retVal) throws InvalidApplicationException { -// if (retVal instanceof EntityManager && tenantScope.isSet()) { -// Session session = ((EntityManager) retVal).unwrap(Session.class); -// if(!tenantScope.isDefaultTenant()) { -// session -// .enableFilter(TenantScopedBaseEntity.TENANT_FILTER) -// .setParameter(TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, tenantScope.getTenant().toString()); -// } else { -// session -// .enableFilter(TenantScopedBaseEntity.DEFAULT_TENANT_FILTER); -// } -// } -// } -// -//} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantListener.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantListener.java deleted file mode 100644 index fbf00d649..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantListener.java +++ /dev/null @@ -1,83 +0,0 @@ -package gr.cite.annotation.data.tenant; - -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.common.scope.tenant.TenantScoped; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.PrePersist; -import jakarta.persistence.PreRemove; -import jakarta.persistence.PreUpdate; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.management.InvalidApplicationException; -import java.util.UUID; - -public class TenantListener { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantListener.class)); - private final TenantScope tenantScope; - - private final ErrorThesaurusProperties errors; - private final TenantEntityManager tenantEntityManager; - - - @Autowired - public TenantListener( - TenantScope tenantScope, ErrorThesaurusProperties errors, TenantEntityManager tenantEntityManager - ) { - this.tenantScope = tenantScope; - this.errors = errors; - this.tenantEntityManager = tenantEntityManager; - } - - @PrePersist - public void setTenantOnCreate(TenantScoped entity) throws InvalidApplicationException { - if (this.tenantEntityManager.isTenantFiltersDisabled()) return; - if (tenantScope.isMultitenant()) { - if (entity.getTenantId() != null && (this.tenantScope.isDefaultTenant() || entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { - logger.error("somebody tried to set not login tenant"); - throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } - if (!tenantScope.isDefaultTenant()) { - final UUID tenantId = tenantScope.getTenant(); - entity.setTenantId(tenantId); - } - } else { - entity.setTenantId(null); - } - } - - @PreUpdate - @PreRemove - public void setTenantOnUpdate(TenantScoped entity) throws InvalidApplicationException { - if (this.tenantEntityManager.isTenantFiltersDisabled()) return; - if (tenantScope.isMultitenant()) { - if (!tenantScope.isDefaultTenant()) { - if (entity.getTenantId() == null) { - logger.error("somebody tried to set null tenant"); - throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } - if (entity.getTenantId().compareTo(tenantScope.getTenant()) != 0) { - logger.error("somebody tried to change an entries tenant"); - throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } - - final UUID tenantId = tenantScope.getTenant(); - entity.setTenantId(tenantId); - } else { - if (entity.getTenantId() != null) { - logger.error("somebody tried to set null tenant"); - throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } - } - } else { - if (entity.getTenantId() != null && (!this.tenantScope.isDefaultTenant() ||entity.getTenantId().compareTo(tenantScope.getTenant()) != 0)) { - logger.error("somebody tried to change an entries tenant"); - throw new MyForbiddenException(this.errors.getTenantTampering().getCode(), this.errors.getTenantTampering().getMessage()); - } - } - - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantScopedBaseEntity.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantScopedBaseEntity.java deleted file mode 100644 index 14dd7f4fb..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/tenant/TenantScopedBaseEntity.java +++ /dev/null @@ -1,45 +0,0 @@ -package gr.cite.annotation.data.tenant; - -import gr.cite.annotation.common.scope.tenant.TenantScoped; -import jakarta.persistence.Column; -import jakarta.persistence.EntityListeners; -import jakarta.persistence.MappedSuperclass; -import org.hibernate.annotations.Filter; -import org.hibernate.annotations.FilterDef; -import org.hibernate.annotations.ParamDef; - -import java.io.Serial; -import java.io.Serializable; -import java.util.UUID; - -@MappedSuperclass -//@Getter -//@Setter -//@NoArgsConstructor -@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER, parameters = @ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)) -@FilterDef(name = TenantScopedBaseEntity.TENANT_FILTER_EXPLICT, parameters = @ParamDef(name = TenantScopedBaseEntity.TENANT_FILTER_TENANT_PARAM, type = String.class)) -@FilterDef(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER) -@Filter(name = TenantScopedBaseEntity.TENANT_FILTER, condition = "(tenant = (cast(:tenantId as uuid)) or tenant is null)") -@Filter(name = TenantScopedBaseEntity.TENANT_FILTER_EXPLICT, condition = "(tenant = (cast(:tenantId as uuid)))") -@Filter(name = TenantScopedBaseEntity.DEFAULT_TENANT_FILTER, condition = "(tenant = tenant is null)") -@EntityListeners(TenantListener.class) -public abstract class TenantScopedBaseEntity implements TenantScoped, Serializable { - private static final long serialVersionUID = 1L; - public static final String TENANT_FILTER = "tenantFilter"; - public static final String DEFAULT_TENANT_FILTER = "defaultTenantFilter"; - public static final String TENANT_FILTER_EXPLICT = "tenantFilterExplict"; - public static final String TENANT_FILTER_TENANT_PARAM = "tenantId"; - - @Column(name = "tenant", columnDefinition = "uuid", nullable = true) - private UUID tenantId; - public static final String _tenantId = "tenantId"; - public UUID getTenantId() { - return this.tenantId; - } - - @Override - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } -} - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/types/JsonSQLType.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/data/types/JsonSQLType.java deleted file mode 100644 index 73fa089f7..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/data/types/JsonSQLType.java +++ /dev/null @@ -1,80 +0,0 @@ -package gr.cite.annotation.data.types; - -import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.SqlTypes; -import org.hibernate.usertype.UserType; - -import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; - -public class JsonSQLType implements UserType { - - @Override - public int getSqlType() { - return SqlTypes.JSON; - } - - @Override - public Class returnedClass() { - return String.class; - } - - @Override - public boolean equals(String x, String y) { - if (x == null) { - return y == null; - } else { - return x.equals(y); - } - } - - @Override - public int hashCode(String x) { - return x.hashCode(); - } - - @Override - public String nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { - String json = rs.getString(position); - return rs.wasNull() ? null : json; - } - - @Override - public void nullSafeSet(PreparedStatement st, String value, int index, SharedSessionContractImplementor session) throws SQLException { - if (value == null) { - st.setNull(index, Types.OTHER); - } else { - st.setObject(index, value, Types.OTHER); - } - } - - @Override - public String deepCopy(String value) throws HibernateException { - return value; - } - - @Override - public boolean isMutable() { - return false; - } - - @Override - public Serializable disassemble(String value) throws HibernateException { - return value; - } - - @Override - public String assemble(Serializable cached, Object owner) throws HibernateException { - return (String) cached; - } - - @Override - public String replace(String original, String target, Object owner) throws HibernateException { - return original; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorDescription.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorDescription.java deleted file mode 100644 index 3de0020f5..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorDescription.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.annotation.errorcode; - -public class ErrorDescription { - private int code; - private String message; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorThesaurusConfiguration.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorThesaurusConfiguration.java deleted file mode 100644 index b05bbad1e..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorThesaurusConfiguration.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.annotation.errorcode; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties(ErrorThesaurusProperties.class) -public class ErrorThesaurusConfiguration { - -// private final ErrorThesaurusProperties properties; -// -// @Autowired -// public ErrorThesaurusConfiguration(ErrorThesaurusProperties properties) { -// this.properties = properties; -// } -// -// public ErrorThesaurusProperties getProperties() { -// return properties; -// } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorThesaurusProperties.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorThesaurusProperties.java deleted file mode 100644 index d8fcce302..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/errorcode/ErrorThesaurusProperties.java +++ /dev/null @@ -1,109 +0,0 @@ -package gr.cite.annotation.errorcode; - - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "error-thesaurus") -public class ErrorThesaurusProperties { - - private ErrorDescription hashConflict; - private ErrorDescription forbidden; - private ErrorDescription systemError; - private ErrorDescription missingTenant; - private ErrorDescription modelValidation; - private ErrorDescription nonPersonPrincipal; - private ErrorDescription singleTenantConfigurationPerTypeSupported; - private ErrorDescription incompatibleTenantConfigurationTypes; - private ErrorDescription overlappingTenantConfigurationNotifierList; - private ErrorDescription tenantNotAllowed; - private ErrorDescription tenantTampering; - - public ErrorDescription getHashConflict() { - return hashConflict; - } - - public void setHashConflict(ErrorDescription hashConflict) { - this.hashConflict = hashConflict; - } - - public ErrorDescription getForbidden() { - return forbidden; - } - - public void setForbidden(ErrorDescription forbidden) { - this.forbidden = forbidden; - } - - public ErrorDescription getSystemError() { - return systemError; - } - - public void setSystemError(ErrorDescription systemError) { - this.systemError = systemError; - } - - public ErrorDescription getMissingTenant() { - return missingTenant; - } - - public void setMissingTenant(ErrorDescription missingTenant) { - this.missingTenant = missingTenant; - } - - public ErrorDescription getModelValidation() { - return modelValidation; - } - - public void setModelValidation(ErrorDescription modelValidation) { - this.modelValidation = modelValidation; - } - - public ErrorDescription getNonPersonPrincipal() { - return nonPersonPrincipal; - } - - public void setNonPersonPrincipal(ErrorDescription nonPersonPrincipal) { - this.nonPersonPrincipal = nonPersonPrincipal; - } - - - public ErrorDescription getSingleTenantConfigurationPerTypeSupported() { - return singleTenantConfigurationPerTypeSupported; - } - - public void setSingleTenantConfigurationPerTypeSupported(ErrorDescription singleTenantConfigurationPerTypeSupported) { - this.singleTenantConfigurationPerTypeSupported = singleTenantConfigurationPerTypeSupported; - } - - public ErrorDescription getIncompatibleTenantConfigurationTypes() { - return incompatibleTenantConfigurationTypes; - } - - public void setIncompatibleTenantConfigurationTypes(ErrorDescription incompatibleTenantConfigurationTypes) { - this.incompatibleTenantConfigurationTypes = incompatibleTenantConfigurationTypes; - } - - public ErrorDescription getOverlappingTenantConfigurationNotifierList() { - return overlappingTenantConfigurationNotifierList; - } - - public void setOverlappingTenantConfigurationNotifierList(ErrorDescription overlappingTenantConfigurationNotifierList) { - this.overlappingTenantConfigurationNotifierList = overlappingTenantConfigurationNotifierList; - } - - public ErrorDescription getTenantNotAllowed() { - return tenantNotAllowed; - } - - public void setTenantNotAllowed(ErrorDescription tenantNotAllowed) { - this.tenantNotAllowed = tenantNotAllowed; - } - - public ErrorDescription getTenantTampering() { - return tenantTampering; - } - - public void setTenantTampering(ErrorDescription tenantTampering) { - this.tenantTampering = tenantTampering; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/EventBroker.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/event/EventBroker.java deleted file mode 100644 index c2479028a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/EventBroker.java +++ /dev/null @@ -1,41 +0,0 @@ -package gr.cite.annotation.event; - -import gr.cite.commons.web.oidc.apikey.events.ApiKeyStaleEvent; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.stereotype.Service; - -@Service -public class EventBroker { - @Autowired - private ApplicationEventPublisher applicationEventPublisher; - - public void emitApiKeyStale(String apiKey) { - this.applicationEventPublisher.publishEvent(new ApiKeyStaleEvent(apiKey)); - } - - public void emit(ApiKeyStaleEvent event) { - this.applicationEventPublisher.publishEvent(event); - } - - public void emit(TenantTouchedEvent event) { - this.applicationEventPublisher.publishEvent(event); - } - - public void emit(UserTouchedEvent event) { - this.applicationEventPublisher.publishEvent(event); - } - - public void emit(UserAddedToTenantEvent event) { - this.applicationEventPublisher.publishEvent(event); - } - - public void emit(UserRemovedFromTenantEvent event) { - this.applicationEventPublisher.publishEvent(event); - } - - public void emit(UserCredentialTouchedEvent event) { - this.applicationEventPublisher.publishEvent(event); - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/TenantTouchedEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/event/TenantTouchedEvent.java deleted file mode 100644 index db51f999a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/TenantTouchedEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -package gr.cite.annotation.event; - -import java.util.UUID; - -public class TenantTouchedEvent { - public TenantTouchedEvent() { - } - - public TenantTouchedEvent(UUID tenantId, String tenantCode) { - this.tenantId = tenantId; - this.tenantCode = tenantCode; - } - - private UUID tenantId; - private String tenantCode; - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - - public String getTenantCode() { - return tenantCode; - } - - public void setTenantCode(String tenantCode) { - this.tenantCode = tenantCode; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserAddedToTenantEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserAddedToTenantEvent.java deleted file mode 100644 index c3b90bbc9..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserAddedToTenantEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.annotation.event; - -import java.util.UUID; - -public class UserAddedToTenantEvent { - public UserAddedToTenantEvent() { - } - - public UserAddedToTenantEvent(UUID userId, UUID tenantId) { - this.userId = userId; - this.tenantId = tenantId; - } - - private UUID userId; - private UUID tenantId; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserCredentialTouchedEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserCredentialTouchedEvent.java deleted file mode 100644 index 35208c369..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserCredentialTouchedEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -package gr.cite.annotation.event; - -import java.util.UUID; - -public class UserCredentialTouchedEvent { - public UserCredentialTouchedEvent() { - } - - public UserCredentialTouchedEvent(UUID id, String subjectId) { - this.id = id; - this.subjectId = subjectId; - } - - private UUID id; - - public UUID getId() { - return this.id; - } - - public void setId(UUID id) { - this.id = id; - } - - private String subjectId; - - public String getSubjectId() { - return this.subjectId; - } - - public void setSubjectId(String subjectId) { - this.subjectId = subjectId; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserRemovedFromTenantEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserRemovedFromTenantEvent.java deleted file mode 100644 index 7b118e088..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserRemovedFromTenantEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.annotation.event; - -import java.util.UUID; - -public class UserRemovedFromTenantEvent { - public UserRemovedFromTenantEvent() { - } - - public UserRemovedFromTenantEvent(UUID userId, UUID tenantId) { - this.userId = userId; - this.tenantId = tenantId; - } - - private UUID userId; - private UUID tenantId; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserTouchedEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserTouchedEvent.java deleted file mode 100644 index 9308116cc..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/event/UserTouchedEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package gr.cite.annotation.event; - -import java.util.UUID; - -public class UserTouchedEvent { - public UserTouchedEvent() { - } - - public UserTouchedEvent(UUID userId) { - this.userId = userId; - } - - private UUID userId; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/AppRabbitConfigurer.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/AppRabbitConfigurer.java deleted file mode 100644 index b4ec3b7d2..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/AppRabbitConfigurer.java +++ /dev/null @@ -1,53 +0,0 @@ -package gr.cite.annotation.integrationevent; - -import gr.cite.annotation.integrationevent.inbox.InboxProperties; -import gr.cite.annotation.integrationevent.outbox.OutboxProperties; -import gr.cite.queueinbox.repository.InboxRepository; -import gr.cite.rabbitmq.RabbitConfigurer; -import gr.cite.rabbitmq.consumer.InboxBindings; -import gr.cite.rabbitmq.consumer.InboxCreator; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.util.ArrayList; -import java.util.List; - -@Configuration -@EnableConfigurationProperties({OutboxProperties.class, InboxProperties.class}) -@ConditionalOnProperty(prefix = "queue.rabbitmq", name = "listenerEnabled") -public class AppRabbitConfigurer extends RabbitConfigurer { - - private final ApplicationContext applicationContext; - - private final InboxProperties inboxProperties; - - public AppRabbitConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties) { - this.applicationContext = applicationContext; - this.inboxProperties = inboxProperties; - } - - @Bean - public InboxBindings inboxBindingsCreator() { - List bindingItems = new ArrayList<>(); - bindingItems.addAll(this.inboxProperties.getTenantRemovalTopic()); - bindingItems.addAll(this.inboxProperties.getTenantTouchTopic()); - bindingItems.addAll(this.inboxProperties.getUserRemovalTopic()); - bindingItems.addAll(this.inboxProperties.getUserTouchTopic()); - bindingItems.addAll(this.inboxProperties.getAnnotationEntitiesTouchTopic()); - bindingItems.addAll(this.inboxProperties.getAnnotationEntitiesRemovalTopic()); - - return new InboxBindings(bindingItems); - } - - @Bean(name = "InboxCreator") - public InboxCreator inboxCreator() { - return (params) -> { - InboxRepository inboxRepository = this.applicationContext.getBean(InboxRepository.class); - return inboxRepository.create(params) != null; - }; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/InboxIntegrationEventConfigurer.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/InboxIntegrationEventConfigurer.java deleted file mode 100644 index 8a86462bc..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/InboxIntegrationEventConfigurer.java +++ /dev/null @@ -1,33 +0,0 @@ -package gr.cite.annotation.integrationevent; - -import gr.cite.annotation.integrationevent.inbox.InboxProperties; -import gr.cite.annotation.integrationevent.inbox.InboxRepositoryImpl; -import gr.cite.queueinbox.InboxConfigurer; -import gr.cite.queueinbox.repository.InboxRepository; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties({InboxProperties.class}) -@ConditionalOnProperty(prefix = "queue.task.listener", name = "enable", matchIfMissing = false) -public class InboxIntegrationEventConfigurer extends InboxConfigurer { - - private final ApplicationContext applicationContext; - - private final InboxProperties inboxProperties; - - public InboxIntegrationEventConfigurer(ApplicationContext applicationContext, InboxProperties inboxProperties) { - this.applicationContext = applicationContext; - this.inboxProperties = inboxProperties; - } - - @Bean - public InboxRepository inboxRepositoryCreator() { - return new InboxRepositoryImpl(this.applicationContext, this.inboxProperties); - } - -} - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/IntegrationEventContextImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/IntegrationEventContextImpl.java deleted file mode 100644 index dae6eddde..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/IntegrationEventContextImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -package gr.cite.annotation.integrationevent; - -import gr.cite.rabbitmq.IntegrationEventContext; -import org.springframework.stereotype.Component; - -import java.util.UUID; - -@Component -public class IntegrationEventContextImpl implements IntegrationEventContext { - - private UUID tenant; - - public IntegrationEventContextImpl() { - } - - public UUID getTenant() { - return tenant; - } - - public void setTenant(UUID tenant) { - this.tenant = tenant; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/OutboxIntegrationEventConfigurer.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/OutboxIntegrationEventConfigurer.java deleted file mode 100644 index 7cb7306cf..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/OutboxIntegrationEventConfigurer.java +++ /dev/null @@ -1,73 +0,0 @@ -package gr.cite.annotation.integrationevent; - -import gr.cite.annotation.data.QueueOutboxEntity; -import gr.cite.annotation.integrationevent.outbox.OutboxProperties; -import gr.cite.annotation.integrationevent.outbox.OutboxRepositoryImpl; -import gr.cite.queueoutbox.IntegrationEventContextCreator; -import gr.cite.queueoutbox.OutboxConfigurer; -import gr.cite.queueoutbox.repository.OutboxRepository; -import gr.cite.rabbitmq.IntegrationEventMessageConstants; -import gr.cite.rabbitmq.RabbitProperties; -import gr.cite.rabbitmq.broker.MessageHydrator; -import org.springframework.amqp.core.MessageProperties; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Date; -import java.util.UUID; - -@Configuration -@EnableConfigurationProperties({OutboxProperties.class}) -@ConditionalOnProperty(prefix = "queue.task.publisher", name = "enable", matchIfMissing = false) -public class OutboxIntegrationEventConfigurer extends OutboxConfigurer { - private final ApplicationContext applicationContext; - private final OutboxProperties outboxProperties; - - public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext, OutboxProperties outboxProperties) { - this.applicationContext = applicationContext; - this.outboxProperties = outboxProperties; - } - - @Bean - public MessageHydrator messageHydrator(RabbitProperties rabbitProperties) { - return (message, event, eventContext) -> { - MessageProperties messageProperties = message.getMessageProperties(); - messageProperties.setAppId(rabbitProperties.getAppId()); - messageProperties.setContentEncoding(StandardCharsets.UTF_8.displayName()); - messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON); - //messageProperties.setUserId(userContext.getCurrentUser().toString()); - messageProperties.setTimestamp(Date.from(Instant.now())); - messageProperties.setMessageId(event.getMessageId().toString()); - - if (eventContext != null) { - UUID tenant = ((IntegrationEventContextImpl) eventContext).getTenant(); - if (tenant != null) { - messageProperties.setHeader(IntegrationEventMessageConstants.TENANT, tenant); - } - } - - return message; - }; - } - - @Bean - public IntegrationEventContextCreator integrationEventContextCreator() { - return (message) -> { - IntegrationEventContextImpl integrationEventContext = new IntegrationEventContextImpl(); - if (message instanceof QueueOutboxEntity) integrationEventContext.setTenant(((QueueOutboxEntity)message).getTenantId()); - return integrationEventContext; - }; - } - - @Bean - public OutboxRepository outboxRepositoryCreator() { - return new OutboxRepositoryImpl(this.applicationContext, this.outboxProperties); - } -} - - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/TrackedEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/TrackedEvent.java deleted file mode 100644 index d184dd1e5..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/TrackedEvent.java +++ /dev/null @@ -1,18 +0,0 @@ -package gr.cite.annotation.integrationevent; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) -public class TrackedEvent { - - public String trackingContextTag; - - public String getTrackingContextTag() { - return trackingContextTag; - } - - public void setTrackingContextTag(String trackingContextTag) { - this.trackingContextTag = trackingContextTag; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/ConsistencyHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/ConsistencyHandler.java deleted file mode 100644 index 158bf3dc4..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/ConsistencyHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox; - -public interface ConsistencyHandler { - - Boolean isConsistent(T consistencyPredicates); - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/ConsistencyPredicates.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/ConsistencyPredicates.java deleted file mode 100644 index c6077c6de..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/ConsistencyPredicates.java +++ /dev/null @@ -1,5 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox; - -public interface ConsistencyPredicates { - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/EventProcessingStatus.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/EventProcessingStatus.java deleted file mode 100644 index c4041160b..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/EventProcessingStatus.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox; - -public enum EventProcessingStatus { - Error, - Success, - Postponed, - Discard -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxPrincipal.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxPrincipal.java deleted file mode 100644 index fa10849f8..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxPrincipal.java +++ /dev/null @@ -1,68 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox; - -import gr.cite.commons.web.oidc.principal.MyPrincipal; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import org.springframework.security.oauth2.core.ClaimAccessor; -import org.springframework.security.oauth2.jwt.JwtClaimNames; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class InboxPrincipal implements MyPrincipal, ClaimAccessor { - - private final Map claims; - - private final boolean isAuthenticated; - - public InboxPrincipal(Boolean isAuthenticated, String name) { - this.claims = new HashMap<>(); - this.put(JwtClaimNames.SUB, name); - this.isAuthenticated = isAuthenticated; - } - - public static InboxPrincipal build(IntegrationEventProperties properties, ClaimExtractorProperties claimExtractorProperties) { - InboxPrincipal inboxPrincipal = new InboxPrincipal(true, "IntegrationEventQueueAppId"); - List clientKey = claimExtractorProperties.getMapping().getOrDefault("Client", null); - inboxPrincipal.put(clientKey != null && clientKey.getFirst() != null ? clientKey.getFirst().getType() : "client_id", properties.getAppId()); - inboxPrincipal.put("active", "true"); - List notBeforeKey = claimExtractorProperties.getMapping().getOrDefault("NotBefore", null); - inboxPrincipal.put(notBeforeKey != null && notBeforeKey.getFirst() != null ? notBeforeKey.getFirst().getType() :"nbf", Instant.now().minus(30, ChronoUnit.SECONDS).toString()); - List expiresAt = claimExtractorProperties.getMapping().getOrDefault("ExpiresAt", null); - inboxPrincipal.put(expiresAt != null && expiresAt.getFirst() != null ? expiresAt.getFirst().getType() :"exp", Instant.now().plus(10, ChronoUnit.MINUTES).toString()); - return inboxPrincipal; - } - - @Override - public Boolean isAuthenticated() { - return this.isAuthenticated; - } - - @Override - public Map getClaims() { - return this.claims; - } - - @Override - public List getClaimAsStringList(String claim) { - if (claims == null) - return null; - if (this.claims.containsKey(claim)){ - return List.of(this.claims.get(claim).toString()); - } - return null; - } - - @Override - public String getName() { - return this.getClaimAsString(JwtClaimNames.SUB); - } - - public void put(String key, Object value) { - this.claims.put(key, value); - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxProperties.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxProperties.java deleted file mode 100644 index b165a3e49..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxProperties.java +++ /dev/null @@ -1,67 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.List; - -@ConfigurationProperties(prefix = "queue.task.listener.options") -public class InboxProperties { - - private final String exchange; - - private final List tenantRemovalTopic; - - private final List tenantTouchTopic; - - private final List userRemovalTopic; - - private final List userTouchTopic; - - private final List annotationEntitiesTouchTopic; - private final List annotationEntitiesRemovalTopic; - - public InboxProperties( - String exchange, - List tenantRemovalTopic, - List tenantTouchTopic, - List userRemovalTopic, - List userTouchTopic, - List annotationEntitiesTouchTopic, List annotationEntitiesRemovalTopic) { - this.exchange = exchange; - this.tenantRemovalTopic = tenantRemovalTopic; - this.tenantTouchTopic = tenantTouchTopic; - this.userRemovalTopic = userRemovalTopic; - this.userTouchTopic = userTouchTopic; - this.annotationEntitiesTouchTopic = annotationEntitiesTouchTopic; - this.annotationEntitiesRemovalTopic = annotationEntitiesRemovalTopic; - } - - public List getTenantRemovalTopic() { - return tenantRemovalTopic; - } - - public List getTenantTouchTopic() { - return tenantTouchTopic; - } - - public List getUserRemovalTopic() { - return userRemovalTopic; - } - - public List getUserTouchTopic() { - return userTouchTopic; - } - - public List getAnnotationEntitiesTouchTopic() { - return annotationEntitiesTouchTopic; - } - - public List getAnnotationEntitiesRemovalTopic() { - return annotationEntitiesRemovalTopic; - } - - public String getExchange() { - return exchange; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxRepositoryImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxRepositoryImpl.java deleted file mode 100644 index 5c043f72e..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/InboxRepositoryImpl.java +++ /dev/null @@ -1,411 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.fake.FakeRequestScope; -import gr.cite.annotation.data.QueueInboxEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.integrationevent.inbox.annotationentitiesremoval.AnnotationEntitiesRemovalIntegrationEventHandler; -import gr.cite.annotation.integrationevent.inbox.annotationentitiestouch.AnnotationEntitiesTouchedIntegrationEventHandler; -import gr.cite.annotation.integrationevent.inbox.tenantremoval.TenantRemovalIntegrationEventHandler; -import gr.cite.annotation.integrationevent.inbox.tenanttouched.TenantTouchedIntegrationEventHandler; -import gr.cite.annotation.integrationevent.inbox.userremoval.UserRemovalIntegrationEventHandler; -import gr.cite.annotation.integrationevent.inbox.usertouched.UserTouchedIntegrationEventHandler; -import gr.cite.annotation.query.QueueInboxQuery; -import gr.cite.queueinbox.entity.QueueInbox; -import gr.cite.queueinbox.entity.QueueInboxStatus; -import gr.cite.queueinbox.repository.CandidateInfo; -import gr.cite.queueinbox.repository.InboxRepository; -import gr.cite.queueinbox.task.MessageOptions; -import gr.cite.rabbitmq.IntegrationEventMessageConstants; -import gr.cite.rabbitmq.consumer.InboxCreatorParams; -import gr.cite.tools.data.query.Ordering; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.*; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; - -import java.time.Instant; -import java.util.List; -import java.util.UUID; -import java.util.function.Function; - -public class InboxRepositoryImpl implements InboxRepository { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InboxRepositoryImpl.class)); - - protected final ApplicationContext applicationContext; - private final InboxProperties inboxProperties; - - @PersistenceUnit - private EntityManagerFactory entityManagerFactory; - - public InboxRepositoryImpl( - ApplicationContext applicationContext, - InboxProperties inboxProperties - ) { - this.applicationContext = applicationContext; - this.inboxProperties = inboxProperties; - } - - @Override - public CandidateInfo candidate(Instant lastCandidateCreationTimestamp, MessageOptions options) { - EntityTransaction transaction = null; - CandidateInfo candidate = null; - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - - transaction = entityManager.getTransaction(); - transaction.begin(); - - QueueInboxEntity item = queryFactory.query(QueueInboxQuery.class) - .isActives(IsActive.Active) - .status(QueueInboxStatus.PENDING, QueueInboxStatus.ERROR) - .retryThreshold(options.getRetryThreashold()) - .createdAfter(lastCandidateCreationTimestamp) - .ordering(new Ordering().addAscending(QueueInboxEntity._createdAt)) - .first(); - - if (item != null) { - QueueInboxStatus prevState = item.getStatus(); - item.setStatus(QueueInboxStatus.PROCESSING); - - entityManager.merge(item); - entityManager.flush(); - - candidate = new CandidateInfo(); - candidate.setId(item.getId()); - candidate.setCreatedAt(item.getCreatedAt()); - candidate.setPreviousState(prevState); - } - - transaction.commit(); - } catch (OptimisticLockException ex) { - // we get this if/when someone else already modified the notifications. We want to essentially ignore this, and keep working - logger.debug("Concurrency exception getting queue inbox. Skipping: {} ", ex.getMessage()); - if (transaction != null) - transaction.rollback(); - candidate = null; - } catch (Exception ex) { - logger.error("Problem getting list of queue inbox. Skipping: {}", ex.getMessage(), ex); - if (transaction != null) - transaction.rollback(); - candidate = null; - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem getting list of queue inbox. Skipping: {}", ex.getMessage(), ex); - } - - return candidate; - } - - @Override - public Boolean shouldOmit(CandidateInfo candidate, Function shouldOmit) { - EntityTransaction transaction = null; - boolean success = false; - - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - QueueInboxEntity item = queryFactory.query(QueueInboxQuery.class).ids(candidate.getId()).first(); - - if (item == null) { - logger.warn("Could not lookup queue inbox {} to process. Continuing...", candidate.getId()); - } else { - if (shouldOmit.apply(item)) { - item.setStatus(QueueInboxStatus.OMITTED); - - entityManager.merge(item); - entityManager.flush(); - success = true; - } - } - - transaction.commit(); - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - success = false; - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - return success; - } - - @Override - public boolean shouldWait(CandidateInfo candidate, Function itIsTimeFunc) { - EntityTransaction transaction = null; - boolean success = false; - - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - QueueInboxEntity item = queryFactory.query(QueueInboxQuery.class).ids(candidate.getId()).first(); - - if (item.getRetryCount() != null && item.getRetryCount() >= 1) { - Boolean itIsTime = itIsTimeFunc.apply(item); - - if (!itIsTime) { - item.setStatus(candidate.getPreviousState()); - - entityManager.merge(item); - entityManager.flush(); - success = true; - } - - success = !itIsTime; - } - transaction.commit(); - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - success = false; - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - return success; - } - - @Override - public QueueInbox create(InboxCreatorParams inboxCreatorParams) { - EntityTransaction transaction = null; - boolean success; - QueueInboxEntity queueMessage = null; - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - - Long messageCount = queryFactory.query(QueueInboxQuery.class).messageIds(UUID.fromString(inboxCreatorParams.getMessageId())).count(); - if (messageCount == null || messageCount == 0) { - queueMessage = this.createQueueInboxEntity(inboxCreatorParams); - transaction = entityManager.getTransaction(); - - transaction.begin(); - entityManager.persist(queueMessage); - entityManager.flush(); - - transaction.commit(); - } - - success = true; - } catch (Exception ex) { - success = false; - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) transaction.rollback(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - success = false; - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - return success ? queueMessage : null; - } - - private QueueInboxEntity createQueueInboxEntity(InboxCreatorParams inboxCreatorParams) { - QueueInboxEntity queueMessage = new QueueInboxEntity(); - queueMessage.setId(UUID.randomUUID()); - Object tenantId = inboxCreatorParams.getHeaders() != null ? inboxCreatorParams.getHeaders().getOrDefault(IntegrationEventMessageConstants.TENANT, null) : null; - if (tenantId instanceof UUID) queueMessage.setTenantId((UUID) tenantId); - else if (tenantId instanceof String) { - try { - queueMessage.setTenantId(UUID.fromString((String) tenantId)); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } - queueMessage.setExchange(this.inboxProperties.getExchange()); - queueMessage.setRoute(inboxCreatorParams.getRoutingKey()); - queueMessage.setQueue(inboxCreatorParams.getQueueName()); - queueMessage.setApplicationId(inboxCreatorParams.getAppId()); - queueMessage.setMessageId(UUID.fromString(inboxCreatorParams.getMessageId())); - queueMessage.setMessage(inboxCreatorParams.getMessageBody()); - queueMessage.setIsActive(IsActive.Active); - queueMessage.setStatus(QueueInboxStatus.PENDING); - queueMessage.setRetryCount(0); - queueMessage.setCreatedAt(Instant.now()); - - return queueMessage; - } - - @Override - public Boolean emit(CandidateInfo candidateInfo) { - EntityTransaction transaction = null; - boolean success = false; - QueueInboxEntity queueInboxMessage; - try (FakeRequestScope ignored = new FakeRequestScope()) { - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - queueInboxMessage = queryFactory.query(QueueInboxQuery.class).ids(candidateInfo.getId()).first(); - } - if (queueInboxMessage == null) { - logger.warn("Could not lookup queue inbox {} to process. Continuing...", candidateInfo.getId()); - } else { - EventProcessingStatus status = this.emitQueueInboxEntity(queueInboxMessage); - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - - transaction.begin(); - - switch (status) { - case Success: { - queueInboxMessage.setStatus(QueueInboxStatus.SUCCESSFUL); - break; - } - case Postponed: { - queueInboxMessage.setStatus(QueueInboxStatus.PARKED); - break; - } - case Error: { - queueInboxMessage.setStatus(QueueInboxStatus.ERROR); - queueInboxMessage.setRetryCount(queueInboxMessage.getRetryCount() != null ? queueInboxMessage.getRetryCount() + 1 : 0); - break; - } - case Discard: - default: { - queueInboxMessage.setStatus(QueueInboxStatus.DISCARD); - break; - } - } - success = status == EventProcessingStatus.Success; - - entityManager.merge(queueInboxMessage); - entityManager.flush(); - - transaction.commit(); - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - success = false; - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - - } - return success; - } - - public EventProcessingStatus emitQueueInboxEntity(QueueInboxEntity queueInboxMessage) { - EntityTransaction transaction = null; - EventProcessingStatus status = EventProcessingStatus.Discard; - try (FakeRequestScope ignored = new FakeRequestScope()) { - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - tenantEntityManager.setEntityManager(entityManager); - - transaction = entityManager.getTransaction(); - - transaction.begin(); - - status = this.processMessage(queueInboxMessage); - - entityManager.flush(); - - switch (status) { - case Error: transaction.rollback(); break; - case Success: - case Postponed: - case Discard: - default: transaction.commit(); break; - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - return status; - } - - - private EventProcessingStatus processMessage(QueueInboxEntity queueInboxMessage) { - IntegrationEventHandler handler; - logger.debug("Processing message with routing key '{}'", queueInboxMessage.getRoute()); - if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getTenantRemovalTopic())) - handler = this.applicationContext.getBean(TenantRemovalIntegrationEventHandler.class); - else if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getTenantTouchTopic())) - handler = this.applicationContext.getBean(TenantTouchedIntegrationEventHandler.class); - else if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getUserRemovalTopic())) - handler = this.applicationContext.getBean(UserRemovalIntegrationEventHandler.class); - else if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getUserTouchTopic())) - handler = this.applicationContext.getBean(UserTouchedIntegrationEventHandler.class); - else if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getAnnotationEntitiesTouchTopic())) - handler = this.applicationContext.getBean(AnnotationEntitiesTouchedIntegrationEventHandler.class); - else if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getAnnotationEntitiesRemovalTopic())) - handler = this.applicationContext.getBean(AnnotationEntitiesRemovalIntegrationEventHandler.class); - else { - logger.error("No handler found for message routing key '{}'. Discarding.", queueInboxMessage.getRoute()); - handler = null; - } - - if (handler == null) - return EventProcessingStatus.Discard; - - IntegrationEventProperties properties = new IntegrationEventProperties(); - properties.setAppId(queueInboxMessage.getApplicationId()); - properties.setMessageId(queueInboxMessage.getMessageId().toString()); - properties.setTenantId(queueInboxMessage.getTenantId()); - -// TrackedEvent event = this.jsonHandlingService.fromJsonSafe(TrackedEvent.class, queueInboxMessage.getMessage()); -// using (LogContext.PushProperty(this._logTrackingConfig.LogTrackingContextName, @event.TrackingContextTag)) -// { - try { - return handler.handle(properties, queueInboxMessage.getMessage()); - } catch (Exception ex) { - logger.error("problem handling event from routing key " + queueInboxMessage.getRoute() + ". Setting nack and continuing...", ex); - return EventProcessingStatus.Error; - } -// } - } - - private Boolean routingKeyMatched(String routingKey, List topics) { - if (topics == null || topics.isEmpty()) - return false; - return topics.stream().anyMatch(x -> x.equals(routingKey)); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/IntegrationEventHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/IntegrationEventHandler.java deleted file mode 100644 index 25e76c126..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/IntegrationEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox; - -public interface IntegrationEventHandler { - - EventProcessingStatus handle(IntegrationEventProperties properties, String message); - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/IntegrationEventProperties.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/IntegrationEventProperties.java deleted file mode 100644 index 535036121..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/IntegrationEventProperties.java +++ /dev/null @@ -1,35 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox; - -import java.util.UUID; - -public class IntegrationEventProperties { - - private String messageId; - - private String appId; - private UUID tenantId; - - public String getMessageId() { - return messageId; - } - - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - public String getAppId() { - return appId; - } - - public void setAppId(String appId) { - this.appId = appId; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEvent.java deleted file mode 100644 index 6ecafb668..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEvent.java +++ /dev/null @@ -1,70 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.annotationentitiesremoval; - -import gr.cite.annotation.common.validation.BaseValidator; -import gr.cite.annotation.common.validation.UuidValidator; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.annotation.integrationevent.TrackedEvent; -import gr.cite.tools.validation.ValidatorFactory; -import gr.cite.tools.validation.specification.Specification; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -public class AnnotationEntitiesRemovalIntegrationEvent extends TrackedEvent { - - private List entityIds; - - public static final String _entityIds = "entityIds"; - - public List getEntityIds() { - return entityIds; - } - - public void setEntityIds(List entityIds) { - this.entityIds = entityIds; - } - - @Component(AnnotationEntitiesRemovalIntegrationEventValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class AnnotationEntitiesRemovalIntegrationEventValidator extends BaseValidator { - - public static final String ValidatorName = "AnnotationEntitiesRemovalIntegrationEventValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected AnnotationEntitiesRemovalIntegrationEventValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return AnnotationEntitiesRemovalIntegrationEvent.class; - } - - @Override - protected List specifications(AnnotationEntitiesRemovalIntegrationEvent item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isListNullOrEmpty(item.getEntityIds())) - .failOn(AnnotationEntitiesRemovalIntegrationEvent._entityIds).failWith(messageSource.getMessage("Validation_Required", new Object[]{AnnotationEntitiesRemovalIntegrationEvent._entityIds}, LocaleContextHolder.getLocale())), - this.navSpec() - .iff(() -> !this.isListNullOrEmpty(item.getEntityIds())) - .on(AnnotationEntitiesRemovalIntegrationEvent._entityIds) - .over(item.getEntityIds()) - .using((i) -> this.validatorFactory.validator(UuidValidator.class)) - ); - } - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEventHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEventHandler.java deleted file mode 100644 index 3c1fa0864..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.annotationentitiesremoval; - -import gr.cite.annotation.integrationevent.inbox.IntegrationEventHandler; - -public interface AnnotationEntitiesRemovalIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEventHandlerImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEventHandlerImpl.java deleted file mode 100644 index 2f779e78f..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiesremoval/AnnotationEntitiesRemovalIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.annotationentitiesremoval; - -import gr.cite.annotation.audit.AuditableAction; -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.fake.FakeRequestScope; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.data.EntityUserEntity; -import gr.cite.annotation.data.TenantEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.integrationevent.inbox.EventProcessingStatus; -import gr.cite.annotation.integrationevent.inbox.InboxPrincipal; -import gr.cite.annotation.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.annotation.model.Tenant; -import gr.cite.annotation.query.EntityUserQuery; -import gr.cite.annotation.query.TenantQuery; -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.validation.ValidatorFactory; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.util.*; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class AnnotationEntitiesRemovalIntegrationEventHandlerImpl implements AnnotationEntitiesRemovalIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AnnotationEntitiesRemovalIntegrationEventHandlerImpl.class)); - - private final JsonHandlingService jsonHandlingService; - - private final ValidatorFactory validatorFactory; - - - private final QueryFactory queryFactory; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - private final DeleterFactory deleterFactory; - private final TenantScope tenantScope; - - - public AnnotationEntitiesRemovalIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, ValidatorFactory validatorFactory, QueryFactory queryFactory, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, AuditService auditService, TenantEntityManager tenantEntityManager, DeleterFactory deleterFactory, TenantScope tenantScope) { - this.jsonHandlingService = jsonHandlingService; - this.validatorFactory = validatorFactory; - this.queryFactory = queryFactory; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - this.deleterFactory = deleterFactory; - this.tenantScope = tenantScope; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - AnnotationEntitiesRemovalIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(AnnotationEntitiesRemovalIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - - logger.debug("Handling {}", AnnotationEntitiesRemovalIntegrationEvent.class.getSimpleName()); - - this.validatorFactory.validator(AnnotationEntitiesRemovalIntegrationEvent.AnnotationEntitiesRemovalIntegrationEventValidator.class).validateForce(event); - - EventProcessingStatus status = EventProcessingStatus.Success; - try { - tenantEntityManager.disableTenantFilters(); - - currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); - - - EntityUserQuery entityUserQuery = this.queryFactory.query(EntityUserQuery.class); - List items = entityUserQuery - .entityIds(event.getEntityIds()) - .isActive(IsActive.Active) - .collect(); - - - deleterFactory.deleter(gr.cite.EntityUser.model.deleter.EntityUserDeleter.class).delete(items); - - tenantEntityManager.flush(); - - auditService.track(AuditableAction.User_Persist, Map.ofEntries( - new AbstractMap.SimpleEntry("model", event) - )); - - - } catch (Exception ex) { - status = EventProcessingStatus.Error; - logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); - } finally { - currentPrincipalResolver.pop(); - try { - tenantEntityManager.reloadTenantFilters(); - } catch (InvalidApplicationException ex) { - logger.error(ex.getMessage(), ex); - } - } - return status; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEvent.java deleted file mode 100644 index a8facce21..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEvent.java +++ /dev/null @@ -1,138 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.annotationentitiestouch; - -import gr.cite.annotation.common.validation.BaseValidator; -import gr.cite.annotation.common.validation.UuidValidator; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.annotation.integrationevent.TrackedEvent; -import gr.cite.tools.validation.ValidatorFactory; -import gr.cite.tools.validation.specification.Specification; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -public class AnnotationEntitiesTouchedIntegrationEvent extends TrackedEvent { - - private List events; - - public static final String _events = "events"; - - public List getEvents() { - return events; - } - - public void setEvents(List events) { - this.events = events; - } - - @Component(AnnotationEntitiesTouchedIntegrationEventValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class AnnotationEntitiesTouchedIntegrationEventValidator extends BaseValidator { - - public static final String ValidatorName = "AnnotationEntitiesTouchedIntegrationEventValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected AnnotationEntitiesTouchedIntegrationEventValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return AnnotationEntitiesTouchedIntegrationEvent.class; - } - - @Override - protected List specifications(AnnotationEntitiesTouchedIntegrationEvent item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isListNullOrEmpty(item.getEvents())) - .failOn(AnnotationEntitiesTouchedIntegrationEvent._events).failWith(messageSource.getMessage("Validation_Required", new Object[]{AnnotationEntitiesTouchedIntegrationEvent._events}, LocaleContextHolder.getLocale())), - this.navSpec() - .iff(() -> !this.isListNullOrEmpty(item.getEvents())) - .on(AnnotationEntitiesTouchedIntegrationEvent._events) - .over(item.getEvents()) - .using((i) -> this.validatorFactory.validator(AnnotationEntityTouchedIntegrationEvent.AnnotationEntityTouchedIntegrationEventValidator.class)) - ); - } - } - - public static class AnnotationEntityTouchedIntegrationEvent { - - private UUID entityId; - - public static final String _entityId = "entityId"; - - private List userIds; - - public static final String _userIds = "userIds"; - - public UUID getEntityId() { - return entityId; - } - - public void setEntityId(UUID entityId) { - this.entityId = entityId; - } - - public List getUserIds() { - return userIds; - } - - public void setUserIds(List userIds) { - this.userIds = userIds; - } - - @Component(AnnotationEntityTouchedIntegrationEvent.AnnotationEntityTouchedIntegrationEventValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class AnnotationEntityTouchedIntegrationEventValidator extends BaseValidator { - - public static final String ValidatorName = "AnnotationEntityTouchedIntegrationEventValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected AnnotationEntityTouchedIntegrationEventValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return AnnotationEntityTouchedIntegrationEvent.class; - } - - @Override - protected List specifications(AnnotationEntityTouchedIntegrationEvent item) { - return Arrays.asList( - this.spec() - .iff(() -> !this.isNull(item.getEntityId())) - .must(() -> this.isValidGuid(item.getEntityId())) - .failOn(AnnotationEntityTouchedIntegrationEvent._entityId).failWith(messageSource.getMessage("Validation_Required", new Object[]{AnnotationEntityTouchedIntegrationEvent._entityId}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isListNullOrEmpty(item.getUserIds())) - .failOn(AnnotationEntityTouchedIntegrationEvent._userIds).failWith(messageSource.getMessage("Validation_Required", new Object[]{AnnotationEntityTouchedIntegrationEvent._userIds}, LocaleContextHolder.getLocale())), - this.navSpec() - .iff(() -> !this.isListNullOrEmpty(item.getUserIds())) - .on(AnnotationEntityTouchedIntegrationEvent._userIds) - .over(item.getUserIds()) - .using((i) -> this.validatorFactory.validator(UuidValidator.class)) - ); - } - } - - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEventHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEventHandler.java deleted file mode 100644 index ef57c6e2c..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.annotationentitiestouch; - -import gr.cite.annotation.integrationevent.inbox.IntegrationEventHandler; - -public interface AnnotationEntitiesTouchedIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEventHandlerImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEventHandlerImpl.java deleted file mode 100644 index 1a6b06be0..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/annotationentitiestouch/AnnotationEntitiesTouchedIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,142 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.annotationentitiestouch; - -import gr.cite.annotation.audit.AuditableAction; -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.data.EntityUserEntity; -import gr.cite.annotation.data.TenantEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.integrationevent.inbox.EventProcessingStatus; -import gr.cite.annotation.integrationevent.inbox.InboxPrincipal; -import gr.cite.annotation.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.annotation.model.Tenant; -import gr.cite.annotation.query.EntityUserQuery; -import gr.cite.annotation.query.TenantQuery; -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.validation.ValidatorFactory; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.*; -import java.util.stream.Collectors; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class AnnotationEntitiesTouchedIntegrationEventHandlerImpl implements AnnotationEntitiesTouchedIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AnnotationEntitiesTouchedIntegrationEventHandlerImpl.class)); - - private final JsonHandlingService jsonHandlingService; - - private final ValidatorFactory validatorFactory; - - private final QueryFactory queryFactory; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - private final DeleterFactory deleterFactory; - private final TenantScope tenantScope; - - public AnnotationEntitiesTouchedIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, ValidatorFactory validatorFactory, QueryFactory queryFactory, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, AuditService auditService, TenantEntityManager tenantEntityManager, DeleterFactory deleterFactory, TenantScope tenantScope) { - this.jsonHandlingService = jsonHandlingService; - this.validatorFactory = validatorFactory; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - this.queryFactory = queryFactory; - this.deleterFactory = deleterFactory; - this.tenantScope = tenantScope; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - AnnotationEntitiesTouchedIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(AnnotationEntitiesTouchedIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - - logger.debug("Handling {}", AnnotationEntitiesTouchedIntegrationEvent.class.getSimpleName()); - - this.validatorFactory.validator(AnnotationEntitiesTouchedIntegrationEvent.AnnotationEntitiesTouchedIntegrationEventValidator.class).validateForce(event); - - EventProcessingStatus status = EventProcessingStatus.Success; - try { - if (this.tenantScope.isMultitenant() && properties.getTenantId() != null) { - TenantEntity tenant = queryFactory.query(TenantQuery.class).disableTracking().ids(properties.getTenantId()).firstAs(new BaseFieldSet().ensure(Tenant._id).ensure(Tenant._code)); - if (tenant == null) { - logger.error("missing tenant from event message"); - return EventProcessingStatus.Error; - } - this.tenantScope.setTempTenant(tenantEntityManager, properties.getTenantId(), tenant.getCode()); - } else if (this.tenantScope.isMultitenant()) { -// logger.error("missing tenant from event message"); -// return EventProcessingStatus.Error; - this.tenantScope.setTempTenant(tenantEntityManager, null, this.tenantScope.getDefaultTenantCode()); - } - - currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); - - tenantEntityManager.disableTenantFilters(); - for (AnnotationEntitiesTouchedIntegrationEvent.AnnotationEntityTouchedIntegrationEvent entityEvent : event.getEvents()) { - - EntityUserQuery entityUserQuery = this.queryFactory.query(EntityUserQuery.class); - List items = entityUserQuery - .entityIds(entityEvent.getEntityId()) - .isActive(IsActive.Active) - .collect(); - List updatedCreatedIds = new ArrayList<>(); - for (UUID user : entityEvent.getUserIds()) { - EntityUserEntity data = items.stream().filter(x -> x.getUserId().equals(user)).findFirst().orElse(null); - if (data == null) { - data = new EntityUserEntity(); - data.setId(UUID.randomUUID()); - data.setEntityId(entityEvent.getEntityId()); - data.setUserId(user); - data.setTenantId(properties.getTenantId()); - data.setCreatedAt(Instant.now()); - data.setUpdatedAt(Instant.now()); - data.setIsActive(IsActive.Active); - tenantEntityManager.persist(data); - } - updatedCreatedIds.add(data.getId()); - } - - List toDelete = items.stream().filter(x -> updatedCreatedIds.stream().noneMatch(y -> y.equals(x.getId()))).collect(Collectors.toList()); - deleterFactory.deleter(gr.cite.EntityUser.model.deleter.EntityUserDeleter.class).delete(toDelete); - - tenantEntityManager.flush(); - - - auditService.track(AuditableAction.User_Persist, Map.ofEntries( - new AbstractMap.SimpleEntry("model", event) - )); - } - - } catch (Exception ex) { - status = EventProcessingStatus.Error; - logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); - } finally { - currentPrincipalResolver.pop(); - try { - tenantScope.removeTempTenant(this.tenantEntityManager); - this.tenantEntityManager.reloadTenantFilters(); - } catch (InvalidApplicationException e) { - } - } - - return status; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyHandler.java deleted file mode 100644 index f895eed8c..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.tenantremoval; - -import gr.cite.annotation.integrationevent.inbox.ConsistencyHandler; -import gr.cite.annotation.query.TenantQuery; -import gr.cite.tools.data.query.QueryFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantRemovalConsistencyHandler implements ConsistencyHandler { - - private final QueryFactory queryFactory; - - public TenantRemovalConsistencyHandler(QueryFactory queryFactory) { - this.queryFactory = queryFactory; - } - - @Override - public Boolean isConsistent(TenantRemovalConsistencyPredicates consistencyPredicates) { - long count = this.queryFactory.query(TenantQuery.class).disableTracking().ids(consistencyPredicates.getTenantId()).count(); - return count > 0; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyPredicates.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyPredicates.java deleted file mode 100644 index 1daa0d483..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyPredicates.java +++ /dev/null @@ -1,23 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.tenantremoval; - -import gr.cite.annotation.integrationevent.inbox.ConsistencyPredicates; - -import java.util.UUID; - -public class TenantRemovalConsistencyPredicates implements ConsistencyPredicates { - - private UUID tenantId; - - public TenantRemovalConsistencyPredicates(UUID tenantId) { - this.tenantId = tenantId; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEvent.java deleted file mode 100644 index dd6e0cd74..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEvent.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.tenantremoval; - -import gr.cite.annotation.integrationevent.TrackedEvent; - -import java.util.UUID; - -public class TenantRemovalIntegrationEvent extends TrackedEvent { - - private UUID id; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandler.java deleted file mode 100644 index e79af0ecf..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.tenantremoval; - - -import gr.cite.annotation.integrationevent.inbox.IntegrationEventHandler; - -public interface TenantRemovalIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java deleted file mode 100644 index 12b249333..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.tenantremoval; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.annotation.audit.AuditableAction; -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.integrationevent.inbox.EventProcessingStatus; -import gr.cite.annotation.integrationevent.inbox.InboxPrincipal; -import gr.cite.annotation.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.annotation.service.tenant.TenantService; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.AbstractMap; -import java.util.Map; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantRemovalIntegrationEventHandlerImpl implements TenantRemovalIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantRemovalIntegrationEventHandlerImpl.class)); - - private final JsonHandlingService jsonHandlingService; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final TenantService tenantService; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - private final TenantRemovalConsistencyHandler tenantRemovalConsistencyHandler; - public TenantRemovalIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, TenantService tenantService, AuditService auditService, TenantEntityManager tenantEntityManager, TenantRemovalConsistencyHandler tenantRemovalConsistencyHandler) { - this.jsonHandlingService = jsonHandlingService; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.tenantService = tenantService; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - this.tenantRemovalConsistencyHandler = tenantRemovalConsistencyHandler; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - TenantRemovalIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(TenantRemovalIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - - EventProcessingStatus status = EventProcessingStatus.Success; - try { - - currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); - - if (!(tenantRemovalConsistencyHandler.isConsistent(new TenantRemovalConsistencyPredicates(event.getId())))) { - status = EventProcessingStatus.Postponed; - currentPrincipalResolver.pop(); - return status; - } - - tenantEntityManager.disableTenantFilters(); - tenantService.deleteAndSave(event.getId()); - - - auditService.track(AuditableAction.Tenant_Delete, Map.ofEntries( - new AbstractMap.SimpleEntry("id", event.getId()) - )); - //auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - - } catch (Exception ex) { - status = EventProcessingStatus.Error; - logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); - } finally { - currentPrincipalResolver.pop(); - } - return status; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEvent.java deleted file mode 100644 index 9ba322ca5..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEvent.java +++ /dev/null @@ -1,30 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.tenanttouched; - - -import gr.cite.annotation.integrationevent.TrackedEvent; - -import java.util.UUID; - -public class TenantTouchedIntegrationEvent extends TrackedEvent { - - private UUID id; - - private String code; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandler.java deleted file mode 100644 index 2e5391235..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.tenanttouched; - -import gr.cite.annotation.integrationevent.inbox.IntegrationEventHandler; - -public interface TenantTouchedIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java deleted file mode 100644 index 3be6e60b2..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.tenanttouched; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.annotation.audit.AuditableAction; -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.integrationevent.inbox.EventProcessingStatus; -import gr.cite.annotation.integrationevent.inbox.InboxPrincipal; -import gr.cite.annotation.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.annotation.model.persist.TenantTouchedIntegrationEventPersist; -import gr.cite.annotation.service.tenant.TenantService; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.validation.ValidatorFactory; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.AbstractMap; -import java.util.Map; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantTouchedIntegrationEventHandlerImpl implements TenantTouchedIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantTouchedIntegrationEventHandlerImpl.class)); - - - private final JsonHandlingService jsonHandlingService; - private final ValidatorFactory validatorFactory; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final TenantService tenantService; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - - public TenantTouchedIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, ValidatorFactory validatorFactory, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, TenantService tenantService, AuditService auditService, TenantEntityManager tenantEntityManager) { - this.jsonHandlingService = jsonHandlingService; - this.validatorFactory = validatorFactory; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.tenantService = tenantService; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - TenantTouchedIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(TenantTouchedIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - - TenantTouchedIntegrationEventPersist model = new TenantTouchedIntegrationEventPersist(); - model.setId(event.getId()); - model.setCode(event.getCode()); - this.validatorFactory.validator(TenantTouchedIntegrationEventPersist.TenantTouchedIntegrationEventPersistValidator.class).validateForce(model); - - EventProcessingStatus status = EventProcessingStatus.Success; - tenantEntityManager.disableTenantFilters(); - try { - currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); - - tenantService.persist(model, null); - - auditService.track(AuditableAction.Tenant_Persist, Map.ofEntries( - new AbstractMap.SimpleEntry("model", model) - )); - - - } catch (Exception ex) { - status = EventProcessingStatus.Error; - logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); - } finally { - currentPrincipalResolver.pop(); - } - return status; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalConsistencyHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalConsistencyHandler.java deleted file mode 100644 index d4340e0bb..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalConsistencyHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.userremoval; - -import gr.cite.annotation.integrationevent.inbox.ConsistencyHandler; -import gr.cite.annotation.query.UserQuery; -import gr.cite.tools.data.query.QueryFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserRemovalConsistencyHandler implements ConsistencyHandler { - - private final QueryFactory queryFactory; - - public UserRemovalConsistencyHandler(QueryFactory queryFactory) { - this.queryFactory = queryFactory; - } - - @Override - public Boolean isConsistent(UserRemovalConsistencyPredicates consistencyPredicates) { - long count = this.queryFactory.query(UserQuery.class).disableTracking().ids(consistencyPredicates.getUserId()).count(); - return count != 0; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalConsistencyPredicates.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalConsistencyPredicates.java deleted file mode 100644 index 226caa447..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalConsistencyPredicates.java +++ /dev/null @@ -1,24 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.userremoval; - - -import gr.cite.annotation.integrationevent.inbox.ConsistencyPredicates; - -import java.util.UUID; - -public class UserRemovalConsistencyPredicates implements ConsistencyPredicates { - - private UUID userId; - - public UserRemovalConsistencyPredicates(UUID userId) { - this.userId = userId; - } - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEvent.java deleted file mode 100644 index 3e7b05a5b..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEvent.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.userremoval; - -import gr.cite.annotation.integrationevent.TrackedEvent; - -import java.util.UUID; - -public class UserRemovalIntegrationEvent extends TrackedEvent { - - private UUID userId; - - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandler.java deleted file mode 100644 index 52060c66b..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.userremoval; - - -import gr.cite.annotation.integrationevent.inbox.IntegrationEventHandler; - -public interface UserRemovalIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java deleted file mode 100644 index 572d52b7d..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,104 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.userremoval; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.annotation.audit.AuditableAction; -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.annotation.integrationevent.inbox.EventProcessingStatus; -import gr.cite.annotation.integrationevent.inbox.InboxPrincipal; -import gr.cite.annotation.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.annotation.service.user.UserService; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Component; - -import java.util.AbstractMap; -import java.util.Map; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserRemovalIntegrationEventHandlerImpl implements UserRemovalIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserRemovalIntegrationEventHandlerImpl.class)); - - private final JsonHandlingService jsonHandlingService; - - - private final ErrorThesaurusProperties errors; - - private final MessageSource messageSource; - private final TenantScope tenantScope; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final UserRemovalConsistencyHandler userRemovalConsistencyHandler; - private final UserService userService; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - - public UserRemovalIntegrationEventHandlerImpl( - JsonHandlingService jsonHandlingService, - ErrorThesaurusProperties errors, - MessageSource messageSource, TenantScope tenantScope, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, UserRemovalConsistencyHandler userRemovalConsistencyHandler, UserService userService, AuditService auditService, TenantEntityManager tenantEntityManager - ) { - this.jsonHandlingService = jsonHandlingService; - this.errors = errors; - this.messageSource = messageSource; - this.tenantScope = tenantScope; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.userRemovalConsistencyHandler = userRemovalConsistencyHandler; - this.userService = userService; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - UserRemovalIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(UserRemovalIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - if (event.getUserId() == null) - throw new MyValidationException(this.errors.getModelValidation().getCode(), "userId", messageSource.getMessage("Validation_Required", new Object[]{"userId"}, LocaleContextHolder.getLocale())); - - logger.debug("Handling {}", UserRemovalIntegrationEvent.class.getSimpleName()); - - EventProcessingStatus status = EventProcessingStatus.Success; - try { - currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); - - try{ - this.tenantEntityManager.disableTenantFilters(); - if (!(userRemovalConsistencyHandler.isConsistent(new UserRemovalConsistencyPredicates(event.getUserId())))) { - status = EventProcessingStatus.Postponed; - currentPrincipalResolver.pop(); - return status; - } - - userService.deleteAndSave(event.getUserId()); - } finally { - this.tenantEntityManager.reloadTenantFilters(); - } - - auditService.track(AuditableAction.User_Delete, Map.ofEntries( - new AbstractMap.SimpleEntry("id", event.getUserId()) - )); - //auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - } catch (Exception ex) { - status = EventProcessingStatus.Error; - logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); - } finally { - currentPrincipalResolver.pop(); - } - - return status; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java deleted file mode 100644 index 889786041..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java +++ /dev/null @@ -1,327 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.usertouched; - -import gr.cite.annotation.common.enums.ContactInfoType; -import gr.cite.annotation.common.validation.BaseValidator; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.annotation.integrationevent.TrackedEvent; -import gr.cite.tools.validation.ValidatorFactory; -import gr.cite.tools.validation.specification.Specification; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -public class UserTouchedIntegrationEvent extends TrackedEvent { - - private UUID id; - - public static final String _id = "id"; - - private String name; - - public static final String _name = "name"; - - public static final int _nameLength = 200; - - private UserProfile profile; - - private List userContactInfo; - - public static final String _userContactInfo = "userContactInfo"; - private List tenantUsers; - - public static final String _tenantUsers = "tenantUsers"; - private List credentials; - - public static final String _credentials = "credentials"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getTenantUsers() { - return tenantUsers; - } - - public void setTenantUsers(List tenantUsers) { - this.tenantUsers = tenantUsers; - } - - public List getCredentials() { - return credentials; - } - - public void setCredentials(List credentials) { - this.credentials = credentials; - } - - public UserProfile getProfile() { - return profile; - } - - public void setProfile(UserProfile profile) { - this.profile = profile; - } - - public List getUserContactInfo() { - return userContactInfo; - } - - public void setUserContactInfo(List userContactInfo) { - this.userContactInfo = userContactInfo; - } - - public static class UserProfile { - - private String timezone; - - private String culture; - - private String language; - - public String getTimezone() { - return timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public String getCulture() { - return culture; - } - - public void setCulture(String culture) { - this.culture = culture; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - } - - public static class UserContactInfo { - - private ContactInfoType type; - - public static final String _type = "type"; - - private String value; - - public static final String _value = "value"; - - private Integer ordinal; - - public static final String _ordinal = "ordinal"; - - public ContactInfoType getType() { - return type; - } - - public void setType(ContactInfoType type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public Integer getOrdinal() { - return ordinal; - } - - public void setOrdinal(Integer ordinal) { - this.ordinal = ordinal; - } - - @Component(UserTouchedIntegrationUserContactInfoEventValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class UserTouchedIntegrationUserContactInfoEventValidator extends BaseValidator { - - public static final String ValidatorName = "UserTouchedIntegrationUserContactInfoEventValidator"; - - private final MessageSource messageSource; - - protected UserTouchedIntegrationUserContactInfoEventValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return UserContactInfo.class; - } - - @Override - protected List specifications(UserContactInfo item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isEmpty(item.getValue())) - .failOn(UserContactInfo._value).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserContactInfo._value}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getType())) - .failOn(UserContactInfo._type).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserContactInfo._type}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getOrdinal())) - .failOn(UserContactInfo._ordinal).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserContactInfo._ordinal}, LocaleContextHolder.getLocale())) - ); - } - } - } - - public static class UserCredential { - - private String subjectId; - - public static final String _subjectId = "subjectId"; - - public String getSubjectId() { - return subjectId; - } - - public void setSubjectId(String subjectId) { - this.subjectId = subjectId; - } - - @Component(UserTouchedIntegrationUserCredentialEventValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class UserTouchedIntegrationUserCredentialEventValidator extends BaseValidator { - - public static final String ValidatorName = "UserTouchedIntegrationUserCredentialEventValidator"; - - private final MessageSource messageSource; - - protected UserTouchedIntegrationUserCredentialEventValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return UserCredential.class; - } - - @Override - protected List specifications(UserCredential item) { - return Collections.singletonList( - this.spec() - .must(() -> !this.isEmpty(item.getSubjectId())) - .failOn(UserCredential._subjectId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserCredential._subjectId}, LocaleContextHolder.getLocale())) - ); - } - } - } - - public static class TenantUser { - - private UUID tenant; - public static final String _tenant = "tenant"; - - public UUID getTenant() { - return tenant; - } - - public void setTenant(UUID tenant) { - this.tenant = tenant; - } - - @Component(UserTouchedIntegrationTenantUserEventValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class UserTouchedIntegrationTenantUserEventValidator extends BaseValidator { - - public static final String ValidatorName = "UserTouchedIntegrationTenantUserEventValidator"; - - private final MessageSource messageSource; - - protected UserTouchedIntegrationTenantUserEventValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return TenantUser.class; - } - - @Override - protected List specifications(TenantUser item) { - return Collections.singletonList( - this.spec() - .must(() -> !this.isNull(item.getTenant())) - .failOn(TenantUser._tenant).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantUser._tenant}, LocaleContextHolder.getLocale())) - ); - } - } - } - - @Component(UserTouchedIntegrationEventValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class UserTouchedIntegrationEventValidator extends BaseValidator { - - public static final String ValidatorName = "UserTouchedIntegrationEventValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected UserTouchedIntegrationEventValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return UserTouchedIntegrationEvent.class; - } - - @Override - protected List specifications(UserTouchedIntegrationEvent item) { - return Arrays.asList( - this.spec() - .iff(() -> !this.isNull(item.getId())) - .must(() -> this.isValidGuid(item.getId())) - .failOn(UserTouchedIntegrationEvent._id).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserTouchedIntegrationEvent._id}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getName())) - .failOn(UserTouchedIntegrationEvent._name).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserTouchedIntegrationEvent._name}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isEmpty(item.getName())) - .must(() -> this.lessEqualLength(item.getName(), UserTouchedIntegrationEvent._nameLength)) - .failOn(UserTouchedIntegrationEvent._name).failWith(messageSource.getMessage("Validation_MaxLength", new Object[]{UserTouchedIntegrationEvent._name}, LocaleContextHolder.getLocale())), - this.navSpec() - .iff(() -> !this.isListNullOrEmpty(item.getUserContactInfo())) - .on(UserTouchedIntegrationEvent._userContactInfo) - .over(item.getUserContactInfo()) - .using((i) -> this.validatorFactory.validator(UserContactInfo.UserTouchedIntegrationUserContactInfoEventValidator.class)) - ); - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandler.java deleted file mode 100644 index e9c38baef..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.usertouched; - - -import gr.cite.annotation.integrationevent.inbox.IntegrationEventHandler; - -public interface UserTouchedIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java deleted file mode 100644 index e52f414ac..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,86 +0,0 @@ -package gr.cite.annotation.integrationevent.inbox.usertouched; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.annotation.audit.AuditableAction; -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.integrationevent.inbox.EventProcessingStatus; -import gr.cite.annotation.integrationevent.inbox.InboxPrincipal; -import gr.cite.annotation.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.annotation.service.user.UserService; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.validation.ValidatorFactory; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.AbstractMap; -import java.util.Map; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserTouchedIntegrationEventHandlerImpl implements UserTouchedIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserTouchedIntegrationEventHandlerImpl.class)); - - - private final JsonHandlingService jsonHandlingService; - - private final ValidatorFactory validatorFactory; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final UserService userService; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - - public UserTouchedIntegrationEventHandlerImpl( - JsonHandlingService jsonHandlingService, - ValidatorFactory validatorFactory, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, UserService userService, AuditService auditService, TenantEntityManager tenantEntityManager) { - this.jsonHandlingService = jsonHandlingService; - this.validatorFactory = validatorFactory; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.userService = userService; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - UserTouchedIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(UserTouchedIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - - logger.debug("Handling {}", UserTouchedIntegrationEvent.class.getSimpleName()); - - this.validatorFactory.validator(UserTouchedIntegrationEvent.UserTouchedIntegrationEventValidator.class).validateForce(event); - - EventProcessingStatus status = EventProcessingStatus.Success; - try { - - currentPrincipalResolver.push(InboxPrincipal.build(properties, claimExtractorProperties)); - try { - this.tenantEntityManager.disableTenantFilters(); - userService.persist(event, null); - } finally { - this.tenantEntityManager.reloadTenantFilters(); - } - auditService.track(AuditableAction.User_Persist, Map.ofEntries( - new AbstractMap.SimpleEntry("model", event) - )); - - } catch (Exception ex) { - status = EventProcessingStatus.Error; - logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); - } finally { - currentPrincipalResolver.pop(); - } - - return status; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxIntegrationEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxIntegrationEvent.java deleted file mode 100644 index 1d2306158..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxIntegrationEvent.java +++ /dev/null @@ -1,21 +0,0 @@ -package gr.cite.annotation.integrationevent.outbox; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import gr.cite.annotation.integrationevent.TrackedEvent; -import gr.cite.rabbitmq.IntegrationEvent; - -@JsonIgnoreProperties(ignoreUnknown = true) -public class OutboxIntegrationEvent extends IntegrationEvent { - - public static final String ANNOTATION_CREATED = "ANNOTATION_CREATED"; - private TrackedEvent event; - - public TrackedEvent getEvent() { - return event; - } - - public void setEvent(TrackedEvent event) { - this.event = event; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxProperties.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxProperties.java deleted file mode 100644 index 119d049e9..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxProperties.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.annotation.integrationevent.outbox; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "queue.task.publisher.options") -public class OutboxProperties { - - private final String exchange; - - private final String annotationCreatedTopic; - - - public OutboxProperties(String exchange, - String annotationCreatedTopic) { - this.exchange = exchange; - this.annotationCreatedTopic = annotationCreatedTopic; - } - - public String getExchange() { - return exchange; - } - - public String getAnnotationCreatedTopic() { - return annotationCreatedTopic; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxRepositoryImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxRepositoryImpl.java deleted file mode 100644 index 36f72a52d..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxRepositoryImpl.java +++ /dev/null @@ -1,408 +0,0 @@ -package gr.cite.annotation.integrationevent.outbox; - -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.fake.FakeRequestScope; -import gr.cite.annotation.data.QueueOutboxEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.query.QueueOutboxQuery; -import gr.cite.queueoutbox.entity.QueueOutbox; -import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; -import gr.cite.queueoutbox.repository.CandidateInfo; -import gr.cite.queueoutbox.repository.OutboxRepository; -import gr.cite.queueoutbox.task.MessageOptions; -import gr.cite.rabbitmq.IntegrationEvent; -import gr.cite.tools.data.query.Ordering; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.*; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; - -import java.time.Instant; -import java.util.List; -import java.util.UUID; -import java.util.function.Function; -import java.util.stream.Collectors; - -public class OutboxRepositoryImpl implements OutboxRepository { - - protected final ApplicationContext applicationContext; - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(OutboxRepositoryImpl.class)); - - @PersistenceUnit - private EntityManagerFactory entityManagerFactory; - private final JsonHandlingService jsonHandlingService; - private final OutboxProperties outboxProperties; - - - public OutboxRepositoryImpl( - ApplicationContext applicationContext, - OutboxProperties outboxProperties) { - this.applicationContext = applicationContext; - this.jsonHandlingService = this.applicationContext.getBean(JsonHandlingService.class); - this.outboxProperties = outboxProperties; - } - - @Override - public CandidateInfo candidate(Instant lastCandidateCreationTimestamp, MessageOptions messageOptions, Function onConfirmTimeout) { - EntityTransaction transaction = null; - CandidateInfo candidate = null; - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - QueueOutboxEntity item = queryFactory.query(QueueOutboxQuery.class) - .isActives(IsActive.Active) - .notifyStatus(QueueOutboxNotifyStatus.PENDING, QueueOutboxNotifyStatus.WAITING_CONFIRMATION, QueueOutboxNotifyStatus.ERROR) - .retryThreshold(messageOptions.getRetryThreashold()) - .confirmTimeout(messageOptions.getConfirmTimeoutSeconds()) - .createdAfter(lastCandidateCreationTimestamp) - .ordering(new Ordering().addAscending(QueueOutboxEntity._createdAt)) - .first(); - - if (item != null) { - boolean confirmTimeout = onConfirmTimeout.apply(item); - - QueueOutboxNotifyStatus prevState = item.getNotifyStatus(); - item.setNotifyStatus(QueueOutboxNotifyStatus.PROCESSING); - - entityManager.merge(item); - entityManager.flush(); - - candidate = new CandidateInfo(); - candidate.setId(item.getId()); - candidate.setCreatedAt(item.getCreatedAt()); - candidate.setPreviousState(prevState); - } - - transaction.commit(); - } catch (OptimisticLockException ex) { - // we get this if/when someone else already modified the notifications. We want to essentially ignore this, and keep working - logger.debug("Concurrency exception getting queue outbox. Skipping: {} ", ex.getMessage()); - if (transaction != null) - transaction.rollback(); - candidate = null; - } catch (Exception ex) { - logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); - if (transaction != null) - transaction.rollback(); - candidate = null; - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem getting list of queue outbox. Skipping: {}", ex.getMessage(), ex); - } - - return candidate; - } - - @Override - public Boolean shouldOmit(CandidateInfo candidate, Function shouldOmit) { - EntityTransaction transaction = null; - boolean success = false; - - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - QueueOutboxEntity item = queryFactory.query(QueueOutboxQuery.class).ids(candidate.getId()).first(); - - if (item == null) { - logger.warn("Could not lookup queue outbox {} to process. Continuing...", candidate.getId()); - } else { - if (shouldOmit.apply(item)) { - item.setNotifyStatus(QueueOutboxNotifyStatus.OMITTED); - - entityManager.merge(item); - entityManager.flush(); - success = true; - } - } - - transaction.commit(); - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - success = false; - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - return success; - } - - @Override - public Boolean shouldWait(CandidateInfo candidate, Function itIsTimeFunc) { - EntityTransaction transaction = null; - boolean success = false; - - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - QueueOutboxEntity item = queryFactory.query(QueueOutboxQuery.class).ids(candidate.getId()).first(); - - if (item.getRetryCount() != null && item.getRetryCount() >= 1) { - Boolean itIsTime = itIsTimeFunc.apply(item); - - if (!itIsTime) { - item.setNotifyStatus(candidate.getPreviousState()); - - entityManager.merge(item); - entityManager.flush(); - success = true; - } - - success = !itIsTime; - } - transaction.commit(); - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - success = false; - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - return success; - } - - @Override - public Boolean process(CandidateInfo candidateInfo, Boolean isAutoconfirmOnPublish, Function publish) { - EntityTransaction transaction = null; - Boolean success = false; - - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - QueueOutboxEntity item = queryFactory.query(QueueOutboxQuery.class).ids(candidateInfo.getId()).first(); - - if (item == null) { - logger.warn("Could not lookup queue outbox {} to process. Continuing...", candidateInfo.getId()); - } else { - - success = publish.apply(item); - if (success) { - if (isAutoconfirmOnPublish) { - item.setNotifyStatus(QueueOutboxNotifyStatus.CONFIRMED); - item.setConfirmedAt(Instant.now()); - } else { - item.setNotifyStatus(QueueOutboxNotifyStatus.WAITING_CONFIRMATION); - } - item.setPublishedAt(Instant.now()); - } else { - item.setNotifyStatus(QueueOutboxNotifyStatus.ERROR); - item.setRetryCount(item.getRetryCount() != null ? item.getRetryCount() + 1 : 0); - item.setPublishedAt(null); - } - - entityManager.merge(item); - entityManager.flush(); - } - - transaction.commit(); - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - success = false; - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - return success; - } - - @Override - public void handleConfirm(List confirmedMessages) { - EntityTransaction transaction = null; - - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - List queueOutboxMessages = queryFactory.query(QueueOutboxQuery.class).ids(confirmedMessages).collect(); - - if (queueOutboxMessages == null) { - logger.warn("Could not lookup messages {} to process. Continuing...", confirmedMessages.stream().map(UUID::toString).collect(Collectors.joining(","))); - } else { - - for (QueueOutboxEntity queueOutboxMessage : queueOutboxMessages) { - queueOutboxMessage.setNotifyStatus(QueueOutboxNotifyStatus.CONFIRMED); - queueOutboxMessage.setConfirmedAt(Instant.now()); - entityManager.merge(queueOutboxMessage); - } - - entityManager.flush(); - } - - transaction.commit(); - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - } - - @Override - public void handleNack(List nackedMessages) { - EntityTransaction transaction = null; - - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - List queueOutboxMessages = queryFactory.query(QueueOutboxQuery.class).ids(nackedMessages).collect(); - - if (queueOutboxMessages == null) { - logger.warn("Could not lookup messages {} to process. Continuing...", nackedMessages.stream().map(UUID::toString).collect(Collectors.joining(","))); - } else { - - for (QueueOutboxEntity queueOutboxMessage : queueOutboxMessages) { - queueOutboxMessage.setNotifyStatus(QueueOutboxNotifyStatus.ERROR); - queueOutboxMessage.setRetryCount(queueOutboxMessage.getRetryCount() != null ? queueOutboxMessage.getRetryCount() + 1 : 0); - entityManager.merge(queueOutboxMessage); - } - - entityManager.flush(); - } - - transaction.commit(); - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - } - - @Override - public QueueOutbox create(IntegrationEvent item) { - EntityTransaction transaction = null; - QueueOutboxEntity queueMessage = null; - boolean success; - try (FakeRequestScope ignored = new FakeRequestScope()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - queueMessage = this.mapEvent((OutboxIntegrationEvent) item); - transaction = entityManager.getTransaction(); - - transaction.begin(); - - entityManager.persist(queueMessage); - entityManager.flush(); - - transaction.commit(); - success = true; - } catch (Exception ex) { - success = false; - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - if (transaction != null) - transaction.rollback(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (Exception ex) { - success = false; - logger.error("Problem executing purge. rolling back any db changes and marking error. Continuing...", ex); - } - return success ? queueMessage : null; - } - - private QueueOutboxEntity mapEvent(OutboxIntegrationEvent event) { - String routingKey; - switch (event.getType()) { - case OutboxIntegrationEvent.ANNOTATION_CREATED: { - routingKey = this.outboxProperties.getAnnotationCreatedTopic(); - break; - } - default: { - logger.error("unrecognized outgoing integration event {}. Skipping...", event.getType()); - return null; - } - } - - UUID correlationId = UUID.randomUUID(); - if (event.getEvent() != null) - event.getEvent().setTrackingContextTag(correlationId.toString()); - event.setMessage(this.jsonHandlingService.toJsonSafe(event.getEvent())); - - QueueOutboxEntity queueMessage = new QueueOutboxEntity(); - queueMessage.setId(UUID.randomUUID()); - queueMessage.setTenantId(event.getTenantId()); - queueMessage.setExchange(this.outboxProperties.getExchange()); - queueMessage.setRoute(routingKey); - queueMessage.setMessageId(event.getMessageId()); - queueMessage.setMessage(this.jsonHandlingService.toJsonSafe(event)); - queueMessage.setIsActive(IsActive.Active); - queueMessage.setNotifyStatus(QueueOutboxNotifyStatus.PENDING); - queueMessage.setRetryCount(0); - queueMessage.setCreatedAt(Instant.now()); - queueMessage.setUpdatedAt(Instant.now()); - - return queueMessage; - - } -} \ No newline at end of file diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxService.java deleted file mode 100644 index ff1861abe..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxService.java +++ /dev/null @@ -1,5 +0,0 @@ -package gr.cite.annotation.integrationevent.outbox; - -public interface OutboxService { - void publish(OutboxIntegrationEvent event); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxServiceImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxServiceImpl.java deleted file mode 100644 index e3a8936e0..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/OutboxServiceImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -package gr.cite.annotation.integrationevent.outbox; - - -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -@Component -@RequestScope -public class OutboxServiceImpl implements OutboxService { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(OutboxServiceImpl.class)); - - private final ApplicationEventPublisher eventPublisher; - - public OutboxServiceImpl( - ApplicationEventPublisher eventPublisher - ) { - this.eventPublisher = eventPublisher; - } - - @Override - public void publish(OutboxIntegrationEvent event) { - try { - eventPublisher.publishEvent(event); - } catch (Exception ex) { - logger.error(new MapLogEntry(String.format("Could not save message ", event.getMessage())).And("message", event.getMessage()).And("ex", ex)); - //Still want to skip it from processing - } - - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedEvent.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedEvent.java deleted file mode 100644 index a79dea3e3..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedEvent.java +++ /dev/null @@ -1,114 +0,0 @@ -package gr.cite.annotation.integrationevent.outbox.annotationcreated; - -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import gr.cite.annotation.integrationevent.TrackedEvent; - -import java.time.Instant; -import java.util.UUID; - -public class AnnotationCreatedEvent extends TrackedEvent { - - private UUID id; - - private UUID entityId; - - private String entityType; - - private String anchor; - - private String payload; - - private UUID subjectId; - - private UUID threadId; - - private UUID parentId; - - private AnnotationProtectionType protectionType; - - private Instant timeStamp; - - public AnnotationCreatedEvent() { - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public UUID getEntityId() { - return entityId; - } - - public void setEntityId(UUID entityId) { - this.entityId = entityId; - } - - public String getEntityType() { - return entityType; - } - - public void setEntityType(String entityType) { - this.entityType = entityType; - } - - public String getAnchor() { - return anchor; - } - - public void setAnchor(String anchor) { - this.anchor = anchor; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public UUID getSubjectId() { - return subjectId; - } - - public void setSubjectId(UUID subjectId) { - this.subjectId = subjectId; - } - - public UUID getThreadId() { - return threadId; - } - - public void setThreadId(UUID threadId) { - this.threadId = threadId; - } - - public UUID getParentId() { - return parentId; - } - - public void setParentId(UUID parentId) { - this.parentId = parentId; - } - - public AnnotationProtectionType getProtectionType() { - return protectionType; - } - - public void setProtectionType(AnnotationProtectionType protectionType) { - this.protectionType = protectionType; - } - - public Instant getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(Instant timeStamp) { - this.timeStamp = timeStamp; - } -} - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedIntegrationEventHandler.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedIntegrationEventHandler.java deleted file mode 100644 index 440572ece..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedIntegrationEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.annotation.integrationevent.outbox.annotationcreated; - -import javax.management.InvalidApplicationException; - -public interface AnnotationCreatedIntegrationEventHandler { - void handle(AnnotationCreatedEvent event) throws InvalidApplicationException; -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedIntegrationEventHandlerImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedIntegrationEventHandlerImpl.java deleted file mode 100644 index b3b15cd52..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/integrationevent/outbox/annotationcreated/AnnotationCreatedIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package gr.cite.annotation.integrationevent.outbox.annotationcreated; - -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.integrationevent.outbox.OutboxIntegrationEvent; -import gr.cite.annotation.integrationevent.outbox.OutboxService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.util.UUID; - -@Component -@RequestScope -public class AnnotationCreatedIntegrationEventHandlerImpl implements AnnotationCreatedIntegrationEventHandler { - - private final OutboxService outboxService; - private final TenantScope tenantScope; - - @Autowired - public AnnotationCreatedIntegrationEventHandlerImpl( - OutboxService outboxService, TenantScope tenantScope) { - this.outboxService = outboxService; - this.tenantScope = tenantScope; - } - - @Override - public void handle(AnnotationCreatedEvent event) throws InvalidApplicationException { - OutboxIntegrationEvent message = new OutboxIntegrationEvent(); - message.setMessageId(UUID.randomUUID()); - message.setType(OutboxIntegrationEvent.ANNOTATION_CREATED); - message.setEvent(event); - if (this.tenantScope.isSet()) message.setTenantId(this.tenantScope.getTenant()); - this.outboxService.publish(message); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleConfiguration.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleConfiguration.java deleted file mode 100644 index 85c77e490..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.annotation.locale; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties(LocaleProperties.class) -public class LocaleConfiguration { -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleProperties.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleProperties.java deleted file mode 100644 index 781fc203b..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleProperties.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.annotation.locale; - - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "locale") -public class LocaleProperties { - - private String timezone; - public String getTimezone() { - return timezone; - } - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - private String language; - public String getLanguage() { - return language; - } - public void setLanguage(String language) { - this.language = language; - } - - private String culture; - public String getCulture() { - return culture; - } - public void setCulture(String culture) { - this.culture = culture; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleService.java deleted file mode 100644 index eaea37fec..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleService.java +++ /dev/null @@ -1,18 +0,0 @@ -package gr.cite.annotation.locale; - -import java.util.Locale; -import java.util.TimeZone; - -public interface LocaleService { - String timezoneName(); - TimeZone timezone(); - TimeZone timezone(String code); - TimeZone timezoneSafe(String code); - - String cultureName(); - Locale culture(); - Locale culture(String code); - Locale cultureSafe(String code); - - String language(); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleServiceImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleServiceImpl.java deleted file mode 100644 index 48375d791..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/locale/LocaleServiceImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -package gr.cite.annotation.locale; - -import gr.cite.annotation.convention.ConventionService; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.ZoneId; -import java.util.Locale; -import java.util.TimeZone; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) -public class LocaleServiceImpl implements LocaleService { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(LocaleServiceImpl.class)); - private final LocaleProperties localeProperties; - private final ConventionService conventionService; - - @Autowired - public LocaleServiceImpl(LocaleProperties localeProperties, ConventionService conventionService) { - this.localeProperties = localeProperties; - this.conventionService = conventionService; - } - - - @Override - public String timezoneName() { - return this.localeProperties.getTimezone(); - } - - @Override - public TimeZone timezone() { - return TimeZone.getTimeZone(ZoneId.of(this.localeProperties.getTimezone())); - } - - @Override - public TimeZone timezone(String code) { - if (this.conventionService.isNullOrEmpty(code)) return this.timezone(); - return TimeZone.getTimeZone(ZoneId.of(code)); - } - - @Override - public TimeZone timezoneSafe(String code) { - try { - return this.timezone(code); - } catch (Exception ex){ - logger.warn("tried to retrieve timezone for '"+ code +"' but failed. falling back to default", ex); - return this.timezone(); - } - } - - @Override - public String cultureName() { - return this.localeProperties.getCulture(); - } - - @Override - public Locale culture() { - return Locale.forLanguageTag(this.localeProperties.getCulture()); - } - - @Override - public Locale culture(String code) { - if (this.conventionService.isNullOrEmpty(code)) return this.culture(); - return Locale.forLanguageTag(code); - } - - @Override - public Locale cultureSafe(String code) { - try { - return this.culture(code); - } catch (Exception ex){ - logger.warn("tried to retrieve timezone for '"+ code +"' but failed. falling back to default", ex); - return this.culture(); - } - } - - @Override - public String language() { - return this.localeProperties.getLanguage(); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/Annotation.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/Annotation.java deleted file mode 100644 index 5d7bbe05a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/Annotation.java +++ /dev/null @@ -1,210 +0,0 @@ -package gr.cite.annotation.model; - -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.conventers.AnnotationProtectionTypeConverter; -import jakarta.persistence.Column; -import jakarta.persistence.Convert; - -import java.time.Instant; -import java.util.List; -import java.util.UUID; - -public class Annotation { - - private UUID id; - - public static final String _id = "id"; - - private UUID entityId; - - public static final String _entityId = "entityId"; - - private String entityType; - - public static final String _entityType = "entityType"; - - private String anchor; - - public static final String _anchor = "anchor"; - - private String payload; - - public static final String _payload = "payload"; - - private UUID subjectId; - - public static final String _subjectId = "subjectId"; - - private UUID threadId; - - public static final String _threadId = "threadId"; - - private UUID parentId; - - public static final String _parentId = "parentId"; - - private AnnotationProtectionType protectionType; - - public static final String _protectionType = "protectionType"; - - private Instant timeStamp; - - public static final String _timeStamp = "timeStamp"; - - private AnnotationAuthor author; - - public static final String _author = "author"; - - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - private IsActive isActive; - - public static final String _isActive = "isActive"; - - private String hash; - - public static final String _hash = "hash"; - - private List authorizationFlags; - public static final String _authorizationFlags = "authorizationFlags"; - - - private Boolean belongsToCurrentTenant; - public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public UUID getEntityId() { - return entityId; - } - - public void setEntityId(UUID entityId) { - this.entityId = entityId; - } - - public String getEntityType() { - return entityType; - } - - public void setEntityType(String entityType) { - this.entityType = entityType; - } - - public String getAnchor() { - return anchor; - } - - public void setAnchor(String anchor) { - this.anchor = anchor; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public UUID getSubjectId() { - return subjectId; - } - - public void setSubjectId(UUID subjectId) { - this.subjectId = subjectId; - } - - public AnnotationAuthor getAuthor() { - return author; - } - - public void setAuthor(AnnotationAuthor author) { - this.author = author; - } - - public UUID getThreadId() { - return threadId; - } - - public void setThreadId(UUID threadId) { - this.threadId = threadId; - } - - public UUID getParentId() { - return parentId; - } - - public void setParentId(UUID parentId) { - this.parentId = parentId; - } - - public AnnotationProtectionType getProtectionType() { - return protectionType; - } - - public void setProtectionType(AnnotationProtectionType protectionType) { - this.protectionType = protectionType; - } - - public Instant getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(Instant timeStamp) { - this.timeStamp = timeStamp; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } - - public List getAuthorizationFlags() { - return authorizationFlags; - } - - public void setAuthorizationFlags(List authorizationFlags) { - this.authorizationFlags = authorizationFlags; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/AnnotationAuthor.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/AnnotationAuthor.java deleted file mode 100644 index 3670e51c5..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/AnnotationAuthor.java +++ /dev/null @@ -1,31 +0,0 @@ -package gr.cite.annotation.model; - -import java.util.UUID; - -public class AnnotationAuthor { - - private UUID id; - - public static final String _id = "id"; - - private String name; - - public static final String _name = "name"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/EntityUser.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/EntityUser.java deleted file mode 100644 index ff80f14de..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/EntityUser.java +++ /dev/null @@ -1,94 +0,0 @@ -package gr.cite.annotation.model; - -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import gr.cite.annotation.common.enums.IsActive; - -import java.time.Instant; -import java.util.UUID; - -public class EntityUser { - - private UUID id; - - public static final String _id = "id"; - - private UUID entityId; - - public static final String _entityId = "entityId"; - - private User user; - - public static final String _user = "user"; - - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - private IsActive isActive; - - public static final String _isActive = "isActive"; - - private String hash; - - public static final String _hash = "hash"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public UUID getEntityId() { - return entityId; - } - - public void setEntityId(UUID entityId) { - this.entityId = entityId; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/Tenant.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/Tenant.java deleted file mode 100644 index 0187ba26a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/Tenant.java +++ /dev/null @@ -1,82 +0,0 @@ -package gr.cite.annotation.model; - -import gr.cite.annotation.common.enums.IsActive; - -import java.time.Instant; -import java.util.UUID; - -public class Tenant { - - private UUID id; - - public static final String _id = "id"; - - private String code; - - public static final String _code = "code"; - - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - private IsActive isActive; - - public static final String _isActive = "isActive"; - - private String hash; - - public static final String _hash = "hash"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/TenantUser.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/TenantUser.java deleted file mode 100644 index 510ca44c8..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/TenantUser.java +++ /dev/null @@ -1,98 +0,0 @@ -package gr.cite.annotation.model; - - -import gr.cite.annotation.common.enums.IsActive; - -import java.time.Instant; -import java.util.UUID; - -public class TenantUser { - - private UUID id; - public final static String _id = "id"; - - private User user; - public final static String _user = "user"; - - private Tenant tenant; - public final static String _tenant = "tenant"; - - private IsActive isActive; - public final static String _isActive = "isActive"; - - private Instant createdAt; - public final static String _createdAt = "createdAt"; - - private Instant updatedAt; - public final static String _updatedAt = "updatedAt"; - - private String hash; - public final static String _hash = "hash"; - - private Boolean belongsToCurrentTenant; - public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public Tenant getTenant() { - return tenant; - } - - public void setTenant(Tenant tenant) { - this.tenant = tenant; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } - - public Boolean getBelongsToCurrentTenant() { - return belongsToCurrentTenant; - } - - public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { - this.belongsToCurrentTenant = belongsToCurrentTenant; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/User.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/User.java deleted file mode 100644 index 58cfaa3ef..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/User.java +++ /dev/null @@ -1,80 +0,0 @@ -package gr.cite.annotation.model; - -import gr.cite.annotation.common.enums.IsActive; - -import java.time.Instant; -import java.util.UUID; - -public class User { - - private UUID id; - public static final String _id = "id"; - - private String name; - public static final String _name = "name"; - - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - private IsActive isActive; - - public static final String _isActive = "isActive"; - - public static final String _hash = "hash"; - private String hash; - - public static final String _tenantUsers = "tenantUsers"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/UserCredential.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/UserCredential.java deleted file mode 100644 index 8375d9668..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/UserCredential.java +++ /dev/null @@ -1,69 +0,0 @@ -package gr.cite.annotation.model; - -import gr.cite.annotation.common.enums.IsActive; - -import java.time.Instant; -import java.util.UUID; - -public class UserCredential { - - private UUID id; - - public static final String _id = "id"; - - private String externalId; - - public static final String _externalId = "externalId"; - - private User user; - - public static final String _user = "user"; - - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - private Instant updatedAt; - - public static final String _updatedAt = "updatedAt"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getExternalId() { - return externalId; - } - - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/AnnotationBuilder.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/AnnotationBuilder.java deleted file mode 100644 index 9228a7d3a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/AnnotationBuilder.java +++ /dev/null @@ -1,120 +0,0 @@ -package gr.cite.annotation.model.builder; - -import gr.cite.annotation.authorization.AffiliatedResource; -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.authorizationcontentresolver.AuthorizationContentResolver; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.data.AnnotationEntity; -import gr.cite.annotation.model.Annotation; -import gr.cite.annotation.model.AnnotationAuthor; -import gr.cite.annotation.model.User; -import gr.cite.annotation.query.UserQuery; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.DataLogEntry; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.*; -import java.util.stream.Collectors; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class AnnotationBuilder extends BaseBuilder { - - private final QueryFactory queryFactory; - - private final BuilderFactory builderFactory; - private final AuthorizationContentResolver authorizationContentResolver; - private final AuthorizationService authorizationService; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - public AnnotationBuilder(ConventionService conventionService, QueryFactory queryFactory, BuilderFactory builderFactory, AuthorizationContentResolver authorizationContentResolver, AuthorizationService authorizationService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(AnnotationBuilder.class))); - this.queryFactory = queryFactory; - this.builderFactory = builderFactory; - this.authorizationContentResolver = authorizationContentResolver; - this.authorizationService = authorizationService; - } - - public AnnotationBuilder authorize(EnumSet values) { - this.authorize = values; - return this; - } - - @Override - public List build(FieldSet fields, List data) throws MyApplicationException { - this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); - this.logger.trace(new DataLogEntry("requested fields", fields)); - if (fields == null || fields.isEmpty()) - return new ArrayList<>(); - - List models = new ArrayList<>(); - if (data == null) return models; - - FieldSet authorFields = fields.extractPrefixed(this.asPrefix(Annotation._author)); - Map authorsMap = this.collectAuthors(authorFields, data); - Set authorizationFlags = this.extractAuthorizationFlags(fields, Annotation._authorizationFlags, this.authorizationContentResolver.getPermissionNames()); - Map affiliatedResourceMap = authorizationFlags == null || authorizationFlags.isEmpty() ? null : this.authorizationContentResolver.annotationsAffiliation(data.stream().map(AnnotationEntity::getId).toList()); - - - for (AnnotationEntity d : data) { - Annotation m = new Annotation(); - if (fields.hasField(this.asIndexer(Annotation._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(Annotation._entityId))) m.setEntityId(d.getEntityId()); - if (fields.hasField(this.asIndexer(Annotation._entityType))) m.setEntityType(d.getEntityType()); - if (fields.hasField(this.asIndexer(Annotation._anchor))) m.setAnchor(d.getAnchor()); - if (fields.hasField(this.asIndexer(Annotation._payload))) m.setPayload(d.getPayload()); - if (fields.hasField(this.asIndexer(Annotation._subjectId))) m.setSubjectId(d.getSubjectId()); - if (fields.hasField(this.asIndexer(Annotation._threadId))) m.setThreadId(d.getThreadId()); - if (fields.hasField(this.asIndexer(Annotation._parentId))) m.setParentId(d.getParentId()); - if (fields.hasField(this.asIndexer(Annotation._protectionType))) m.setProtectionType(d.getProtectionType()); - if (fields.hasField(this.asIndexer(Annotation._timeStamp))) m.setTimeStamp(d.getTimeStamp()); - if (fields.hasField(this.asIndexer(Annotation._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(Annotation._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(Annotation._isActive))) m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(Annotation._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); - if (!authorFields.isEmpty() && authorsMap != null && authorsMap.containsKey(d.getSubjectId())) m.setAuthor(authorsMap.get(d.getSubjectId())); - if (affiliatedResourceMap != null && !authorizationFlags.isEmpty()) m.setAuthorizationFlags(this.evaluateAuthorizationFlags(this.authorizationService, authorizationFlags, affiliatedResourceMap.getOrDefault(d.getId(), null))); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } - - private Map collectAuthors(FieldSet fields, List data) { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", User.class.getSimpleName()); - - Map itemMap = new HashMap<>(); - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(this.asIndexer(User._id), this.asIndexer(User._name)); - List userIds = data.stream() - .map(AnnotationEntity::getSubjectId) - .distinct() - .collect(Collectors.toList()); - UserQuery query = this.queryFactory.query(UserQuery.class).disableTracking().ids(userIds); - Map> users = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asMasterKey(query, clone, User::getId); - - users.forEach((key, val) -> { - itemMap.put(key, this.authorFromUser(val.getFirst())); - }); - - return itemMap; - } - - private AnnotationAuthor authorFromUser(User user) { - AnnotationAuthor author = new AnnotationAuthor(); - author.setId(user.getId()); - author.setName(user.getName()); - return author; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/BaseBuilder.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/BaseBuilder.java deleted file mode 100644 index bc9e04835..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/BaseBuilder.java +++ /dev/null @@ -1,118 +0,0 @@ -package gr.cite.annotation.model.builder; - -import gr.cite.annotation.authorization.AffiliatedResource; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.builder.Builder; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.LoggerService; - -import java.time.Instant; -import java.util.*; -import java.util.function.Function; -import java.util.stream.Collectors; - -public abstract class BaseBuilder implements Builder { - protected final LoggerService logger; - protected final ConventionService conventionService; - - public BaseBuilder( - ConventionService conventionService, - LoggerService logger - ) { - this.conventionService = conventionService; - this.logger = logger; - } - - public M build(FieldSet directives, D data) throws MyApplicationException { - if (data == null) { - //this.logger.Debug(new MapLogEntry("requested build for null item requesting fields").And("fields", directives)); -// return default(M); - M model = null; - return null; //TODO - } - List models = this.build(directives, List.of(data)); - return models.stream().findFirst().orElse(null); //TODO - } - - public abstract List build(FieldSet directives, List data) throws MyApplicationException; - - public Map asForeignKey(QueryBase query, FieldSet directives, Function keySelector) throws MyApplicationException { - this.logger.trace("Building references from query"); - List datas = query.collectAs(directives); - this.logger.debug("collected {} items to build", Optional.ofNullable(datas).map(List::size).orElse(0)); - return this.asForeignKey(datas, directives, keySelector); - } - - public Map asForeignKey(List data, FieldSet directives, Function keySelector) throws MyApplicationException { - this.logger.trace("building references"); - List models = this.build(directives, data); - this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(List::size).orElse(0), Optional.ofNullable(data).map(List::size).orElse(0)); - Map map = models.stream().collect(Collectors.toMap(keySelector, o -> o)); - return map; - } - - public Map> asMasterKey(QueryBase query, FieldSet directives, Function keySelector) throws MyApplicationException { - this.logger.trace("Building details from query"); - List datas = query.collectAs(directives); - this.logger.debug("collected {} items to build", Optional.ofNullable(datas).map(List::size).orElse(0)); - return this.asMasterKey(datas, directives, keySelector); - } - - public Map> asMasterKey(List data, FieldSet directives, Function keySelector) throws MyApplicationException { - this.logger.trace("building details"); - List models = this.build(directives, data); - this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(List::size).orElse(0), Optional.ofNullable(data).map(List::size).orElse(0)); - Map> map = new HashMap<>(); - for (M model : models) { - K key = keySelector.apply(model); - if (!map.containsKey(key)) map.put(key, new ArrayList()); - map.get(key).add(model); - } - return map; - } - - public Map asEmpty(List keys, Function mapper, Function keySelector) { - this.logger.trace("building static references"); - List models = keys.stream().map(mapper).collect(Collectors.toList()); - this.logger.debug("mapping {} build items from {} requested", Optional.of(models).map(List::size).orElse(0), Optional.of(keys).map(List::size)); - Map map = models.stream().collect(Collectors.toMap(keySelector, o -> o)); - return map; - } - - protected String hashValue(Instant value) throws MyApplicationException { - return this.conventionService.hashValue(value); - } - - protected String asPrefix(String name) { - return this.conventionService.asPrefix(name); - } - - protected String asIndexer(String... names) { - return this.conventionService.asIndexer(names); - } - - protected Set extractAuthorizationFlags(FieldSet fields, String propertyName, List permissionNames){ - if (fields == null) return new HashSet<>(); - if (permissionNames == null) return new HashSet<>(); - - FieldSet authorizationFlags = fields.extractPrefixed(this.asPrefix(propertyName)); - List permissions = new ArrayList<>(); - for (String fieldValue : authorizationFlags.getFields()) permissions.addAll(permissionNames.stream().filter(x-> x.equalsIgnoreCase(fieldValue)).toList()); - return new HashSet<>(permissions); - } - - protected List evaluateAuthorizationFlags(AuthorizationService authorizationService, Set authorizationFlags, AffiliatedResource affiliatedResource) { - List allowed = new ArrayList<>(); - if (authorizationFlags == null) return allowed; - if (authorizationService == null) return allowed; - - for (String permission : authorizationFlags) { - Boolean isAllowed = affiliatedResource == null ? authorizationService.authorize(permission) : authorizationService.authorizeAtLeastOne(List.of(affiliatedResource), permission); - if (isAllowed) allowed.add(permission); - } - return allowed; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/TenantBuilder.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/TenantBuilder.java deleted file mode 100644 index 1718ff3d8..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/TenantBuilder.java +++ /dev/null @@ -1,68 +0,0 @@ -package gr.cite.annotation.model.builder; - -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.data.TenantEntity; -import gr.cite.annotation.model.Tenant; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.DataLogEntry; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.*; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantBuilder extends BaseBuilder { - - private final BuilderFactory builderFactory; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public TenantBuilder( - ConventionService conventionService, - BuilderFactory builderFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(TenantBuilder.class))); - this.builderFactory = builderFactory; - } - - public TenantBuilder authorize(EnumSet values) { - this.authorize = values; - return this; - } - - @Override - public List build(FieldSet fields, List data) throws MyApplicationException { - this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(data).map(List::size).orElse(0), Optional.ofNullable(fields).map(FieldSet::getFields).map(Set::size).orElse(0)); - this.logger.trace(new DataLogEntry("requested fields", fields)); - if (fields == null || data == null || fields.isEmpty()) - return new ArrayList<>(); - - List models = new ArrayList<>(); - for (TenantEntity d : data) { - Tenant m = new Tenant(); - if (fields.hasField(this.asIndexer(Tenant._id))) - m.setId(d.getId()); - if (fields.hasField(this.asIndexer(Tenant._code))) - m.setCode(d.getCode()); - if (fields.hasField(this.asIndexer(Tenant._isActive))) - m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(Tenant._createdAt))) - m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(Tenant._updatedAt))) - m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(Tenant._hash))) - m.setHash(this.hashValue(d.getUpdatedAt())); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/UserBuilder.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/UserBuilder.java deleted file mode 100644 index 05882378c..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/builder/UserBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -package gr.cite.annotation.model.builder; - -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.data.UserEntity; -import gr.cite.annotation.model.User; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.DataLogEntry; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Optional; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserBuilder extends BaseBuilder { - - private final BuilderFactory builderFactory; - private final QueryFactory queryFactory; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public UserBuilder( - ConventionService conventionService, - BuilderFactory builderFactory, - QueryFactory queryFactory - ) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(UserBuilder.class))); - this.builderFactory = builderFactory; - this.queryFactory = queryFactory; - } - - public UserBuilder authorize(EnumSet values) { - this.authorize = values; - return this; - } - - @Override - public List build(FieldSet fields, List datas) throws MyApplicationException { - this.logger.debug("building for {} items requesting {} fields", Optional.ofNullable(datas).map(e -> e.size()).orElse(0), Optional.ofNullable(fields).map(e -> e.getFields()).map(e -> e.size()).orElse(0)); - this.logger.trace(new DataLogEntry("requested fields", fields)); - if (fields == null || fields.isEmpty()) return new ArrayList<>(); - - List models = new ArrayList<>(); - - for (UserEntity d : datas) { - User m = new User(); - if (fields.hasField(this.asIndexer(User._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(User._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); - if (fields.hasField(this.asIndexer(User._name))) m.setName(d.getName()); - if (fields.hasField(this.asIndexer(User._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(User._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(User._isActive))) m.setIsActive(d.getIsActive()); - models.add(m); - } - this.logger.debug("build {} items", Optional.ofNullable(models).map(e -> e.size()).orElse(0)); - return models; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/AnnotationAuthorCensor.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/AnnotationAuthorCensor.java deleted file mode 100644 index 27891f289..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/AnnotationAuthorCensor.java +++ /dev/null @@ -1,38 +0,0 @@ -package gr.cite.annotation.model.censorship; - -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.model.Annotation; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.DataLogEntry; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class AnnotationAuthorCensor extends BaseCensor{ - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AnnotationAuthorCensor.class)); - - protected final AuthorizationService authService; - - public AnnotationAuthorCensor(ConventionService conventionService, AuthorizationService authService) { - super(conventionService); - this.authService = authService; - } - - public void censor(FieldSet fields, UUID userId) { - logger.debug(new DataLogEntry("censoring fields", fields)); - if (fields == null || fields.isEmpty()) - return; - - this.authService.authorizeForce(Permission.BrowseAnnotation, Permission.DeferredAffiliation); - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/AnnotationCensor.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/AnnotationCensor.java deleted file mode 100644 index c7ea75c0f..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/AnnotationCensor.java +++ /dev/null @@ -1,45 +0,0 @@ -package gr.cite.annotation.model.censorship; - -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.model.Annotation; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.censor.CensorFactory; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.DataLogEntry; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class AnnotationCensor extends BaseCensor{ - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AnnotationCensor.class)); - - protected final AuthorizationService authService; - - protected final CensorFactory censorFactory; - - public AnnotationCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { - super(conventionService); - this.authService = authService; - this.censorFactory = censorFactory; - } - - public void censor(FieldSet fields, UUID userId) { - logger.debug(new DataLogEntry("censoring fields", fields)); - if (fields == null || fields.isEmpty()) - return; - - this.authService.authorizeForce(Permission.BrowseAnnotation, Permission.DeferredAffiliation); - - FieldSet authorFields = fields.extractPrefixed(this.asIndexerPrefix(Annotation._author)); - this.censorFactory.censor(AnnotationAuthorCensor.class).censor(authorFields, userId); - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/BaseCensor.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/BaseCensor.java deleted file mode 100644 index 127cb0b4b..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/BaseCensor.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.annotation.model.censorship; - -import gr.cite.annotation.convention.ConventionService; -import gr.cite.tools.data.censor.Censor; -import gr.cite.tools.fieldset.FieldSet; - -public class BaseCensor implements Censor { - - protected final ConventionService conventionService; - - public BaseCensor(ConventionService conventionService){ - this.conventionService = conventionService; - } - - protected Boolean isEmpty(FieldSet fields) { - return fields == null || fields.isEmpty(); - } - - protected String asIndexerPrefix(String part){ - return this.conventionService.asPrefix(part); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/TenantCensor.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/TenantCensor.java deleted file mode 100644 index fb2096b70..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/TenantCensor.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.annotation.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.DataLogEntry; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantCensor.class)); - private final AuthorizationService authService; - - @Autowired - public TenantCensor(ConventionService conventionService, AuthorizationService authService) { - super(conventionService); - this.authService = authService; - } - - public void censor(FieldSet fields) { - logger.debug(new DataLogEntry("censoring fields", fields)); - if (this.isEmpty(fields)) return; - this.authService.authorizeForce(Permission.BrowseTenant); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/UserCensor.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/UserCensor.java deleted file mode 100644 index cdd9fb976..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/censorship/UserCensor.java +++ /dev/null @@ -1,50 +0,0 @@ -package gr.cite.annotation.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.annotation.authorization.OwnedResource; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.model.User; -import gr.cite.tools.data.censor.CensorFactory; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.DataLogEntry; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.List; -import java.util.UUID; - - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserCensor.class)); - - protected final AuthorizationService authService; - protected final CensorFactory censorFactory; - - @Autowired - public UserCensor( - ConventionService conventionService, - AuthorizationService authService, - CensorFactory censorFactory - ) { - super(conventionService); - this.authService = authService; - this.censorFactory = censorFactory; - } - - public void censor(FieldSet fields, UUID userId) throws MyForbiddenException { - logger.debug(new DataLogEntry("censoring fields", fields)); - if (this.isEmpty(fields)) return; - this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUser); - FieldSet tenantUsersFields = fields.extractPrefixed(this.asIndexerPrefix(User._tenantUsers)); - //FieldSet indicatorAccessesFields = fields.extractPrefixed(this.asIndexerPrefix(User._indicatorAccesses)); - //this.censorFactory.censor(IndicatorAccessCensor.class).censor(indicatorAccessesFields, userId); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/AnnotationDeleter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/AnnotationDeleter.java deleted file mode 100644 index d2af087cc..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/AnnotationDeleter.java +++ /dev/null @@ -1,74 +0,0 @@ -package gr.cite.annotation.model.deleter; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.AnnotationEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.query.AnnotationQuery; -import gr.cite.tools.data.deleter.Deleter; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class AnnotationDeleter implements Deleter { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserCredentialDeleter.class)); - - private final TenantEntityManager entityManager; - - private final QueryFactory queryFactory; - - @Autowired - public AnnotationDeleter( - TenantEntityManager entityManager, - QueryFactory queryFactory - ) { - this.entityManager = entityManager; - this.queryFactory = queryFactory; - } - - public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { - logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); - List data = this.queryFactory.query(AnnotationQuery.class).ids(ids).collect(); - logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.deleteAndSave(data); - } - - public void deleteAndSave(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.delete(data); - logger.trace("saving changes"); - this.entityManager.flush(); - logger.trace("changes saved"); - } - - public void delete(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - if (data == null || data.isEmpty()) - return; - - Instant now = Instant.now(); - - for (AnnotationEntity item : data) { - logger.trace("deleting item {}", item); - item.setIsActive(IsActive.Inactive); - item.setUpdatedAt(now); - logger.trace("updating item"); - this.entityManager.merge(item); - logger.trace("updated item"); - } - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/EntityUserDeleter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/EntityUserDeleter.java deleted file mode 100644 index ce96c4852..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/EntityUserDeleter.java +++ /dev/null @@ -1,74 +0,0 @@ -package gr.cite.EntityUser.model.deleter; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.EntityUserEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.query.EntityUserQuery; -import gr.cite.tools.data.deleter.Deleter; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class EntityUserDeleter implements Deleter { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(EntityUserDeleter.class)); - - private final TenantEntityManager entityManager; - - private final QueryFactory queryFactory; - - @Autowired - public EntityUserDeleter( - TenantEntityManager entityManager, - QueryFactory queryFactory - ) { - this.entityManager = entityManager; - this.queryFactory = queryFactory; - } - - public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { - logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); - List data = this.queryFactory.query(EntityUserQuery.class).ids(ids).collect(); - logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.deleteAndSave(data); - } - - public void deleteAndSave(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.delete(data); - logger.trace("saving changes"); - this.entityManager.flush(); - logger.trace("changes saved"); - } - - public void delete(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - if (data == null || data.isEmpty()) - return; - - Instant now = Instant.now(); - - for (EntityUserEntity item : data) { - logger.trace("deleting item {}", item); - item.setIsActive(IsActive.Inactive); - item.setUpdatedAt(now); - logger.trace("updating item"); - this.entityManager.merge(item); - logger.trace("updated item"); - } - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/TenantDeleter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/TenantDeleter.java deleted file mode 100644 index 7711c4727..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/TenantDeleter.java +++ /dev/null @@ -1,77 +0,0 @@ -package gr.cite.annotation.model.deleter; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.TenantEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.event.EventBroker; -import gr.cite.annotation.event.TenantTouchedEvent; -import gr.cite.annotation.query.TenantQuery; -import gr.cite.tools.data.deleter.Deleter; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantDeleter.class)); - - private final TenantEntityManager entityManager; - protected final QueryFactory queryFactory; - private final EventBroker eventBroker; - - @Autowired - public TenantDeleter( - TenantEntityManager entityManager, - QueryFactory queryFactory, EventBroker eventBroker - ) { - this.entityManager = entityManager; - this.queryFactory = queryFactory; - this.eventBroker = eventBroker; - } - - public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { - logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); - List data = this.queryFactory.query(TenantQuery.class).ids(ids).collect(); - logger.trace("received {} items", Optional.of(data).map(List::size).orElse(0)); - this.deleteAndSave(data); - } - - public void deleteAndSave(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.delete(data); - logger.trace("saving changes"); - this.entityManager.flush(); - logger.trace("changes saved"); - } - - public void delete(List datas) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(datas).map(List::size).orElse(0)); - if (datas == null || datas.isEmpty()) return; - - Instant now = Instant.now(); - - for (TenantEntity item : datas) { - logger.trace("deleting item {}", item.getId()); - item.setIsActive(IsActive.Inactive); - item.setUpdatedAt(now); - logger.trace("updating item"); - this.entityManager.merge(item); - logger.trace("updated item"); - this.eventBroker.emit(new TenantTouchedEvent(item.getId(), item.getCode())); - } - - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/TenantUserDeleter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/TenantUserDeleter.java deleted file mode 100644 index 094ffaf3a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/TenantUserDeleter.java +++ /dev/null @@ -1,75 +0,0 @@ -package gr.cite.annotation.model.deleter; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.data.TenantUserEntity; -import gr.cite.annotation.event.EventBroker; -import gr.cite.annotation.event.UserRemovedFromTenantEvent; -import gr.cite.annotation.query.TenantUserQuery; -import gr.cite.tools.data.deleter.Deleter; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantUserDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantUserDeleter.class)); - - private final TenantEntityManager entityManager; - private final QueryFactory queryFactory; - private final EventBroker eventBroker; - @Autowired - public TenantUserDeleter( - TenantEntityManager entityManager, - QueryFactory queryFactory, EventBroker eventBroker - ) { - this.entityManager = entityManager; - this.queryFactory = queryFactory; - this.eventBroker = eventBroker; - } - - public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { - logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(e -> e.size()).orElse(0)).And("ids", ids)); - List datas = this.queryFactory.query(TenantUserQuery.class).ids(ids).collect(); - logger.trace("retrieved {} items", Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); - this.deleteAndSave(datas); - } - - public void deleteAndSave(List datas) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); - this.delete(datas); - logger.trace("saving changes"); - this.entityManager.flush(); - logger.trace("changes saved"); - } - - public void delete(List datas) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(datas).map(x -> x.size()).orElse(0)); - if (datas == null || datas.isEmpty()) return; - - Instant now = Instant.now(); - - for (TenantUserEntity item : datas) { - logger.trace("deleting item {}", item.getId()); - item.setIsActive(IsActive.Inactive); - item.setUpdatedAt(now); - logger.trace("updating item"); - this.entityManager.merge(item); - logger.trace("updated item"); - this.eventBroker.emit(new UserRemovedFromTenantEvent(item.getUserId(), item.getTenantId())); - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/UserCredentialDeleter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/UserCredentialDeleter.java deleted file mode 100644 index 77df59d82..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/UserCredentialDeleter.java +++ /dev/null @@ -1,72 +0,0 @@ -package gr.cite.annotation.model.deleter; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.data.UserCredentialEntity; -import gr.cite.annotation.query.UserCredentialQuery; -import gr.cite.tools.data.deleter.Deleter; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserCredentialDeleter implements Deleter { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserCredentialDeleter.class)); - - private final TenantEntityManager entityManager; - - private final QueryFactory queryFactory; - - @Autowired - public UserCredentialDeleter( - TenantEntityManager entityManager, - QueryFactory queryFactory - ) { - this.entityManager = entityManager; - this.queryFactory = queryFactory; - } - - public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { - logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); - List data = this.queryFactory.query(UserCredentialQuery.class).ids(ids).collect(); - logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.deleteAndSave(data); - } - - public void deleteAndSave(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.delete(data); - logger.trace("saving changes"); - this.entityManager.flush(); - logger.trace("changes saved"); - } - - public void delete(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - if (data == null || data.isEmpty()) - return; - - Instant now = Instant.now(); - - for (UserCredentialEntity item : data) { - logger.trace("deleting item {}", item.getId()); - logger.trace("deleting item"); - this.entityManager.remove(item); - logger.trace("deleted item"); - } - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/UserDeleter.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/UserDeleter.java deleted file mode 100644 index 046a62cab..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/deleter/UserDeleter.java +++ /dev/null @@ -1,95 +0,0 @@ -package gr.cite.annotation.model.deleter; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.*; -import gr.cite.annotation.query.TenantUserQuery; -import gr.cite.annotation.query.UserCredentialQuery; -import gr.cite.annotation.query.UserQuery; -import gr.cite.tools.data.deleter.Deleter; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserDeleter implements Deleter { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserDeleter.class)); - - private final TenantEntityManager entityManager; - - protected final QueryFactory queryFactory; - - protected final DeleterFactory deleterFactory; - - @Autowired - public UserDeleter( - TenantEntityManager entityManager, - QueryFactory queryFactory, - DeleterFactory deleterFactory - ) { - this.entityManager = entityManager; - this.queryFactory = queryFactory; - this.deleterFactory = deleterFactory; - } - - public void deleteAndSaveByIds(List ids) throws InvalidApplicationException { - logger.debug(new MapLogEntry("collecting to delete").And("count", Optional.ofNullable(ids).map(List::size).orElse(0)).And("ids", ids)); - List data = this.queryFactory.query(UserQuery.class).ids(ids).collect(); - logger.trace("retrieved {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.deleteAndSave(data); - } - - public void deleteAndSave(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - this.delete(data); - logger.trace("saving changes"); - this.entityManager.flush(); - logger.trace("changes saved"); - } - - public void delete(List data) throws InvalidApplicationException { - logger.debug("will delete {} items", Optional.ofNullable(data).map(List::size).orElse(0)); - if (data == null || data.isEmpty()) - return; - - List ids = data.stream().map(UserEntity::getId).distinct().collect(Collectors.toList()); - - { - logger.debug("checking related - {}", UserCredentialEntity.class.getSimpleName()); - List items = this.queryFactory.query(UserCredentialQuery.class).userIds(ids).collect(); - UserCredentialDeleter deleter = this.deleterFactory.deleter(UserCredentialDeleter.class); - deleter.delete(items); - } - - { - logger.debug("checking related - {}", TenantUserEntity.class.getSimpleName()); - List items = this.queryFactory.query(TenantUserQuery.class).userIds(ids).collect(); - TenantUserDeleter deleter = this.deleterFactory.deleter(TenantUserDeleter.class); - deleter.delete(items); - } - Instant now = Instant.now(); - - for (UserEntity item : data) { - logger.trace("deleting item {}", item.getId()); - item.setIsActive(IsActive.Inactive); - item.setUpdatedAt(now); - logger.trace("updating item"); - this.entityManager.merge(item); - logger.trace("updated item"); - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/AnnotationPersist.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/AnnotationPersist.java deleted file mode 100644 index ed0b7985f..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/AnnotationPersist.java +++ /dev/null @@ -1,154 +0,0 @@ -package gr.cite.annotation.model.persist; - -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import gr.cite.annotation.common.validation.BaseValidator; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.tools.validation.specification.Specification; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -public class AnnotationPersist { - - private UUID entityId; - - public static final String _entityId = "entityId"; - - private String entityType; - - public static final String _entityType = "entityType"; - - private String anchor; - - public static final String _anchor = "anchor"; - - private String payload; - - public static final String _payload = "payload"; - - private UUID threadId; - - public static final String _threadId = "threadId"; - - private UUID parentId; - - public static final String _parentId = "parentId"; - - private AnnotationProtectionType protectionType; - - public static final String _protectionType = "protectionType"; - - public UUID getEntityId() { - return entityId; - } - - public void setEntityId(UUID entityId) { - this.entityId = entityId; - } - - public String getEntityType() { - return entityType; - } - - public void setEntityType(String entityType) { - this.entityType = entityType; - } - - public String getAnchor() { - return anchor; - } - - public void setAnchor(String anchor) { - this.anchor = anchor; - } - - public String getPayload() { - return payload; - } - - public void setPayload(String payload) { - this.payload = payload; - } - - public UUID getThreadId() { - return threadId; - } - - public void setThreadId(UUID threadId) { - this.threadId = threadId; - } - - public UUID getParentId() { - return parentId; - } - - public void setParentId(UUID parentId) { - this.parentId = parentId; - } - - public AnnotationProtectionType getProtectionType() { - return protectionType; - } - - public void setProtectionType(AnnotationProtectionType protectionType) { - this.protectionType = protectionType; - } - - @Component(AnnotationPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class AnnotationPersistValidator extends BaseValidator { - - public static final String ValidatorName = "AnnotationIntegrationEventPersistValidator"; - - private final MessageSource messageSource; - - protected AnnotationPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return AnnotationPersist.class; - } - - @Override - protected List specifications(AnnotationPersist item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isNull(item.getEntityId())) - .failOn(AnnotationPersist._entityId).failWith(messageSource.getMessage("Validation_Required", new Object[]{AnnotationPersist._entityId}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isNull(item.getEntityId())) - .must(() -> this.isValidGuid(item.getEntityId())) - .failOn(AnnotationPersist._entityId).failWith(messageSource.getMessage("validation.invalidid", new Object[]{AnnotationPersist._entityId}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getEntityType())) - .failOn(AnnotationPersist._entityType).failWith(messageSource.getMessage("Validation_Required", new Object[]{AnnotationPersist._entityType}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getPayload())) - .failOn(AnnotationPersist._payload).failWith(messageSource.getMessage("Validation_Required", new Object[]{AnnotationPersist._payload}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isNull(item.getThreadId())) - .must(() -> this.isValidGuid(item.getThreadId())) - .failOn(AnnotationPersist._threadId).failWith(messageSource.getMessage("Validation_UnexpectedValue", new Object[]{AnnotationPersist._threadId}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isNull(item.getParentId())) - .must(() -> this.isValidGuid(item.getParentId())) - .failOn(AnnotationPersist._parentId).failWith(messageSource.getMessage("Validation_UnexpectedValue", new Object[]{AnnotationPersist._parentId}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getProtectionType())) - .failOn(AnnotationPersist._protectionType).failWith(messageSource.getMessage("Validation_Required", new Object[]{AnnotationPersist._protectionType}, LocaleContextHolder.getLocale())) - ); - } - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/TenantTouchedIntegrationEventPersist.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/TenantTouchedIntegrationEventPersist.java deleted file mode 100644 index dc02ad6da..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/TenantTouchedIntegrationEventPersist.java +++ /dev/null @@ -1,78 +0,0 @@ -package gr.cite.annotation.model.persist; - -import gr.cite.annotation.common.validation.BaseValidator; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.tools.validation.specification.Specification; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -public class TenantTouchedIntegrationEventPersist { - - private UUID id; - public static final String _id = "id"; - - private String code; - public static final String _code = "code"; - public static final int _codeLength = 50; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - @Component(TenantTouchedIntegrationEventPersist.TenantTouchedIntegrationEventPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class TenantTouchedIntegrationEventPersistValidator extends BaseValidator { - - public static final String ValidatorName = "TenantTouchedIntegrationEventPersistValidator"; - - private final MessageSource messageSource; - - protected TenantTouchedIntegrationEventPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return TenantTouchedIntegrationEventPersist.class; - } - - @Override - protected List specifications(TenantTouchedIntegrationEventPersist item) { - return Arrays.asList( - this.spec() - .iff(() -> !this.isNull(item.getId())) - .must(() -> this.isValidGuid(item.getId())) - .failOn(TenantTouchedIntegrationEventPersist._id).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantTouchedIntegrationEventPersist._id}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getCode())) - .failOn(TenantTouchedIntegrationEventPersist._code).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantTouchedIntegrationEventPersist._code}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isEmpty(item.getCode())) - .must(() -> this.lessEqualLength(item.getCode(), TenantTouchedIntegrationEventPersist._codeLength)) - .failOn(TenantTouchedIntegrationEventPersist._code).failWith(messageSource.getMessage("Validation_MaxLength", new Object[]{TenantTouchedIntegrationEventPersist._code}, LocaleContextHolder.getLocale())) - ); - } - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/UserTouchedIntegrationEventPersist.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/UserTouchedIntegrationEventPersist.java deleted file mode 100644 index da06b8cee..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/persist/UserTouchedIntegrationEventPersist.java +++ /dev/null @@ -1,80 +0,0 @@ -package gr.cite.annotation.model.persist; - -import gr.cite.annotation.common.validation.BaseValidator; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.errorcode.ErrorThesaurusProperties; -import gr.cite.annotation.integrationevent.inbox.usertouched.UserTouchedIntegrationEvent; -import gr.cite.tools.validation.specification.Specification; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Scope; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Component; - -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -public class UserTouchedIntegrationEventPersist { - - private UUID id; - public static final String _id = "id"; - - private String name; - - public static final String _name = "name"; - - public static final int _nameLength = 200; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Component(UserTouchedIntegrationEventPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class UserTouchedIntegrationEventPersistValidator extends BaseValidator { - - public static final String ValidatorName = "UserTouchedIntegrationEventPersistValidator"; - - private final MessageSource messageSource; - - protected UserTouchedIntegrationEventPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return UserTouchedIntegrationEventPersist.class; - } - - @Override - protected List specifications(UserTouchedIntegrationEventPersist item) { - return Arrays.asList( - this.spec() - .iff(() -> !this.isNull(item.getId())) - .must(() -> this.isValidGuid(item.getId())) - .failOn(UserTouchedIntegrationEvent._id).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserTouchedIntegrationEventPersist._id}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getName())) - .failOn(UserTouchedIntegrationEvent._name).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserTouchedIntegrationEventPersist._name}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isEmpty(item.getName())) - .must(() -> this.lessEqualLength(item.getName(), UserTouchedIntegrationEvent._nameLength)) - .failOn(UserTouchedIntegrationEvent._name).failWith(messageSource.getMessage("Validation_MaxLength", new Object[]{UserTouchedIntegrationEventPersist._name}, LocaleContextHolder.getLocale())) - ); - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/user/PublicUser.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/model/user/PublicUser.java deleted file mode 100644 index 9ae1cb0ac..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/model/user/PublicUser.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.annotation.model.user; - - -import java.util.UUID; - -public class PublicUser { - - public static final String _id = "id"; - private UUID id; - - public static final String _name = "name"; - private String name = null; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/AnnotationQuery.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/AnnotationQuery.java deleted file mode 100644 index e03cad741..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/AnnotationQuery.java +++ /dev/null @@ -1,356 +0,0 @@ -package gr.cite.annotation.query; - -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.AnnotationEntity; -import gr.cite.annotation.data.EntityUserEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.model.Annotation; -import gr.cite.annotation.query.utils.BuildSubQueryInput; -import gr.cite.annotation.query.utils.QueryUtilsService; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.query.FieldResolver; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -import jakarta.persistence.criteria.Subquery; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class AnnotationQuery extends QueryBase { - - private String like; - - private Collection ids; - - private Collection excludedIds; - - private Collection isActives; - - private Collection entityIds; - - private Collection entityTypes; - - private Collection anchors; - - private Collection threadIds; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final UserScope userScope; - - private final QueryUtilsService queryUtilsService; - - private final AuthorizationService authService; - - private final TenantEntityManager tenantEntityManager; - public AnnotationQuery(UserScope userScope, QueryUtilsService queryUtilsService, AuthorizationService authService, TenantEntityManager tenantEntityManager) { - this.userScope = userScope; - this.queryUtilsService = queryUtilsService; - this.authService = authService; - this.tenantEntityManager = tenantEntityManager; - } - - public AnnotationQuery like(String value) { - this.like = like; - return this; - } - - public AnnotationQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public AnnotationQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public AnnotationQuery ids(Collection values) { - this.ids = values; - return this; - } - - public AnnotationQuery excludedIds(Collection values) { - this.excludedIds = values; - return this; - } - - public AnnotationQuery excludedIds(UUID value) { - this.excludedIds = List.of(value); - return this; - } - - public AnnotationQuery excludedIds(UUID... value) { - this.excludedIds = Arrays.asList(value); - return this; - } - - public AnnotationQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public AnnotationQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public AnnotationQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public AnnotationQuery entityIds(UUID value) { - this.entityIds = List.of(value); - return this; - } - - public AnnotationQuery entityIds(UUID... value) { - this.entityIds = Arrays.asList(value); - return this; - } - - public AnnotationQuery entityIds(Collection values) { - this.entityIds = values; - return this; - } - - public AnnotationQuery entityTypes(String value) { - this.entityTypes = List.of(value); - return this; - } - - public AnnotationQuery entityTypes(String... value) { - this.entityTypes = Arrays.asList(value); - return this; - } - - public AnnotationQuery entityTypes(Collection values) { - this.entityTypes = values; - return this; - } - - public AnnotationQuery anchors(String value) { - this.anchors = List.of(value); - return this; - } - - public AnnotationQuery anchors(String... value) { - this.anchors = Arrays.asList(value); - return this; - } - - public AnnotationQuery anchors(Collection values) { - this.anchors = values; - return this; - } - - public AnnotationQuery threadIds(UUID value) { - this.threadIds = List.of(value); - return this; - } - - public AnnotationQuery threadIds(UUID... value) { - this.threadIds = Arrays.asList(value); - return this; - } - - public AnnotationQuery threadIds(Collection values) { - this.threadIds = values; - return this; - } - - public AnnotationQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public AnnotationQuery enableTracking() { - this.noTracking = false; - return this; - } - - public AnnotationQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Boolean isFalseQuery() { - return this.isEmpty(this.ids) || this.isEmpty(this.excludedIds) || this.isEmpty(this.isActives) || this.isEmpty(this.entityIds); - } - - @Override - protected Class entityClass() { - return AnnotationEntity.class; - } - - @Override - protected Predicate applyAuthZ(QueryContext queryContext) { - if (this.authorize.contains(AuthorizationFlags.None)) return null; - if (this.authorize.contains(AuthorizationFlags.Permission) && this.authService.authorize(Permission.BrowseAnnotation)) return null; - UUID userId = null; - if (this.authorize.contains(AuthorizationFlags.Associated)) userId = this.userScope.getUserIdSafe(); - if (this.authorize.contains(AuthorizationFlags.Owner)) userId = this.userScope.getUserIdSafe(); - - List predicates = new ArrayList<>(); - if (userId != null ) { - UUID finalUserId = userId; - Subquery subquery = this.queryUtilsService.buildSubQuery(new BuildSubQueryInput<>(new BuildSubQueryInput.Builder<>(EntityUserEntity.class, UUID.class) - .query(queryContext.Query) - .criteriaBuilder(queryContext.CriteriaBuilder) - .keyPathFunc((subQueryRoot) -> subQueryRoot.get(EntityUserEntity._entityId)) - .filterFunc((subQueryRoot, cb) -> - cb.and( - cb.equal(subQueryRoot.get(EntityUserEntity._userId), finalUserId), - cb.equal(subQueryRoot.get(EntityUserEntity._isActive), IsActive.Active) - ) - ) - )); - predicates.add(queryContext.CriteriaBuilder.or( - queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._subjectId)).value(userId), - queryContext.CriteriaBuilder.and( - queryContext.CriteriaBuilder.equal(queryContext.Root.get(AnnotationEntity._protectionType), AnnotationProtectionType.EntityAccessors), - queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._entityId)).value(subquery) - ))); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return queryContext.CriteriaBuilder.or(); //Creates a false query - } - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - - if (this.like != null && !this.like.isBlank()) { - Predicate likePredicate = queryContext.CriteriaBuilder.or( - queryContext.CriteriaBuilder.like(queryContext.Root.get(AnnotationEntity._payload), this.like) - ); - predicates.add(likePredicate); - } - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._id)); - for (UUID item : this.ids) - inClause.value(item); - predicates.add(inClause); - } - if (this.excludedIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._id)); - for (UUID item : this.ids) - inClause.value(item); - predicates.add(inClause.not()); - } - if (this.isActives != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._isActive)); - for (IsActive item : this.isActives) - inClause.value(item); - predicates.add(inClause); - } - if (this.entityIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._entityId)); - for (UUID item : this.entityIds) - inClause.value(item); - predicates.add(inClause); - } - if (this.entityTypes != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._entityType)); - for (String item : this.entityTypes) - inClause.value(item); - predicates.add(inClause); - } - if (this.anchors != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._anchor)); - for (String item : this.anchors) - inClause.value(item); - predicates.add(inClause); - } - if (this.threadIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(AnnotationEntity._threadId)); - for (UUID item : this.threadIds) - inClause.value(item); - predicates.add(inClause); - } - - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(Annotation._id)) - return AnnotationEntity._id; - else if (item.match(Annotation._entityId)) - return AnnotationEntity._entityId; - else if (item.match(Annotation._entityType)) - return AnnotationEntity._entityType; - else if (item.match(Annotation._anchor)) - return AnnotationEntity._anchor; - else if (item.match(Annotation._payload)) - return AnnotationEntity._payload; - else if (item.match(Annotation._subjectId)) - return AnnotationEntity._subjectId; - else if (item.match(Annotation._threadId)) - return AnnotationEntity._threadId; - else if (item.match(Annotation._parentId)) - return AnnotationEntity._parentId; - else if (item.match(Annotation._protectionType)) - return AnnotationEntity._protectionType; - else if (item.match(Annotation._timeStamp)) - return AnnotationEntity._timeStamp; - else if (item.match(Annotation._createdAt)) - return AnnotationEntity._createdAt; - else if (item.match(Annotation._updatedAt)) - return AnnotationEntity._updatedAt; -// else if (item.match(Annotation._hash)) return AnnotationEntity._updatedAt; - else if (item.match(Annotation._isActive)) - return AnnotationEntity._isActive; - else - return null; - } - - @Override - protected AnnotationEntity convert(Tuple tuple, Set columns) { - AnnotationEntity item = new AnnotationEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, AnnotationEntity._id, UUID.class)); - item.setEntityId(QueryBase.convertSafe(tuple, columns, AnnotationEntity._entityId, UUID.class)); - item.setEntityType(QueryBase.convertSafe(tuple, columns, AnnotationEntity._entityType, String.class)); - item.setAnchor(QueryBase.convertSafe(tuple, columns, AnnotationEntity._anchor, String.class)); - item.setPayload(QueryBase.convertSafe(tuple, columns, AnnotationEntity._payload, String.class)); - item.setSubjectId(QueryBase.convertSafe(tuple, columns, AnnotationEntity._subjectId, UUID.class)); - item.setThreadId(QueryBase.convertSafe(tuple, columns, AnnotationEntity._threadId, UUID.class)); - item.setParentId(QueryBase.convertSafe(tuple, columns, AnnotationEntity._parentId, UUID.class)); - item.setProtectionType(QueryBase.convertSafe(tuple, columns, AnnotationEntity._protectionType, AnnotationProtectionType.class)); - item.setTimeStamp(QueryBase.convertSafe(tuple, columns, AnnotationEntity._timeStamp, Instant.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, AnnotationEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, AnnotationEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, AnnotationEntity._isActive, IsActive.class)); - return item; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/EntityUserQuery.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/EntityUserQuery.java deleted file mode 100644 index 5c40c4788..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/EntityUserQuery.java +++ /dev/null @@ -1,227 +0,0 @@ -package gr.cite.annotation.query; - -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.AnnotationEntity; -import gr.cite.annotation.data.EntityUserEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.model.EntityUser; -import gr.cite.annotation.query.utils.BuildSubQueryInput; -import gr.cite.annotation.query.utils.QueryUtilsService; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.query.FieldResolver; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import java.time.Instant; -import java.util.*; - -@Component -@RequestScope -public class EntityUserQuery extends QueryBase { - - private Collection ids, entityIds, userIds; - - private Collection isActives; - - private final AuthorizationService authService; - - private final UserScope userScope; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final TenantEntityManager tenantEntityManager; - public EntityUserQuery(AuthorizationService authService, UserScope userScope, TenantEntityManager tenantEntityManager) { - this.authService = authService; - this.userScope = userScope; - this.tenantEntityManager = tenantEntityManager; - } - - public EntityUserQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public EntityUserQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public EntityUserQuery ids(Collection values) { - this.ids = values; - return this; - } - - public EntityUserQuery entityIds(UUID value) { - this.entityIds = List.of(value); - return this; - } - - public EntityUserQuery entityIds(UUID... value) { - this.entityIds = Arrays.asList(value); - return this; - } - - public EntityUserQuery entityIds(Collection values) { - this.entityIds = values; - return this; - } - - public EntityUserQuery userIds(UUID value) { - this.userIds = List.of(value); - return this; - } - - public EntityUserQuery userIds(UUID... value) { - this.userIds = Arrays.asList(value); - return this; - } - - public EntityUserQuery userIds(Collection values) { - this.userIds = values; - return this; - } - - public EntityUserQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public EntityUserQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public EntityUserQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public EntityUserQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public EntityUserQuery enableTracking() { - this.noTracking = false; - return this; - } - - public EntityUserQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Boolean isFalseQuery() { - return false; - } - - @Override - protected Class entityClass() { - return EntityUserEntity.class; - } - @Override - protected Predicate applyAuthZ(QueryContext queryContext) { - if (this.authorize.contains(AuthorizationFlags.None)) return null; - if (this.authorize.contains(AuthorizationFlags.Permission) && this.authService.authorize(Permission.BrowseAnnotation)) return null; - UUID userId = null; - if (this.authorize.contains(AuthorizationFlags.Associated)) userId = this.userScope.getUserIdSafe(); - if (this.authorize.contains(AuthorizationFlags.Owner)) userId = this.userScope.getUserIdSafe(); - - List predicates = new ArrayList<>(); - if (userId != null ) { - predicates.add( queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityUserEntity._userId)).value(userId)); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return queryContext.CriteriaBuilder.or(); //Creates a false query - } - } - - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityUserEntity._id)); - for (UUID item : this.ids) - inClause.value(item); - predicates.add(inClause); - } - if (this.entityIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityUserEntity._entityId)); - for (UUID item : this.entityIds) - inClause.value(item); - predicates.add(inClause); - } - if (this.userIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityUserEntity._userId)); - for (UUID item : this.userIds) - inClause.value(item); - predicates.add(inClause); - } - if (this.isActives != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(EntityUserEntity._isActive)); - for (IsActive item : this.isActives) - inClause.value(item); - predicates.add(inClause); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(EntityUser._id)) - return EntityUserEntity._id; - else if (item.match(EntityUser._entityId)) - return EntityUserEntity._entityId; - else if (item.match(EntityUser._user)) - return EntityUserEntity._userId; - else if (item.prefix(EntityUser._user)) - return EntityUserEntity._userId; - else if (item.match(EntityUser._createdAt)) - return EntityUserEntity._createdAt; - else if (item.match(EntityUser._updatedAt)) - return EntityUserEntity._updatedAt; - else if (item.match(EntityUser._hash)) - return EntityUserEntity._updatedAt; - else if (item.match(EntityUser._isActive)) - return EntityUserEntity._isActive; - else - return null; - } - - @Override - protected EntityUserEntity convert(Tuple tuple, Set columns) { - EntityUserEntity item = new EntityUserEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, EntityUserEntity._id, UUID.class)); - item.setEntityId(QueryBase.convertSafe(tuple, columns, EntityUserEntity._entityId, UUID.class)); - item.setUserId(QueryBase.convertSafe(tuple, columns, EntityUserEntity._userId, UUID.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, EntityUserEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, EntityUserEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, EntityUserEntity._isActive, IsActive.class)); - return item; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/QueueInboxQuery.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/QueueInboxQuery.java deleted file mode 100644 index 5714ef8d9..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/QueueInboxQuery.java +++ /dev/null @@ -1,263 +0,0 @@ -package gr.cite.annotation.query; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.QueueInboxEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.queueinbox.entity.QueueInboxStatus; -import gr.cite.tools.data.query.FieldResolver; -import gr.cite.tools.data.query.Ordering; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class QueueInboxQuery extends QueryBase { - - private Collection ids; - private Collection messageIds; - private Instant createdAfter; - private Collection isActives; - private Collection exchanges; - private Collection routes; - private Collection status; - private Integer retryThreshold; - - private final TenantEntityManager tenantEntityManager; - - public QueueInboxQuery(TenantEntityManager tenantEntityManager) { - this.tenantEntityManager = tenantEntityManager; - } - - public QueueInboxQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public QueueInboxQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public QueueInboxQuery ids(List value) { - this.ids = value; - return this; - } - - public QueueInboxQuery messageIds(UUID value) { - this.messageIds = List.of(value); - return this; - } - - public QueueInboxQuery messageIds(UUID... value) { - this.messageIds = Arrays.asList(value); - return this; - } - - public QueueInboxQuery messageIds(List value) { - this.messageIds = value; - return this; - } - - public QueueInboxQuery isActives(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public QueueInboxQuery isActives(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public QueueInboxQuery isActives(List value) { - this.isActives = value; - return this; - } - - public QueueInboxQuery exchanges(String value) { - this.exchanges = List.of(value); - return this; - } - - public QueueInboxQuery exchanges(String... value) { - this.exchanges = Arrays.asList(value); - return this; - } - - public QueueInboxQuery exchanges(List value) { - this.exchanges = value; - return this; - } - - public QueueInboxQuery routes(String value) { - this.routes = List.of(value); - return this; - } - - public QueueInboxQuery routes(String... value) { - this.routes = Arrays.asList(value); - return this; - } - - public QueueInboxQuery routes(List value) { - this.routes = value; - return this; - } - - public QueueInboxQuery status(QueueInboxStatus value) { - this.status = List.of(value); - return this; - } - - public QueueInboxQuery status(QueueInboxStatus... value) { - this.status = Arrays.asList(value); - return this; - } - - public QueueInboxQuery status(List value) { - this.status = value; - return this; - } - - public QueueInboxQuery createdAfter(Instant value) { - this.createdAfter = value; - return this; - } - - public QueueInboxQuery retryThreshold(Integer value) { - this.retryThreshold = value; - return this; - } - - public QueueInboxQuery ordering(Ordering ordering) { - this.setOrder(ordering); - return this; - } - - public QueueInboxQuery enableTracking() { - this.noTracking = false; - return this; - } - - public QueueInboxQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Class entityClass() { - return QueueInboxEntity.class; - } - - @Override - protected Boolean isFalseQuery() { - return this.isEmpty(this.ids) || this.isEmpty(this.messageIds) || this.isEmpty(this.isActives) || this.isEmpty(this.exchanges) - || this.isEmpty(this.routes) || this.isEmpty(this.status); - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueInboxEntity._id)); - for (UUID item : this.ids) inClause.value(item); - predicates.add(inClause); - } - if (this.messageIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueInboxEntity._messageId)); - for (UUID item : this.messageIds) inClause.value(item); - predicates.add(inClause); - } - - if (this.createdAfter != null) { - predicates.add(queryContext.CriteriaBuilder.greaterThan(queryContext.Root.get(QueueInboxEntity._createdAt), this.createdAfter)); - } - if (this.isActives != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueInboxEntity._isActive)); - for (IsActive item : this.isActives) inClause.value(item); - predicates.add(inClause); - } - if (this.exchanges != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueInboxEntity._exchange)); - for (String item : this.exchanges) inClause.value(item); - predicates.add(inClause); - } - if (this.routes != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueInboxEntity._route)); - for (String item : this.routes) inClause.value(item); - predicates.add(inClause); - } - - if (this.status != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueInboxEntity._status)); - for (QueueInboxStatus item : this.status) inClause.value(item); - predicates.add(inClause); - } - - if (this.retryThreshold != null) { - predicates.add(queryContext.CriteriaBuilder.or(queryContext.CriteriaBuilder.isNull(queryContext.Root.get(QueueInboxEntity._retryCount)), - queryContext.CriteriaBuilder.lessThanOrEqualTo(queryContext.Root.get(QueueInboxEntity._retryCount), this.retryThreshold))); - } - - if (predicates.size() > 0) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - } - - @Override - protected QueueInboxEntity convert(Tuple tuple, Set columns) { - QueueInboxEntity item = new QueueInboxEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._id, UUID.class)); - item.setExchange(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._exchange, String.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._tenantId, UUID.class)); - item.setRoute(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._route, String.class)); - item.setMessage(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._message, String.class)); - item.setMessageId(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._messageId, UUID.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._createdAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._isActive, IsActive.class)); - item.setStatus(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._status, QueueInboxStatus.class)); - item.setRetryCount(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._retryCount, Integer.class)); - item.setQueue(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._queue, String.class)); - item.setApplicationId(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._applicationId, String.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, QueueInboxEntity._updatedAt, Instant.class)); - return item; - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(QueueInboxEntity._id)) return QueueInboxEntity._id; - else if (item.match(QueueInboxEntity._exchange)) return QueueInboxEntity._exchange; - else if (item.match(QueueInboxEntity._tenantId)) return QueueInboxEntity._tenantId; - else if (item.match(QueueInboxEntity._route)) return QueueInboxEntity._route; - else if (item.match(QueueInboxEntity._message)) return QueueInboxEntity._message; - else if (item.match(QueueInboxEntity._messageId)) return QueueInboxEntity._messageId; - else if (item.match(QueueInboxEntity._createdAt)) return QueueInboxEntity._createdAt; - else if (item.match(QueueInboxEntity._isActive)) return QueueInboxEntity._isActive; - else if (item.match(QueueInboxEntity._status)) return QueueInboxEntity._status; - else if (item.match(QueueInboxEntity._retryCount)) return QueueInboxEntity._retryCount; - else if (item.match(QueueInboxEntity._queue)) return QueueInboxEntity._queue; - else if (item.match(QueueInboxEntity._applicationId)) return QueueInboxEntity._applicationId; - else if (item.match(QueueInboxEntity._createdAt)) return QueueInboxEntity._createdAt; - else if (item.match(QueueInboxEntity._updatedAt)) return QueueInboxEntity._updatedAt; - else return null; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/QueueOutboxQuery.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/QueueOutboxQuery.java deleted file mode 100644 index 10fd8042d..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/QueueOutboxQuery.java +++ /dev/null @@ -1,258 +0,0 @@ -package gr.cite.annotation.query; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.QueueOutboxEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.queueoutbox.entity.QueueOutboxNotifyStatus; -import gr.cite.tools.data.query.FieldResolver; -import gr.cite.tools.data.query.Ordering; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class QueueOutboxQuery extends QueryBase { - - private Collection ids; - private Instant createdAfter; - private Collection isActives; - private Collection exchanges; - private Collection routes; - private Collection notifyStatus; - private Integer retryThreshold; - private Integer confirmTimeout; - - private final TenantEntityManager tenantEntityManager; - - public QueueOutboxQuery(TenantEntityManager tenantEntityManager) { - this.tenantEntityManager = tenantEntityManager; - } - - public QueueOutboxQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public QueueOutboxQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public QueueOutboxQuery ids(List value) { - this.ids = value; - return this; - } - - public QueueOutboxQuery isActives(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public QueueOutboxQuery isActives(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public QueueOutboxQuery isActives(List value) { - this.isActives = value; - return this; - } - - public QueueOutboxQuery exchanges(String value) { - this.exchanges = List.of(value); - return this; - } - - public QueueOutboxQuery exchanges(String... value) { - this.exchanges = Arrays.asList(value); - return this; - } - - public QueueOutboxQuery exchanges(List value) { - this.exchanges = value; - return this; - } - - public QueueOutboxQuery routes(String value) { - this.routes = List.of(value); - return this; - } - - public QueueOutboxQuery routes(String... value) { - this.routes = Arrays.asList(value); - return this; - } - - public QueueOutboxQuery routes(List value) { - this.routes = value; - return this; - } - - public QueueOutboxQuery notifyStatus(QueueOutboxNotifyStatus value) { - this.notifyStatus = List.of(value); - return this; - } - - public QueueOutboxQuery notifyStatus(QueueOutboxNotifyStatus... value) { - this.notifyStatus = Arrays.asList(value); - return this; - } - - public QueueOutboxQuery notifyStatus(List value) { - this.notifyStatus = value; - return this; - } - - public QueueOutboxQuery createdAfter(Instant value) { - this.createdAfter = value; - return this; - } - - public QueueOutboxQuery retryThreshold(Integer value) { - this.retryThreshold = value; - return this; - } - - public QueueOutboxQuery confirmTimeout(Integer value) { - this.confirmTimeout = value; - return this; - } - - public QueueOutboxQuery ordering(Ordering ordering) { - this.setOrder(ordering); - return this; - } - - public QueueOutboxQuery enableTracking() { - this.noTracking = false; - return this; - } - - public QueueOutboxQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Class entityClass() { - return QueueOutboxEntity.class; - } - - @Override - protected Boolean isFalseQuery() { - return this.isEmpty(this.ids) || this.isEmpty(this.isActives) || this.isEmpty(this.exchanges) - || this.isEmpty(this.routes) || this.isEmpty(this.notifyStatus); - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueOutboxEntity._id)); - for (UUID item : this.ids) inClause.value(item); - predicates.add(inClause); - } - - if (this.createdAfter != null) { - predicates.add(queryContext.CriteriaBuilder.greaterThan(queryContext.Root.get(QueueOutboxEntity._createdAt), this.createdAfter)); - } - if (this.isActives != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueOutboxEntity._isActive)); - for (IsActive item : this.isActives) inClause.value(item); - predicates.add(inClause); - } - if (this.exchanges != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueOutboxEntity._exchange)); - for (String item : this.exchanges) inClause.value(item); - predicates.add(inClause); - } - if (this.routes != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueOutboxEntity._route)); - for (String item : this.routes) inClause.value(item); - predicates.add(inClause); - } - - if (this.notifyStatus != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(QueueOutboxEntity._notifyStatus)); - for (QueueOutboxNotifyStatus item : this.notifyStatus) inClause.value(item); - predicates.add(inClause); - } - - if (this.retryThreshold != null) { - predicates.add(queryContext.CriteriaBuilder.or(queryContext.CriteriaBuilder.isNull(queryContext.Root.get(QueueOutboxEntity._retryCount)), - queryContext.CriteriaBuilder.lessThanOrEqualTo(queryContext.Root.get(QueueOutboxEntity._retryCount), this.retryThreshold))); - } - - if (this.confirmTimeout != null) { - predicates.add(queryContext.CriteriaBuilder.or(queryContext.CriteriaBuilder.isNull(queryContext.Root.get(QueueOutboxEntity._publishedAt)), - queryContext.CriteriaBuilder.and( - queryContext.CriteriaBuilder.isNotNull(queryContext.Root.get(QueueOutboxEntity._publishedAt)), - queryContext.CriteriaBuilder.isNull(queryContext.Root.get(QueueOutboxEntity._confirmedAt)), - queryContext.CriteriaBuilder.lessThan(queryContext.Root.get(QueueOutboxEntity._publishedAt), Instant.now().minusSeconds(this.confirmTimeout)) - ) - )); - } - - - if (predicates.size() > 0) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - } - - @Override - protected QueueOutboxEntity convert(Tuple tuple, Set columns) { - QueueOutboxEntity item = new QueueOutboxEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._id, UUID.class)); - item.setExchange(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._exchange, String.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._tenantId, UUID.class)); - item.setRoute(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._route, String.class)); - item.setMessage(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._message, String.class)); - item.setMessageId(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._messageId, UUID.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._createdAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._isActive, IsActive.class)); - item.setNotifyStatus(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._notifyStatus, QueueOutboxNotifyStatus.class)); - item.setRetryCount(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._retryCount, Integer.class)); - item.setPublishedAt(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._publishedAt, Instant.class)); - item.setConfirmedAt(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._confirmedAt, Instant.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, QueueOutboxEntity._updatedAt, Instant.class)); - return item; - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(QueueOutboxEntity._id)) return QueueOutboxEntity._id; - else if (item.match(QueueOutboxEntity._exchange)) return QueueOutboxEntity._exchange; - else if (item.match(QueueOutboxEntity._tenantId)) return QueueOutboxEntity._tenantId; - else if (item.match(QueueOutboxEntity._route)) return QueueOutboxEntity._route; - else if (item.match(QueueOutboxEntity._message)) return QueueOutboxEntity._message; - else if (item.match(QueueOutboxEntity._messageId)) return QueueOutboxEntity._messageId; - else if (item.match(QueueOutboxEntity._createdAt)) return QueueOutboxEntity._createdAt; - else if (item.match(QueueOutboxEntity._isActive)) return QueueOutboxEntity._isActive; - else if (item.match(QueueOutboxEntity._notifyStatus)) return QueueOutboxEntity._notifyStatus; - else if (item.match(QueueOutboxEntity._retryCount)) return QueueOutboxEntity._retryCount; - else if (item.match(QueueOutboxEntity._publishedAt)) return QueueOutboxEntity._publishedAt; - else if (item.match(QueueOutboxEntity._confirmedAt)) return QueueOutboxEntity._confirmedAt; - else if (item.match(QueueOutboxEntity._createdAt)) return QueueOutboxEntity._createdAt; - else if (item.match(QueueOutboxEntity._updatedAt)) return QueueOutboxEntity._updatedAt; - else return null; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/TenantQuery.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/TenantQuery.java deleted file mode 100644 index abafd5940..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/TenantQuery.java +++ /dev/null @@ -1,154 +0,0 @@ -package gr.cite.annotation.query; - -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.data.TenantEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.model.Tenant; -import gr.cite.tools.data.query.FieldResolver; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.Predicate; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantQuery extends QueryBase { - - private String like; - - private Collection ids; - - private Collection isActives; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final TenantEntityManager tenantEntityManager; - - public TenantQuery(TenantEntityManager tenantEntityManager) { - this.tenantEntityManager = tenantEntityManager; - } - - public TenantQuery like(String value) { - this.like = value; - return this; - } - - public TenantQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public TenantQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public TenantQuery ids(Collection values) { - this.ids = values; - return this; - } - - public TenantQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public TenantQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public TenantQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public TenantQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public TenantQuery enableTracking() { - this.noTracking = false; - return this; - } - - public TenantQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Boolean isFalseQuery() { - return this.isEmpty(this.ids) || this.isEmpty(this.isActives); - } - - @Override - protected Class entityClass() { - return TenantEntity.class; - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - predicates.add(queryContext.Root.get(TenantEntity._id).in(ids)); - } - - if (this.like != null && !this.like.isEmpty()) { - predicates.add(queryContext.CriteriaBuilder.like(queryContext.Root.get(TenantEntity._isActive), this.like)); - } - - if (this.isActives != null) { - predicates.add(queryContext.Root.get(TenantEntity._isActive).in(isActives)); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(Tenant._id)) - return TenantEntity._id; - else if (item.match(Tenant._code)) - return TenantEntity._code; - else if (item.match(Tenant._createdAt)) - return TenantEntity._createdAt; - else if (item.match(Tenant._updatedAt)) - return TenantEntity._updatedAt; - else if (item.match(Tenant._isActive)) - return TenantEntity._isActive; - else - return null; - } - - @Override - protected TenantEntity convert(Tuple tuple, Set columns) { - TenantEntity item = new TenantEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, TenantEntity._id, UUID.class)); - item.setCode(QueryBase.convertSafe(tuple, columns, TenantEntity._code, String.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, TenantEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, TenantEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, TenantEntity._isActive, IsActive.class)); - return item; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/TenantUserQuery.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/TenantUserQuery.java deleted file mode 100644 index 92da4154f..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/TenantUserQuery.java +++ /dev/null @@ -1,228 +0,0 @@ -package gr.cite.annotation.query; - -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.data.TenantUserEntity; -import gr.cite.annotation.data.UserEntity; -import gr.cite.annotation.model.Tenant; -import gr.cite.annotation.model.TenantUser; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.query.FieldResolver; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantUserQuery extends QueryBase { - - private Collection ids; - private Collection userIds; - private Collection tenantIds; - private Collection isActives; - private UserQuery userQuery; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - private final UserScope userScope; - private final AuthorizationService authService; - - private final TenantEntityManager tenantEntityManager; - public TenantUserQuery( - UserScope userScope, - AuthorizationService authService, TenantEntityManager tenantEntityManager - ) { - this.userScope = userScope; - this.authService = authService; - this.tenantEntityManager = tenantEntityManager; - } - - public TenantUserQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public TenantUserQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public TenantUserQuery ids(Collection values) { - this.ids = values; - return this; - } - - public TenantUserQuery userIds(UUID value) { - this.userIds = List.of(value); - return this; - } - - public TenantUserQuery userIds(UUID... value) { - this.userIds = Arrays.asList(value); - return this; - } - - public TenantUserQuery userIds(Collection values) { - this.userIds = values; - return this; - } - - public TenantUserQuery tenantIds(UUID value) { - this.tenantIds = List.of(value); - return this; - } - - public TenantUserQuery tenantIds(UUID... value) { - this.tenantIds = Arrays.asList(value); - return this; - } - - public TenantUserQuery tenantIds(Collection values) { - this.tenantIds = values; - return this; - } - - public TenantUserQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public TenantUserQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public TenantUserQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public TenantUserQuery userSubQuery(UserQuery subQuery) { - this.userQuery = subQuery; - return this; - } - - public TenantUserQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public TenantUserQuery enableTracking() { - this.noTracking = false; - return this; - } - - public TenantUserQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Class entityClass() { - return TenantUserEntity.class; - } - - @Override - protected Boolean isFalseQuery() { - return this.isEmpty(this.ids) || this.isEmpty(this.userIds) || this.isEmpty(this.tenantIds) || this.isEmpty(this.isActives) || this.isFalseQuery(this.userQuery); - } - - - @Override - protected Predicate applyAuthZ(QueryContext queryContext) { - if (this.authorize.contains(AuthorizationFlags.None)) return null; - if (this.authorize.contains(AuthorizationFlags.Permission) && this.authService.authorize(Permission.BrowseTenant)) return null; - UUID ownerId = null; - if (this.authorize.contains(AuthorizationFlags.Owner)) ownerId = this.userScope.getUserIdSafe(); - - List predicates = new ArrayList<>(); - if (ownerId != null) { - predicates.add(queryContext.CriteriaBuilder.equal(queryContext.Root.get(TenantUserEntity._userId), ownerId)); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return queryContext.CriteriaBuilder.or(); //Creates a false query - } - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantUserEntity._id)); - for (UUID item : this.ids) inClause.value(item); - predicates.add(inClause); - } - if (this.userIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantUserEntity._userId)); - for (UUID item : this.userIds) inClause.value(item); - predicates.add(inClause); - } - if (this.tenantIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantUserEntity._tenantId)); - for (UUID item : this.tenantIds) inClause.value(item); - predicates.add(inClause); - } - if (this.isActives != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantUserEntity._isActive)); - for (IsActive item : this.isActives) inClause.value(item); - predicates.add(inClause); - } - if (this.userQuery != null) { - QueryContext subQuery = this.applySubQuery(this.userQuery, queryContext, UUID.class, root -> root.get(TenantUserEntity._userId)); - predicates.add(queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantUserEntity._userId)).value(subQuery.Query)); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - } - - @Override - protected TenantUserEntity convert(Tuple tuple, Set columns) { - TenantUserEntity item = new TenantUserEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, TenantUserEntity._id, UUID.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, TenantUserEntity._tenantId, UUID.class)); - item.setUserId(QueryBase.convertSafe(tuple, columns, TenantUserEntity._userId, UUID.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, TenantUserEntity._tenantId, UUID.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, TenantUserEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, TenantUserEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, TenantUserEntity._isActive, IsActive.class)); - return item; - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(TenantUser._id)) return TenantUserEntity._id; - else if (item.match(TenantUser._tenant, Tenant._id)) return TenantUserEntity._tenantId; - else if (item.prefix(TenantUser._tenant)) return TenantUserEntity._tenantId; - else if (item.match(TenantUser._isActive)) return TenantUserEntity._isActive; - else if (item.match(TenantUser._createdAt)) return TenantUserEntity._createdAt; - else if (item.match(TenantUser._updatedAt)) return TenantUserEntity._updatedAt; - else if (item.match(TenantUser._hash)) return TenantUserEntity._updatedAt; - else if (item.match(TenantUser._user, UserEntity._id)) return TenantUserEntity._userId; - else if (item.prefix(TenantUser._user)) return TenantUserEntity._userId; - else if (item.match(TenantUser._belongsToCurrentTenant)) return TenantUserEntity._tenantId; - else return null; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/UserCredentialQuery.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/UserCredentialQuery.java deleted file mode 100644 index 41b28e6ed..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/UserCredentialQuery.java +++ /dev/null @@ -1,249 +0,0 @@ -package gr.cite.annotation.query; - -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.UserCredentialEntity; -import gr.cite.annotation.model.UserCredential; -import gr.cite.tools.data.query.FieldResolver; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserCredentialQuery extends QueryBase { - - private Collection ids; - - private Collection excludedIds; - - private Collection isActives; - - private Collection userIds; - - private Collection externalIds; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final UserScope userScope; - - private final AuthorizationService authService; - - private final TenantEntityManager tenantEntityManager; - public UserCredentialQuery(UserScope userScope, AuthorizationService authService, TenantEntityManager tenantEntityManager) { - this.userScope = userScope; - this.authService = authService; - this.tenantEntityManager = tenantEntityManager; - } - - public UserCredentialQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public UserCredentialQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public UserCredentialQuery ids(Collection values) { - this.ids = values; - return this; - } - - public UserCredentialQuery excludedIds(Collection values) { - this.excludedIds = values; - return this; - } - - public UserCredentialQuery excludedIds(UUID value) { - this.excludedIds = List.of(value); - return this; - } - - public UserCredentialQuery excludedIds(UUID... value) { - this.excludedIds = Arrays.asList(value); - return this; - } - - public UserCredentialQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public UserCredentialQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public UserCredentialQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public UserCredentialQuery userIds(UUID value) { - this.userIds = List.of(value); - return this; - } - - public UserCredentialQuery userIds(UUID... value) { - this.userIds = Arrays.asList(value); - return this; - } - - public UserCredentialQuery userIds(Collection values) { - this.userIds = values; - return this; - } - - public UserCredentialQuery externalIds(String value) { - this.externalIds = List.of(value); - return this; - } - - public UserCredentialQuery externalIds(String... value) { - this.externalIds = Arrays.asList(value); - return this; - } - - public UserCredentialQuery externalIds(Collection values) { - this.externalIds = values; - return this; - } - - public UserCredentialQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public UserCredentialQuery enableTracking() { - this.noTracking = false; - return this; - } - - public UserCredentialQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Boolean isFalseQuery() { - return - this.isEmpty(this.ids) || - this.isEmpty(this.userIds) || - this.isEmpty(this.externalIds) || - this.isEmpty(this.excludedIds); - } - - @Override - protected Class entityClass() { - return UserCredentialEntity.class; - } - - @Override - protected Predicate applyAuthZ(QueryContext queryContext) { - if (this.authorize.contains(AuthorizationFlags.None)) - return null; - if (this.authorize.contains(AuthorizationFlags.Permission) && this.authService.authorize(Permission.BrowseUser)) - return null; - UUID userId; - if (this.authorize.contains(AuthorizationFlags.Owner)) - userId = this.userScope.getUserIdSafe(); - else - userId = null; - - List predicates = new ArrayList<>(); - if (userId != null) { - predicates.add(queryContext.CriteriaBuilder.in(queryContext.Root.get(UserCredentialEntity._userId)).value(userId)); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return queryContext.CriteriaBuilder.or(); //Creates a false query - } - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserCredentialEntity._id)); - for (UUID item : this.ids) - inClause.value(item); - predicates.add(inClause); - } - if (this.userIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserCredentialEntity._userId)); - for (UUID item : this.userIds) - inClause.value(item); - predicates.add(inClause); - } - if (this.excludedIds != null) { - CriteriaBuilder.In notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserCredentialEntity._id)); - for (UUID item : this.excludedIds) - notInClause.value(item); - predicates.add(notInClause.not()); - } - if (this.externalIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserCredentialEntity._externalId)); - for (String item : this.externalIds) - inClause.value(item); - predicates.add(inClause); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(UserCredential._id)) - return UserCredentialEntity._id; - else if (item.match(UserCredential._externalId)) - return UserCredentialEntity._externalId; - else if (item.prefix(UserCredential._user)) - return UserCredentialEntity._userId; - else if (item.match(UserCredential._user)) - return UserCredentialEntity._userId; - else if (item.match(UserCredential._createdAt)) - return UserCredentialEntity._createdAt; - else if (item.match(UserCredential._updatedAt)) - return UserCredentialEntity._updatedAt; - else - return null; - } - - @Override - protected UserCredentialEntity convert(Tuple tuple, Set columns) { - UserCredentialEntity item = new UserCredentialEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, UserCredentialEntity._id, UUID.class)); - item.setExternalId(QueryBase.convertSafe(tuple, columns, UserCredentialEntity._externalId, String.class)); - item.setUserId(QueryBase.convertSafe(tuple, columns, UserCredentialEntity._userId, UUID.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, UserCredentialEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, UserCredentialEntity._updatedAt, Instant.class)); - return item; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/UserQuery.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/UserQuery.java deleted file mode 100644 index 8862cab65..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/UserQuery.java +++ /dev/null @@ -1,193 +0,0 @@ -package gr.cite.annotation.query; - -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.data.UserEntity; -import gr.cite.annotation.model.User; -import gr.cite.annotation.model.user.PublicUser; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.query.FieldResolver; -import gr.cite.tools.data.query.QueryBase; -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import java.time.Instant; -import java.util.*; - -@Component -@RequestScope -public class UserQuery extends QueryBase { - - private String like; - - private Collection ids; - - private Collection isActives; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final UserScope userScope; - - private final AuthorizationService authService; - - private final TenantEntityManager tenantEntityManager; - public UserQuery( - UserScope userScope, - AuthorizationService authService, TenantEntityManager tenantEntityManager - ) { - this.userScope = userScope; - this.authService = authService; - this.tenantEntityManager = tenantEntityManager; - } - - public UserQuery like(String value) { - this.like = value; - return this; - } - - public UserQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public UserQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public UserQuery ids(Collection values) { - this.ids = values; - return this; - } - - public UserQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public UserQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public UserQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public UserQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public UserQuery enableTracking() { - this.noTracking = false; - return this; - } - - public UserQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Class entityClass() { - return UserEntity.class; - } - - @Override - protected Boolean isFalseQuery() { - return this.isEmpty(this.ids) || this.isEmpty(this.isActives); - } - - @Override - protected Predicate applyAuthZ(QueryContext queryContext) { - if (this.authorize.contains(AuthorizationFlags.None)) - return null; - if (this.authorize.contains(AuthorizationFlags.Permission) && this.authService.authorize(Permission.BrowseUser)) - return null; - UUID ownerId = null; - if (this.authorize.contains(AuthorizationFlags.Owner)) - ownerId = this.userScope.getUserIdSafe(); - - List predicates = new ArrayList<>(); - if (ownerId != null) { - predicates.add(queryContext.CriteriaBuilder.equal(queryContext.Root.get(User._id), ownerId)); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return queryContext.CriteriaBuilder.or(); //Creates a false query - } - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserEntity._id)); - for (UUID item : this.ids) - inClause.value(item); - predicates.add(inClause); - } - if (this.like != null && !this.like.isEmpty()) { - predicates.add(queryContext.CriteriaBuilder.like(queryContext.Root.get(UserEntity._name), this.like)); - } - if (this.isActives != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserEntity._isActive)); - for (IsActive item : this.isActives) - inClause.value(item); - predicates.add(inClause); - } - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - } - - @Override - protected UserEntity convert(Tuple tuple, Set columns) { - UserEntity item = new UserEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, UserEntity._id, UUID.class)); - item.setName(QueryBase.convertSafe(tuple, columns, UserEntity._name, String.class)); - item.setAdditionalInfo(QueryBase.convertSafe(tuple, columns, UserEntity._additionalInfo, String.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, UserEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, UserEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, UserEntity._isActive, IsActive.class)); - return item; - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(User._id) || item.match(PublicUser._id)) - return UserEntity._id; - else if (item.match(User._name) || item.match(PublicUser._name)) - return UserEntity._name; - else if (item.match(User._createdAt)) - return UserEntity._createdAt; - else if (item.match(User._updatedAt)) - return UserEntity._updatedAt; - else if (item.match(User._hash)) - return UserEntity._updatedAt; - else if (item.match(User._isActive)) - return UserEntity._isActive; - else - return null; - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/AnnotationLookup.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/AnnotationLookup.java deleted file mode 100644 index a5adf4dce..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/AnnotationLookup.java +++ /dev/null @@ -1,117 +0,0 @@ -package gr.cite.annotation.query.lookup; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.query.AnnotationQuery; -import gr.cite.tools.data.query.Lookup; -import gr.cite.tools.data.query.QueryFactory; - -import java.util.List; -import java.util.UUID; - -public class AnnotationLookup extends Lookup { - - private String like; - - private List ids; - - private List excludedIds; - - private List isActive; - - private List entityIds; - - private List entityTypes; - - private List anchors; - - private List threadIds; - - public String getLike() { - return like; - } - - public void setLike(String like) { - this.like = like; - } - - public List getIds() { - return ids; - } - - public void setIds(List ids) { - this.ids = ids; - } - - public List getExcludedIds() { - return excludedIds; - } - - public void setExcludedIds(List excludedIds) { - this.excludedIds = excludedIds; - } - - public List getIsActive() { - return isActive; - } - - public void setIsActive(List isActive) { - this.isActive = isActive; - } - - public List getEntityIds() { - return entityIds; - } - - public void setEntityIds(List entityIds) { - this.entityIds = entityIds; - } - - public List getEntityTypes() { - return entityTypes; - } - - public void setEntityTypes(List entityTypes) { - this.entityTypes = entityTypes; - } - - public List getAnchors() { - return anchors; - } - - public void setAnchors(List anchors) { - this.anchors = anchors; - } - - public List getThreadIds() { - return threadIds; - } - - public void setThreadIds(List threadIds) { - this.threadIds = threadIds; - } - - public AnnotationQuery enrich(QueryFactory queryFactory) { - AnnotationQuery query = queryFactory.query(AnnotationQuery.class); - if (this.like != null) - query.like(this.like); - if (this.ids != null) - query.ids(this.ids); - if (this.excludedIds != null) - query.excludedIds(this.excludedIds); - if (this.isActive != null) - query.isActive(this.isActive); - if (this.entityIds != null) - query.entityIds(this.entityIds); - if (this.entityTypes != null) - query.entityTypes(this.entityTypes); - if (this.anchors != null) - query.anchors(this.anchors); - if (this.threadIds != null) - query.threadIds(this.threadIds); - - this.enrichCommon(query); - - return query; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/TenantLookup.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/TenantLookup.java deleted file mode 100644 index f2e663e33..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/TenantLookup.java +++ /dev/null @@ -1,51 +0,0 @@ -package gr.cite.annotation.query.lookup; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.query.TenantQuery; -import gr.cite.tools.data.query.Lookup; -import gr.cite.tools.data.query.QueryFactory; - -import java.util.List; -import java.util.UUID; - -public class TenantLookup extends Lookup { - private String like; - private List isActive; - private List ids; - - public String getLike() { - return like; - } - - public void setLike(String like) { - this.like = like; - } - - public List getIsActive() { - return isActive; - } - - public void setIsActive(List isActive) { - this.isActive = isActive; - } - - public List getIds() { - return ids; - } - - public void setIds(List ids) { - this.ids = ids; - } - - public TenantQuery enrich(QueryFactory queryFactory) { - TenantQuery query = queryFactory.query(TenantQuery.class); - if (this.like != null) query.like(this.like); - if (this.isActive != null) query.isActive(this.isActive); - if (this.ids != null) query.ids(this.ids); - - this.enrichCommon(query); - - return query; - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/UserLookup.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/UserLookup.java deleted file mode 100644 index 0b32ffd55..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/lookup/UserLookup.java +++ /dev/null @@ -1,52 +0,0 @@ -package gr.cite.annotation.query.lookup; - -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.query.UserQuery; -import gr.cite.tools.data.query.Lookup; -import gr.cite.tools.data.query.QueryFactory; - -import java.util.List; -import java.util.UUID; - -public class UserLookup extends Lookup { - private String like; - private List isActive; - private List ids; - - public String getLike() { - return like; - } - - public void setLike(String like) { - this.like = like; - } - - public List getIsActive() { - return isActive; - } - - public void setIsActive(List isActive) { - this.isActive = isActive; - } - - public List getIds() { - return ids; - } - - public void setIds(List ids) { - this.ids = ids; - } - - public UserQuery enrich(QueryFactory queryFactory) { - UserQuery query = queryFactory.query(UserQuery.class); - if (this.like != null) query.like(this.like); - if (this.isActive != null) query.isActive(this.isActive); - if (this.ids != null) query.ids(this.ids); - - this.enrichCommon(query); - - return query; - } - - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/BuildSubQueryInput.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/BuildSubQueryInput.java deleted file mode 100644 index aab5c915b..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/BuildSubQueryInput.java +++ /dev/null @@ -1,90 +0,0 @@ -package gr.cite.annotation.query.utils; - -import gr.cite.tools.data.query.QueryContext; -import jakarta.persistence.criteria.*; - -import java.util.function.BiFunction; -import java.util.function.Function; - -public class BuildSubQueryInput { - private final AbstractQuery query; - private final CriteriaBuilder criteriaBuilder; - private final Class entityType; - private final Class keyType; - private final Function, Expression> keyPathFunc; - private final BiFunction, CriteriaBuilder, Predicate> filterFunc; - - public BuildSubQueryInput(Builder builder) { - query = builder.query; - criteriaBuilder = builder.criteriaBuilder; - entityType = builder.entityType; - keyType = builder.keyType; - keyPathFunc = builder.keyPathFunc; - filterFunc = builder.filterFunc; - } - - public AbstractQuery getQuery() { - return query; - } - - public CriteriaBuilder getCriteriaBuilder() { - return criteriaBuilder; - } - - public Class getEntityType() { - return entityType; - } - - public Class getKeyType() { - return keyType; - } - - public Function, Expression> getKeyPathFunc() { - return keyPathFunc; - } - - public BiFunction, CriteriaBuilder, Predicate> getFilterFunc() { - return filterFunc; - } - - public static class Builder { - private final Class entityType; - private final Class keyType; - private AbstractQuery query; - private CriteriaBuilder criteriaBuilder; - private Function, Expression> keyPathFunc; - private BiFunction, CriteriaBuilder, Predicate> filterFunc; - - public Builder(Class entityType, Class keyType) { - this.entityType = entityType; - this.keyType = keyType; - } - - public Builder(Class entityType, Class keyType, QueryContext queryContext) { - this.entityType = entityType; - this.keyType = keyType; - this.query = queryContext.Query; - this.criteriaBuilder = queryContext.CriteriaBuilder; - } - - public Builder query(AbstractQuery query) { - this.query = query; - return this; - } - - public Builder criteriaBuilder(CriteriaBuilder criteriaBuilder) { - this.criteriaBuilder = criteriaBuilder; - return this; - } - - public Builder keyPathFunc(Function, Expression> keyPathFunc) { - this.keyPathFunc = keyPathFunc; - return this; - } - - public Builder filterFunc(BiFunction, CriteriaBuilder, Predicate> filterFunc) { - this.filterFunc = filterFunc; - return this; - } - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/QueryUtilsService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/QueryUtilsService.java deleted file mode 100644 index a64a0277a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/QueryUtilsService.java +++ /dev/null @@ -1,11 +0,0 @@ -package gr.cite.annotation.query.utils; - -import jakarta.persistence.criteria.AbstractQuery; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Subquery; - -import java.util.UUID; - -public interface QueryUtilsService { - Subquery buildSubQuery(BuildSubQueryInput parameters); -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/QueryUtilsServiceImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/QueryUtilsServiceImpl.java deleted file mode 100644 index f668f5cea..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/query/utils/QueryUtilsServiceImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.annotation.query.utils; - -import jakarta.persistence.criteria.Root; -import jakarta.persistence.criteria.Subquery; -import org.springframework.stereotype.Component; - -import java.util.UUID; - -@Component -public class QueryUtilsServiceImpl implements QueryUtilsService { - @Override - public Subquery buildSubQuery(BuildSubQueryInput parameters){ - Subquery subQuery = parameters.getQuery().subquery(parameters.getKeyType()); - Root subQueryRoot = subQuery.from(parameters.getEntityType()); - subQuery.select(parameters.getKeyPathFunc().apply(subQueryRoot)).distinct(true); - subQuery.where(parameters.getFilterFunc().apply(subQueryRoot, parameters.getCriteriaBuilder())); - return subQuery; - } -} - diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/AuthnSandbox.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/service/AuthnSandbox.java deleted file mode 100644 index 02aca445b..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/AuthnSandbox.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.annotation.service; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.MyPrincipal; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.web.context.annotation.RequestScope; - -@Service -@RequestScope -public class AuthnSandbox { - - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractor claimExtractor; - - @Autowired - public AuthnSandbox( - CurrentPrincipalResolver currentPrincipalResolver, - ClaimExtractor claimExtractor) { - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractor = claimExtractor; - } - - public String sayHi() { - MyPrincipal principal = this.currentPrincipalResolver.currentPrincipal(); - return "Hi " + this.claimExtractor.name(principal); - } -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/annotation/AnnotationService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/service/annotation/AnnotationService.java deleted file mode 100644 index 013ba7f53..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/annotation/AnnotationService.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.annotation.service.annotation; - -import gr.cite.annotation.model.Annotation; -import gr.cite.annotation.model.persist.AnnotationPersist; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.exception.MyNotFoundException; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.fieldset.FieldSet; - -import javax.management.InvalidApplicationException; -import java.util.UUID; - -public interface AnnotationService { - - Annotation persist(AnnotationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException; - - void deleteAndSave(UUID id) throws InvalidApplicationException; - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/annotation/AnnotationServiceImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/service/annotation/AnnotationServiceImpl.java deleted file mode 100644 index f289b0e37..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/annotation/AnnotationServiceImpl.java +++ /dev/null @@ -1,135 +0,0 @@ -package gr.cite.annotation.service.annotation; - -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.OwnedResource; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.authorization.authorizationcontentresolver.AuthorizationContentResolver; -import gr.cite.annotation.common.enums.AnnotationProtectionType; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.user.UserScope; -import gr.cite.annotation.data.AnnotationEntity; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.integrationevent.outbox.annotationcreated.AnnotationCreatedEvent; -import gr.cite.annotation.integrationevent.outbox.annotationcreated.AnnotationCreatedIntegrationEventHandler; -import gr.cite.annotation.model.Annotation; -import gr.cite.annotation.model.builder.AnnotationBuilder; -import gr.cite.annotation.model.deleter.AnnotationDeleter; -import gr.cite.annotation.model.persist.AnnotationPersist; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.exception.MyNotFoundException; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Service; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.*; - -@Service -public class AnnotationServiceImpl implements AnnotationService { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(AnnotationServiceImpl.class)); - - private final AuthorizationService authorizationService; - - private final DeleterFactory deleterFactory; - - private final TenantEntityManager entityManager; - - private final BuilderFactory builderFactory; - - private final UserScope userScope; - private final AuthorizationContentResolver authorizationContentResolver; - - private final MessageSource messageSource; - - private final AnnotationCreatedIntegrationEventHandler annotationCreatedEventHandler; - - - public AnnotationServiceImpl( - AuthorizationService authorizationService, - DeleterFactory deleterFactory, - TenantEntityManager entityManager, - BuilderFactory builderFactory, UserScope userScope, AuthorizationContentResolver authorizationContentResolver, MessageSource messageSource, AnnotationCreatedIntegrationEventHandler annotationCreatedEventHandler) { - this.authorizationService = authorizationService; - this.deleterFactory = deleterFactory; - this.entityManager = entityManager; - this.builderFactory = builderFactory; - this.userScope = userScope; - this.authorizationContentResolver = authorizationContentResolver; - this.messageSource = messageSource; - this.annotationCreatedEventHandler = annotationCreatedEventHandler; - } - - @Override - public Annotation persist(AnnotationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("persisting annotation").And("model", model).And("fields", fields)); - - this.authorizationService.authorizeAtLeastOneForce(List.of(this.authorizationContentResolver.entityAffiliation(model.getEntityId())), Permission.NewAnnotation); - - AnnotationEntity data = new AnnotationEntity(); - data.setId(UUID.randomUUID()); - data.setSubjectId(userScope.getUserIdSafe()); - data.setEntityId(model.getEntityId()); - data.setEntityType(model.getEntityType()); - data.setAnchor(model.getAnchor()); - data.setPayload(model.getPayload()); - data.setThreadId(model.getThreadId()); - data.setParentId(model.getParentId()); - data.setProtectionType(model.getProtectionType()); - data.setTimeStamp(Instant.now()); - data.setCreatedAt(Instant.now()); - data.setUpdatedAt(Instant.now()); - data.setIsActive(IsActive.Active); - - this.entityManager.persist(data); - - this.entityManager.flush(); - - if (data.getProtectionType().equals(AnnotationProtectionType.EntityAccessors)) this.sendAnnotationCreatedEvent(data); - - return this.builderFactory.builder(AnnotationBuilder.class).authorize(EnumSet.of(AuthorizationFlags.None)).build(BaseFieldSet.build(fields, Annotation._id), data); - } - - private void sendAnnotationCreatedEvent(AnnotationEntity annotation) throws InvalidApplicationException { - AnnotationCreatedEvent event = new AnnotationCreatedEvent(); - - event.setId(annotation.getId()); - event.setSubjectId(annotation.getSubjectId()); - event.setEntityId(annotation.getEntityId()); - event.setEntityType(annotation.getEntityType()); - event.setAnchor(annotation.getAnchor()); - event.setPayload(annotation.getPayload()); - event.setThreadId(annotation.getThreadId()); - event.setParentId(annotation.getParentId()); - event.setProtectionType(annotation.getProtectionType()); - event.setTimeStamp(Instant.now()); - - this.annotationCreatedEventHandler.handle(event); - } - - - - @Override - public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug("deleting Annotation: {}", id); - - AnnotationEntity annotation = this.entityManager.find(AnnotationEntity.class, id); - if (annotation == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, Annotation.class.getSimpleName()}, LocaleContextHolder.getLocale())); - - this.authorizationService.authorizeAtLeastOneForce(annotation.getSubjectId() != null ? List.of(new OwnedResource(annotation.getSubjectId())) : null, Permission.DeleteAnnotation); - - this.deleterFactory.deleter(AnnotationDeleter.class).deleteAndSaveByIds(List.of(id)); - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/tenant/TenantService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/service/tenant/TenantService.java deleted file mode 100644 index 8e343f11a..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/tenant/TenantService.java +++ /dev/null @@ -1,21 +0,0 @@ -package gr.cite.annotation.service.tenant; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.annotation.model.Tenant; -import gr.cite.annotation.model.persist.TenantTouchedIntegrationEventPersist; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.exception.MyNotFoundException; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.fieldset.FieldSet; - -import javax.management.InvalidApplicationException; -import java.util.UUID; - -public interface TenantService { - - Tenant persist(TenantTouchedIntegrationEventPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException; - - void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/tenant/TenantServiceImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/service/tenant/TenantServiceImpl.java deleted file mode 100644 index 7c597c661..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/tenant/TenantServiceImpl.java +++ /dev/null @@ -1,120 +0,0 @@ -package gr.cite.annotation.service.tenant; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.annotation.data.TenantEntityManager; -import gr.cite.annotation.event.EventBroker; -import gr.cite.annotation.event.TenantTouchedEvent; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.data.TenantEntity; -import gr.cite.annotation.model.Tenant; -import gr.cite.annotation.model.builder.TenantBuilder; -import gr.cite.annotation.model.deleter.TenantDeleter; -import gr.cite.annotation.model.persist.TenantTouchedIntegrationEventPersist; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.exception.MyNotFoundException; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Service; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.EnumSet; -import java.util.List; -import java.util.UUID; - -@Service -public class TenantServiceImpl implements TenantService { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantServiceImpl.class)); - - private final AuthorizationService authorizationService; - - private final DeleterFactory deleterFactory; - - private final ConventionService conventionService; - - private final TenantEntityManager entityManager; - - private final BuilderFactory builderFactory; - private final EventBroker eventBroker; - private final MessageSource messageSource; - - public TenantServiceImpl(AuthorizationService authorizationService, - DeleterFactory deleterFactory, - ConventionService conventionService, - TenantEntityManager entityManager, - BuilderFactory builderFactory, EventBroker eventBroker, MessageSource messageSource) { - this.authorizationService = authorizationService; - this.deleterFactory = deleterFactory; - this.conventionService = conventionService; - this.entityManager = entityManager; - this.builderFactory = builderFactory; - this.eventBroker = eventBroker; - this.messageSource = messageSource; - } - - @Override - public Tenant persist(TenantTouchedIntegrationEventPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException { - logger.debug(new MapLogEntry("persisting tenant").And("model", model).And("fields", fields)); - - this.authorizationService.authorizeForce(Permission.EditTenant); - - Boolean isValid = this.conventionService.isValidGuid(model.getId()); - - TenantEntity data; - if (isValid) { - data = this.entityManager.find(TenantEntity.class, model.getId()); - if (data == null) { - data = new TenantEntity(); - data.setId(model.getId()); - data.setCode(model.getCode()); - data.setIsActive(IsActive.Active); - data.setCreatedAt(Instant.now()); - data.setUpdatedAt(Instant.now()); - - this.entityManager.persist(data); - } else { - data.setCode(model.getCode()); - data.setUpdatedAt(Instant.now()); - data.setIsActive(IsActive.Active); - - this.entityManager.merge(data); - } - } else { - throw new MyApplicationException("Not valid tenant id"); - } - - this.entityManager.flush(); - - this.eventBroker.emit(new TenantTouchedEvent(data.getId(), data.getCode())); - return this.builderFactory.builder(TenantBuilder.class).authorize(EnumSet.of(AuthorizationFlags.None)).build(BaseFieldSet.build(fields, Tenant._id), data); - } - - @Override - public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug("deleting Tenant: {}", id); - - TenantEntity data = this.entityManager.find(TenantEntity.class, id); - if (data == null) throw new MyNotFoundException(this.messageSource.getMessage("General_ItemNotFound", new Object[]{id, Tenant.class.getSimpleName()}, LocaleContextHolder.getLocale())); - - this.authorizationService.authorizeForce(Permission.DeleteTenant); - - this.deleterFactory.deleter(TenantDeleter.class).deleteAndSaveByIds(List.of(id)); - - this.eventBroker.emit(new TenantTouchedEvent(data.getId(), data.getCode())); - } - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/user/UserService.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/service/user/UserService.java deleted file mode 100644 index 8d32d3d12..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/user/UserService.java +++ /dev/null @@ -1,21 +0,0 @@ -package gr.cite.annotation.service.user; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.annotation.integrationevent.inbox.usertouched.UserTouchedIntegrationEvent; -import gr.cite.annotation.model.User; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.exception.MyNotFoundException; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.fieldset.FieldSet; - -import javax.management.InvalidApplicationException; -import java.util.UUID; - -public interface UserService { - - User persist(UserTouchedIntegrationEvent model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException; - - void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; - -} diff --git a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/user/UserServiceImpl.java b/annotation-service/annotation/src/main/java/gr/cite/annotation/service/user/UserServiceImpl.java deleted file mode 100644 index 155aadc33..000000000 --- a/annotation-service/annotation/src/main/java/gr/cite/annotation/service/user/UserServiceImpl.java +++ /dev/null @@ -1,217 +0,0 @@ -package gr.cite.annotation.service.user; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.annotation.authorization.AuthorizationFlags; -import gr.cite.annotation.authorization.Permission; -import gr.cite.annotation.common.JsonHandlingService; -import gr.cite.annotation.common.enums.IsActive; -import gr.cite.annotation.common.scope.tenant.TenantScope; -import gr.cite.annotation.convention.ConventionService; -import gr.cite.annotation.data.*; -import gr.cite.annotation.event.EventBroker; -import gr.cite.annotation.event.UserAddedToTenantEvent; -import gr.cite.annotation.event.UserCredentialTouchedEvent; -import gr.cite.annotation.event.UserTouchedEvent; -import gr.cite.annotation.integrationevent.inbox.usertouched.UserTouchedIntegrationEvent; -import gr.cite.annotation.model.Tenant; -import gr.cite.annotation.model.User; -import gr.cite.annotation.model.builder.UserBuilder; -import gr.cite.annotation.model.deleter.TenantUserDeleter; -import gr.cite.annotation.model.deleter.UserCredentialDeleter; -import gr.cite.annotation.model.deleter.UserDeleter; -import gr.cite.annotation.query.TenantQuery; -import gr.cite.annotation.query.TenantUserQuery; -import gr.cite.annotation.query.UserCredentialQuery; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.exception.MyNotFoundException; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.fieldset.FieldSet; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.logging.MapLogEntry; -import org.slf4j.LoggerFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Service; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -@Service -public class UserServiceImpl implements UserService { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserServiceImpl.class)); - - private final AuthorizationService authorizationService; - - private final DeleterFactory deleterFactory; - - private final ConventionService conventionService; - - private final TenantEntityManager entityManager; - - private final BuilderFactory builderFactory; - - private final QueryFactory queryFactory; - private final TenantScope tenantScope; - - private final MessageSource messageSource; - private final EventBroker eventBroker; - - - private final JsonHandlingService jsonHandlingService; - - public UserServiceImpl(AuthorizationService authorizationService, - DeleterFactory deleterFactory, - ConventionService conventionService, - TenantEntityManager entityManager, - BuilderFactory builderFactory, QueryFactory queryFactory, TenantScope tenantScope, MessageSource messageSource, EventBroker eventBroker, - JsonHandlingService jsonHandlingService) { - this.authorizationService = authorizationService; - this.deleterFactory = deleterFactory; - this.conventionService = conventionService; - this.entityManager = entityManager; - this.builderFactory = builderFactory; - this.queryFactory = queryFactory; - this.tenantScope = tenantScope; - this.messageSource = messageSource; - this.eventBroker = eventBroker; - this.jsonHandlingService = jsonHandlingService; - } - - @Override - public User persist(UserTouchedIntegrationEvent model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException { - logger.debug(new MapLogEntry("persisting user").And("model", model).And("fields", fields)); - -// this.authorizationService.authorizeAtLeastOneForce(model.getId() != null ? List.of(new OwnedResource(model.getId())) : null, Permission.EditUser); - - Boolean isValid = this.conventionService.isValidGuid(model.getId()); - - UserEntity data; - if (isValid) { - data = this.entityManager.find(UserEntity.class, model.getId()); - if (data == null) { - data = new UserEntity(); - data.setId(model.getId()); - data.setName(model.getName()); - data.setAdditionalInfo(this.jsonHandlingService.toJson(model.getProfile())); - data.setCreatedAt(Instant.now()); - data.setUpdatedAt(Instant.now()); - data.setIsActive(IsActive.Active); - - this.entityManager.persist(data); - - } else { - data.setName(model.getName()); - data.setAdditionalInfo(this.jsonHandlingService.toJson(model.getProfile())); - data.setUpdatedAt(Instant.now()); - data.setIsActive(IsActive.Active); - - this.entityManager.merge(data); - - } - } else { - throw new MyApplicationException("Not valid user id"); - } - - this.entityManager.flush(); - - this.persistUserCredential(model.getCredentials(), data.getId()); - this.persistTenantUser(model.getTenantUsers(), data.getId()); - - this.entityManager.flush(); - this.eventBroker.emit(new UserTouchedEvent(data.getId())); - - return this.builderFactory.builder(UserBuilder.class).authorize(EnumSet.of(AuthorizationFlags.None)).build(BaseFieldSet.build(fields, User._id), data); - } - - @Override - public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug("deleting User: {}", id); - - this.authorizationService.authorizeForce(Permission.DeleteUser); - - this.deleterFactory.deleter(UserDeleter.class).deleteAndSaveByIds(List.of(id)); - this.eventBroker.emit(new UserTouchedEvent(id)); - } - - private void persistUserCredential(List models, UUID userId) throws InvalidApplicationException { - List items = this.queryFactory.query(UserCredentialQuery.class) - .userIds(userId) - .isActive(IsActive.Active) - .collect(); - List updatedCreatedIds = new ArrayList<>(); - if (models != null) { - for (UserTouchedIntegrationEvent.UserCredential model : models) { - UserCredentialEntity data = items.stream().filter(x -> x.getExternalId().equals(model.getSubjectId())).findFirst().orElse(null); - if (data == null) { - data = new UserCredentialEntity(); - data.setId(UUID.randomUUID()); - data.setUserId(userId); - data.setExternalId(model.getSubjectId()); - data.setCreatedAt(Instant.now()); - data.setUpdatedAt(Instant.now()); - entityManager.persist(data); - } - this.eventBroker.emit(new UserCredentialTouchedEvent(data.getId(), data.getExternalId())); - updatedCreatedIds.add(data.getId()); - } - } - List toDelete = items.stream().filter(x -> updatedCreatedIds.stream().noneMatch(y -> y.equals(x.getId()))).collect(Collectors.toList()); - deleterFactory.deleter(UserCredentialDeleter.class).delete(toDelete); - - entityManager.flush(); - } - - private void persistTenantUser(List models, UUID userId) throws InvalidApplicationException { - List items = this.queryFactory.query(TenantUserQuery.class) - .userIds(userId) - .isActive(IsActive.Active) - .collect(); - - List updatedCreatedIds = new ArrayList<>(); - if (models != null) { - List tenantEntities = this.queryFactory.query(TenantQuery.class) - .ids(models.stream().map(UserTouchedIntegrationEvent.TenantUser::getTenant).toList()) - .isActive(IsActive.Active) - .collectAs(new BaseFieldSet().ensure(Tenant._id).ensure(Tenant._code)); - for (UserTouchedIntegrationEvent.TenantUser model : models) { - TenantUserEntity data = items.stream().filter(x -> x.getTenantId().equals(model.getTenant())).findFirst().orElse(null); - if (data == null) { - try { - TenantEntity tenant = tenantEntities.stream().filter(x -> x.getId().equals(model.getTenant())).findFirst().orElse(null); - if (tenant == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getTenant(), Tenant.class.getSimpleName()}, LocaleContextHolder.getLocale())); - this.tenantScope.setTempTenant(this.entityManager, tenant.getId(), tenant.getCode()); - data = new TenantUserEntity(); - data.setId(UUID.randomUUID()); - data.setUserId(userId); - data.setTenantId(model.getTenant()); - data.setCreatedAt(Instant.now()); - data.setUpdatedAt(Instant.now()); - data.setIsActive(IsActive.Active); - entityManager.persist(data); - this.eventBroker.emit(new UserAddedToTenantEvent(data.getUserId(), data.getTenantId())); - } finally { - this.tenantScope.removeTempTenant(this.entityManager); - } - } - updatedCreatedIds.add(data.getId()); - } - } - List toDelete = items.stream().filter(x -> updatedCreatedIds.stream().noneMatch(y -> y.equals(x.getId()))).collect(Collectors.toList()); - deleterFactory.deleter(TenantUserDeleter.class).delete(toDelete); - - entityManager.flush(); - } - -} diff --git a/annotation-service/pom.xml b/annotation-service/pom.xml deleted file mode 100644 index 23acf8587..000000000 --- a/annotation-service/pom.xml +++ /dev/null @@ -1,191 +0,0 @@ - - - - 4.0.0 - gr.cite - annotation-service-parent - Annotation Parent - ${revision} - pom - - - org.springframework.boot - spring-boot-starter-parent - 3.2.5 - - - - annotation - annotation-web - - - - 21 - 21 - 21 - 21 - 1.0.0-SNAPSHOT - - - - - org.springframework - spring-context-support - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.hibernate.orm - hibernate-core - compile - 6.5.2.Final - - - org.hibernate.orm - hibernate-c3p0 - compile - - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - - - - - - com.fasterxml.jackson.core - jackson-core - - - - com.fasterxml.jackson.core - jackson-databind - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - 2.17.0 - - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - - - - - javax.xml.bind - jaxb-api - 2.3.1 - - - - - jakarta.annotation - jakarta.annotation-api - - - - - jakarta.validation - jakarta.validation-api - - - - jakarta.persistence - jakarta.persistence-api - 3.1.0 - - - - gr.cite - data-tools - 2.1.5 - - - - gr.cite - logging - 2.1.0 - - - - gr.cite - validation - 3.0.3 - - - - gr.cite - oidc-authn - 2.2.2 - - - gr.cite - oidc-authz - 2.1.0 - - - - gr.cite - rabbitmq-core - 2.1.2 - - - - gr.cite - queue-inbox - 2.1.1 - - - gr.cite - queue-outbox - 2.1.1 - - - - gr.cite - cache - 2.2.0 - - - - - - devel - - true - - - jar - - - - production - - jar - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - - - profile - production - - - - - - \ No newline at end of file diff --git a/annotation-service/settings.xml b/annotation-service/settings.xml deleted file mode 100644 index 847f42c30..000000000 --- a/annotation-service/settings.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - org.sonarsource.scanner.maven - - - - cite-repo - ${server_username} - ${server_password} - - - - - release - - - central - Central Repository - https://repo.maven.apache.org/maven2 - default - - false - - - - cite-repo - CITE Maven Repo - ${citeMavenRepoUrl} - - - - - diff --git a/backend/web/src/main/java/org/opencdmp/controllers/DmpBlueprintController.java b/backend/web/src/main/java/org/opencdmp/controllers/DmpBlueprintController.java index 1785db11d..c58fc4b0a 100644 --- a/backend/web/src/main/java/org/opencdmp/controllers/DmpBlueprintController.java +++ b/backend/web/src/main/java/org/opencdmp/controllers/DmpBlueprintController.java @@ -12,11 +12,24 @@ import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.validation.ValidationFilterAnnotation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.transaction.Transactional; import jakarta.xml.bind.JAXBException; import org.opencdmp.audit.AuditableAction; import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.controllers.swagger.SwaggerHelpers; +import org.opencdmp.controllers.swagger.annotation.OperationWithTenantHeader; +import org.opencdmp.controllers.swagger.annotation.Swagger400; +import org.opencdmp.controllers.swagger.annotation.Swagger404; +import org.opencdmp.controllers.swagger.annotation.SwaggerCommonErrorResponses; import org.opencdmp.data.DmpBlueprintEntity; +import org.opencdmp.model.DescriptionTemplateType; import org.opencdmp.model.builder.dmpblueprint.DmpBlueprintBuilder; import org.opencdmp.model.censorship.dmpblueprint.DmpBlueprintCensor; import org.opencdmp.model.dmpblueprint.DmpBlueprint; @@ -45,6 +58,8 @@ import java.util.UUID; @RestController @RequestMapping(path = "api/dmp-blueprint") +@Tag(name = "Plan Blueprints", description = "Manage plan blueprints") +@SwaggerCommonErrorResponses public class DmpBlueprintController { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpBlueprintController.class)); @@ -77,6 +92,25 @@ public class DmpBlueprintController { } @PostMapping("query") + @OperationWithTenantHeader(summary = "Query all plan blueprints", description = SwaggerHelpers.DmpBlueprint.endpoint_query, requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = SwaggerHelpers.DmpBlueprint.endpoint_query_request_body, content = @Content( + examples = { + @ExampleObject( + name = "Pagination and projection", + description = "Simple paginated request using a property projection list and pagination info", + value = SwaggerHelpers.DmpBlueprint.endpoint_query_request_body_example + ) + } + )), responses = @ApiResponse(description = "OK", responseCode = "200", content = @Content( + array = @ArraySchema( + schema = @Schema( + implementation = DmpBlueprint.class + ) + ), + examples = @ExampleObject( + name = "First page", + description = "Example with the first page of paginated results", + value = SwaggerHelpers.DmpBlueprint.endpoint_query_response_example + )))) public QueryResult query(@RequestBody DmpBlueprintLookup lookup) throws MyApplicationException, MyForbiddenException { logger.debug("querying {}", DmpBlueprint.class.getSimpleName()); @@ -93,7 +127,12 @@ public class DmpBlueprintController { } @GetMapping("{id}") - public DmpBlueprint get(@PathVariable("id") UUID id, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException { + @OperationWithTenantHeader(summary = "Fetch a specific plan blueprint by id") + @Swagger404 + public DmpBlueprint get( + @Parameter(name = "id", description = "The id of a plan blueprint to fetch", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id, + @Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet + ) throws MyApplicationException, MyForbiddenException, MyNotFoundException { logger.debug(new MapLogEntry("retrieving" + DmpBlueprint.class.getSimpleName()).And("id", id).And("fields", fieldSet)); this.censorFactory.censor(DmpBlueprintCensor.class).censor(fieldSet, null); @@ -112,9 +151,15 @@ public class DmpBlueprintController { } @PostMapping("persist") + @OperationWithTenantHeader(summary = "Create a new or update an existing plan blueprint") + @Swagger400 + @Swagger404 @Transactional @ValidationFilterAnnotation(validator = DmpBlueprintPersist.DmpBlueprintPersistValidator.ValidatorName, argumentName = "model") - public DmpBlueprint persist(@RequestBody DmpBlueprintPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException { + public DmpBlueprint persist( + @RequestBody DmpBlueprintPersist model, + @Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet + ) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JAXBException, ParserConfigurationException, JsonProcessingException, TransformerException { logger.debug(new MapLogEntry("persisting" + DmpBlueprint.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); this.censorFactory.censor(DmpBlueprintCensor.class).censor(fieldSet, null); @@ -129,8 +174,12 @@ public class DmpBlueprintController { } @DeleteMapping("{id}") + @OperationWithTenantHeader(summary = "Delete a plan blueprint by id") + @Swagger404 @Transactional - public void delete(@PathVariable("id") UUID id) throws MyForbiddenException, InvalidApplicationException { + public void delete( + @Parameter(name = "id", description = "The id of a plan blueprint to delete", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id + ) throws MyForbiddenException, InvalidApplicationException { logger.debug(new MapLogEntry("retrieving" + DmpBlueprint.class.getSimpleName()).And("id", id)); this.dmpBlueprintService.deleteAndSave(id); @@ -139,7 +188,12 @@ public class DmpBlueprintController { } @GetMapping("clone/{id}") - public DmpBlueprint buildClone(@PathVariable("id") UUID id, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException { + @OperationWithTenantHeader(summary = "Clone a plan blueprint by id") + @Swagger404 + public DmpBlueprint buildClone( + @Parameter(name = "id", description = "The id of a plan blueprint to clone", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id, + @Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet + ) throws MyApplicationException, MyForbiddenException, MyNotFoundException { logger.debug(new MapLogEntry("clone" + DmpBlueprint.class.getSimpleName()).And("id", id).And("fields", fieldSet)); this.censorFactory.censor(DmpBlueprintCensor.class).censor(fieldSet, null); @@ -155,9 +209,15 @@ public class DmpBlueprintController { } @PostMapping("new-version") + @OperationWithTenantHeader(summary = "Create a new version of an existing plan blueprint") + @Swagger400 + @Swagger404 @Transactional @ValidationFilterAnnotation(validator = NewVersionDmpBlueprintPersist.NewVersionDmpBlueprintPersistValidator.ValidatorName, argumentName = "model") - public DmpBlueprint createNewVersion(@RequestBody NewVersionDmpBlueprintPersist model, FieldSet fieldSet) throws JAXBException, InvalidApplicationException, ParserConfigurationException, JsonProcessingException, TransformerException { + public DmpBlueprint createNewVersion( + @RequestBody NewVersionDmpBlueprintPersist model, + @Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet + ) throws JAXBException, InvalidApplicationException, ParserConfigurationException, JsonProcessingException, TransformerException { logger.debug(new MapLogEntry("persisting" + NewVersionDmpBlueprintPersist.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); DmpBlueprint persisted = this.dmpBlueprintService.createNewVersion(model, fieldSet); @@ -170,7 +230,11 @@ public class DmpBlueprintController { } @RequestMapping(method = RequestMethod.GET, value = "/xml/export/{id}", produces = "application/xml") - public @ResponseBody ResponseEntity getXml(@PathVariable UUID id) throws JAXBException, ParserConfigurationException, IOException, TransformerException, InstantiationException, IllegalAccessException, SAXException, InvalidApplicationException { + @OperationWithTenantHeader(summary = "Export a plan blueprint in xml format by id") + @Swagger404 + public @ResponseBody ResponseEntity getXml( + @Parameter(name = "id", description = "The id of a plan blueprint to export", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable UUID id + ) throws JAXBException, ParserConfigurationException, IOException, TransformerException, InstantiationException, IllegalAccessException, SAXException, InvalidApplicationException { logger.debug(new MapLogEntry("export" + DmpBlueprint.class.getSimpleName()).And("id", id)); ResponseEntity response = this.dmpBlueprintService.exportXml(id); @@ -182,8 +246,13 @@ public class DmpBlueprintController { } @RequestMapping(method = RequestMethod.POST, value = {"/xml/import/{groupId}", "/xml/import"}) + @OperationWithTenantHeader(summary = "Import a plan blueprint from an xml file") @Transactional - public DmpBlueprint importXml(@RequestParam("file") MultipartFile file, @PathVariable(value = "groupId", required = false) UUID groupId, FieldSet fieldSet) throws IOException, JAXBException, InvalidApplicationException, ParserConfigurationException, TransformerException, InstantiationException, IllegalAccessException, SAXException { + public DmpBlueprint importXml( + @RequestParam("file") MultipartFile file, + @Parameter(name = "groupId", description = "The group id of a plan blueprint to import. This is optional.", example = "c0c163dc-2965-45a5-9608-f76030578609") @PathVariable(value = "groupId", required = false) UUID groupId, + @Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet + ) throws IOException, JAXBException, InvalidApplicationException, ParserConfigurationException, TransformerException, InstantiationException, IllegalAccessException, SAXException { logger.debug(new MapLogEntry("clone" + DmpBlueprint.class.getSimpleName()).And("file", file)); this.censorFactory.censor(DmpBlueprintCensor.class).censor(fieldSet, null); diff --git a/backend/web/src/main/java/org/opencdmp/controllers/EntityDoiController.java b/backend/web/src/main/java/org/opencdmp/controllers/EntityDoiController.java index 616e473c6..9a7760fae 100644 --- a/backend/web/src/main/java/org/opencdmp/controllers/EntityDoiController.java +++ b/backend/web/src/main/java/org/opencdmp/controllers/EntityDoiController.java @@ -11,13 +11,25 @@ import gr.cite.tools.fieldset.FieldSet; import gr.cite.tools.logging.LoggerService; import gr.cite.tools.logging.MapLogEntry; import gr.cite.tools.validation.ValidationFilterAnnotation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.ExampleObject; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; import org.opencdmp.audit.AuditableAction; import org.opencdmp.authorization.AuthorizationFlags; +import org.opencdmp.controllers.swagger.SwaggerHelpers; +import org.opencdmp.controllers.swagger.annotation.OperationWithTenantHeader; +import org.opencdmp.controllers.swagger.annotation.Swagger400; +import org.opencdmp.controllers.swagger.annotation.Swagger404; import org.opencdmp.data.EntityDoiEntity; import org.opencdmp.model.DescriptionTemplateType; import org.opencdmp.model.EntityDoi; import org.opencdmp.model.builder.EntityDoiBuilder; import org.opencdmp.model.censorship.EntityDoiCensor; +import org.opencdmp.model.dmpblueprint.DmpBlueprint; import org.opencdmp.model.persist.EntityDoiPersist; import org.opencdmp.model.result.QueryResult; import org.opencdmp.query.EntityDoiQuery; @@ -34,6 +46,7 @@ import java.util.*; @RestController @RequestMapping(path = "api/entity-doi") +@Tag(name = "Entity DOIs", description = "Manage entity dois") public class EntityDoiController { private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(EntityDoiController.class)); @@ -65,6 +78,25 @@ public class EntityDoiController { } @PostMapping("query") + @OperationWithTenantHeader(summary = "Query all entity dois", description = SwaggerHelpers.EntityDoi.endpoint_query, requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = SwaggerHelpers.EntityDoi.endpoint_query_request_body, content = @Content( + examples = { + @ExampleObject( + name = "Pagination and projection", + description = "Simple paginated request using a property projection list and pagination info", + value = SwaggerHelpers.EntityDoi.endpoint_query_request_body_example + ) + } + )), responses = @ApiResponse(description = "OK", responseCode = "200", content = @Content( + array = @ArraySchema( + schema = @Schema( + implementation = EntityDoi.class + ) + ), + examples = @ExampleObject( + name = "First page", + description = "Example with the first page of paginated results", + value = SwaggerHelpers.EntityDoi.endpoint_query_response_example + )))) public QueryResult query(@RequestBody EntityDoiLookup lookup) throws MyApplicationException, MyForbiddenException { logger.debug("querying {}", EntityDoi.class.getSimpleName()); @@ -82,7 +114,13 @@ public class EntityDoiController { } @GetMapping("{id}") - public EntityDoi get(@PathVariable("id") UUID id, FieldSet fieldSet, Locale locale) throws MyApplicationException, MyForbiddenException, MyNotFoundException { + @OperationWithTenantHeader(summary = "Fetch a specific entity doi by id") + @Swagger404 + public EntityDoi get( + @Parameter(name = "id", description = "The id of an entity doi to fetch", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id, + @Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet, + Locale locale + ) throws MyApplicationException, MyForbiddenException, MyNotFoundException { logger.debug(new MapLogEntry("retrieving" + EntityDoi.class.getSimpleName()).And("id", id).And("fields", fieldSet)); this.censorFactory.censor(EntityDoiCensor.class).censor(fieldSet, null); @@ -101,9 +139,15 @@ public class EntityDoiController { } @PostMapping("persist") + @OperationWithTenantHeader(summary = "Create a new or update an existing entity doi") + @Swagger400 + @Swagger404 @Transactional @ValidationFilterAnnotation(validator = EntityDoiPersist.EntityDoiPersistValidator.ValidatorName, argumentName = "model") - public EntityDoi persist(@RequestBody EntityDoiPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException { + public EntityDoi persist( + @RequestBody EntityDoiPersist model, + @Parameter(name = "fieldSet", description = SwaggerHelpers.Commons.fieldset_description, required = true) FieldSet fieldSet + ) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException { logger.debug(new MapLogEntry("persisting" + DescriptionTemplateType.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); EntityDoi persisted = this.entityDoiService.persist(model, false, fieldSet); @@ -116,8 +160,12 @@ public class EntityDoiController { } @DeleteMapping("{id}") + @OperationWithTenantHeader(summary = "Delete an entity doi by id") + @Swagger404 @Transactional - public void delete(@PathVariable("id") UUID id) throws MyForbiddenException, InvalidApplicationException { + public void delete( + @Parameter(name = "id", description = "The id of an entity doi to delete", example = "c0c163dc-2965-45a5-9608-f76030578609", required = true) @PathVariable("id") UUID id + ) throws MyForbiddenException, InvalidApplicationException { logger.debug(new MapLogEntry("retrieving" + EntityDoi.class.getSimpleName()).And("id", id)); this.entityDoiService.deleteAndSave(id); diff --git a/backend/web/src/main/java/org/opencdmp/controllers/swagger/SwaggerHelpers.java b/backend/web/src/main/java/org/opencdmp/controllers/swagger/SwaggerHelpers.java index b08e7c428..c7114e0fa 100644 --- a/backend/web/src/main/java/org/opencdmp/controllers/swagger/SwaggerHelpers.java +++ b/backend/web/src/main/java/org/opencdmp/controllers/swagger/SwaggerHelpers.java @@ -2309,6 +2309,243 @@ public class SwaggerHelpers { public static class DmpBlueprint { + public static final String endpoint_query = + """ + This endpoint is used to fetch all the available blueprints for the plans.
+ It also allows to restrict the results using a query object passed in the request body.
+ """; + + public static final String endpoint_query_request_body = + """ + Let's explore the options this object gives us. + + ### General query parameters: + +
    +
  • page: + This is an object controlling the pagination of the results. It contains two properties. +
  • +
      +
    • offset: + How many records to omit. +
    • +
    • size: + How many records to include in each page. +
    • +
    +
+ + For example, if we want the third page, and our pages to contain 15 elements, we would pass the following object: + + ```JSON + { + "offset": 30, + "size": 15 + } + ``` + +
    +
  • order: + This is an object controlling the ordering of the results. + It contains a list of strings called items with the names of the properties to use. +
    If the name of the property is prefixed with a '-', the ordering direction is DESC. Otherwise, it is ASC. +
  • +
+ + For example, if we wanted to order based on the field 'createdAt' in descending order, we would pass the following object: + + ```JSON + { + "items": [ + "-createdAt" + ], + } + ``` + +
    +
  • metadata: + This is an object containing metadata for the request. There is only one available option. +
      +
    • countAll: + If this is set to true, the count property included in the response will account for all the records regardless the pagination, + with all the rest of filtering options applied of course. + Otherwise, if it is set to false or not present, only the returned results will be counted. +
      The first option is useful for the UI clients to calculate how many result pages are available. +
    • +
    +
  • +
  • project: + This is an object controlling the data projection of the results. + It contains a list of strings called fields with the names of the properties to project. +
    You can also include properties that are deeper in the object tree by prefixing them with dots. +
  • +
+ + ### Plan blueprint specific query parameters: + +
    +
  • like: + If there is a like parameter present in the query, only the blueprint entities that include the contents of the parameter in their labels will be in the response. +
  • +
  • ids: + This is a list and contains the ids we want to include in the response.
    If empty, every record is included. +
  • +
  • excludedIds: + This is a list and contains the ids we want to exclude from the response.
    If empty, no record gets excluded. +
  • +
  • groupIds: + This is a list and contains the group ids we want the blueprints to have. Every blueprint and all its versions, have the same groupId.
    If empty, every record is included. +
  • +
  • isActives: + This is a list and determines which records we want to include in the response, based on if they are deleted or not. + This filter works like this. If we want to view only the active records we pass [1] and for only the deleted records we pass [0]. +
    If not present or if we pass [0,1], every record is included. +
  • +
  • statuses: + This is a list and determines which records we want to include in the response, based on their status. + The status can be Draft or Finalized. We add 0 or 1 to the list respectively. +
    If not present, every record is included. +
  • +
  • versionStatuses: + This is a list and determines which records we want to include in the response, based on their version status. + The status can be Current, Previous or NotFinalized. We add 0, 1 or 2 to the list respectively. +
    If not present, every record is included. +
  • +
+ """; + + public static final String endpoint_query_request_body_example = + """ + { + "project":{ + "fields":[ + "id", + "label", + "status", + "version", + "groupId", + "updatedAt", + "createdAt", + "hash", + "isActive", + "belongsToCurrentTenant" + ] + }, + "metadata":{ + "countAll":true + }, + "page":{ + "offset":0, + "size":10 + }, + "isActive":[ + 1 + ], + "order":{ + "items":[ + "-createdAt" + ] + }, + "versionStatuses":[ + 0, + 2 + ] + } + """; + + public static final String endpoint_query_response_example = + """ + { + "items":[ + { + "id":"ef8d828b-a127-4621-8a75-c607ddc441b8", + "label":"Purple blueprint cl.1v.2", + "status":1, + "groupId":"60b43495-4c45-42c6-a9e0-462180b968a5", + "version":2, + "createdAt":"2024-06-19T09:54:19.227934Z", + "updatedAt":"2024-06-19T09:54:25.208065Z", + "isActive":1, + "hash":"1718790865", + "belongsToCurrentTenant":true + }, + { + "id":"ff3d5601-45b1-4211-ab4b-012c344827d7", + "label":"Latvian_Council_of_Science_Blueprint.xml", + "status":0, + "groupId":"63b61613-d864-4f49-9d5b-76b5273d83dc", + "version":2, + "createdAt":"2024-06-19T07:14:37.558442Z", + "updatedAt":"2024-06-19T07:14:37.558442Z", + "isActive":1, + "hash":"1718781277", + "belongsToCurrentTenant":true + }, + { + "id":"4c64705f-ff8b-4135-8dd7-4ad147fb46b2", + "label":"RDA Blueprint", + "status":1, + "groupId":"3c3589e5-5ce0-405e-a754-db9e2c9af371", + "version":1, + "createdAt":"2024-06-14T09:15:27.082540Z", + "updatedAt":"2024-06-14T10:42:50.075378Z", + "isActive":1, + "hash":"1718361770", + "belongsToCurrentTenant":true + }, + { + "id":"bcbbdc41-dbb2-444f-86d3-dd33eda8e0a8", + "label":"University of Bologna", + "status":1, + "groupId":"595efece-365a-43bd-99db-cfa9141bcf94", + "version":1, + "createdAt":"2024-04-11T09:14:09Z", + "updatedAt":"2024-04-11T09:14:40Z", + "isActive":1, + "hash":"1712826880", + "belongsToCurrentTenant":true + }, + { + "id":"eb02f2ae-69fd-456d-8143-6b0a98af64c4", + "label":"Latvian Council of Science Blueprint", + "status":1, + "groupId":"63b61613-d864-4f49-9d5b-76b5273d83dc", + "version":1, + "createdAt":"2024-03-25T12:33:59Z", + "updatedAt":"2024-03-04T10:09:05Z", + "isActive":1, + "hash":"1709546945", + "belongsToCurrentTenant":true + }, + { + "id":"86635178-36a6-484f-9057-a934e4eeecd5", + "label":"Dmp Default Blueprint", + "status":1, + "groupId":"20da24e2-575d-40e5-aea4-0986c982fd9c", + "version":1, + "createdAt":"2024-02-15T10:26:49.804431Z", + "updatedAt":"2024-02-15T10:26:49.804431Z", + "isActive":1, + "hash":"1707992809", + "belongsToCurrentTenant":true + }, + { + "id":"37701076-e0ff-4e4f-95aa-9f3d6a23083a", + "label":"CHIST-ERA", + "status":1, + "groupId":"b7eb5ba1-4cc6-4f74-9eb6-b47a6153cba5", + "version":1, + "createdAt":"2023-10-03T09:00:48Z", + "updatedAt":"2023-10-03T09:01:00Z", + "isActive":1, + "hash":"1696323660", + "belongsToCurrentTenant":true + } + ], + "count":7 + } + """; + } public static class FileTransformer { @@ -2317,6 +2554,267 @@ public class SwaggerHelpers { public static class EntityDoi { + public static final String endpoint_query = + """ + This endpoint is used to fetch all the available entity dois.
+ It also allows to restrict the results using a query object passed in the request body.
+ """; + + public static final String endpoint_query_request_body = + """ + Let's explore the options this object gives us. + + ### General query parameters: + +
    +
  • page: + This is an object controlling the pagination of the results. It contains two properties. +
  • +
      +
    • offset: + How many records to omit. +
    • +
    • size: + How many records to include in each page. +
    • +
    +
+ + For example, if we want the third page, and our pages to contain 15 elements, we would pass the following object: + + ```JSON + { + "offset": 30, + "size": 15 + } + ``` + +
    +
  • order: + This is an object controlling the ordering of the results. + It contains a list of strings called items with the names of the properties to use. +
    If the name of the property is prefixed with a '-', the ordering direction is DESC. Otherwise, it is ASC. +
  • +
+ + For example, if we wanted to order based on the field 'createdAt' in descending order, we would pass the following object: + + ```JSON + { + "items": [ + "-createdAt" + ], + } + ``` + +
    +
  • metadata: + This is an object containing metadata for the request. There is only one available option. +
      +
    • countAll: + If this is set to true, the count property included in the response will account for all the records regardless the pagination, + with all the rest of filtering options applied of course. + Otherwise, if it is set to false or not present, only the returned results will be counted. +
      The first option is useful for the UI clients to calculate how many result pages are available. +
    • +
    +
  • +
  • project: + This is an object controlling the data projection of the results. + It contains a list of strings called fields with the names of the properties to project. +
    You can also include properties that are deeper in the object tree by prefixing them with dots. +
  • +
+ + ### Entity doi specific query parameters: + +
    +
  • ids: + This is a list and contains the ids we want to include in the response.
    If empty, every record is included. +
  • +
  • excludedIds: + This is a list and contains the ids we want to exclude from the response.
    If empty, no record gets excluded. +
  • +
  • isActive: + This is a list and determines which records we want to include in the response, based on if they are deleted or not. + This filter works like this. If we want to view only the active records we pass [1] and for only the deleted records we pass [0]. +
    If not present or if we pass [0,1], every record is included. +
  • +
  • types: + This is a list and determines which records we want to include in the response, based on their type. + The type can only be DMP currently. We add 0 to the list respectively. +
    If not present, every record is included. +
  • +
  • dois: + This is a list and determines which records we want to include in the response, based on their doi string. +
    If not present, every record is included. +
  • +
+ """; + + public static final String endpoint_query_request_body_example = + """ + { + "project":{ + "fields":[ + "id", + "doi", + "entityId", + "entityType", + "repositoryId", + "updatedAt", + "createdAt", + "hash", + "isActive", + "belongsToCurrentTenant" + ] + }, + "metadata":{ + "countAll":true + }, + "page":{ + "offset":0, + "size":10 + }, + "isActive":[ + 1 + ], + "order":{ + "items":[ + "-createdAt" + ] + } + } + """; + + public static final String endpoint_query_response_example = + """ + { + "items":[ + { + "id":"d6a8d517-e7a8-406c-9d47-66189e58236f", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11174908", + "createdAt":"2024-05-10T13:21:26Z", + "updatedAt":"2024-05-10T13:21:26Z", + "isActive":1, + "entityId":"139f4197-1145-4440-ad5a-4f00398da12e", + "hash":"1715347286", + "belongsToCurrentTenant":true + }, + { + "id":"0c486d94-a37f-4042-81a2-7698971cf30a", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11174466", + "createdAt":"2024-05-10T11:43:46Z", + "updatedAt":"2024-05-10T11:43:46Z", + "isActive":1, + "entityId":"4a8a6642-5de6-4de5-b257-5c119109607a", + "hash":"1715341426", + "belongsToCurrentTenant":true + }, + { + "id":"ad850e47-ce75-465f-ad29-d394dda531b1", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11161991", + "createdAt":"2024-05-09T10:39:10Z", + "updatedAt":"2024-05-09T10:39:10Z", + "isActive":1, + "entityId":"5089fa85-76e2-46e6-b7e5-82bf62f66d13", + "hash":"1715251150", + "belongsToCurrentTenant":true + }, + { + "id":"5c356559-872d-4f07-bafd-197c92df1564", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11152565", + "createdAt":"2024-05-08T18:11:24Z", + "updatedAt":"2024-05-08T18:11:24Z", + "isActive":1, + "entityId":"e36915dc-6496-4b35-b9c4-37576dc08389", + "hash":"1715191884", + "belongsToCurrentTenant":true + }, + { + "id":"05bb9602-b640-428b-a9b0-74025bece4ee", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11091371", + "createdAt":"2024-04-30T08:58:34Z", + "updatedAt":"2024-04-30T08:58:34Z", + "isActive":1, + "entityId":"8d1f813b-ad96-4449-a197-7dc828a6598d", + "hash":"1714467514", + "belongsToCurrentTenant":true + }, + { + "id":"9402523a-1836-4464-a9b2-4ac1c61493cc", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11082522", + "createdAt":"2024-04-29T07:53:04Z", + "updatedAt":"2024-04-29T07:53:04Z", + "isActive":1, + "entityId":"a092bbca-1dbe-4095-a3b9-ba65c7b85e13", + "hash":"1714377184", + "belongsToCurrentTenant":true + }, + { + "id":"85c58f3b-5063-4ddf-a1ab-426268c55565", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11082395", + "createdAt":"2024-04-29T07:28:04Z", + "updatedAt":"2024-04-29T07:28:04Z", + "isActive":1, + "entityId":"c0df9b41-5166-44a6-bdd9-12e0f7b6d5c7", + "hash":"1714375684", + "belongsToCurrentTenant":true + }, + { + "id":"72284e9e-cdf4-4d57-ac8d-59e3ed5bef9a", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11082383", + "createdAt":"2024-04-29T07:25:07Z", + "updatedAt":"2024-04-29T07:25:07Z", + "isActive":1, + "entityId":"e8e93ea4-e983-4299-a1ea-fd3a75c95ef5", + "hash":"1714375507", + "belongsToCurrentTenant":true + }, + { + "id":"ecf6fb11-58f0-42d5-a127-d263703dcd92", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11082161", + "createdAt":"2024-04-29T06:51:43Z", + "updatedAt":"2024-04-29T06:51:43Z", + "isActive":1, + "entityId":"6a4b7b4f-7507-4c52-9356-1f652f2cc430", + "hash":"1714373503", + "belongsToCurrentTenant":true + }, + { + "id":"4ce9b1e6-1e58-48c3-ae80-2ef09f1ef2d0", + "entityType":0, + "repositoryId":"Zenodo", + "doi":"10.5281/zenodo.11081970", + "createdAt":"2024-04-29T05:42:35Z", + "updatedAt":"2024-04-29T05:42:35Z", + "isActive":1, + "entityId":"15e2c0ce-e65a-4c4b-9dfc-1393f042081c", + "hash":"1714369355", + "belongsToCurrentTenant":true + } + ], + "count":118 + } + """; } public static class Deposit { diff --git a/backend/web/src/main/resources/config/swagger.yml b/backend/web/src/main/resources/config/swagger.yml index ac2bd06c4..0310255b0 100644 --- a/backend/web/src/main/resources/config/swagger.yml +++ b/backend/web/src/main/resources/config/swagger.yml @@ -11,7 +11,7 @@ springdoc: displayName: Current packagesToScan: org.opencdmp.controllers packagesToExclude: org.opencdmp.controllers.publicapi - pathsToMatch: "/api/dmp/**, /api/description/**, /api/description-template/**, /api/description-template-type/**" + pathsToMatch: "/api/dmp/**, /api/description/**, /api/description-template/**, /api/description-template-type/**, /api/dmp-blueprint/**, /api/entity-doi/**" swaggerUi: enabled: true useRootPath: true diff --git a/dmp-migration-tool/web/pom.xml b/dmp-migration-tool/web/pom.xml index 60bc6302c..3aa56a473 100644 --- a/dmp-migration-tool/web/pom.xml +++ b/dmp-migration-tool/web/pom.xml @@ -37,9 +37,19 @@ 1.0.0-SNAPSHOT - gr.cite.opendmp + org.opencdmp repositorydepositbase - 2.0.0 + 2.0.15 + + + org.opencdmp + file-transformer-base + 0.0.23 + + + org.opencdmp + common-models + 0.0.18