diff --git a/notification-service/Dockerfile b/notification-service/Dockerfile deleted file mode 100644 index 243a46810..000000000 --- a/notification-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 notification /build/notification/ -COPY notification-web /build/notification-web/ -COPY settings.xml /root/.m2/settings.xml -RUN rm -f /build/notification-web/src/main/resources/config/app.env -RUN rm -f /build/notification-web/src/main/resources/config/*-devel.yml -RUN rm -f /build/notification-web/src/main/resources/logging/*.xml -RUN rm -f /build/notification-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/notification-web/target/notification-web-${REVISION}.jar /app/notification-web.jar - -ENTRYPOINT ["java","-Dspring.config.additional-location=file:/config/","-Dspring.profiles.active=${PROFILE}","-Djava.security.egd=file:/dev/./urandom","-jar","/app/notification-web.jar"] \ No newline at end of file diff --git a/notification-service/Dockerfile.Sonar b/notification-service/Dockerfile.Sonar deleted file mode 100644 index 7bf834b01..000000000 --- a/notification-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 notification /build/notification/ -COPY notification-web /build/notification-web/ -COPY settings.xml /root/.m2/settings.xml -RUN rm -f /build/notification-web/src/main/resources/config/app.env -RUN rm -f /build/notification-web/src/main/resources/config/*-devel.yml -RUN rm -f /build/notification-web/src/main/resources/logging/*.xml -RUN rm -f /build/notification-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:notification-api -Dsonar.login=${ORACLE_TOKEN} -Dsonar.host.url=${ORACLE_URL} -Dsonar.projectName='OpenDMP Notification API' \ No newline at end of file diff --git a/notification-service/notification-web/.gitignore b/notification-service/notification-web/.gitignore deleted file mode 100644 index 5eac309eb..000000000 --- a/notification-service/notification-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/notification-service/notification-web/pom.xml b/notification-service/notification-web/pom.xml deleted file mode 100644 index d6efdc081..000000000 --- a/notification-service/notification-web/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - 4.0.0 - - - gr.cite - notification-service-parent - ${revision} - ../pom.xml - - - notification-web - jar - - - 21 - 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 - notification - ${revision} - - - - gr.cite - oidc-authz - 2.1.0 - - - - gr.cite - exceptions-web - 1.0.0 - - - gr.cite - cors-web - 1.0.0 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/NotificationApplication.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/NotificationApplication.java deleted file mode 100644 index 8d0f9c0c9..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/NotificationApplication.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.notification.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.notification.*", - "gr.cite", - "gr.cite.queueoutbox", - "gr.cite.queueinbox", - "gr.cite.notification.integrationevent", - "gr.cite.tools", - "gr.cite.commons"}) -@EntityScan({ - "gr.cite.notification.data"}) -@EnableAsync -public class NotificationApplication { - - public static void main(String[] args) { - SpringApplication.run(NotificationApplication.class, args); - } - -} diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/WebConfiguration.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/WebConfiguration.java deleted file mode 100644 index 8f0f8367e..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/WebConfiguration.java +++ /dev/null @@ -1,40 +0,0 @@ -package gr.cite.notification.web; - -import gr.cite.notification.web.scope.tenant.TenantInterceptor; -import gr.cite.notification.web.scope.tenant.TenantScopeClaimInterceptor; -import gr.cite.notification.web.scope.tenant.TenantScopeHeaderInterceptor; -import gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/authorization/OwnedAuthorizationHandler.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/authorization/OwnedAuthorizationHandler.java deleted file mode 100644 index e95eb1556..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/authorization/OwnedAuthorizationHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -package gr.cite.notification.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.notification.authorization.OwnedAuthorizationRequirement; -import gr.cite.notification.authorization.OwnedResource; -import gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/config/AppMessageSourceConfiguration.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/config/AppMessageSourceConfiguration.java deleted file mode 100644 index 66adc10da..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/config/AppMessageSourceConfiguration.java +++ /dev/null @@ -1,25 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/config/SecurityConfiguration.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/config/SecurityConfiguration.java deleted file mode 100644 index a82ec7a23..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/config/SecurityConfiguration.java +++ /dev/null @@ -1,144 +0,0 @@ -package gr.cite.notification.web.config; - -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.notification.authorization.OwnedAuthorizationRequirement; -import gr.cite.notification.authorization.OwnedResource; -import gr.cite.notification.web.authorization.OwnedAuthorizationHandler; -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 jakarta.servlet.Filter; -import jakarta.servlet.http.HttpServletRequest; - -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; - - @Autowired - public SecurityConfiguration(WebSecurityProperties webSecurityProperties, - @Qualifier("tokenAuthenticationResolver") AuthenticationManagerResolver authenticationManagerResolver, - @Qualifier("apiKeyFilter") Filter apiKeyFilter, - @Qualifier("ownedAuthorizationHandler") OwnedAuthorizationHandler ownedAuthorizationHandler) { - this.webSecurityProperties = webSecurityProperties; - this.authenticationManagerResolver = authenticationManagerResolver; - this.apiKeyFilter = apiKeyFilter; - this.ownedAuthorizationHandler = ownedAuthorizationHandler; - } - - @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(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(); - } - 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/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java deleted file mode 100644 index 1adb80c48..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllerhandler/GlobalExceptionHandler.java +++ /dev/null @@ -1,193 +0,0 @@ -package gr.cite.notification.web.controllerhandler; - -import gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/InAppNotificationController.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/InAppNotificationController.java deleted file mode 100644 index f87adc370..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/InAppNotificationController.java +++ /dev/null @@ -1,198 +0,0 @@ -package gr.cite.notification.web.controllers; - -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationInAppTracking; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.InAppNotificationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.InAppNotification; -import gr.cite.notification.model.Notification; -import gr.cite.notification.model.builder.InAppNotificationBuilder; -import gr.cite.notification.model.censorship.InAppNotificationCensor; -import gr.cite.notification.query.InAppNotificationQuery; -import gr.cite.notification.query.lookup.InAppNotificationLookup; -import gr.cite.notification.service.inappnotification.InAppNotificationService; -import gr.cite.notification.service.notification.NotificationService; -import gr.cite.notification.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.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.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.web.bind.annotation.*; - -import javax.management.InvalidApplicationException; -import jakarta.transaction.Transactional; -import java.util.*; - -@RestController -@RequestMapping(path = "api/notification/inapp-notification") -public class InAppNotificationController { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InAppNotificationController.class)); - - private final BuilderFactory builderFactory; - private final AuditService auditService; - private final CensorFactory censorFactory; - private final QueryFactory queryFactory; - private final MessageSource messageSource; - private final InAppNotificationService inAppNotificationService; - private final UserScope userScope; - private final ErrorThesaurusProperties errors; - private final TenantEntityManager tenantEntityManager; - - @Autowired - public InAppNotificationController(BuilderFactory builderFactory, - AuditService auditService, - NotificationService notificationService, CensorFactory censorFactory, - QueryFactory queryFactory, - MessageSource messageSource, - InAppNotificationService inAppNotificationService, UserScope userScope, ErrorThesaurusProperties errors, TenantEntityManager tenantEntityManager) { - this.builderFactory = builderFactory; - this.auditService = auditService; - this.censorFactory = censorFactory; - this.queryFactory = queryFactory; - this.messageSource = messageSource; - this.inAppNotificationService = inAppNotificationService; - this.userScope = userScope; - this.errors = errors; - this.tenantEntityManager = tenantEntityManager; - } - - @PostMapping("query") - public QueryResult Query(@RequestBody InAppNotificationLookup lookup) throws MyApplicationException, MyForbiddenException, InvalidApplicationException { - logger.debug("querying {}", InAppNotification.class.getSimpleName()); - UUID userId = this.userScope.getUserId(); - this.censorFactory.censor(InAppNotificationCensor.class).censor(lookup.getProject(), userId); - - try { - this.tenantEntityManager.loadExplictTenantFilters(); - - if (userId == null) throw new MyForbiddenException(this.errors.getNonPersonPrincipal().getCode(), this.errors.getNonPersonPrincipal().getMessage()); - InAppNotificationQuery query = lookup.enrich(this.queryFactory).disableTracking().userId(userId); - List data = query.collectAs(lookup.getProject()); - List models = this.builderFactory.builder(InAppNotificationBuilder.class).build(lookup.getProject(), data); - long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size(); - - this.auditService.track(AuditableAction.InApp_Notification_Query, "lookup", lookup); - - return new QueryResult<>(models, count); - } finally { - this.tenantEntityManager.reloadTenantFilters(); - } - } - - @GetMapping("{id}") - @Transactional - public InAppNotification Get(@PathVariable UUID id, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("retrieving" + InAppNotification.class.getSimpleName()).And("id", id).And("fields", fieldSet)); - UUID userId = this.userScope.getUserId(); - this.censorFactory.censor(InAppNotificationCensor.class).censor(fieldSet, userId); - - try { - this.tenantEntityManager.loadExplictTenantFilters(); - - InAppNotificationQuery query = this.queryFactory.query(InAppNotificationQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission).userId(userId).ids(id); - InAppNotification model = this.builderFactory.builder(InAppNotificationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(fieldSet, query.firstAs(fieldSet)); - if (model == null) - throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, Notification.class.getSimpleName()}, LocaleContextHolder.getLocale())); - - this.auditService.track(AuditableAction.InApp_Notification_Lookup, Map.ofEntries( - new AbstractMap.SimpleEntry("id", id), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return model; - } finally { - this.tenantEntityManager.reloadTenantFilters(); - } - } - - @PostMapping("{id}/read") - @Transactional - public Boolean persist(@PathVariable UUID id) throws InvalidApplicationException { - logger.debug(new MapLogEntry("marking as read").And("id", id)); - - try { - this.tenantEntityManager.loadExplictTenantFilters(); - - this.inAppNotificationService.markAsRead(id); - - this.auditService.track(AuditableAction.InApp_Notification_Read, Map.of("id", id)); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - return true; - } finally { - this.tenantEntityManager.reloadTenantFilters(); - } - } - - @PostMapping("read-all") - @Transactional - public Boolean MarkAsReadAllUserInAppNotification() throws InvalidApplicationException { - logger.debug(new MapLogEntry("marking as read all")); - - UUID userId = this.userScope.getUserId(); - if (userId == null) throw new MyForbiddenException(this.errors.getNonPersonPrincipal().getCode(), this.errors.getNonPersonPrincipal().getMessage()); - try { - this.tenantEntityManager.loadExplictTenantFilters(); - this.inAppNotificationService.markAsReadAllUserNotification(userId); - - this.auditService.track(AuditableAction.InApp_Notification_Read_All, Map.of("userId", userId)); - return true; - } finally { - this.tenantEntityManager.reloadTenantFilters(); - } - } - - @GetMapping("count-unread") - @Transactional - public Integer CountUnread() throws InvalidApplicationException { - logger.debug("count-unread"); - - UUID userId = this.userScope.getUserId(); - if (userId == null) throw new MyForbiddenException(this.errors.getNonPersonPrincipal().getCode(), this.errors.getNonPersonPrincipal().getMessage()); - - this.censorFactory.censor(InAppNotificationCensor.class).censor(new BaseFieldSet(InAppNotification.Field.ID), userId); - try { - this.tenantEntityManager.loadExplictTenantFilters(); - InAppNotificationQuery query = this.queryFactory.query(InAppNotificationQuery.class).disableTracking().isActive(IsActive.Active).trackingState(NotificationInAppTracking.STORED).userId(userId); - int count = Math.toIntExact(query.count()); - - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return count; - } finally { - this.tenantEntityManager.reloadTenantFilters(); - } - } - - @DeleteMapping("{id}") - @Transactional - public void Delete(@PathVariable("id") UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug(new MapLogEntry("deleting" + Notification.class.getSimpleName()).And("id", id)); - - try { - this.tenantEntityManager.loadExplictTenantFilters(); - this.inAppNotificationService.deleteAndSave(id); - - this.auditService.track(AuditableAction.InApp_Notification_Delete, "id", id); - - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - } finally { - this.tenantEntityManager.reloadTenantFilters(); - } - } -} diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/NotificationController.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/NotificationController.java deleted file mode 100644 index abd8b9607..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/NotificationController.java +++ /dev/null @@ -1,127 +0,0 @@ -package gr.cite.notification.web.controllers; - -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.model.Notification; -import gr.cite.notification.model.builder.NotificationBuilder; -import gr.cite.notification.model.censorship.NotificationCensor; -import gr.cite.notification.model.persist.NotificationPersist; -import gr.cite.notification.query.NotificationQuery; -import gr.cite.notification.query.lookup.NotificationLookup; -import gr.cite.notification.service.notification.NotificationService; -import gr.cite.notification.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 org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.web.bind.annotation.*; - -import javax.management.InvalidApplicationException; -import java.util.*; - -@RestController -@RequestMapping(path = "api/notification") -public class NotificationController { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationController.class)); - - private final BuilderFactory builderFactory; - private final AuditService auditService; - private final NotificationService notificationService; - private final CensorFactory censorFactory; - private final QueryFactory queryFactory; - private final MessageSource messageSource; - - @Autowired - public NotificationController(BuilderFactory builderFactory, - AuditService auditService, - NotificationService notificationService, CensorFactory censorFactory, - QueryFactory queryFactory, - MessageSource messageSource) { - this.builderFactory = builderFactory; - this.auditService = auditService; - this.notificationService = notificationService; - this.censorFactory = censorFactory; - this.queryFactory = queryFactory; - this.messageSource = messageSource; - } - - @PostMapping("query") - public QueryResult Query(@RequestBody NotificationLookup lookup) throws MyApplicationException, MyForbiddenException { - logger.debug("querying {}", Notification.class.getSimpleName()); - - this.censorFactory.censor(NotificationCensor.class).censor(lookup.getProject()); - - NotificationQuery query = lookup.enrich(this.queryFactory).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission); - List data = query.collectAs(lookup.getProject()); - List models = this.builderFactory.builder(NotificationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(lookup.getProject(), data); - long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size(); - - this.auditService.track(AuditableAction.Notification_Query, "lookup", lookup); - - return new QueryResult<>(models, count); - } - - @GetMapping("{id}") - @Transactional - public Notification Get(@PathVariable UUID id, FieldSet fieldSet, Locale locale) throws MyApplicationException, MyForbiddenException, MyNotFoundException { - logger.debug(new MapLogEntry("retrieving" + Notification.class.getSimpleName()).And("id", id).And("fields", fieldSet)); - - this.censorFactory.censor(NotificationCensor.class).censor(fieldSet); - - NotificationQuery query = this.queryFactory.query(NotificationQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission).ids(id); - Notification model = this.builderFactory.builder(NotificationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(fieldSet, query.firstAs(fieldSet)); - if (model == null) - throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, Notification.class.getSimpleName()}, LocaleContextHolder.getLocale())); - - this.auditService.track(AuditableAction.Notification_Lookup, Map.ofEntries( - new AbstractMap.SimpleEntry("id", id), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return model; - } - - @PostMapping("persist") - @Transactional - @ValidationFilterAnnotation(validator = NotificationPersist.NotificationPersistValidator.ValidatorName, argumentName = "model") - public Notification Persist(@RequestBody NotificationPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("persisting" + Notification.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); - - Notification persisted = this.notificationService.persist(model, fieldSet); - - this.auditService.track(AuditableAction.Notification_Persist, Map.ofEntries( - new AbstractMap.SimpleEntry("model", model), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return persisted; - } - - @DeleteMapping("{id}") - @Transactional - public void Delete(@PathVariable("id") UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug(new MapLogEntry("deleting" + Notification.class.getSimpleName()).And("id", id)); - - this.notificationService.deleteAndSave(id); - - this.auditService.track(AuditableAction.InApp_Notification_Delete, "id", id); - - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - } - -} diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/NotificationTemplateController.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/NotificationTemplateController.java deleted file mode 100644 index eb4cf3f45..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/NotificationTemplateController.java +++ /dev/null @@ -1,123 +0,0 @@ -package gr.cite.notification.web.controllers; - -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.data.NotificationTemplateEntity; -import gr.cite.notification.model.NotificationTemplate; -import gr.cite.notification.model.builder.NotificationTemplateBuilder; -import gr.cite.notification.model.censorship.NotificationTemplateCensor; -import gr.cite.notification.model.persist.NotificationTemplatePersist; -import gr.cite.notification.query.NotificationTemplateQuery; -import gr.cite.notification.query.lookup.NotificationTemplateLookup; -import gr.cite.notification.service.notificationtemplate.NotificationTemplateService; -import gr.cite.notification.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 org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.web.bind.annotation.*; - -import javax.management.InvalidApplicationException; -import jakarta.transaction.Transactional; -import java.util.*; - -@RestController -@RequestMapping(path = "api/notification/notification-template") -public class NotificationTemplateController { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationTemplateController.class)); - - private final BuilderFactory builderFactory; - private final AuditService auditService; - private final NotificationTemplateService notificationTemplateService; - private final CensorFactory censorFactory; - private final QueryFactory queryFactory; - private final MessageSource messageSource; - - @Autowired - public NotificationTemplateController(BuilderFactory builderFactory, - AuditService auditService, - NotificationTemplateService notificationTemplateService, - CensorFactory censorFactory, - QueryFactory queryFactory, - MessageSource messageSource) { - this.builderFactory = builderFactory; - this.auditService = auditService; - this.notificationTemplateService = notificationTemplateService; - this.censorFactory = censorFactory; - this.queryFactory = queryFactory; - this.messageSource = messageSource; - } - - @PostMapping("query") - public QueryResult query(@RequestBody NotificationTemplateLookup lookup) throws MyApplicationException, MyForbiddenException { - logger.debug("querying {}", NotificationTemplate.class.getSimpleName()); - - this.censorFactory.censor(NotificationTemplateCensor.class).censor(lookup.getProject()); - - NotificationTemplateQuery query = lookup.enrich(this.queryFactory).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission); - List data = query.collectAs(lookup.getProject()); - List models = this.builderFactory.builder(NotificationTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(lookup.getProject(), data); - long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size(); - - this.auditService.track(AuditableAction.Notification_Template_Query, "lookup", lookup); - - return new QueryResult<>(models, count); - } - - @GetMapping("{id}") - public NotificationTemplate get(@PathVariable UUID id, FieldSet fieldSet, Locale locale) throws MyApplicationException, MyForbiddenException, MyNotFoundException { - logger.debug(new MapLogEntry("retrieving" + NotificationTemplate.class.getSimpleName()).And("id", id).And("fields", fieldSet)); - - this.censorFactory.censor(NotificationTemplateCensor.class).censor(fieldSet); - - NotificationTemplateQuery query = this.queryFactory.query(NotificationTemplateQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission).ids(id); - NotificationTemplate model = this.builderFactory.builder(NotificationTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(fieldSet, query.first()); - if (model == null) - throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, NotificationTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); - - this.auditService.track(AuditableAction.Notification_Template_Lookup, Map.ofEntries( - new AbstractMap.SimpleEntry("id", id), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - - return model; - } - - @PostMapping("persist") - @Transactional - @ValidationFilterAnnotation(validator = NotificationTemplatePersist.NotificationTemplatePersistValidator.ValidatorName, argumentName = "model") - public NotificationTemplate persist(@RequestBody NotificationTemplatePersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("persisting" + NotificationTemplate.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); - - NotificationTemplate persisted = this.notificationTemplateService.persist(model, fieldSet); - - this.auditService.track(AuditableAction.Notification_Template_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("deleting" + NotificationTemplate.class.getSimpleName()).And("id", id)); - - this.notificationTemplateService.deleteAndSave(id); - - this.auditService.track(AuditableAction.Notification_Template_Delete, "id", id); - } - -} diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/PrincipalController.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/PrincipalController.java deleted file mode 100644 index 71b1dfd47..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/PrincipalController.java +++ /dev/null @@ -1,75 +0,0 @@ -package gr.cite.notification.web.controllers; - -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.notification.audit.AuditableAction; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.web.model.Account; -import gr.cite.notification.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/notification/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/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/TenantConfigurationController.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/TenantConfigurationController.java deleted file mode 100644 index bfd19884a..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/TenantConfigurationController.java +++ /dev/null @@ -1,179 +0,0 @@ -package gr.cite.notification.web.controllers; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.model.builder.tenantconfiguration.TenantConfigurationBuilder; -import gr.cite.notification.model.censorship.tenantconfiguration.TenantConfigurationCensor; -import gr.cite.notification.model.persist.tenantconfiguration.TenantConfigurationPersist; -import gr.cite.notification.model.tenantconfiguration.TenantConfiguration; -import gr.cite.notification.query.TenantConfigurationQuery; -import gr.cite.notification.query.lookup.NotifierListLookup; -import gr.cite.notification.query.lookup.TenantConfigurationLookup; -import gr.cite.notification.service.tenantconfiguration.TenantConfigurationService; -import gr.cite.notification.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 org.slf4j.LoggerFactory; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.*; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.management.InvalidApplicationException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.AbstractMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -@RestController -@RequestMapping(path = "api/notification/tenant-configuration") -public class TenantConfigurationController { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantConfigurationController.class)); - - private final BuilderFactory builderFactory; - - private final AuditService auditService; - - private final TenantConfigurationService tenantConfigurationService; - - private final CensorFactory censorFactory; - - private final QueryFactory queryFactory; - - private final MessageSource messageSource; - private final TenantScope tenantScope; - - public TenantConfigurationController( - BuilderFactory builderFactory, - AuditService auditService, - TenantConfigurationService tenantConfigurationService, CensorFactory censorFactory, - QueryFactory queryFactory, - MessageSource messageSource, TenantScope tenantScope) { - this.builderFactory = builderFactory; - this.auditService = auditService; - this.tenantConfigurationService = tenantConfigurationService; - this.censorFactory = censorFactory; - this.queryFactory = queryFactory; - this.messageSource = messageSource; - this.tenantScope = tenantScope; - } - - @PostMapping("query") - public QueryResult query(@RequestBody TenantConfigurationLookup lookup) throws MyApplicationException, MyForbiddenException { - logger.debug("querying {}", TenantConfiguration.class.getSimpleName()); - - this.censorFactory.censor(TenantConfigurationCensor.class).censor(lookup.getProject(), null); - - TenantConfigurationQuery query = lookup.enrich(this.queryFactory).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission); - - List data = query.collectAs(lookup.getProject()); - List models = this.builderFactory.builder(TenantConfigurationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(lookup.getProject(), data); - long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size(); - - this.auditService.track(AuditableAction.Tenant_Configuration_Query, "lookup", lookup); - - return new QueryResult<>(models, count); - } - - @GetMapping("{id}") - public TenantConfiguration get(@PathVariable("id") UUID id, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException { - logger.debug(new MapLogEntry("retrieving" + TenantConfiguration.class.getSimpleName()).And("id", id).And("fields", fieldSet)); - - this.censorFactory.censor(TenantConfigurationCensor.class).censor(fieldSet, null); - - TenantConfigurationQuery query = this.queryFactory.query(TenantConfigurationQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission).ids(id); - TenantConfiguration model = this.builderFactory.builder(TenantConfigurationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(fieldSet, query.firstAs(fieldSet)); - if (model == null) - throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, TenantConfiguration.class.getSimpleName()}, LocaleContextHolder.getLocale())); - - this.auditService.track(AuditableAction.Tenant_Configuration_Lookup, Map.ofEntries( - new AbstractMap.SimpleEntry("id", id), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - - return model; - } - - @GetMapping("current-tenant/{type}") - public TenantConfiguration getCurrentTenantType(@PathVariable("type") Short type, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("retrieving" + TenantConfiguration.class.getSimpleName()).And("type", type).And("fields", fieldSet)); - - this.censorFactory.censor(TenantConfigurationCensor.class).censor(fieldSet, null); - - TenantConfigurationQuery query = this.queryFactory.query(TenantConfigurationQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission).isActive(IsActive.Active).types(TenantConfigurationType.of(type)); - if (this.tenantScope.isDefaultTenant()) query.tenantIsSet(false); - else query.tenantIsSet(true).tenantIds(this.tenantScope.getTenant()); - - TenantConfiguration model = this.builderFactory.builder(TenantConfigurationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(fieldSet, query.firstAs(fieldSet)); - - this.auditService.track(AuditableAction.TenantConfiguration_LookupByType, Map.ofEntries( - new AbstractMap.SimpleEntry("type", type), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - - return model; - } - - @PostMapping("persist") - @org.springframework.transaction.annotation.Transactional - @ValidationFilterAnnotation(validator = TenantConfigurationPersist.TenantConfigurationPersistValidator.ValidatorName, argumentName = "model") - public TenantConfiguration persist(@RequestBody TenantConfigurationPersist model, FieldSet fieldSet) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException, JsonProcessingException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException { - logger.debug(new MapLogEntry("persisting" + TenantConfiguration.class.getSimpleName()).And("model", model).And("fieldSet", fieldSet)); - TenantConfiguration persisted = this.tenantConfigurationService.persist(model, fieldSet); - - this.auditService.track(AuditableAction.Tenant_Configuration_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" + TenantConfiguration.class.getSimpleName()).And("id", id)); - - this.tenantConfigurationService.deleteAndSave(id); - - this.auditService.track(AuditableAction.Tenant_Configuration_Delete, "id", id); - } - - @PostMapping("notifier-list/available") - public NotifierListTenantConfigurationEntity getAvailableNotifiers(@RequestBody NotifierListLookup tenantNotifierListLookup) - { - logger.debug("querying available notifiers"); - - NotifierListTenantConfigurationEntity notifierListData = this.tenantConfigurationService.collectTenantAvailableNotifierList(tenantNotifierListLookup.getNotificationTypes()); - - this.auditService.track(AuditableAction.Tenant_Configuration_Notifiers_Query, Map.of( - "lookup", tenantNotifierListLookup - )); - //this._auditService.TrackIdentity(AuditableAction.IdentityTracking_Action); - - return notifierListData; - } - -} diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/UserNotificationPreferenceController.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/UserNotificationPreferenceController.java deleted file mode 100644 index 22a46598f..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/UserNotificationPreferenceController.java +++ /dev/null @@ -1,163 +0,0 @@ -package gr.cite.notification.web.controllers; - -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.UserNotificationPreferenceEntity; -import gr.cite.notification.event.TenantConfigurationTouchedEvent; -import gr.cite.notification.model.UserNotificationPreference; -import gr.cite.notification.model.builder.UserNotificationPreferenceBuilder; -import gr.cite.notification.model.censorship.UserNotificationPreferenceCensor; -import gr.cite.notification.model.persist.UserNotificationPreferencePersist; -import gr.cite.notification.query.UserNotificationPreferenceQuery; -import gr.cite.notification.query.lookup.NotifierListLookup; -import gr.cite.notification.query.lookup.UserNotificationPreferenceLookup; -import gr.cite.notification.service.userNotificationPreference.UserNotificationPreferenceService; -import gr.cite.notification.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.Ordering; -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 org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.web.bind.annotation.*; - -import jakarta.transaction.Transactional; - -import javax.management.InvalidApplicationException; -import java.util.*; - -@RestController -@RequestMapping(path = "api/notification/notification-preference") -public class UserNotificationPreferenceController { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserNotificationPreferenceController.class)); - - private final BuilderFactory builderFactory; - private final AuditService auditService; - private final UserNotificationPreferenceService userNotificationPreferenceService; - private final CensorFactory censorFactory; - private final QueryFactory queryFactory; - private final MessageSource messageSource; - private final TenantScope tenantScope; - - @Autowired - public UserNotificationPreferenceController(BuilderFactory builderFactory, - AuditService auditService, - UserNotificationPreferenceService userNotificationPreferenceService, - CensorFactory censorFactory, - QueryFactory queryFactory, - MessageSource messageSource, TenantScope tenantScope) { - this.builderFactory = builderFactory; - this.auditService = auditService; - this.userNotificationPreferenceService = userNotificationPreferenceService; - this.censorFactory = censorFactory; - this.queryFactory = queryFactory; - this.messageSource = messageSource; - this.tenantScope = tenantScope; - } - - @PostMapping("query") - public QueryResult query(@RequestBody UserNotificationPreferenceLookup lookup) throws MyApplicationException, MyForbiddenException { - logger.debug("querying {}", UserNotificationPreference.class.getSimpleName()); - - this.censorFactory.censor(UserNotificationPreferenceCensor.class).censor(lookup.getProject(), null); - - UserNotificationPreferenceQuery query = lookup.enrich(this.queryFactory).disableTracking(); - List data = query.collectAs(lookup.getProject()); - List models = this.builderFactory.builder(UserNotificationPreferenceBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(lookup.getProject(), data); - long count = (lookup.getMetadata() != null && lookup.getMetadata().getCountAll()) ? query.count() : models.size(); - - this.auditService.track(AuditableAction.User_Notification_Preference_Query, "lookup", lookup); - - return new QueryResult<>(models, count); - } - - @GetMapping("user/{userId}/current") - @Transactional - public List current(@PathVariable UUID userId, FieldSet fieldSet, Locale locale) throws MyApplicationException, MyForbiddenException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("retrieving" + UserNotificationPreference.class.getSimpleName()).And("userId", userId).And("fields", fieldSet)); - - this.censorFactory.censor(UserNotificationPreferenceCensor.class).censor(fieldSet, userId); - - Ordering ordering = new Ordering(); - ordering.addAscending(UserNotificationPreference._ordinal); - UserNotificationPreferenceQuery query = this.queryFactory.query(UserNotificationPreferenceQuery.class).disableTracking().userId(userId).isActives(IsActive.Active); - query.setOrder(ordering); - if (this.tenantScope.isMultitenant() && this.tenantScope.isSet()) { - if (!this.tenantScope.isDefaultTenant()) { - query.tenantIsSet(true).tenantIds(this.tenantScope.getTenant()); - } else { - query.tenantIsSet(false); - } - } - List model = this.builderFactory.builder(UserNotificationPreferenceBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(fieldSet, query.collectAs(fieldSet)); - - this.auditService.track(AuditableAction.User_Notification_Preference_Lookup, Map.ofEntries( - new AbstractMap.SimpleEntry("userId", userId), - new AbstractMap.SimpleEntry("fields", fieldSet) - )); - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - - return model; - } - - @PostMapping("notifier-list/available") - public NotifierListTenantConfigurationEntity getAvailableNotifiers(@RequestBody NotifierListLookup tenantNotifierListLookup) - { - logger.debug("querying available notifiers"); - - NotifierListTenantConfigurationEntity notifierListData = this.userNotificationPreferenceService.collectUserAvailableNotifierList(tenantNotifierListLookup.getNotificationTypes()); - - this.auditService.track(AuditableAction.User_Available_Notifiers_Query, Map.of( - "lookup", tenantNotifierListLookup - )); - //this._auditService.TrackIdentity(AuditableAction.IdentityTracking_Action); - - return notifierListData; - } - - @PostMapping("persist") - @Transactional - @ValidationFilterAnnotation(validator = UserNotificationPreferencePersist.UserNotificationPreferencePersistValidator.ValidatorName, argumentName = "model") - public List persist(@RequestBody UserNotificationPreferencePersist model, FieldSet fieldSet) - { - logger.debug(new MapLogEntry("persisting").And("type", TenantConfigurationType.NotifierList).And("model", model).And("fields", fieldSet)); - - List persisted = this.userNotificationPreferenceService.persist(model, fieldSet); - - this.auditService.track(AuditableAction.User_Notification_Preference_Persist, Map.of( - "type", TenantConfigurationType.NotifierList, - "model", model, - "fields", fieldSet - )); - //this._auditService.TrackIdentity(AuditableAction.IdentityTracking_Action); - - return persisted; - } - -/* @DeleteMapping("{id}") - @Transactional - public void delete(@PathVariable("id") UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug(new MapLogEntry("deleting" + TenantConfiguration.class.getSimpleName()).And("id", id)); - - this.tenantConfigurationService.deleteAndSave(id); - - this.auditService.track(AuditableAction.Tenant_Configuration_Delete, "id", id); - - //this.auditService.trackIdentity(AuditableAction.IdentityTracking_Action); - }*/ -} diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/error/GenericErrorHandler.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/error/GenericErrorHandler.java deleted file mode 100644 index 1a7ebfc3a..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/controllers/error/GenericErrorHandler.java +++ /dev/null @@ -1,17 +0,0 @@ -//package gr.cite.intelcomp.stiviewer.web.controllers.error; -// -//import gr.cite.tools.exception.MyValidationException; -//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.context.request.WebRequest; -// -//@ControllerAdvice -//public class GenericErrorHandler { -// -// @ExceptionHandler(MyValidationException.class) -// public ResponseEntity handleValidationException(MyValidationException e, WebRequest webRequest) { -// return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(e); -// } -//} diff --git a/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/Account.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/Account.java deleted file mode 100644 index 601dc19b0..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/Account.java +++ /dev/null @@ -1,160 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/AccountBuilder.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/AccountBuilder.java deleted file mode 100644 index 792b25965..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/AccountBuilder.java +++ /dev/null @@ -1,86 +0,0 @@ -package gr.cite.notification.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.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/QueryResult.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/QueryResult.java deleted file mode 100644 index 2e0899843..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/model/QueryResult.java +++ /dev/null @@ -1,37 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByCodeCacheOptions.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByCodeCacheOptions.java deleted file mode 100644 index 752c8965f..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByCodeCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByCodeCacheService.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByCodeCacheService.java deleted file mode 100644 index 33ffb5a2a..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByCodeCacheService.java +++ /dev/null @@ -1,76 +0,0 @@ -package gr.cite.notification.web.scope.tenant; - -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByIdCacheOptions.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByIdCacheOptions.java deleted file mode 100644 index 1c5f69520..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByIdCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByIdCacheService.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByIdCacheService.java deleted file mode 100644 index f513fb4d7..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantByIdCacheService.java +++ /dev/null @@ -1,77 +0,0 @@ -package gr.cite.notification.web.scope.tenant; - -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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; - } - } - - private final ConventionService conventionService; - - @Autowired - public TenantByIdCacheService(TenantByIdCacheOptions options, ConventionService conventionService) { - super(options); - this.conventionService = conventionService; - } - - @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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java deleted file mode 100644 index ef5fc0e34..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantInterceptor.java +++ /dev/null @@ -1,184 +0,0 @@ -package gr.cite.notification.web.scope.tenant; - - -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.notification.authorization.ClaimNames; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.TenantUserEntity; -import gr.cite.notification.data.UserEntity; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.query.utils.BuildSubQueryInput; -import gr.cite.notification.query.utils.QueryUtilsService; -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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeClaimInterceptor.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeClaimInterceptor.java deleted file mode 100644 index 700d0288d..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeClaimInterceptor.java +++ /dev/null @@ -1,184 +0,0 @@ -package gr.cite.notification.web.scope.tenant; - - -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.notification.authorization.ClaimNames; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeConfiguration.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeConfiguration.java deleted file mode 100644 index 13d77c9ad..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeHeaderInterceptor.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeHeaderInterceptor.java deleted file mode 100644 index 5058b130d..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeHeaderInterceptor.java +++ /dev/null @@ -1,146 +0,0 @@ -package gr.cite.notification.web.scope.tenant; - - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorContext; -import gr.cite.notification.authorization.ClaimNames; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.TenantEntity; -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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeProperties.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeProperties.java deleted file mode 100644 index 7e60e5f50..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/TenantScopeProperties.java +++ /dev/null @@ -1,44 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/UserAllowedTenantCacheOptions.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/UserAllowedTenantCacheOptions.java deleted file mode 100644 index 0973b33e7..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/UserAllowedTenantCacheOptions.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/UserAllowedTenantCacheService.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/UserAllowedTenantCacheService.java deleted file mode 100644 index 4a51ba9b0..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/tenant/UserAllowedTenantCacheService.java +++ /dev/null @@ -1,91 +0,0 @@ -package gr.cite.notification.web.scope.tenant; - -import gr.cite.notification.event.UserAddedToTenantEvent; -import gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptor.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptor.java deleted file mode 100644 index 36ad1e83f..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptor.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.notification.web.scope.user; - - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractor; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.UserCredentialEntity; -import gr.cite.notification.model.UserCredential; -import gr.cite.notification.query.UserCredentialQuery; -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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptorCacheOptions.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptorCacheOptions.java deleted file mode 100644 index 8a35750a6..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptorCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.notification.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/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptorCacheService.java b/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptorCacheService.java deleted file mode 100644 index e19162843..000000000 --- a/notification-service/notification-web/src/main/java/gr/cite/notification/web/scope/user/UserInterceptorCacheService.java +++ /dev/null @@ -1,77 +0,0 @@ -package gr.cite.notification.web.scope.user; - -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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 conventionService1) { - super(options); - this.conventionService = conventionService1; - } - - @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/notification-service/notification-web/src/main/resources/config/application.yml b/notification-service/notification-web/src/main/resources/config/application.yml deleted file mode 100644 index 06b5f37c9..000000000 --- a/notification-service/notification-web/src/main/resources/config/application.yml +++ /dev/null @@ -1,21 +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/notification.yml[.yml], optional:classpath:config/notification-${spring.profiles.active}.yml[.yml], optional:file:../config/notification-${spring.profiles.active}.yml[.yml], - optional:classpath:config/email.yml[.yml], optional:classpath:config/email-${spring.profiles.active}.yml[.yml], optional:file:../config/email-${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], - optional:classpath:config/formatting.yml[.yml], optional:classpath:config/formatting-${spring.profiles.active}.yml[.yml], optional:file:../config/formatting-${spring.profiles.active}.yml[.yml] diff --git a/notification-service/notification-web/src/main/resources/config/cache.yml b/notification-service/notification-web/src/main/resources/config/cache.yml deleted file mode 100644 index fb0072062..000000000 --- a/notification-service/notification-web/src/main/resources/config/cache.yml +++ /dev/null @@ -1,62 +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: 5000 - enableRecordStats: false - expireAfterWriteSeconds: 20 - - names: [ userAccessTenant ] - allowNullValues: true - initialCapacity: 100 - maximumSize: 500 - enableRecordStats: false - expireAfterWriteSeconds: 20 - - names: [ formattingUserProfile ] - allowNullValues: true - initialCapacity: 100 - maximumSize: 500 - enableRecordStats: false - expireAfterWriteSeconds: 20 - mapCaches: - apiKey: - name: apikey - keyPattern: ntf_resolve_$keyhash$:v0 - userBySubjectId: - name: userBySubjectId - keyPattern: ntf_user_by_subject_$subject$:v0 - tenantByCode: - name: tenantByCode - keyPattern: ntf_tenant_by_code_$code$:v0 - tenantById: - name: tenantById - keyPattern: ntf_tenant_by_id_$tenantId$:v0 - userAllowedTenant: - name: userAccessTenant - keyPattern: ntf_user_access_tenant_$user_id$_$tenant_id$:v0 - formattingUserProfileCache: - name: formattingUserProfile - keyPattern: ntf_formatting_user_profile$user_id$:v0 - template: - name: template - key-pattern: ------ diff --git a/notification-service/notification-web/src/main/resources/config/cipher.yml b/notification-service/notification-web/src/main/resources/config/cipher.yml deleted file mode 100644 index caa559296..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/cors-devel.yml b/notification-service/notification-web/src/main/resources/config/cors-devel.yml deleted file mode 100644 index 3e9227ef3..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/cors.yml b/notification-service/notification-web/src/main/resources/config/cors.yml deleted file mode 100644 index 3774f14d4..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/db-devel.yml b/notification-service/notification-web/src/main/resources/config/db-devel.yml deleted file mode 100644 index 22a089fbd..000000000 --- a/notification-service/notification-web/src/main/resources/config/db-devel.yml +++ /dev/null @@ -1,7 +0,0 @@ -spring: - jpa: - show-sql: true - properties: - hibernate: - show_sql: true - format_sql: false diff --git a/notification-service/notification-web/src/main/resources/config/db.yml b/notification-service/notification-web/src/main/resources/config/db.yml deleted file mode 100644 index 18ca948e4..000000000 --- a/notification-service/notification-web/src/main/resources/config/db.yml +++ /dev/null @@ -1,29 +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.notification.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: ntf_ diff --git a/notification-service/notification-web/src/main/resources/config/email.yml b/notification-service/notification-web/src/main/resources/config/email.yml deleted file mode 100644 index 364788161..000000000 --- a/notification-service/notification-web/src/main/resources/config/email.yml +++ /dev/null @@ -1,14 +0,0 @@ -spring: - mail: - host: ${MAIL_HOST} - port: ${MAIL_PORT} - username: ${MAIL_USERNAME} - password: ${MAIL_PASSWORD} - properties: - mail: - smtp: - auth: ${MAIL_AUTH} - starttls: - enable: ${MAIL_TLS} -email: - address: ${MAIL_ADDRESS} \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/config/errors.yml b/notification-service/notification-web/src/main/resources/config/errors.yml deleted file mode 100644 index 3764076c2..000000000 --- a/notification-service/notification-web/src/main/resources/config/errors.yml +++ /dev/null @@ -1,59 +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 - tenant-configuration-type-can-not-change: - code: 128 - message: Tenant configuration type can not change - multiple-tenant-configuration-type-not-allowed: - code: 129 - message: Multiple Tenant Configuration Type Not Allowed - -# 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 - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/config/formatting.yml b/notification-service/notification-web/src/main/resources/config/formatting.yml deleted file mode 100644 index abdc31184..000000000 --- a/notification-service/notification-web/src/main/resources/config/formatting.yml +++ /dev/null @@ -1,6 +0,0 @@ -formatting: - options: - integer-format: "%,d" - decimal-digits-round: 2 - decimal-format: "#0.00" - date-time-format: "YYYY-MM-dd'T'HH:mm:ss" diff --git a/notification-service/notification-web/src/main/resources/config/idpclaims.yml b/notification-service/notification-web/src/main/resources/config/idpclaims.yml deleted file mode 100644 index 26e00f2a1..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/locale.yml b/notification-service/notification-web/src/main/resources/config/locale.yml deleted file mode 100644 index b09c59e53..000000000 --- a/notification-service/notification-web/src/main/resources/config/locale.yml +++ /dev/null @@ -1,4 +0,0 @@ -locale: - timezone: UTC - language: en - culture: en-US diff --git a/notification-service/notification-web/src/main/resources/config/logging-devel.yml b/notification-service/notification-web/src/main/resources/config/logging-devel.yml deleted file mode 100644 index 2f565c0d7..000000000 --- a/notification-service/notification-web/src/main/resources/config/logging-devel.yml +++ /dev/null @@ -1,2 +0,0 @@ -logging: - config: classpath:logging/logback-dev.xml diff --git a/notification-service/notification-web/src/main/resources/config/logging.yml b/notification-service/notification-web/src/main/resources/config/logging.yml deleted file mode 100644 index 56e152d3f..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/notification-devel.yml b/notification-service/notification-web/src/main/resources/config/notification-devel.yml deleted file mode 100644 index 05d82e565..000000000 --- a/notification-service/notification-web/src/main/resources/config/notification-devel.yml +++ /dev/null @@ -1,728 +0,0 @@ -notification: - staticFields: - fields: - - key: "{installation-url}" - type: "String" - value: "http://localhost:4200" - resolver: - global-policies: - - #planInvitationExternalUser - type: 065DEECD-21BB-44AF-9983-E660FDF24BC4 - contacts: [ email ] - - #planInvitationExistingUser - type: 4904dea2-5079-46d3-83be-3a19c9ab45dc - contacts: [ email, inapp ] - - #dpmModified - type: 4542262A-22F8-4BAA-9DB6-1C8E70AC1DBB - contacts: [ inapp, email ] - - #planFinalised - type: 90DB0B46-42DE-BD89-AEBF-6F27EFEB256E - contacts: [ inapp, email ] - - #descriptionCreated - type: 8965b1d5-99a6-4acf-9016-c0d0ce341364 - contacts: [ inapp, email ] - - #descriptionModified - type: 4FDBFA80-7A71-4A69-B854-67CBB70648F1 - contacts: [ inapp, email ] - - #descriptionFinalised - type: 33790bad-94d4-488a-8ee2-7f6295ca18ea - contacts: [ inapp, email ] - - #descriptionAnnotationCreated - type: db1e99d2-a240-4e75-9bb2-ef25b234c1f0 - contacts: [ inapp, email ] - - #mergeAcountConfirmation - type: BFE68845-CB05-4C5A-A03D-29161A7C9660 - contacts: [ email ] - - #removeCredentialConfirmation - type: C9BC3F16-057E-4BBA-8A5F-36BD835E5604 - contacts: [ email ] - - #planDeposit - type: 55736F7A-83AB-4190-AF43-9D031A6F9612 - contacts: [ inapp, email ] - - #descriptionTemplateInvitation - type: 223BB607-EFA1-4CE7-99EC-4BEABFEF9A8B - contacts: [ inapp, email ] - - #contactSupportType - type: 5B1D6C52-88F9-418B-9B8A-6F1F963D9EAD - contacts: [ email ] - - #publicContactSupportType - type: B542B606-ACC6-4629-ADEF-4D8EE2F01222 - contacts: [ email ] - - #tenantSpecificInvitationExternalUserType - type: 497dada5-eccc-4bc0-9e0b-63e22b4eb0be - contacts: [ email ] - - #tenantSpecificInvitationExistingUserType - type: b3809c17-d1e4-420a-919c-828564114191 - contacts: [ inapp, email ] - message: - email: - flows: - - #planInvitationExternalUser - key: 065DEECD-21BB-44AF-9983-E660FDF24BC4 - subject-path: classpath:notification_templates/planinvitationexternaluser/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/planinvitationexternaluser/email/body.{language}.html - body-field-options: - mandatory: [ "{planname}", "{planrole}", "{installation-url}", "{confirmationToken}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{planname}]': null - '[{planrole}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #planInvitationExistingUser - key: 4904dea2-5079-46d3-83be-3a19c9ab45dc - subject-path: classpath:notification_templates/planinvitationexistinguser/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/planinvitationexistinguser/email/body.{language}.html - body-field-options: - mandatory: [ "{planname}", "{planrole}", "{reasonName}", "{installation-url}", "{id}"] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{planname}]': null - '[{planrole}]': null - '[{reasonName}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #planModified - key: 4542262A-22F8-4BAA-9DB6-1C8E70AC1DBB - subject-path: classpath:notification_templates/planmodified/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/planmodified/email/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #planFinalised - key: 90DB0B46-42DE-BD89-AEBF-6F27EFEB256E - subject-path: classpath:notification_templates/planfinalised/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/planfinalised/email/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #desriptionCreated - key: 8965b1d5-99a6-4acf-9016-c0d0ce341364 - subject-path: classpath:notification_templates/descriptioncreated/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptioncreated/email/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #desriptionModified - key: 4FDBFA80-7A71-4A69-B854-67CBB70648F1 - subject-path: classpath:notification_templates/descriptionmodified/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptionmodified/email/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #descriptionFinalised - key: 33790bad-94d4-488a-8ee2-7f6295ca18ea - subject-path: classpath:notification_templates/descriptionfinalised/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptionfinalised/email/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #descriptionAnnotationCreated - key: db1e99d2-a240-4e75-9bb2-ef25b234c1f0 - subject-path: classpath:notification_templates/descriptionannotationcreated/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptionannotationcreated/email/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #mergeAccountConfirmation - key: BFE68845-CB05-4C5A-A03D-29161A7C9660 - subject-path: classpath:notification_templates/mergeacountconfirmation/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/mergeacountconfirmation/email/body.{language}.html - body-field-options: - mandatory: [ "{userName}", "{installation-url}", "{confirmationToken}" ] - optional: - - key: "{expiration_time}" - value: --- - formatting: - '[{userName}]': null - '[{installation-url}]': null - '[{expiration_time}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #removeCredentialConfirmation - key: C9BC3F16-057E-4BBA-8A5F-36BD835E5604 - subject-path: classpath:notification_templates/removecredentialconfirmation/email/subject.{language}.txt - subject-field-options: - mandatory: [ "{installation-url}", "{confirmationToken}" ] - optional: [ ] - body-path: classpath:notification_templates/removecredentialconfirmation/email/body.{language}.html - body-field-options: - mandatory: [ ] - optional: - - key: "{email}" - value: email - - key: "{expiration_time}" - value: -- - formatting: - '[{email}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #planDeposit - key: 55736F7A-83AB-4190-AF43-9D031A6F9612 - subject-path: classpath:notification_templates/plandeposit/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/plandeposit/email/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #descriptionTemplateInvitation - key: 223BB607-EFA1-4CE7-99EC-4BEABFEF9A8B - subject-path: classpath:notification_templates/descriptiontemplateinvitation/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptiontemplateinvitation/email/body.{language}.html - body-field-options: - mandatory: [ "{templateName}", "{installation-url}", "{templateID}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{templateName}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #contactSupportType - key: 5B1D6C52-88F9-418B-9B8A-6F1F963D9EAD - subject-path: classpath:notification_templates/contactsupport/email/subject.{language}.txt - subject-field-options: - mandatory: [ "{subject}" ] - optional: [ ] - body-path: classpath:notification_templates/contactsupport/email/body.{language}.html - body-field-options: - mandatory: [ "{description}", "{email}" ] - formatting: - '[{subject}]': null - '[{description}]': null - '[{email}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #publicContactSupportType - key: B542B606-ACC6-4629-ADEF-4D8EE2F01222 - subject-path: classpath:notification_templates/publiccontactsupport/email/subject.{language}.txt - subject-field-options: - mandatory: [ "{subject}" ] - optional: [ ] - body-path: classpath:notification_templates/publiccontactsupport/email/body.{language}.html - body-field-options: - mandatory: [ "{description}", "{email}", "{name}" ] - formatting: - '[{subject}]': null - '[{description}]': null - '[{email}]': null - '[{name}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #tenantSpecificInvitationExternalUserType - key: 497dada5-eccc-4bc0-9e0b-63e22b4eb0be - subject-path: classpath:notification_templates/tenantspecificinvitationexternaluser/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/tenantspecificinvitationexternaluser/email/body.{language}.html - body-field-options: - mandatory: [ "{userName}", "{installation-url}", "{confirmationToken}" ] - optional: - - key: "{expiration_time}" - value: --- - - key: "{tenantName}" - value: OpenCDMP - formatting: - '[{userName}]': null - '[{tenantName}]': null - '[{installation-url}]': null - '[{expiration_time}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #tenantSpecificInvitationExistingUserType - key: b3809c17-d1e4-420a-919c-828564114191 - subject-path: classpath:notification_templates/tenantspecificinvitationexistinguser/email/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/tenantspecificinvitationexistinguser/email/body.{language}.html - body-field-options: - mandatory: [ "{userName}", "{installation-url}", "{confirmationToken}" ] - optional: - - key: "{expiration_time}" - value: --- - - key: "{tenantName}" - value: OpenCDMP - formatting: - '[{userName}]': null - '[{tenantName}]': null - '[{installation-url}]': null - '[{expiration_time}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - template-cache: - prefix: ${CACHE_DISAMBIGUATION:} - key-pattern: "{prefix}:Notification_Message_Email_Template:{key}:v0" - in-app: - flows: - - #planInvitationExistingUser - key: 4904dea2-5079-46d3-83be-3a19c9ab45dc - subject-path: classpath:notification_templates/planinvitationexistinguser/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/planinvitationexistinguser/inapp/body.{language}.html - body-field-options: - mandatory: [ "{planname}", "{planrole}", "{reasonName}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{planname}]': null - '[{planrole}]': null - '[{reasonName}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #planModified - key: 4542262A-22F8-4BAA-9DB6-1C8E70AC1DBB - subject-path: classpath:notification_templates/planmodified/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/planmodified/inapp/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{installation-url}]': null - '[{id}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #planFinalised - key: 90DB0B46-42DE-BD89-AEBF-6F27EFEB256E - subject-path: classpath:notification_templates/planfinalised/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/planfinalised/inapp/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{installation-url}]': null - '[{id}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #desriptionCreated - key: 8965b1d5-99a6-4acf-9016-c0d0ce341364 - subject-path: classpath:notification_templates/descriptioncreated/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptioncreated/inapp/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - - #desriptionModified - key: 4FDBFA80-7A71-4A69-B854-67CBB70648F1 - subject-path: classpath:notification_templates/descriptionmodified/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptionmodified/inapp/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{installation-url}]': null - '[{id}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #descriptionFinalised - key: 33790bad-94d4-488a-8ee2-7f6295ca18ea - subject-path: classpath:notification_templates/descriptionfinalised/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptionfinalised/inapp/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{installation-url}]': null - '[{id}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #descriptionAnnotationCreated - key: db1e99d2-a240-4e75-9bb2-ef25b234c1f0 - subject-path: classpath:notification_templates/descriptionannotationcreated/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptionannotationcreated/inapp/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{installation-url}]': null - '[{id}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #mergeAccountConfirmation - key: BFE68845-CB05-4C5A-A03D-29161A7C9660 - subject-path: classpath:notification_templates/mergeacountconfirmation/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/mergeacountconfirmation/inapp/body.{language}.html - body-field-options: - mandatory: [ "{userName}", "{installation-url}", "{confirmationToken}" ] - optional: - - key: "{expiration_time}" - value: --- - - key: "{tenant-url-path}" - value: - formatting: - '[{userName}]': null - '[{installation-url}]': null - '[{confirmationToken}]': null - '[{expiration_time}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #removeCredentialConfirmation - key: C9BC3F16-057E-4BBA-8A5F-36BD835E5604 - subject-path: classpath:notification_templates/removecredentialconfirmation/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ "{installation-url}", "{confirmationToken}" ] - optional: [ ] - body-path: classpath:notification_templates/removecredentialconfirmation/inapp/body.{language}.html - body-field-options: - mandatory: [ ] - optional: - - key: "{email}" - value: email - - key: "{expiration_time}" - value: -- - - key: "{tenant-url-path}" - value: - formatting: - '[{email}]': null - '[{expiration_time}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #planDeposit - key: 55736F7A-83AB-4190-AF43-9D031A6F9612 - subject-path: classpath:notification_templates/plandeposit/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/plandeposit/inapp/body.{language}.html - body-field-options: - mandatory: [ "{reasonName}", "{name}", "{installation-url}", "{id}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{reasonName}]': null - '[{name}]': null - '[{installation-url}]': null - '[{id}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #descriptionTemplateInvitation - key: 223BB607-EFA1-4CE7-99EC-4BEABFEF9A8B - subject-path: classpath:notification_templates/descriptiontemplateinvitation/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/descriptiontemplateinvitation/inapp/body.{language}.html - body-field-options: - mandatory: [ "{templateName}", "{installation-url}", "{templateID}" ] - optional: - - key: "{recipient}" - value: - - key: "{tenant-url-path}" - value: - formatting: - '[{templateName}]': null - '[{installation-url}]': null - '[{templateID}]': null - '[{recipient}]': null - '[{tenant-url-path}]': null - priority-key: null - cipher-fields: [ ] - - #tenantSpecificInvitationExistingUserType - key: b3809c17-d1e4-420a-919c-828564114191 - subject-path: classpath:notification_templates/tenantspecificinvitationexistinguser/inapp/subject.{language}.txt - subject-field-options: - mandatory: [ ] - optional: [ ] - body-path: classpath:notification_templates/tenantspecificinvitationexistinguser/inapp/body.{language}.html - body-field-options: - mandatory: [ "{userName}", "{installation-url}", "{confirmationToken}" ] - optional: - - key: "{expiration_time}" - value: --- - - key: "{tenantName}" - value: OpenCDMP - formatting: - '[{userName}]': null - '[{tenantName}]': null - '[{installation-url}]': null - '[{expiration_time}]': null - cc: [ ] - cc-mode: 0 - bcc: [ ] - bcc-mode: 0 - allow-attachments: false - cipher-fields: [ ] - template-cache: - prefix: ${CACHE_DISAMBIGUATION} - key-pattern: "{prefix}:Notification_Message_InApp_Template:{key}:v0" \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/config/notification.yml b/notification-service/notification-web/src/main/resources/config/notification.yml deleted file mode 100644 index f9cbdbb05..000000000 --- a/notification-service/notification-web/src/main/resources/config/notification.yml +++ /dev/null @@ -1,17 +0,0 @@ -notification: - task: - processor: - enable: true - interval-seconds: 5 - options: - retry-threshold: 300 - max-retry-delay-seconds: 10800 - too-old-to-send-seconds: 36000 - too-old-to-track-seconds: 604800 - overrides: [] - ad-hoc-config: - ad-hoc-notification-type: null - override-cache: - template-cache: - prefix: ${CACHE_DISAMBIGUATION:} - key-pattern: "{prefix}:Notification_Override_Template:{tenant}:{type}:{channel}:{{language}}:v0" \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/config/permissions.yml b/notification-service/notification-web/src/main/resources/config/permissions.yml deleted file mode 100644 index bd754c750..000000000 --- a/notification-service/notification-web/src/main/resources/config/permissions.yml +++ /dev/null @@ -1,193 +0,0 @@ -permissions: - extendedClaims: [ ] - policies: - - # 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 - # UserContactInfo - BrowseUserContactInfo: - roles: - - Admin - - InstallationAdmin - clients: [ "opencdmp-api-dev" ] - allowAnonymous: false - allowAuthenticated: false - EditUserContactInfo: - roles: - - Admin - - InstallationAdmin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - DeleteUserContactInfo: - roles: - - Admin - - InstallationAdmin - claims: [ ] - clients: [ "opencdmp-api-dev" ] - allowAnonymous: false - allowAuthenticated: false - #Notification - BrowseNotification: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - EditNotification: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - DeleteNotification: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - # TenantConfiguration - BrowseTenantConfiguration: - roles: - - Admin - - TenantAdmin - claims: [ ] - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - EditTenantConfiguration: - roles: - - Admin - - TenantAdmin - clients: [ "opencdmp-api-dev" ] - allowAnonymous: false - allowAuthenticated: false - DeleteTenantConfiguration: - roles: - - Admin - - TenantAdmin - clients: [ "opencdmp-api-dev" ] - allowAnonymous: false - allowAuthenticated: false - #User Notification Preference - BrowseUserNotificationPreference: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - EditUserNotificationPreference: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - - # ViewPage Permissions - ViewNotificationPage: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - ViewNotificationEventRulePage: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - ViewInAppNotificationPage: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - ViewNotificationTemplatePage: - roles: - - Admin - - TenantAdmin - - TenantConfigManager - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - - # Notification Template Permissions - BrowseNotificationTemplate: - roles: - - Admin - - TenantAdmin - - TenantConfigManager - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - EditNotificationTemplate: - roles: - - Admin - - TenantAdmin - - TenantConfigManager - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - DeleteNotificationTemplate: - roles: - - Admin - - TenantAdmin - - TenantConfigManager - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - - # In App Notification Permissions - BrowseInAppNotification: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false - DeleteInAppNotification: - roles: - - Admin - clients: [ ] - allowAnonymous: false - allowAuthenticated: false \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/config/queue-devel.yml b/notification-service/notification-web/src/main/resources/config/queue-devel.yml deleted file mode 100644 index 1c761d9e5..000000000 --- a/notification-service/notification-web/src/main/resources/config/queue-devel.yml +++ /dev/null @@ -1,21 +0,0 @@ -queue: - rabbitmq: - enable: true - durable: true - queue: cite_dmp_devel_notification_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/notification-service/notification-web/src/main/resources/config/queue.yml b/notification-service/notification-web/src/main/resources/config/queue.yml deleted file mode 100644 index 64bbeb07e..000000000 --- a/notification-service/notification-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 - rabbitmq: - enable: false - interval-seconds: 5 - 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-default-locale-removal-topic: tenant_default_locale.remove - tenant-default-locale-touched-topic: tenant_default_locale.touch - notify-topic: notification.notify - tenant-removal-topic: tenant.remove - tenant-touched-topic: tenant.touch - user-removal-topic: user.remove - user-touched-topic: user.touch - rabbitmq: - enable: false - interval-seconds: 5 - 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/notification-service/notification-web/src/main/resources/config/security-devel.yml b/notification-service/notification-web/src/main/resources/config/security-devel.yml deleted file mode 100644 index dbb097b19..000000000 --- a/notification-service/notification-web/src/main/resources/config/security-devel.yml +++ /dev/null @@ -1,6 +0,0 @@ -web: - security: - idp: - resource: - jwt: - audiences: [ "dmp_notification" ] \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/config/security.yml b/notification-service/notification-web/src/main/resources/config/security.yml deleted file mode 100644 index 8f41034ac..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/server-devel.yml b/notification-service/notification-web/src/main/resources/config/server-devel.yml deleted file mode 100644 index 2a628f82f..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/server.yml b/notification-service/notification-web/src/main/resources/config/server.yml deleted file mode 100644 index 9a4a97cbc..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/tenant-devel.yml b/notification-service/notification-web/src/main/resources/config/tenant-devel.yml deleted file mode 100644 index f2149021a..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/config/tenant.yml b/notification-service/notification-web/src/main/resources/config/tenant.yml deleted file mode 100644 index 11cb03a00..000000000 --- a/notification-service/notification-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/notification/principal/me' ] \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/logging/logback-dev.xml b/notification-service/notification-web/src/main/resources/logging/logback-dev.xml deleted file mode 100644 index e304c45df..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/messages/messages.properties b/notification-service/notification-web/src/main/resources/messages/messages.properties deleted file mode 100644 index 93d6cd27a..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/messages/messages_el.properties b/notification-service/notification-web/src/main/resources/messages/messages_el.properties deleted file mode 100644 index 4d060cc58..000000000 --- a/notification-service/notification-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/notification-service/notification-web/src/main/resources/notification_templates/contactsupport/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/contactsupport/email/body.en.html deleted file mode 100644 index f2c3845c0..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/contactsupport/email/body.en.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - OpenCDMP Notification - - -{description} -
-
-Send by user: {email} - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/contactsupport/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/contactsupport/email/subject.en.txt deleted file mode 100644 index 9140c4034..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/contactsupport/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - {subject} \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/email/body.en.html deleted file mode 100644 index dc9b2e8de..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

{reasonName} made a comment on the Description {name}.

- - - - - - - -
- - - - - - -
Click here to view it.
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/email/subject.en.txt deleted file mode 100644 index aa807d661..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Comment for Description \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/inapp/body.en.html deleted file mode 100644 index d16a3e0b2..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/inapp/body.en.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - -

Dear {recipient},

-

{reasonName} made a comment on the Description {name}.

- Click here to view it. - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/inapp/subject.en.txt deleted file mode 100644 index aa807d661..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionannotationcreated/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Comment for Description \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/email/body.en.html deleted file mode 100644 index f021ad9ea..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

{reasonName} created new Description with name {name}.

- - - - - - - -
- - - - - - -
Click here to view it.
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/email/subject.en.txt deleted file mode 100644 index c680595b0..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Description Created \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/inapp/body.en.html deleted file mode 100644 index e28ad9712..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/inapp/body.en.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - -

Dear {recipient},

-

{reasonName} created new Description with name {name}.

- Click here to view it. - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/inapp/subject.en.txt deleted file mode 100644 index c680595b0..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptioncreated/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Description Created \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/email/body.en.html deleted file mode 100644 index d9699a6f6..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

{reasonName} just finalised the Description {name}.

- - - - - - - -
- - - - - - -
Click here to view it.
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/email/subject.en.txt deleted file mode 100644 index 4809b12c1..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Description Finalised \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/inapp/body.en.html deleted file mode 100644 index a21e28549..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/inapp/body.en.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - -

Dear {recipient},

-

{reasonName} just finalised the Description {name}.

- Click here to view it. - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/inapp/subject.en.txt deleted file mode 100644 index 4809b12c1..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionfinalised/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Description Finalised \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/email/body.en.html deleted file mode 100644 index 910958d3c..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

{reasonName} just made changes to the Description {name}.

- - - - - - - -
- - - - - - -
Click here to view it.
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/email/subject.en.txt deleted file mode 100644 index a40529163..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Description Modified \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/inapp/body.en.html deleted file mode 100644 index dd96fb870..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/inapp/body.en.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - -

Dear {recipient},

-

{reasonName} just made changes to the Description {name}.

- Click here to view it. - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/inapp/subject.en.txt deleted file mode 100644 index a40529163..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptionmodified/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Description Modified \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/email/body.en.html deleted file mode 100644 index a6a71319a..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/email/body.en.html +++ /dev/null @@ -1,305 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

You have been invited to co-develop the Template {templateName}.

-

Click the button to redirect to {templateName}.

- - - - - - - -
- - - - - - -
{templateName}
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/email/subject.en.txt deleted file mode 100644 index 61ecc7bfd..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Description Template Invite \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/inapp/body.en.html deleted file mode 100644 index 94efa2da6..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/inapp/body.en.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - -

Dear {recipient},

-

You have been invited to co-develop the Template {templateName}.

-

Click the button to redirect to {templateName}.

- {templateName} - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/inapp/subject.en.txt deleted file mode 100644 index 61ecc7bfd..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/descriptiontemplateinvitation/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Description Template Invite \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/email/body.en.html deleted file mode 100644 index 90b7607e6..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
- OpenCDMP -

User {userName} have sent you a merge Request.

-

Please confirm that you want to merge your {installation-url} account with that account. -
The link will expire in {expiration_time}.

- - - - - - -
- - - - - - -
Confirm Merge Request
-
-
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/email/subject.en.txt deleted file mode 100644 index 3c94ab18d..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Merge Account Confirmation \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/inapp/body.en.html deleted file mode 100644 index fd2e7a0c7..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/inapp/body.en.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - OpenCDMP -

User {userName} have sent you a merge Request.

-

Please confirm that you want to merge your {installation-url} account with that account. -
The link will expire in {expiration_time}.

- Confirm Merge Request - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/inapp/subject.en.txt deleted file mode 100644 index 3c94ab18d..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/mergeacountconfirmation/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Merge Account Confirmation \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/email/body.en.html deleted file mode 100644 index 1937f6eae..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

{reasonName} just publish the {name}.

- - - - - - - -
- - - - - - -
Click here to view it.
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/email/subject.en.txt deleted file mode 100644 index a9831981b..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Deposit \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/inapp/body.en.html deleted file mode 100644 index 7002e6fcd..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/inapp/body.en.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - -

Dear {recipient},

-

{reasonName} just publish the {name}.

- Click here to view it. - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/inapp/subject.en.txt deleted file mode 100644 index a9831981b..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/plandeposit/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Deposit \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/email/body.en.html deleted file mode 100644 index 69ddbc8dd..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

{reasonName} just finalised the Plan {name}.

- - - - - - - -
- - - - - - -
Click here to view it.
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/email/subject.en.txt deleted file mode 100644 index 0f3ce0f3e..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Finalised \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/inapp/body.en.html deleted file mode 100644 index 185926b1d..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/inapp/body.en.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - -

Dear {recipient},

-

{reasonName} just finalised the Plan {name}.

- Click here to view it. - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/inapp/subject.en.txt deleted file mode 100644 index 0f3ce0f3e..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planfinalised/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Finalised \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/email/body.en.html deleted file mode 100644 index 3da19a3a6..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

{reasonName} just add you to collaborate to the Plan {planname} with role {planrole}.

-

Click the button to redirect to {planname}.

- - - - - - - -
- - - - - - -
Join
-
-
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/email/subject.en.txt deleted file mode 100644 index 54de9f6b1..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Invite \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/inapp/body.en.html deleted file mode 100644 index 96a721f3a..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/inapp/body.en.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - OpenCDMP Notification - - -

Dear {recipient},

-

{reasonName} just added you to collaborate to the Plan {planname} with role {planrole}.

-

Click the button to redirect to {planname}.

- Join - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/inapp/subject.en.txt deleted file mode 100644 index 54de9f6b1..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexistinguser/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Invite \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexternaluser/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexternaluser/email/body.en.html deleted file mode 100644 index fb3551b1e..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexternaluser/email/body.en.html +++ /dev/null @@ -1,305 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

You have been invited to collaborate to the Plan {planname} with role {planrole}.

-

Click the button to redirect to {planname}.

- - - - - - - -
- - - - - - -
Join
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexternaluser/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexternaluser/email/subject.en.txt deleted file mode 100644 index 54de9f6b1..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planinvitationexternaluser/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Invite \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planmodified/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/planmodified/email/body.en.html deleted file mode 100644 index 8cd6a97b0..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planmodified/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
-

Dear {recipient},

-

{reasonName} just made changes to the Plan {name}.

- - - - - - - -
- - - - - - -
Click here to view it.
-
- -
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planmodified/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/planmodified/email/subject.en.txt deleted file mode 100644 index df045f3ca..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planmodified/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Modified \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planmodified/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/planmodified/inapp/body.en.html deleted file mode 100644 index 57dfa1277..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planmodified/inapp/body.en.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - -

Dear {recipient},

-

{reasonName} just made changes to the Plan {name}.

- Click here to view it. - - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/planmodified/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/planmodified/inapp/subject.en.txt deleted file mode 100644 index df045f3ca..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/planmodified/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Plan Modified \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/publiccontactsupport/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/publiccontactsupport/email/body.en.html deleted file mode 100644 index f2c3845c0..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/publiccontactsupport/email/body.en.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - OpenCDMP Notification - - -{description} -
-
-Send by user: {email} - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/publiccontactsupport/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/publiccontactsupport/email/subject.en.txt deleted file mode 100644 index 9140c4034..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/publiccontactsupport/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - {subject} \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/email/body.en.html deleted file mode 100644 index 059cae435..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
- OpenCDMP -

You have made a request to unlink your email account in OpenCDMP.

-

Please confirm that you want to unlink your {email} account. -
The link will expire in {expiration_time}.

- - - - - - -
- - - - - - -
Confirm Unlink Request
-
-
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/email/subject.en.txt deleted file mode 100644 index d942b4dbe..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Unlink Email Confirmation \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/inapp/body.en.html deleted file mode 100644 index 4a3d5dd30..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/inapp/body.en.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - OpenCDMP -

You have made a request to unlink your email account in OpenCDMP.

-

Please confirm that you want to unlink your {email} account. -
The link will expire in {expiration_time}.

- Confirm Unlink Request - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/inapp/subject.en.txt deleted file mode 100644 index d942b4dbe..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/removecredentialconfirmation/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Unlink Email Confirmation \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/email/body.en.html deleted file mode 100644 index 4dfb9edc0..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
- OpenCDMP -

User {userName} invited you to join the {tenantName}.

-

Please confirm that you want to continue. -
The link will expire in {expiration_time}.

- - - - - - -
- - - - - - -
Confirm Invitation
-
-
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/email/subject.en.txt deleted file mode 100644 index f10926ab7..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Invitation \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/inapp/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/inapp/body.en.html deleted file mode 100644 index cd51b691b..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/inapp/body.en.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - OpenCDMP -

User {userName} invited you to join the {tenantName}.

-

Please confirm that you want to continue. -
The link will expire in {expiration_time}.

- Confirm Invitation - - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/inapp/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/inapp/subject.en.txt deleted file mode 100644 index f10926ab7..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexistinguser/inapp/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Invitation \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexternaluser/email/body.en.html b/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexternaluser/email/body.en.html deleted file mode 100644 index 4dfb9edc0..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexternaluser/email/body.en.html +++ /dev/null @@ -1,304 +0,0 @@ - - - - - - OpenCDMP Notification - - - - - - - - - -
  -
- - - This is preheader text. Some clients will show this text as a preview. - - - - - - - - -
- - - - -
- OpenCDMP -

User {userName} invited you to join the {tenantName}.

-

Please confirm that you want to continue. -
The link will expire in {expiration_time}.

- - - - - - -
- - - - - - -
Confirm Invitation
-
-
-
- - - - - - -
-
 
- - \ No newline at end of file diff --git a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexternaluser/email/subject.en.txt b/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexternaluser/email/subject.en.txt deleted file mode 100644 index f10926ab7..000000000 --- a/notification-service/notification-web/src/main/resources/notification_templates/tenantspecificinvitationexternaluser/email/subject.en.txt +++ /dev/null @@ -1 +0,0 @@ -OpenCDMP - Invitation \ No newline at end of file diff --git a/notification-service/notification/.gitignore b/notification-service/notification/.gitignore deleted file mode 100644 index 549e00a2a..000000000 --- a/notification-service/notification/.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/notification-service/notification/pom.xml b/notification-service/notification/pom.xml deleted file mode 100644 index 388c2108c..000000000 --- a/notification-service/notification/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - 4.0.0 - - - gr.cite - notification-service-parent - ${revision} - ../pom.xml - - - notification - ${revision} - - - 21 - 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 - 1.0.0 - - - gr.cite - validation - 3.0.3 - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - - - - gr.cite - cipher - 1.0.0 - compile - - - - diff --git a/notification-service/notification/src/main/java/gr/cite/notification/audit/AuditableAction.java b/notification-service/notification/src/main/java/gr/cite/notification/audit/AuditableAction.java deleted file mode 100644 index 8fdb53f81..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/audit/AuditableAction.java +++ /dev/null @@ -1,52 +0,0 @@ -package gr.cite.notification.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 TenantConfiguration_LookupByType = new EventId(210004, "TenantConfiguration_LookupByType"); - public static final EventId Tenant_Configuration_DefaultUserLocale_Delete = new EventId(21005, "Tenant_Configuration_DefaultUserLocale_Delete"); - public static final EventId Tenant_Configuration_DefaultUserLocale_Persist = new EventId(21006, "Tenant_Configuration_DefaultUserLocale_Persist"); - public static final EventId Tenant_Configuration_Notifiers_Query = new EventId(21007, "Tenant_Configuration_Notifiers_Query"); - - 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"); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/authorization/AuthorizationFlags.java b/notification-service/notification/src/main/java/gr/cite/notification/authorization/AuthorizationFlags.java deleted file mode 100644 index 2cba3132b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/authorization/AuthorizationFlags.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.authorization; - -import java.util.EnumSet; - -public enum AuthorizationFlags { - None, Permission, Owner; - public static final EnumSet OwnerOrPermission = EnumSet.of(Owner, Permission); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/authorization/ClaimNames.java b/notification-service/notification/src/main/java/gr/cite/notification/authorization/ClaimNames.java deleted file mode 100644 index c59d6a58e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/authorization/ClaimNames.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/authorization/OwnedAuthorizationRequirement.java b/notification-service/notification/src/main/java/gr/cite/notification/authorization/OwnedAuthorizationRequirement.java deleted file mode 100644 index 8171339da..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/authorization/OwnedAuthorizationRequirement.java +++ /dev/null @@ -1,6 +0,0 @@ -package gr.cite.notification.authorization; - -import gr.cite.commons.web.authz.policy.AuthorizationRequirement; - -public class OwnedAuthorizationRequirement implements AuthorizationRequirement { -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/authorization/OwnedResource.java b/notification-service/notification/src/main/java/gr/cite/notification/authorization/OwnedResource.java deleted file mode 100644 index 124f7ba2b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/authorization/OwnedResource.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/authorization/Permission.java b/notification-service/notification/src/main/java/gr/cite/notification/authorization/Permission.java deleted file mode 100644 index 4abf5ca0f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/authorization/Permission.java +++ /dev/null @@ -1,49 +0,0 @@ -package gr.cite.notification.authorization; - -public final class Permission { - //User - public static String BrowseUser = "BrowseUser"; - public static String EditUser = "EditUser"; - public static String DeleteUser = "DeleteUser"; - - //UserContactInfo - public static String BrowseUserContactInfo = "BrowseUserContactInfo"; - public static String EditUserContactInfo = "EditUserContactInfo"; - public static String DeleteUserContactInfo = "DeleteUserContactInfo"; - - //Tenant - public static String BrowseTenant = "BrowseTenant"; - public static String EditTenant = "EditTenant"; - public static String DeleteTenant = "DeleteTenant"; - public static String AllowNoTenant = "AllowNoTenant"; - - //Notification - public static final String BrowseNotification = "BrowseNotification"; - public static String EditNotification = "EditNotification"; - public static String DeleteNotification = "DeleteNotification"; - - public static final String BrowseTenantConfiguration = "BrowseTenantConfiguration"; - public static final String EditTenantConfiguration = "EditTenantConfiguration"; - public static final String DeleteTenantConfiguration = "DeleteTenantConfiguration"; - - //Notification Preference - public static final String BrowseUserNotificationPreference = "BrowseUserNotificationPreference"; - public static final String EditUserNotificationPreference = "EditUserNotificationPreference"; - - //Notification Template - public static final String BrowseNotificationTemplate = "BrowseNotificationTemplate"; - public static String EditNotificationTemplate = "EditNotificationTemplate"; - public static String DeleteNotificationTemplate = "DeleteNotificationTemplate"; - - //InApp Notification - public static final String BrowseInAppNotification = "BrowseInAppNotification"; - public static String DeleteInAppNotification = "DeleteInAppNotification"; - - // UI Pages - public static String ViewTenantConfigurationPage = "ViewTenantConfigurationPage"; - public static String ViewNotificationPage = "ViewNotificationPage"; - public static String ViewNotificationEventRulePage = "ViewNotificationEventRulePage"; - public static String ViewInAppNotificationPage = "ViewInAppNotificationPage"; - public static String ViewNotificationTemplatePage = "ViewNotificationTemplatePage"; - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/JsonHandlingService.java b/notification-service/notification/src/main/java/gr/cite/notification/common/JsonHandlingService.java deleted file mode 100644 index c76b3d7c7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/JsonHandlingService.java +++ /dev/null @@ -1,45 +0,0 @@ -package gr.cite.notification.common; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -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; - -@Component -public class JsonHandlingService { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(JsonHandlingService.class)); - private final ObjectMapper objectMapper = new ObjectMapper(); - - public String toJson(Object item) throws JsonProcessingException { - if (item == null) return null; - return objectMapper.writeValueAsString(item); - } - - public String toJsonSafe(Object item) { - if (item == null) return null; - try { - return objectMapper.writeValueAsString(item); - } catch (Exception ex) { - logger.error("Json Parsing Error: " + ex.getLocalizedMessage(), ex); - return null; - } - } - - public T fromJson(Class type, String json) throws JsonProcessingException { - if (json == null) return null; - return objectMapper.readValue(json, type); - } - - public T fromJsonSafe(Class type, String json) { - if (json == null) return null; - try { - return objectMapper.readValue(json, type); - } catch (Exception ex) { - logger.error("Json Parsing Error: " + ex.getLocalizedMessage(), ex); - return null; - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/StringUtils.java b/notification-service/notification/src/main/java/gr/cite/notification/common/StringUtils.java deleted file mode 100644 index 0a73b94ef..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/StringUtils.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.common; - -public class StringUtils { - - public static Boolean isNullOrEmpty(String string) { - return string == null || string.isEmpty(); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java b/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java deleted file mode 100644 index 1207e4580..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/XmlHandlingService.java +++ /dev/null @@ -1,117 +0,0 @@ -package gr.cite.notification.common; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.notification.common.types.xml.XmlSerializable; -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 jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Marshaller; -import jakarta.xml.bind.Unmarshaller; -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/notification-service/notification/src/main/java/gr/cite/notification/common/enums/ContactInfoType.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/ContactInfoType.java deleted file mode 100644 index e0d52875c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/ContactInfoType.java +++ /dev/null @@ -1,30 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.HashMap; -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/notification-service/notification/src/main/java/gr/cite/notification/common/enums/EmailOverrideMode.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/EmailOverrideMode.java deleted file mode 100644 index 5af7c2f1e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/EmailOverrideMode.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum EmailOverrideMode implements DatabaseEnum { - NotOverride((short)0), - Additive((short)1), - Replace((short)2); - - private final Short value; - - EmailOverrideMode(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(EmailOverrideMode.class); - - public static EmailOverrideMode of(Short i) { - return map.get(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/EnumUtils.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/EnumUtils.java deleted file mode 100644 index fa581f847..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/EnumUtils.java +++ /dev/null @@ -1,16 +0,0 @@ -package gr.cite.notification.common.enums; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/enums/InAppNotificationPriority.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/InAppNotificationPriority.java deleted file mode 100644 index e85733fd2..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/InAppNotificationPriority.java +++ /dev/null @@ -1,30 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum InAppNotificationPriority implements DatabaseEnum { - LOW((short)-1), - NORMAL((short)0), - HIGH((short)1), - EMERGENCY((short)2); - - private final Short value; - - InAppNotificationPriority(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(InAppNotificationPriority.class); - - public static InAppNotificationPriority of(Short i) { - return map.get(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/IsActive.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/IsActive.java deleted file mode 100644 index 10b9dc528..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/IsActive.java +++ /dev/null @@ -1,28 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationContactType.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationContactType.java deleted file mode 100644 index 8b30d02e7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationContactType.java +++ /dev/null @@ -1,30 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum NotificationContactType implements DatabaseEnum { - EMAIL((short) 0), - SLACK_BROADCAST((short) 1), - SMS((short) 2), - IN_APP((short) 3); - - private final Short value; - - NotificationContactType(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(NotificationContactType.class); - - public static NotificationContactType of(Short i) { - return map.get(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationDataType.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationDataType.java deleted file mode 100644 index a0d9918b3..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationDataType.java +++ /dev/null @@ -1,31 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum NotificationDataType implements DatabaseEnum { - Integer((short)0), - Decimal((short)1), - Double((short)2), - DateTime((short)3), - //TimeSpan(4), - String((short)5); - private final Short value; - - NotificationDataType(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(NotificationDataType.class); - - public static NotificationDataType of(Short i) { - return map.get(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationInAppTracking.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationInAppTracking.java deleted file mode 100644 index 97957b507..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationInAppTracking.java +++ /dev/null @@ -1,28 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum NotificationInAppTracking implements DatabaseEnum { - STORED((short)0), - DELIVERED((short)1); - - private final Short value; - - NotificationInAppTracking(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(NotificationInAppTracking.class); - - public static NotificationInAppTracking of(Short i) { - return map.get(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationNotifyState.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationNotifyState.java deleted file mode 100644 index 1dce8ba38..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationNotifyState.java +++ /dev/null @@ -1,33 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum NotificationNotifyState implements DatabaseEnum { - - PENDING((short)0), - PROCESSING((short)1), - SUCCESSFUL((short)2), - ERROR((short)3), - OMITTED((short)4); - - private final Short value; - - NotificationNotifyState(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(NotificationNotifyState.class); - - public static NotificationNotifyState of(Short i) { - return map.get(i); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTemplateChannel.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTemplateChannel.java deleted file mode 100644 index d484f9198..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTemplateChannel.java +++ /dev/null @@ -1,30 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum NotificationTemplateChannel implements DatabaseEnum { - - Email((short)0), - InApp((short)1); - - private final Short value; - - NotificationTemplateChannel(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(NotificationTemplateChannel.class); - - public static NotificationTemplateChannel of(Short i) { - return map.get(i); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTemplateKind.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTemplateKind.java deleted file mode 100644 index a735ececf..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTemplateKind.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum NotificationTemplateKind implements DatabaseEnum { - - Draft((short)0), - Secondary((short)1), - Primary((short)2), - Default((short)3); - - private final Short value; - - NotificationTemplateKind(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(NotificationTemplateKind.class); - - public static NotificationTemplateKind of(Short i) { - return map.get(i); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTrackingProcess.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTrackingProcess.java deleted file mode 100644 index 61777b4cb..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTrackingProcess.java +++ /dev/null @@ -1,31 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum NotificationTrackingProcess implements DatabaseEnum { - PENDING((short)0), - PROCESSING((short)1), - COMPLETED((short)2), - ERROR((short)3), - OMITTED((short)4); - - private final Short value; - - NotificationTrackingProcess(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(NotificationTrackingProcess.class); - - public static NotificationTrackingProcess of(Short i) { - return map.get(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTrackingState.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTrackingState.java deleted file mode 100644 index 4a3998d88..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/NotificationTrackingState.java +++ /dev/null @@ -1,40 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum NotificationTrackingState implements DatabaseEnum { - /* * - * Initial state - */ - UNDEFINED((short)0), - /* * - * Final for notifiers that do not provide any kind of tracking - */ - NA((short)1), - QUEUED((short)2), - SENT((short)3), - DELIVERED((short)4), - UNDELIVERED((short)5), - FAILED((short)6), - UNSENT((short)7); - - private final Short value; - - NotificationTrackingState(Short value) { - this.value = value; - } - - @JsonValue - public Short getValue() { - return value; - } - - private static final Map map = EnumUtils.getEnumValueMap(NotificationTrackingState.class); - - public static NotificationTrackingState of(Short i) { - return map.get(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/TenantConfigurationType.java b/notification-service/notification/src/main/java/gr/cite/notification/common/enums/TenantConfigurationType.java deleted file mode 100644 index 0f7b4f739..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/enums/TenantConfigurationType.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.notification.common.enums; - -import com.fasterxml.jackson.annotation.JsonValue; -import gr.cite.notification.data.conventers.DatabaseEnum; - -import java.util.Map; - -public enum TenantConfigurationType implements DatabaseEnum { - NotifierList((short)0), - DefaultUserLocale((short) 1), - ; - - 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/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java b/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java deleted file mode 100644 index 59ffd49b4..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/lock/LockByKeyManager.java +++ /dev/null @@ -1,58 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java deleted file mode 100644 index 726be9a97..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestAttributes.java +++ /dev/null @@ -1,125 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestScope.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestScope.java deleted file mode 100644 index e8b6716e2..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/fake/FakeRequestScope.java +++ /dev/null @@ -1,40 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/MultitenancyConfiguration.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/MultitenancyConfiguration.java deleted file mode 100644 index 52ed9fa9f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/MultitenancyConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/MultitenancyProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/MultitenancyProperties.java deleted file mode 100644 index 7fedb1b92..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/MultitenancyProperties.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java deleted file mode 100644 index c09af9a5e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScope.java +++ /dev/null @@ -1,85 +0,0 @@ -package gr.cite.notification.common.scope.tenant; - -import gr.cite.notification.data.TenantEntityManager; -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/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScoped.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScoped.java deleted file mode 100644 index 77ecacaea..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/tenant/TenantScoped.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.common.scope.tenant; - -import java.util.UUID; - -public interface TenantScoped { - void setTenantId(UUID tenantId); - UUID getTenantId(); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/user/UserScope.java b/notification-service/notification/src/main/java/gr/cite/notification/common/scope/user/UserScope.java deleted file mode 100644 index 0315f7dac..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/scope/user/UserScope.java +++ /dev/null @@ -1,34 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/Attachment.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/Attachment.java deleted file mode 100644 index da6249e93..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/Attachment.java +++ /dev/null @@ -1,36 +0,0 @@ -package gr.cite.notification.common.types.notification; - -public class Attachment { - - private String fileRef, fileName, mimeType; - - public Attachment(String fileRef, String fileName, String mimeType) { - this.fileRef = fileRef; - this.fileName = fileName; - this.mimeType = mimeType; - } - - public String getFileRef() { - return fileRef; - } - - public void setFileRef(String fileRef) { - this.fileRef = fileRef; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getMimeType() { - return mimeType; - } - - public void setMimeType(String mimeType) { - this.mimeType = mimeType; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/ContactPair.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/ContactPair.java deleted file mode 100644 index dcb9adac2..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/ContactPair.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.common.types.notification; - -import gr.cite.notification.common.enums.ContactInfoType; - -public class ContactPair { - private ContactInfoType type; - private String contact; - - public ContactPair(ContactInfoType type, String contact) { - this.type = type; - this.contact = contact; - } - - public ContactPair() { - } - - public ContactInfoType getType() { - return type; - } - - public void setType(ContactInfoType type) { - this.type = type; - } - - public String getContact() { - return contact; - } - - public void setContact(String contact) { - this.contact = contact; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/FieldInfo.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/FieldInfo.java deleted file mode 100644 index 2170ae554..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/FieldInfo.java +++ /dev/null @@ -1,45 +0,0 @@ -package gr.cite.notification.common.types.notification; - -import gr.cite.notification.common.enums.NotificationDataType; - -public class FieldInfo { - private String key; - public static final String _key = "key"; - private NotificationDataType type; - public static final String _type = "type"; - private String value; - public static final String _value = "value"; - - public FieldInfo(String key, NotificationDataType type, String value) { - this.key = key; - this.type = type; - this.value = value; - } - - public FieldInfo() { - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public NotificationDataType getType() { - return type; - } - - public void setType(NotificationDataType type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/InAppTrackingData.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/InAppTrackingData.java deleted file mode 100644 index aeb1eb989..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/InAppTrackingData.java +++ /dev/null @@ -1,38 +0,0 @@ -package gr.cite.notification.common.types.notification; - -import java.util.List; -import java.util.UUID; - -public class InAppTrackingData { - - private UUID inAppNotificationId; - private List traces; - - public InAppTrackingData() { - } - - public InAppTrackingData(UUID inAppNotificationId) { - this.inAppNotificationId = inAppNotificationId; - } - - public InAppTrackingData(UUID inAppNotificationId, List traces) { - this.inAppNotificationId = inAppNotificationId; - this.traces = traces; - } - - public UUID getInAppNotificationId() { - return inAppNotificationId; - } - - public void setInAppNotificationId(UUID inAppNotificationId) { - this.inAppNotificationId = inAppNotificationId; - } - - public List getTraces() { - return traces; - } - - public void setTraces(List traces) { - this.traces = traces; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/NotificationContactData.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/NotificationContactData.java deleted file mode 100644 index b781a8c82..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/NotificationContactData.java +++ /dev/null @@ -1,42 +0,0 @@ -package gr.cite.notification.common.types.notification; - -import java.util.List; - -public class NotificationContactData { - private List contacts; - private List bcc; - private List cc; - - public NotificationContactData() { - } - - public NotificationContactData(List contacts, List bcc, List cc) { - this.contacts = contacts; - this.bcc = bcc; - this.cc = cc; - } - - public List getContacts() { - return contacts; - } - - public void setContacts(List contacts) { - this.contacts = contacts; - } - - public List getBcc() { - return bcc; - } - - public void setBcc(List bcc) { - this.bcc = bcc; - } - - public List getCc() { - return cc; - } - - public void setCc(List cc) { - this.cc = cc; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/NotificationFieldData.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/NotificationFieldData.java deleted file mode 100644 index 7e8dde5a6..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/NotificationFieldData.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.common.types.notification; - -import java.util.List; - -public class NotificationFieldData { - private List fields; - private List attachments; - - public NotificationFieldData(List fields, List attachments) { - this.fields = fields; - this.attachments = attachments; - } - - public NotificationFieldData() { - } - - public List getFields() { - return fields; - } - - public void setFields(List fields) { - this.fields = fields; - } - - public List getAttachments() { - return attachments; - } - - public void setAttachments(List attachments) { - this.attachments = attachments; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/RouteTrackingData.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/RouteTrackingData.java deleted file mode 100644 index 06c52701d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/RouteTrackingData.java +++ /dev/null @@ -1,30 +0,0 @@ -package gr.cite.notification.common.types.notification; - -import java.util.List; - -public class RouteTrackingData { - - private String trackingId; - private List traces; - - public RouteTrackingData(String trackingId, List traces) { - this.trackingId = trackingId; - this.traces = traces; - } - - public String getTrackingId() { - return trackingId; - } - - public void setTrackingId(String trackingId) { - this.trackingId = trackingId; - } - - public List getTraces() { - return traces; - } - - public void setTraces(List traces) { - this.traces = traces; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/TrackingTrace.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/TrackingTrace.java deleted file mode 100644 index b3bffba06..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notification/TrackingTrace.java +++ /dev/null @@ -1,33 +0,0 @@ -package gr.cite.notification.common.types.notification; - -import java.time.Instant; - -public class TrackingTrace { - - private Instant at; - private String data; - - public TrackingTrace() { - } - - public TrackingTrace(Instant at, String data) { - this.at = at; - this.data = data; - } - - public Instant getAt() { - return at; - } - - public void setAt(Instant at) { - this.at = at; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/FieldInfoEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/FieldInfoEntity.java deleted file mode 100644 index 90afc8a87..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/FieldInfoEntity.java +++ /dev/null @@ -1,42 +0,0 @@ -package gr.cite.notification.common.types.notificationtemplate; - -import gr.cite.notification.common.enums.NotificationDataType; - -public class FieldInfoEntity { - private String key; - private NotificationDataType type; - private String value; - - public FieldInfoEntity(String key, NotificationDataType type, String value) { - this.key = key; - this.type = type; - this.value = value; - } - - public FieldInfoEntity() { - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public NotificationDataType getType() { - return type; - } - - public void setType(NotificationDataType type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/FieldOptionsEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/FieldOptionsEntity.java deleted file mode 100644 index 15b24149f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/FieldOptionsEntity.java +++ /dev/null @@ -1,38 +0,0 @@ -package gr.cite.notification.common.types.notificationtemplate; - - -import java.util.List; -import java.util.Map; - -public class FieldOptionsEntity { - - private List mandatory; - - private List optional; - - private Map formatting; - - public List getMandatory() { - return mandatory; - } - - public void setMandatory(List mandatory) { - this.mandatory = mandatory; - } - - public List getOptional() { - return optional; - } - - public void setOptional(List optional) { - this.optional = optional; - } - - public Map getFormatting() { - return formatting; - } - - public void setFormatting(Map formatting) { - this.formatting = formatting; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/NotificationTemplateValueEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/NotificationTemplateValueEntity.java deleted file mode 100644 index 698bfbcd8..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/notificationtemplate/NotificationTemplateValueEntity.java +++ /dev/null @@ -1,126 +0,0 @@ -package gr.cite.notification.common.types.notificationtemplate; - -import gr.cite.notification.common.enums.EmailOverrideMode; - -import java.util.List; - -public class NotificationTemplateValueEntity { - - private String subjectText; - private String subjectKey; - private FieldOptionsEntity subjectFieldOptions; - private String bodyText; - private String bodyKey; - private String priorityKey; - private Boolean allowAttachments; - private List cc; - private EmailOverrideMode ccMode; - private List bcc; - private EmailOverrideMode bccMode; - private List extraDataKeys; - private FieldOptionsEntity bodyFieldOptions; - - public String getSubjectText() { - return subjectText; - } - - public void setSubjectText(String subjectText) { - this.subjectText = subjectText; - } - - public String getSubjectKey() { - return subjectKey; - } - - public void setSubjectKey(String subjectKey) { - this.subjectKey = subjectKey; - } - - public FieldOptionsEntity getSubjectFieldOptions() { - return subjectFieldOptions; - } - - public void setSubjectFieldOptions(FieldOptionsEntity subjectFieldOptions) { - this.subjectFieldOptions = subjectFieldOptions; - } - - public String getBodyText() { - return bodyText; - } - - public void setBodyText(String bodyText) { - this.bodyText = bodyText; - } - - public String getBodyKey() { - return bodyKey; - } - - public void setBodyKey(String bodyKey) { - this.bodyKey = bodyKey; - } - - public String getPriorityKey() { - return priorityKey; - } - - public void setPriorityKey(String priorityKey) { - this.priorityKey = priorityKey; - } - - public Boolean getAllowAttachments() { - return allowAttachments; - } - - public void setAllowAttachments(Boolean allowAttachments) { - this.allowAttachments = allowAttachments; - } - - public List getCc() { - return cc; - } - - public void setCc(List cc) { - this.cc = cc; - } - - public EmailOverrideMode getCcMode() { - return ccMode; - } - - public void setCcMode(EmailOverrideMode ccMode) { - this.ccMode = ccMode; - } - - public List getBcc() { - return bcc; - } - - public void setBcc(List bcc) { - this.bcc = bcc; - } - - public EmailOverrideMode getBccMode() { - return bccMode; - } - - public void setBccMode(EmailOverrideMode bccMode) { - this.bccMode = bccMode; - } - - public List getExtraDataKeys() { - return extraDataKeys; - } - - public void setExtraDataKeys(List extraDataKeys) { - this.extraDataKeys = extraDataKeys; - } - - public FieldOptionsEntity getBodyFieldOptions() { - return bodyFieldOptions; - } - - public void setBodyFieldOptions(FieldOptionsEntity bodyFieldOptions) { - this.bodyFieldOptions = bodyFieldOptions; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/tenantconfiguration/DefaultUserLocaleTenantConfigurationEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/tenantconfiguration/DefaultUserLocaleTenantConfigurationEntity.java deleted file mode 100644 index 6e6f29251..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/tenantconfiguration/DefaultUserLocaleTenantConfigurationEntity.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.common.types.tenantconfiguration; - -public class DefaultUserLocaleTenantConfigurationEntity { - private String timezone; - private String language; - private String culture; - - public String getTimezone() { - return timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public String getCulture() { - return culture; - } - - public void setCulture(String culture) { - this.culture = culture; - } -} - diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/tenantconfiguration/NotifierListTenantConfigurationEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/tenantconfiguration/NotifierListTenantConfigurationEntity.java deleted file mode 100644 index f98090688..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/tenantconfiguration/NotifierListTenantConfigurationEntity.java +++ /dev/null @@ -1,27 +0,0 @@ -package gr.cite.notification.common.types.tenantconfiguration; - -import gr.cite.notification.common.enums.NotificationContactType; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class NotifierListTenantConfigurationEntity { - - private Map> notifiers; - - public NotifierListTenantConfigurationEntity() { - } - - public NotifierListTenantConfigurationEntity(Map> notifiers) { - this.notifiers = notifiers; - } - - public Map> getNotifiers() { - return notifiers; - } - - public void setNotifiers(Map> notifiers) { - this.notifiers = notifiers; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/user/AdditionalInfoEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/user/AdditionalInfoEntity.java deleted file mode 100644 index efdc268bd..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/user/AdditionalInfoEntity.java +++ /dev/null @@ -1,34 +0,0 @@ -package gr.cite.notification.common.types.user; - -import java.util.UUID; - -public class AdditionalInfoEntity { - 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; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/common/types/xml/XmlBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/xml/XmlBuilder.java deleted file mode 100644 index 356bbd0a1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/xml/XmlBuilder.java +++ /dev/null @@ -1,87 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/types/xml/XmlSerializable.java b/notification-service/notification/src/main/java/gr/cite/notification/common/types/xml/XmlSerializable.java deleted file mode 100644 index 8a9d2bc7c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/types/xml/XmlSerializable.java +++ /dev/null @@ -1,11 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/common/validation/BaseValidator.java b/notification-service/notification/src/main/java/gr/cite/notification/common/validation/BaseValidator.java deleted file mode 100644 index 97f72042a..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/common/validation/BaseValidator.java +++ /dev/null @@ -1,63 +0,0 @@ -package gr.cite.notification.common.validation; - -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java b/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java deleted file mode 100644 index c6af9e3bb..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationConfig.java +++ /dev/null @@ -1,80 +0,0 @@ -package gr.cite.notification.config.notification; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.schedule.NotificationScheduleTask; -import gr.cite.notification.service.message.common.MessageBuilderBase; -import gr.cite.notification.service.notificationscheduling.NotificationSchedulingService; -import gr.cite.notification.service.notificationscheduling.NotificationSchedulingServiceImpl; -import org.springframework.beans.factory.annotation.Autowired; -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; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -@Configuration -@EnableConfigurationProperties(NotificationProperties.class) -public class NotificationConfig { - - public static class BeanQualifier { - public static final String GLOBAL_POLICIES_MAP = "globalPoliciesMap"; - public static final String FLOW_MAP = "flowMap"; - public static final String STATIC_FIELD_LIST = "staticFieldList"; - public static final String CIPHER_FIELDS = "cipherFields"; - - } - private final ApplicationContext applicationContext; - private final NotificationProperties properties; - - @Autowired - public NotificationConfig(ApplicationContext applicationContext, NotificationProperties properties) { - this.applicationContext = applicationContext; - this.properties = properties; - } - - @Bean(BeanQualifier.GLOBAL_POLICIES_MAP) - public Map> getGlobalPoliciesMap() { - return properties.getResolver().getGlobalPolicies().stream() - .collect(Collectors.toMap(NotificationProperties.Resolver.GlobalPolicy::getType, - NotificationProperties.Resolver.GlobalPolicy::getContacts)); - } - - @Bean(BeanQualifier.FLOW_MAP) - public Map> getFlowMap() { - return properties.getMessage().entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, - stringTemplateEntry -> stringTemplateEntry.getValue().getFlows() - .stream().collect(Collectors.toMap(NotificationProperties.Flow::getKey, flow -> flow)))); - } - - @Bean(BeanQualifier.STATIC_FIELD_LIST) - public List getStaticFieldList() { - return properties.getStaticFields() != null && properties.getStaticFields() - .getFields() != null ? new ArrayList<>(properties.getStaticFields() - .getFields()) : new ArrayList<>(); - } - - @Bean(BeanQualifier.CIPHER_FIELDS) - public Map getFieldCiphers() { - return properties.getMessage().values().stream().flatMap(template -> template.getFlows().stream()) - .filter(flow -> flow.getCipherFields() != null && !flow.getCipherFields().isEmpty()) - .collect(Collectors.toMap(NotificationProperties.Flow::getKey, flow -> new MessageBuilderBase.FieldCiphering(flow.getCipherFields()))); - } - - @Bean - public NotificationSchedulingService notificationSchedulingService() { - return new NotificationSchedulingServiceImpl(this.applicationContext, this.properties); - } - - @Bean - @ConditionalOnProperty(name = "notification.task.processor.enable", havingValue = "true") - public NotificationScheduleTask notificationScheduleTask() { - return new NotificationScheduleTask(this.applicationContext, this.properties); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationProperties.java deleted file mode 100644 index 1e963fcd7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/config/notification/NotificationProperties.java +++ /dev/null @@ -1,385 +0,0 @@ -package gr.cite.notification.config.notification; - -import gr.cite.notification.common.enums.EmailOverrideMode; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.types.notification.FieldInfo; -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -@ConfigurationProperties(prefix = "notification") -public class NotificationProperties { - - private final Task task; - - private final Resolver resolver; - - private final Map message; - - private final Template overrideCache; - - private final StaticFieldItems staticFields; - - public NotificationProperties(Task task, Resolver resolver, Map message, Template overrideCache, StaticFieldItems staticFields) { - this.task = task; - this.resolver = resolver; - this.message = message; - this.overrideCache = overrideCache; - this.staticFields = staticFields; - } - - public Task getTask() { - return task; - } - - public Resolver getResolver() { - return resolver; - } - - public Map getMessage() { - return message; - } - - public Template getOverrideCache() { - return overrideCache; - } - - public StaticFieldItems getStaticFields() { - return staticFields; - } - - public static class Task { - - private final Processor processor; - - public Task(Processor processor) { - this.processor = processor; - } - - public Processor getProcessor() { - return processor; - } - - public static class Processor { - - private final Boolean enable; - - private final Long intervalSeconds; - - private final Options options; - - private final List overrides; - - public Processor(Boolean enable, Long intervalSeconds, Options options, List overrides) { - this.enable = enable; - this.intervalSeconds = intervalSeconds; - this.options = options; - this.overrides = overrides; - } - - public Boolean getEnable() { - return enable; - } - - public Long getIntervalSeconds() { - return intervalSeconds; - } - - public Options getOptions() { - return options; - } - - public List getOverrides() { - return overrides; - } - - public static class Options { - - private final Long retryThreshold; - - private final Long maxRetryDelaySeconds; - - private final Long tooOldToSendSeconds; - - private final Long tooOldToTrackSeconds; - - public Options(Long retryThreshold, Long maxRetryDelaySeconds, Long tooOldToSendSeconds, Long tooOldToTrackSeconds) { - this.retryThreshold = retryThreshold; - this.maxRetryDelaySeconds = maxRetryDelaySeconds; - this.tooOldToSendSeconds = tooOldToSendSeconds; - this.tooOldToTrackSeconds = tooOldToTrackSeconds; - } - - public Long getRetryThreshold() { - return retryThreshold; - } - - public Long getMaxRetryDelaySeconds() { - return maxRetryDelaySeconds; - } - - public Long getTooOldToSendSeconds() { - return tooOldToSendSeconds; - } - - public Long getTooOldToTrackSeconds() { - return tooOldToTrackSeconds; - } - } - } - } - - public static class Resolver { - - private final List globalPolicies; - - public Resolver(List globalPolicies) { - this.globalPolicies = globalPolicies; - } - - public List getGlobalPolicies() { - return globalPolicies; - } - - public static class GlobalPolicy { - - private final UUID type; - - private final List contacts; - - public GlobalPolicy(UUID type, List contacts) { - this.type = type; - this.contacts = contacts; - } - - public UUID getType() { - return type; - } - - public List getContacts() { - return contacts; - } - } - } - - public static class Template { - - private final TemplateCache templateCache; - - private final List flows; - - public Template(TemplateCache templateCache, List flows) { - this.templateCache = templateCache; - this.flows = flows; - } - - public TemplateCache getTemplateCache() { - return templateCache; - } - - public List getFlows() { - return flows; - } - - public static class TemplateCache { - - private final String prefix; - - private final String keyPattern; - - public TemplateCache(String prefix, String keyPattern) { - this.prefix = prefix; - this.keyPattern = keyPattern; - } - - public String getPrefix() { - return prefix; - } - - public String getKeyPattern() { - return keyPattern; - } - } - } - - public static class StaticFieldItems { - - private final List Fields; - - public StaticFieldItems(List fields) { - Fields = fields; - } - - public List getFields() { - return Fields; - } - } - - public static class Field { - - private final String key; - - private final String type; - - private final String value; - - public Field(String key, String type, String value) { - this.key = key; - this.type = type; - this.value = value; - } - - public String getKey() { - return key; - } - - public String getType() { - return type; - } - - public String getValue() { - return value; - } - } - - public static class Flow { - - private final UUID key; - - private final String subjectPath; - - private final String subjectKey; - - private final FieldOption subjectFieldOptions; - - private final String bodyPath; - - private final String bodyKey; - - private final FieldOption bodyFieldOptions; - - private final List cc; - - private final EmailOverrideMode ccMode; - - private final List bcc; - - private final EmailOverrideMode bccMode; - - private final Boolean allowAttachments; - - private final List cipherFields; - - private final String priorityKey; - - private final List extraDataKeys; - - public Flow(UUID key, String subjectPath, String subjectKey, FieldOption subjectFieldOptions, String bodyPath, String bodyKey, FieldOption bodyFieldOptions, List cc, EmailOverrideMode ccMode, List bcc, EmailOverrideMode bccMode, Boolean allowAttachments, List cipherFields, String priorityKey, List extraDataKeys) { - this.key = key; - this.subjectPath = subjectPath; - this.subjectKey = subjectKey; - this.subjectFieldOptions = subjectFieldOptions; - this.bodyPath = bodyPath; - this.bodyKey = bodyKey; - this.bodyFieldOptions = bodyFieldOptions; - this.cc = cc; - this.ccMode = ccMode; - this.bcc = bcc; - this.bccMode = bccMode; - this.allowAttachments = allowAttachments; - this.cipherFields = cipherFields; - this.priorityKey = priorityKey; - this.extraDataKeys = extraDataKeys; - } - - public UUID getKey() { - return key; - } - - public String getSubjectPath() { - return subjectPath; - } - - public String getSubjectKey() { - return subjectKey; - } - - public FieldOption getSubjectFieldOptions() { - return subjectFieldOptions; - } - - public String getBodyPath() { - return bodyPath; - } - - public String getBodyKey() { - return bodyKey; - } - - public FieldOption getBodyFieldOptions() { - return bodyFieldOptions; - } - - public List getCc() { - return cc; - } - - public EmailOverrideMode getCcMode() { - return ccMode; - } - - public List getBcc() { - return bcc; - } - - public EmailOverrideMode getBccMode() { - return bccMode; - } - - public Boolean getAllowAttachments() { - return allowAttachments; - } - - public List getCipherFields() { - return cipherFields; - } - - public String getPriorityKey() { - return priorityKey; - } - - public List getExtraDataKeys() { - return extraDataKeys; - } - - public static class FieldOption { - - private final List mandatory; - - private final List optional; - - private final Map formatting; - - public FieldOption(List mandatory, List optional, Map formatting) { - this.mandatory = mandatory; - this.optional = optional; - this.formatting = formatting; - } - - public List getMandatory() { - return mandatory; - } - - public List getOptional() { - return optional; - } - - public Map getFormatting() { - return formatting; - } - - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/convention/ConventionService.java b/notification-service/notification/src/main/java/gr/cite/notification/convention/ConventionService.java deleted file mode 100644 index cfc2c3a02..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/convention/ConventionService.java +++ /dev/null @@ -1,41 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/convention/ConventionServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/convention/ConventionServiceImpl.java deleted file mode 100644 index 2ae59083c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/convention/ConventionServiceImpl.java +++ /dev/null @@ -1,150 +0,0 @@ -package gr.cite.notification.convention; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/InAppNotificationEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/InAppNotificationEntity.java deleted file mode 100644 index efbb95432..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/InAppNotificationEntity.java +++ /dev/null @@ -1,178 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.InAppNotificationPriority; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationInAppTracking; -import gr.cite.notification.data.conventers.InAppNotificationPriorityConverter; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.data.conventers.NotificationInAppTrackingConverter; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"InAppNotification\"") -public class InAppNotificationEntity extends TenantScopedBaseEntity { - - @Id - @Column(name = "\"id\"", columnDefinition = "uuid", 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 = "\"type\"", columnDefinition = "uuid", nullable = false) - private UUID type; - - public static final String _type = "type"; - - @Column(name = "\"read_time\"") - private Instant readTime; - - public static final String _readTime = "readTime"; - - @Column(name = "\"tracking_state\"", nullable = false) - @Convert(converter = NotificationInAppTrackingConverter.class) - private NotificationInAppTracking trackingState; - - public static final String _trackingState = "trackingState"; - - @Column(name = "\"priority\"", nullable = false) - @Convert(converter = InAppNotificationPriorityConverter.class) - private InAppNotificationPriority priority; - - public static final String _priority = "priority"; - - @Column(name = "\"subject\"") - private String subject; - - public static final String _subject = "subject"; - - @Column(name = "\"body\"") - private String body; - - public static final String _body = "body"; - - @Column(name = "\"extra_data\"") - private String extraData; - - public static final String _extraData = "extraData"; - - @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 UUID getType() { - return type; - } - - public void setType(UUID type) { - this.type = type; - } - - public Instant getReadTime() { - return readTime; - } - - public void setReadTime(Instant readTime) { - this.readTime = readTime; - } - - public NotificationInAppTracking getTrackingState() { - return trackingState; - } - - public void setTrackingState(NotificationInAppTracking trackingState) { - this.trackingState = trackingState; - } - - public InAppNotificationPriority getPriority() { - return priority; - } - - public void setPriority(InAppNotificationPriority priority) { - this.priority = priority; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public String getExtraData() { - return extraData; - } - - public void setExtraData(String extraData) { - this.extraData = extraData; - } - - 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/notification-service/notification/src/main/java/gr/cite/notification/data/NotificationEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/NotificationEntity.java deleted file mode 100644 index 163676aa7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/NotificationEntity.java +++ /dev/null @@ -1,247 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.*; -import gr.cite.notification.data.conventers.*; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"Notification\"") -public class NotificationEntity 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") - private UUID userId; - - public static final String _userId = "userId"; - - @Column(name = "\"tenant\"", columnDefinition = "uuid") - private UUID tenantId; - - public static final String _tenantId = "tenantId"; - - @Column(name = "\"type\"", columnDefinition = "uuid", nullable = false) - private UUID type; - - public static final String _type = "type"; - - @Column(name = "\"contact_type_hint\"") - @Convert(converter = NotificationContactTypeConverter.class) - private NotificationContactType contactTypeHint; - - public static final String _contactTypeHint = "contactTypeHint"; - - @Column(name = "\"contact_hint\"", length = _contactHintLength) - private String contactHint; - - public static final String _contactHint = "contactHint"; - - public static final int _contactHintLength = 200; - - @Column(name = "\"notify_state\"", nullable = false) - @Convert(converter = NotificationNotifyStateConverter.class) - private NotificationNotifyState notifyState; - - public static final String _notifyState = "notifyState"; - - @Column(name = "\"notified_with\"") - @Convert(converter = NotificationContactTypeConverter.class) - private NotificationContactType notifiedWith; - - public static final String _notifiedWith = "notifiedWith"; - - @Column(name = "\"notified_at\"") - private Instant notifiedAt; - - public static final String _notifiedAt = "notifiedAt"; - - @Column(name = "\"data\"") - private String data; - - public static final String _data = "data"; - - @Column(name = "\"retry_count\"") - private Integer retryCount; - - public static final String _retryCount = "retryCount"; - - @Column(name = "\"tracking_state\"", nullable = false) - @Convert(converter = NotificationTrackingStateConverter.class) - private NotificationTrackingState trackingState; - - public static final String _trackingState = "trackingState"; - - @Column(name = "\"tracking_process\"", nullable = false) - @Convert(converter = NotificationTrackingProcessConverter.class) - private NotificationTrackingProcess trackingProcess; - - public static final String _trackingProcess = "trackingProcess"; - - @Column(name = "\"tracking_data\"") - private String trackingData; - - public static final String _trackingData = "trackingData"; - - @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"; - - 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; - } - - @Override - public UUID getTenantId() { - return tenantId; - } - - @Override - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - - public UUID getType() { - return type; - } - - public void setType(UUID type) { - this.type = type; - } - - public NotificationContactType getContactTypeHint() { - return contactTypeHint; - } - - public void setContactTypeHint(NotificationContactType contactTypeHint) { - this.contactTypeHint = contactTypeHint; - } - - public String getContactHint() { - return contactHint; - } - - public void setContactHint(String contactHint) { - this.contactHint = contactHint; - } - - public NotificationNotifyState getNotifyState() { - return notifyState; - } - - public void setNotifyState(NotificationNotifyState notifyState) { - this.notifyState = notifyState; - } - - public NotificationContactType getNotifiedWith() { - return notifiedWith; - } - - public void setNotifiedWith(NotificationContactType notifiedWith) { - this.notifiedWith = notifiedWith; - } - - public Instant getNotifiedAt() { - return notifiedAt; - } - - public void setNotifiedAt(Instant notifiedAt) { - this.notifiedAt = notifiedAt; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public Integer getRetryCount() { - return retryCount; - } - - public void setRetryCount(Integer retryCount) { - this.retryCount = retryCount; - } - - public NotificationTrackingState getTrackingState() { - return trackingState; - } - - public void setTrackingState(NotificationTrackingState trackingState) { - this.trackingState = trackingState; - } - - public NotificationTrackingProcess getTrackingProcess() { - return trackingProcess; - } - - public void setTrackingProcess(NotificationTrackingProcess trackingProcess) { - this.trackingProcess = trackingProcess; - } - - public String getTrackingData() { - return trackingData; - } - - public void setTrackingData(String trackingData) { - this.trackingData = trackingData; - } - - 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/notification-service/notification/src/main/java/gr/cite/notification/data/NotificationTemplateEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/NotificationTemplateEntity.java deleted file mode 100644 index f8b4db388..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/NotificationTemplateEntity.java +++ /dev/null @@ -1,140 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationTemplateChannel; -import gr.cite.notification.common.enums.NotificationTemplateKind; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.data.conventers.NotificationTemplateChannelConverter; -import gr.cite.notification.data.conventers.NotificationTemplateKindConverter; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"NotificationTemplate\"") -public class NotificationTemplateEntity extends TenantScopedBaseEntity { - - @Id - @Column(name = "\"id\"", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "\"channel\"", nullable = false) - @Convert(converter = NotificationTemplateChannelConverter.class) - private NotificationTemplateChannel channel; - - public static final String _channel = "channel"; - - @Column(name = "\"notification_type\"", columnDefinition = "uuid", nullable = false) - private UUID notificationType; - - public static final String _notificationType = "notificationType"; - - @Column(name = "\"kind\"", nullable = false) - @Convert(converter = NotificationTemplateKindConverter.class) - private NotificationTemplateKind kind; - - public static final String _kind = "kind"; - - @Column(name = "\"language_code\"", nullable = false, length = 200) - private String languageCode; - - public static final String _languageCode = "languageCode"; - - @Column(name = "\"value\"", nullable = false) - private String value; - - public static final String _value = "value"; - - @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 NotificationTemplateChannel getChannel() { - return channel; - } - - public void setChannel(NotificationTemplateChannel channel) { - this.channel = channel; - } - - public UUID getNotificationType() { - return notificationType; - } - - public void setNotificationType(UUID notificationType) { - this.notificationType = notificationType; - } - - public NotificationTemplateKind getKind() { - return kind; - } - - public void setKind(NotificationTemplateKind kind) { - this.kind = kind; - } - - public String getLanguageCode() { - return languageCode; - } - - public void setLanguageCode(String languageCode) { - this.languageCode = languageCode; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - 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/notification-service/notification/src/main/java/gr/cite/notification/data/QueueInboxEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/QueueInboxEntity.java deleted file mode 100644 index 97126f92d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/QueueInboxEntity.java +++ /dev/null @@ -1,195 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.data.conventers.QueueInboxStatusConverter; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/QueueOutboxEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/QueueOutboxEntity.java deleted file mode 100644 index ea3470c1c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/QueueOutboxEntity.java +++ /dev/null @@ -1,206 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.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\"", 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/notification-service/notification/src/main/java/gr/cite/notification/data/TenantConfigurationEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/TenantConfigurationEntity.java deleted file mode 100644 index 9b7b4cbd4..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantConfigurationEntity.java +++ /dev/null @@ -1,91 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.data.conventers.TenantConfigurationTypeConverter; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"TenantConfiguration\"") -public class TenantConfigurationEntity extends TenantScopedBaseEntity { - - @Id - @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - public final static String _id = "id"; - - @Column(name = "type", nullable = false) - @Convert(converter = TenantConfigurationTypeConverter.class) - private TenantConfigurationType type; - public final static String _type = "type"; - - @Column(name = "value", nullable = false) - private String value; - public final static String _value = "value"; - - @Column(name = "created_at", nullable = false) - private Instant createdAt; - public final static String _createdAt = "createdAt"; - - @Column(name = "updated_at", nullable = false) - private Instant updatedAt; - public final static String _updatedAt = "updatedAt"; - - @Column(name = "is_active", nullable = false) - @Convert(converter = IsActiveConverter.class) - private IsActive isActive; - public final static String _isActive = "isActive"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public TenantConfigurationType getType() { - return type; - } - - public void setType(TenantConfigurationType type) { - this.type = type; - } - - 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; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntity.java deleted file mode 100644 index f893aaa8c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntity.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java b/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java deleted file mode 100644 index 592c331dd..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantEntityManager.java +++ /dev/null @@ -1,162 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.scope.tenant.TenantScoped; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import gr.cite.notification.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 tenantFiltersDisabled; - } - - public EntityManager getEntityManager() { - return this.entityManager; - } - - public void setEntityManager(EntityManager entityManager) { - this.entityManager = entityManager; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantUserEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/TenantUserEntity.java deleted file mode 100644 index 3ff3e610e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/TenantUserEntity.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/UserContactInfoEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/UserContactInfoEntity.java deleted file mode 100644 index ee27b9b0f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/UserContactInfoEntity.java +++ /dev/null @@ -1,125 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.ContactInfoType; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.conventers.ContactInfoTypeConverter; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"UserContactInfo\"") -public class UserContactInfoEntity { - - @Id - @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "\"user\"", nullable = false) - private UUID userId; - - public static final String _userId = "userId"; - - @Column(name = "\"ordinal\"", nullable = false) - private Integer ordinal; - - public static final String _ordinal = "ordinal"; - - @Column(name = "type", length = 100, nullable = false) - @Convert(converter = ContactInfoTypeConverter.class) - private ContactInfoType type; - - public static final String _type = "type"; - - @Column(name = "value", nullable = false) - private String value; - - public static final String _value = "value"; - - @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 getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public ContactInfoType getType() { - return type; - } - - public void setType(ContactInfoType type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public Integer getOrdinal() { - return ordinal; - } - - public void setOrdinal(Integer ordinal) { - this.ordinal = ordinal; - } - - public void setValue(String value) { - this.value = value; - } - - 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/notification-service/notification/src/main/java/gr/cite/notification/data/UserCredentialEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/UserCredentialEntity.java deleted file mode 100644 index 71e08b15a..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/UserCredentialEntity.java +++ /dev/null @@ -1,82 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/UserEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/UserEntity.java deleted file mode 100644 index 477695f65..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/UserEntity.java +++ /dev/null @@ -1,96 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/UserNotificationPreferenceEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/UserNotificationPreferenceEntity.java deleted file mode 100644 index 36c64ed5b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/UserNotificationPreferenceEntity.java +++ /dev/null @@ -1,123 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.data.conventers.NotificationContactTypeConverter; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"UserNotificationPreference\"") -public class UserNotificationPreferenceEntity 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", nullable = false) - private UUID userId; - - public static final String _userId = "userId"; - - @Column(name = "type", columnDefinition = "uuid", nullable = false) - private UUID type; - - public static final String _type = "type"; - - @Column(name = "channel", nullable = false) - @Convert(converter = NotificationContactTypeConverter.class) - private NotificationContactType channel; - - public static final String _channel = "channel"; - - @Column(name = "ordinal", nullable = false) - private Integer ordinal; - - public static final String _ordinal = "ordinal"; - - @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 UUID getType() { - return type; - } - - public void setType(UUID type) { - this.type = type; - } - - public NotificationContactType getChannel() { - return channel; - } - - public void setChannel(NotificationContactType channel) { - this.channel = channel; - } - - public Integer getOrdinal() { - return ordinal; - } - - public void setOrdinal(Integer ordinal) { - this.ordinal = ordinal; - } - - 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/notification-service/notification/src/main/java/gr/cite/notification/data/UserRoleEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/UserRoleEntity.java deleted file mode 100644 index ba3e9baf1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/UserRoleEntity.java +++ /dev/null @@ -1,97 +0,0 @@ -package gr.cite.notification.data; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.conventers.IsActiveConverter; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import jakarta.persistence.*; - -import java.time.Instant; -import java.util.UUID; - -@Entity -@Table(name = "\"UserRole\"") -public class UserRoleEntity extends TenantScopedBaseEntity { - - @Id - @Column(name = "id", columnDefinition = "uuid", updatable = false, nullable = false) - private UUID id; - - public static final String _id = "id"; - - @Column(name = "role", length = UserRoleEntity._roleLength, nullable = false) - private String role; - - public static final String _role = "role"; - - public static final int _roleLength = 512; - - @Column(name = "\"user\"", 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 String getRole() { - return role; - } - - public void setRole(String role) { - this.role = role; - } - - 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/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/ContactInfoTypeConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/ContactInfoTypeConverter.java deleted file mode 100644 index 76617646e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/ContactInfoTypeConverter.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.notification.data.conventers; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/DatabaseEnum.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/DatabaseEnum.java deleted file mode 100644 index 4dd378c02..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/DatabaseEnum.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.data.conventers; - -import com.fasterxml.jackson.annotation.JsonValue; - -public interface DatabaseEnum { - @JsonValue - T getValue(); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/DatabaseEnumConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/DatabaseEnumConverter.java deleted file mode 100644 index 6cb0dd82c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/DatabaseEnumConverter.java +++ /dev/null @@ -1,21 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/InAppNotificationPriorityConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/InAppNotificationPriorityConverter.java deleted file mode 100644 index 42a43d3b1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/InAppNotificationPriorityConverter.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.notification.data.conventers; - -import gr.cite.notification.common.enums.InAppNotificationPriority; - -import jakarta.persistence.Converter; - -@Converter -public class InAppNotificationPriorityConverter extends DatabaseEnumConverter { - public InAppNotificationPriority of(Short i) { - return InAppNotificationPriority.of(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/IsActiveConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/IsActiveConverter.java deleted file mode 100644 index b761adc7e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/IsActiveConverter.java +++ /dev/null @@ -1,13 +0,0 @@ -package gr.cite.notification.data.conventers; - - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationContactTypeConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationContactTypeConverter.java deleted file mode 100644 index ad21a70a3..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationContactTypeConverter.java +++ /dev/null @@ -1,24 +0,0 @@ -package gr.cite.notification.data.conventers; - - -import gr.cite.notification.common.enums.NotificationContactType; - -import jakarta.persistence.Converter; - -@Converter -public class NotificationContactTypeConverter extends DatabaseEnumConverter { - public NotificationContactType of(Short i) { - return NotificationContactType.of(i); - } - - @Override - public Short convertToDatabaseColumn(NotificationContactType value) { - if (value == null) return null; - return value.getValue(); - } - - @Override - public NotificationContactType convertToEntityAttribute(Short dbData) { - return dbData == null ? null : this.of(dbData); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationInAppTrackingConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationInAppTrackingConverter.java deleted file mode 100644 index 1ed3bb9e1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationInAppTrackingConverter.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.notification.data.conventers; - -import gr.cite.notification.common.enums.NotificationInAppTracking; - -import jakarta.persistence.Converter; - -@Converter -public class NotificationInAppTrackingConverter extends DatabaseEnumConverter { - public NotificationInAppTracking of(Short i) { - return NotificationInAppTracking.of(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationNotifyStateConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationNotifyStateConverter.java deleted file mode 100644 index 7116e9b39..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationNotifyStateConverter.java +++ /dev/null @@ -1,24 +0,0 @@ -package gr.cite.notification.data.conventers; - - -import gr.cite.notification.common.enums.NotificationNotifyState; - -import jakarta.persistence.Converter; - -@Converter -public class NotificationNotifyStateConverter extends DatabaseEnumConverter { - public NotificationNotifyState of(Short i) { - return NotificationNotifyState.of(i); - } - - @Override - public Short convertToDatabaseColumn(NotificationNotifyState value) { - if (value == null) return null; - return value.getValue(); - } - - @Override - public NotificationNotifyState convertToEntityAttribute(Short dbData) { - return dbData == null ? null : this.of(dbData); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTemplateChannelConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTemplateChannelConverter.java deleted file mode 100644 index a18b99656..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTemplateChannelConverter.java +++ /dev/null @@ -1,25 +0,0 @@ -package gr.cite.notification.data.conventers; - - - -import gr.cite.notification.common.enums.NotificationTemplateChannel; - -import jakarta.persistence.Converter; - -@Converter -public class NotificationTemplateChannelConverter extends DatabaseEnumConverter { - public NotificationTemplateChannel of(Short i) { - return NotificationTemplateChannel.of(i); - } - - @Override - public Short convertToDatabaseColumn(NotificationTemplateChannel value) { - if (value == null) return null; - return value.getValue(); - } - - @Override - public NotificationTemplateChannel convertToEntityAttribute(Short dbData) { - return dbData == null ? null : this.of(dbData); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTemplateKindConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTemplateKindConverter.java deleted file mode 100644 index 4d6f1cce2..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTemplateKindConverter.java +++ /dev/null @@ -1,24 +0,0 @@ -package gr.cite.notification.data.conventers; - - -import gr.cite.notification.common.enums.NotificationTemplateKind; - -import jakarta.persistence.Converter; - -@Converter -public class NotificationTemplateKindConverter extends DatabaseEnumConverter { - public NotificationTemplateKind of(Short i) { - return NotificationTemplateKind.of(i); - } - - @Override - public Short convertToDatabaseColumn(NotificationTemplateKind value) { - if (value == null) return null; - return value.getValue(); - } - - @Override - public NotificationTemplateKind convertToEntityAttribute(Short dbData) { - return dbData == null ? null : this.of(dbData); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTrackingProcessConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTrackingProcessConverter.java deleted file mode 100644 index c85a83240..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTrackingProcessConverter.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.notification.data.conventers; - -import gr.cite.notification.common.enums.NotificationTrackingProcess; - -import jakarta.persistence.Converter; - -@Converter -public class NotificationTrackingProcessConverter extends DatabaseEnumConverter { - public NotificationTrackingProcess of(Short i) { - return NotificationTrackingProcess.of(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTrackingStateConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTrackingStateConverter.java deleted file mode 100644 index 290639cda..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/NotificationTrackingStateConverter.java +++ /dev/null @@ -1,13 +0,0 @@ -package gr.cite.notification.data.conventers; - - -import gr.cite.notification.common.enums.NotificationTrackingState; - -import jakarta.persistence.Converter; - -@Converter -public class NotificationTrackingStateConverter extends DatabaseEnumConverter { - public NotificationTrackingState of(Short i) { - return NotificationTrackingState.of(i); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/QueueInboxStatusConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/QueueInboxStatusConverter.java deleted file mode 100644 index 27e108488..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/QueueInboxStatusConverter.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/QueueOutboxNotifyStatusConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/QueueOutboxNotifyStatusConverter.java deleted file mode 100644 index e7c5bfb52..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/QueueOutboxNotifyStatusConverter.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/TenantConfigurationTypeConverter.java b/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/TenantConfigurationTypeConverter.java deleted file mode 100644 index d0ed545cb..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/conventers/TenantConfigurationTypeConverter.java +++ /dev/null @@ -1,13 +0,0 @@ -package gr.cite.notification.data.conventers; - - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/namingstrategy/NamingStrategyProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/data/namingstrategy/NamingStrategyProperties.java deleted file mode 100644 index 7e68244a9..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/namingstrategy/NamingStrategyProperties.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/namingstrategy/PrefixPhysicalNamingStrategy.java b/notification-service/notification/src/main/java/gr/cite/notification/data/namingstrategy/PrefixPhysicalNamingStrategy.java deleted file mode 100644 index ce04dc72c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/namingstrategy/PrefixPhysicalNamingStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package gr.cite.notification.data.namingstrategy; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java deleted file mode 100644 index f0628ed9a..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantFilterAspect.java +++ /dev/null @@ -1,44 +0,0 @@ -//package gr.cite.notification.data.tenant; -// -//import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java deleted file mode 100644 index a1527d51e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantListener.java +++ /dev/null @@ -1,85 +0,0 @@ -package gr.cite.notification.data.tenant; - -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.scope.tenant.TenantScoped; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java b/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java deleted file mode 100644 index 6f5d5c0fb..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/tenant/TenantScopedBaseEntity.java +++ /dev/null @@ -1,44 +0,0 @@ -package gr.cite.notification.data.tenant; - -import gr.cite.notification.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.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/notification-service/notification/src/main/java/gr/cite/notification/data/types/JsonSQLType.java b/notification-service/notification/src/main/java/gr/cite/notification/data/types/JsonSQLType.java deleted file mode 100644 index 434f8eda1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/data/types/JsonSQLType.java +++ /dev/null @@ -1,80 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorDescription.java b/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorDescription.java deleted file mode 100644 index eb1279ae6..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorDescription.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorThesaurusConfiguration.java b/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorThesaurusConfiguration.java deleted file mode 100644 index 08adb6f11..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorThesaurusConfiguration.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorThesaurusProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorThesaurusProperties.java deleted file mode 100644 index 97bf86ead..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/errorcode/ErrorThesaurusProperties.java +++ /dev/null @@ -1,129 +0,0 @@ -package gr.cite.notification.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; - - private ErrorDescription tenantConfigurationTypeCanNotChange; - - private ErrorDescription multipleTenantConfigurationTypeNotAllowed; - - 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; - } - - public ErrorDescription getTenantConfigurationTypeCanNotChange() { - return tenantConfigurationTypeCanNotChange; - } - - public void setTenantConfigurationTypeCanNotChange(ErrorDescription tenantConfigurationTypeCanNotChange) { - this.tenantConfigurationTypeCanNotChange = tenantConfigurationTypeCanNotChange; - } - - public ErrorDescription getMultipleTenantConfigurationTypeNotAllowed() { - return multipleTenantConfigurationTypeNotAllowed; - } - - public void setMultipleTenantConfigurationTypeNotAllowed(ErrorDescription multipleTenantConfigurationTypeNotAllowed) { - this.multipleTenantConfigurationTypeNotAllowed = multipleTenantConfigurationTypeNotAllowed; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/event/EventBroker.java b/notification-service/notification/src/main/java/gr/cite/notification/event/EventBroker.java deleted file mode 100644 index ddfb6b952..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/event/EventBroker.java +++ /dev/null @@ -1,44 +0,0 @@ -package gr.cite.notification.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(TenantConfigurationTouchedEvent event) { - this.applicationEventPublisher.publishEvent(event); - } - - public void emit(UserCredentialTouchedEvent event) { - this.applicationEventPublisher.publishEvent(event); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/event/TenantConfigurationTouchedEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/event/TenantConfigurationTouchedEvent.java deleted file mode 100644 index c86e3c5d7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/event/TenantConfigurationTouchedEvent.java +++ /dev/null @@ -1,45 +0,0 @@ -package gr.cite.notification.event; - - -import gr.cite.notification.common.enums.TenantConfigurationType; - -import java.util.UUID; - -public class TenantConfigurationTouchedEvent { - public TenantConfigurationTouchedEvent() { - } - - public TenantConfigurationTouchedEvent(UUID tenantId, String tenantCode, TenantConfigurationType type) { - this.tenantId = tenantId; - this.tenantCode = tenantCode; - this.type = type; - } - - private UUID tenantId; - private String tenantCode; - private TenantConfigurationType type; - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - - public TenantConfigurationType getType() { - return type; - } - - public void setType(TenantConfigurationType type) { - this.type = type; - } - - public String getTenantCode() { - return tenantCode; - } - - public void setTenantCode(String tenantCode) { - this.tenantCode = tenantCode; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/event/TenantTouchedEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/event/TenantTouchedEvent.java deleted file mode 100644 index f8ff83043..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/event/TenantTouchedEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/event/UserAddedToTenantEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/event/UserAddedToTenantEvent.java deleted file mode 100644 index c6c0c0f58..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/event/UserAddedToTenantEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/event/UserCredentialTouchedEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/event/UserCredentialTouchedEvent.java deleted file mode 100644 index a56d83b81..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/event/UserCredentialTouchedEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/event/UserRemovedFromTenantEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/event/UserRemovedFromTenantEvent.java deleted file mode 100644 index 6a175e34f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/event/UserRemovedFromTenantEvent.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/event/UserTouchedEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/event/UserTouchedEvent.java deleted file mode 100644 index 3f49b620c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/event/UserTouchedEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/AppRabbitConfigurer.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/AppRabbitConfigurer.java deleted file mode 100644 index 46dbd2ec5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/AppRabbitConfigurer.java +++ /dev/null @@ -1,54 +0,0 @@ -package gr.cite.notification.integrationevent; - -import gr.cite.notification.integrationevent.inbox.InboxProperties; -import gr.cite.notification.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.getNotifyTopic()); - bindingItems.addAll(this.inboxProperties.getTenantDefaultLocaleRemovalTopic()); - bindingItems.addAll(this.inboxProperties.getTenantDefaultLocaleTouchedTopic()); - bindingItems.addAll(this.inboxProperties.getTenantRemovalTopic()); - bindingItems.addAll(this.inboxProperties.getTenantTouchedTopic()); - bindingItems.addAll(this.inboxProperties.getUserRemovalTopic()); - bindingItems.addAll(this.inboxProperties.getUserTouchedTopic()); - - 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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java deleted file mode 100644 index 49a575b3a..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/InboxIntegrationEventConfigurer.java +++ /dev/null @@ -1,33 +0,0 @@ -package gr.cite.notification.integrationevent; - -import gr.cite.notification.integrationevent.inbox.InboxProperties; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/IntegrationEventContextImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/IntegrationEventContextImpl.java deleted file mode 100644 index fd8c02dc3..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/IntegrationEventContextImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java deleted file mode 100644 index dfcb358b9..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/OutboxIntegrationEventConfigurer.java +++ /dev/null @@ -1,71 +0,0 @@ -package gr.cite.notification.integrationevent; - -import gr.cite.notification.data.QueueOutboxEntity; -import gr.cite.notification.integrationevent.outbox.OutboxProperties; -import gr.cite.notification.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; - - public OutboxIntegrationEventConfigurer(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @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); - } -} - - diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/TrackedEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/TrackedEvent.java deleted file mode 100644 index c5ecb2542..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/TrackedEvent.java +++ /dev/null @@ -1,18 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/ConsistencyHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/ConsistencyHandler.java deleted file mode 100644 index 78f4f7f67..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/ConsistencyHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.notification.integrationevent.inbox; - -public interface ConsistencyHandler { - - Boolean isConsistent(T consistencyPredicates); - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/ConsistencyPredicates.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/ConsistencyPredicates.java deleted file mode 100644 index e77c546a2..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/ConsistencyPredicates.java +++ /dev/null @@ -1,5 +0,0 @@ -package gr.cite.notification.integrationevent.inbox; - -public interface ConsistencyPredicates { - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/EventProcessingStatus.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/EventProcessingStatus.java deleted file mode 100644 index 274049473..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/EventProcessingStatus.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.integrationevent.inbox; - -public enum EventProcessingStatus { - Error, - Success, - Postponed, - Discard -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxPrincipal.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxPrincipal.java deleted file mode 100644 index 288c11095..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxPrincipal.java +++ /dev/null @@ -1,67 +0,0 @@ -package gr.cite.notification.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.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxProperties.java deleted file mode 100644 index c24e96488..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxProperties.java +++ /dev/null @@ -1,75 +0,0 @@ -package gr.cite.notification.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 notifyTopic; - private final List tenantDefaultLocaleRemovalTopic; - private final List tenantDefaultLocaleTouchedTopic; - - private final List tenantRemovalTopic; - - private final List tenantTouchedTopic; - - private final List userRemovalTopic; - - private final List userTouchedTopic; - - public InboxProperties( - String exchange, - List notifyTopic, - List tenantDefaultLocaleRemovalTopic, - List tenantDefaultLocaleTouchedTopic, - List tenantRemovalTopic, - List tenantTouchedTopic, - List userRemovalTopic, - List userTouchedTopic) { - this.exchange = exchange; - this.notifyTopic = notifyTopic; - this.tenantDefaultLocaleRemovalTopic = tenantDefaultLocaleRemovalTopic; - this.tenantDefaultLocaleTouchedTopic = tenantDefaultLocaleTouchedTopic; - this.tenantRemovalTopic = tenantRemovalTopic; - this.tenantTouchedTopic = tenantTouchedTopic; - this.userRemovalTopic = userRemovalTopic; - this.userTouchedTopic = userTouchedTopic; - } - - public List getNotifyTopic() { - return notifyTopic; - } - - public List getTenantDefaultLocaleRemovalTopic() { - return tenantDefaultLocaleRemovalTopic; - } - - public List getTenantDefaultLocaleTouchedTopic() { - return tenantDefaultLocaleTouchedTopic; - } - - public List getTenantRemovalTopic() { - return tenantRemovalTopic; - } - - public List getTenantTouchedTopic() { - return tenantTouchedTopic; - } - - public List getUserRemovalTopic() { - return userRemovalTopic; - } - - public List getUserTouchedTopic() { - return userTouchedTopic; - } - - public String getExchange() { - return exchange; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java deleted file mode 100644 index 3caa4f49d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/InboxRepositoryImpl.java +++ /dev/null @@ -1,413 +0,0 @@ -package gr.cite.notification.integrationevent.inbox; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.fake.FakeRequestScope; -import gr.cite.notification.data.QueueInboxEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.integrationevent.inbox.notify.NotifyIntegrationEventHandler; -import gr.cite.notification.integrationevent.inbox.tenantdefaultlocaleremoval.TenantDefaultLocaleRemovalIntegrationEventHandler; -import gr.cite.notification.integrationevent.inbox.tenantdefaultlocaletouched.TenantDefaultLocaleTouchedIntegrationEventHandler; -import gr.cite.notification.integrationevent.inbox.tenantremoval.TenantRemovalIntegrationEventHandler; -import gr.cite.notification.integrationevent.inbox.tenanttouched.TenantTouchedIntegrationEventHandler; -import gr.cite.notification.integrationevent.inbox.userremoval.UserRemovalIntegrationEventHandler; -import gr.cite.notification.integrationevent.inbox.usertouched.UserTouchedIntegrationEventHandler; -import gr.cite.notification.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.getTenantTouchedTopic())) - 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.getUserTouchedTopic())) - handler = this.applicationContext.getBean(UserTouchedIntegrationEventHandler.class); - else if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getNotifyTopic())) - handler = this.applicationContext.getBean(NotifyIntegrationEventHandler.class); - else if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getTenantDefaultLocaleRemovalTopic())) - handler = this.applicationContext.getBean(TenantDefaultLocaleRemovalIntegrationEventHandler.class); - else if (this.routingKeyMatched(queueInboxMessage.getRoute(), this.inboxProperties.getTenantDefaultLocaleTouchedTopic())) - handler = this.applicationContext.getBean(TenantDefaultLocaleTouchedIntegrationEventHandler.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 {}. Setting nack and continuing...", queueInboxMessage.getRoute(), 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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/IntegrationEventHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/IntegrationEventHandler.java deleted file mode 100644 index 729cd7642..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/IntegrationEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.notification.integrationevent.inbox; - -public interface IntegrationEventHandler { - - EventProcessingStatus handle(IntegrationEventProperties properties, String message); - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/IntegrationEventProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/IntegrationEventProperties.java deleted file mode 100644 index cb07b4c41..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/IntegrationEventProperties.java +++ /dev/null @@ -1,35 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyConsistencyHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyConsistencyHandler.java deleted file mode 100644 index a7cd2e64f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyConsistencyHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.notify; - -import gr.cite.notification.common.StringUtils; -import gr.cite.notification.common.enums.ContactInfoType; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.data.UserContactInfoEntity; -import gr.cite.notification.integrationevent.inbox.ConsistencyHandler; -import gr.cite.notification.model.User; -import gr.cite.notification.model.UserContactInfo; -import gr.cite.notification.model.builder.UserBuilder; -import gr.cite.notification.query.UserContactInfoQuery; -import gr.cite.notification.query.UserQuery; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.fieldset.BaseFieldSet; -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 NotifyConsistencyHandler implements ConsistencyHandler { - - private final QueryFactory queryFactory; - - private final BuilderFactory builderFactory; - - public NotifyConsistencyHandler(QueryFactory queryFactory, BuilderFactory builderFactory) { - this.queryFactory = queryFactory; - this.builderFactory = builderFactory; - } - - @Override - public Boolean isConsistent(NotifyConsistencyPredicates consistencyPredicates) { - if (consistencyPredicates.getUserId() != null) { - UserQuery query = this.queryFactory.query(UserQuery.class).disableTracking().ids(consistencyPredicates.getUserId()).isActive(IsActive.Active); - - BaseFieldSet fieldSet = new BaseFieldSet( - User._id, - User._isActive - ); - User user = this.builderFactory.builder(UserBuilder.class).build(fieldSet, query.firstAs(fieldSet)); - if (user == null) - return false; - Long activeEmails = this.queryFactory.query(UserContactInfoQuery.class).disableTracking().ids(consistencyPredicates.getUserId()).isActive(IsActive.Active).type(ContactInfoType.Email).count(); - return consistencyPredicates.getContactTypeHint() == null || consistencyPredicates.getContactTypeHint() == NotificationContactType.IN_APP || !StringUtils.isNullOrEmpty(consistencyPredicates.getContactHint()) || activeEmails != 0; - } else { - return !StringUtils.isNullOrEmpty(consistencyPredicates.getContactHint()); - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyConsistencyPredicates.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyConsistencyPredicates.java deleted file mode 100644 index 9d87ad1ac..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyConsistencyPredicates.java +++ /dev/null @@ -1,45 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.notify; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.integrationevent.inbox.ConsistencyPredicates; - -import java.util.UUID; - -public class NotifyConsistencyPredicates implements ConsistencyPredicates { - - private UUID userId; - - private NotificationContactType contactTypeHint; - - private String contactHint; - - public NotifyConsistencyPredicates(UUID userId, NotificationContactType contactTypeHint, String contactHint) { - this.userId = userId; - this.contactTypeHint = contactTypeHint; - this.contactHint = contactHint; - } - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public NotificationContactType getContactTypeHint() { - return contactTypeHint; - } - - public void setContactTypeHint(NotificationContactType contactTypeHint) { - this.contactTypeHint = contactTypeHint; - } - - public String getContactHint() { - return contactHint; - } - - public void setContactHint(String contactHint) { - this.contactHint = contactHint; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEvent.java deleted file mode 100644 index f11558abd..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEvent.java +++ /dev/null @@ -1,73 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.notify; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.integrationevent.TrackedEvent; - -import java.util.UUID; - -public class NotifyIntegrationEvent extends TrackedEvent { - - private UUID userId; - - private UUID notificationType; - - private NotificationContactType contactTypeHint; - - private String contactHint; - - private String data; - - private String provenanceRef; - - public NotifyIntegrationEvent() { - } - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public UUID getNotificationType() { - return notificationType; - } - - public void setNotificationType(UUID notificationType) { - this.notificationType = notificationType; - } - - public NotificationContactType getContactTypeHint() { - return contactTypeHint; - } - - public void setContactTypeHint(NotificationContactType contactTypeHint) { - this.contactTypeHint = contactTypeHint; - } - - public String getContactHint() { - return contactHint; - } - - public void setContactHint(String contactHint) { - this.contactHint = contactHint; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public String getProvenanceRef() { - return provenanceRef; - } - - public void setProvenanceRef(String provenanceRef) { - this.provenanceRef = provenanceRef; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandler.java deleted file mode 100644 index fadf33f60..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.notify; - -import gr.cite.notification.integrationevent.inbox.IntegrationEventHandler; - -public interface NotifyIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java deleted file mode 100644 index dd580a1a4..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/notify/NotifyIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,125 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.notify; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.NotificationNotifyState; -import gr.cite.notification.common.enums.NotificationTrackingProcess; -import gr.cite.notification.common.enums.NotificationTrackingState; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; -import gr.cite.notification.integrationevent.inbox.InboxPrincipal; -import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.persist.NotificationPersist; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.service.notification.NotificationService; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.fieldset.BaseFieldSet; -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 javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.AbstractMap; -import java.util.Map; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class NotifyIntegrationEventHandlerImpl implements NotifyIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotifyIntegrationEventHandlerImpl.class)); - - private final JsonHandlingService jsonHandlingService; - private final QueryFactory queryFactory; - private final TenantScope tenantScope; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final NotifyConsistencyHandler notifyConsistencyHandler; - private final NotificationService notificationService; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - public NotifyIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, QueryFactory queryFactory, TenantScope tenantScope, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, NotifyConsistencyHandler notifyConsistencyHandler, NotificationService notificationService, AuditService auditService, TenantEntityManager tenantEntityManager) { - this.jsonHandlingService = jsonHandlingService; - this.queryFactory = queryFactory; - this.tenantScope = tenantScope; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.notifyConsistencyHandler = notifyConsistencyHandler; - this.notificationService = notificationService; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - NotifyIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(NotifyIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - logger.debug("Handling {}", NotifyIntegrationEvent.class.getSimpleName()); - - NotificationPersist model = new NotificationPersist(); - model.setType(event.getNotificationType()); - model.setUserId(event.getUserId()); - model.setContactHint(event.getContactHint()); - model.setContactTypeHint(event.getContactTypeHint()); - model.setData(event.getData()); - model.setNotifyState(NotificationNotifyState.PENDING); - model.setNotifiedWith(event.getContactTypeHint()); - model.setRetryCount(0); - model.setTrackingState(NotificationTrackingState.UNDEFINED); - model.setTrackingProcess(NotificationTrackingProcess.PENDING); - model.setTrackingData(null); - model.setProvenanceRef(event.getProvenanceRef()); - model.setNotifiedAt(Instant.now()); - - 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)); - - if (!(notifyConsistencyHandler.isConsistent(new NotifyConsistencyPredicates(event.getUserId(), event.getContactTypeHint(), event.getContactHint())))) { - status = EventProcessingStatus.Postponed; - currentPrincipalResolver.pop(); - tenantScope.removeTempTenant(this.tenantEntityManager); - return status; - } - notificationService.persist(model, new BaseFieldSet()); - - auditService.track(AuditableAction.Notification_Persist, Map.ofEntries( - new AbstractMap.SimpleEntry("id", event.getUserId() != null ? event.getUserId() : event.getContactHint()) - )); - } 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); - } catch (InvalidApplicationException e) { - logger.error( e.getMessage(), e); - } - } - return status; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalConsistencyHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalConsistencyHandler.java deleted file mode 100644 index ffab90cdf..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalConsistencyHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaleremoval; - -import gr.cite.notification.integrationevent.inbox.ConsistencyHandler; -import gr.cite.notification.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 TenantDefaultLocaleRemovalConsistencyHandler implements ConsistencyHandler { - - private final QueryFactory queryFactory; - - public TenantDefaultLocaleRemovalConsistencyHandler(QueryFactory queryFactory) { - this.queryFactory = queryFactory; - } - - @Override - public Boolean isConsistent(TenantDefaultLocaleRemovalConsistencyPredicates consistencyPredicates) { - if (consistencyPredicates.getTenantId() == null) return true; - long count = this.queryFactory.query(TenantQuery.class).disableTracking().ids(consistencyPredicates.getTenantId()).count(); - return count > 0; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalConsistencyPredicates.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalConsistencyPredicates.java deleted file mode 100644 index a5954db7b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalConsistencyPredicates.java +++ /dev/null @@ -1,23 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaleremoval; - -import gr.cite.notification.integrationevent.inbox.ConsistencyPredicates; - -import java.util.UUID; - -public class TenantDefaultLocaleRemovalConsistencyPredicates implements ConsistencyPredicates { - - private UUID tenantId; - - public TenantDefaultLocaleRemovalConsistencyPredicates(UUID tenantId) { - this.tenantId = tenantId; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEvent.java deleted file mode 100644 index 29cd64baf..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEvent.java +++ /dev/null @@ -1,18 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaleremoval; - -import gr.cite.notification.integrationevent.TrackedEvent; - -import java.util.UUID; - -public class TenantDefaultLocaleRemovalIntegrationEvent extends TrackedEvent { - - private UUID tenantId; - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandler.java deleted file mode 100644 index 8fbd6e685..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaleremoval; - - -import gr.cite.notification.integrationevent.inbox.IntegrationEventHandler; - -public interface TenantDefaultLocaleRemovalIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java deleted file mode 100644 index b3b69a600..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaleremoval/TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,106 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaleremoval; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; -import gr.cite.notification.integrationevent.inbox.InboxPrincipal; -import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.service.tenantconfiguration.TenantConfigurationService; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.fieldset.BaseFieldSet; -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 TenantDefaultLocaleRemovalIntegrationEventHandlerImpl implements TenantDefaultLocaleRemovalIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantDefaultLocaleRemovalIntegrationEventHandlerImpl.class)); - - private final JsonHandlingService jsonHandlingService; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final TenantConfigurationService tenantConfigurationService; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - private final TenantScope tenantScope; - private final QueryFactory queryFactory; - private final TenantDefaultLocaleRemovalConsistencyHandler tenantConfigurationRemovalConsistencyHandler; - public TenantDefaultLocaleRemovalIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, TenantConfigurationService tenantConfigurationService, AuditService auditService, TenantEntityManager tenantEntityManager, TenantScope tenantScope, QueryFactory queryFactory, TenantDefaultLocaleRemovalConsistencyHandler tenantConfigurationRemovalConsistencyHandler) { - this.jsonHandlingService = jsonHandlingService; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.tenantConfigurationService = tenantConfigurationService; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - this.tenantScope = tenantScope; - this.queryFactory = queryFactory; - this.tenantConfigurationRemovalConsistencyHandler = tenantConfigurationRemovalConsistencyHandler; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - TenantDefaultLocaleRemovalIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(TenantDefaultLocaleRemovalIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - - EventProcessingStatus status = EventProcessingStatus.Success; - try { - if (!(tenantConfigurationRemovalConsistencyHandler.isConsistent(new TenantDefaultLocaleRemovalConsistencyPredicates(event.getTenantId())))) { - status = EventProcessingStatus.Postponed; - return status; - } - - 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)); - - TenantConfigurationEntity tenantConfiguration = tenantConfigurationService.getTenantConfigurationEntityForType(TenantConfigurationType.DefaultUserLocale); - if (tenantConfiguration == null){ - status = EventProcessingStatus.Discard; - currentPrincipalResolver.pop(); - return status; - } - - tenantConfigurationService.deleteAndSave(tenantConfiguration.getId()); - - auditService.track(AuditableAction.Tenant_Configuration_DefaultUserLocale_Delete, Map.ofEntries( - new AbstractMap.SimpleEntry("tenantId", event.getTenantId() != null ? event.getTenantId() : "") - )); - //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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedConsistencyHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedConsistencyHandler.java deleted file mode 100644 index 23e86ee34..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedConsistencyHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaletouched; - -import gr.cite.notification.integrationevent.inbox.ConsistencyHandler; -import gr.cite.notification.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 TenantDefaultLocaleTouchedConsistencyHandler implements ConsistencyHandler { - - private final QueryFactory queryFactory; - - public TenantDefaultLocaleTouchedConsistencyHandler(QueryFactory queryFactory) { - this.queryFactory = queryFactory; - } - - @Override - public Boolean isConsistent(TenantDefaultLocaleTouchedConsistencyPredicates consistencyPredicates) { - if (consistencyPredicates.getTenantId() == null) return true; - long count = this.queryFactory.query(TenantQuery.class).disableTracking().ids(consistencyPredicates.getTenantId()).count(); - return count > 0; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedConsistencyPredicates.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedConsistencyPredicates.java deleted file mode 100644 index 0b00aedfa..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedConsistencyPredicates.java +++ /dev/null @@ -1,23 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaletouched; - -import gr.cite.notification.integrationevent.inbox.ConsistencyPredicates; - -import java.util.UUID; - -public class TenantDefaultLocaleTouchedConsistencyPredicates implements ConsistencyPredicates { - - private UUID tenantId; - - public TenantDefaultLocaleTouchedConsistencyPredicates(UUID tenantId) { - this.tenantId = tenantId; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEvent.java deleted file mode 100644 index 82cd208b5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaletouched; - -import gr.cite.notification.integrationevent.TrackedEvent; - -import java.util.UUID; - -public class TenantDefaultLocaleTouchedIntegrationEvent extends TrackedEvent { - - private UUID tenantId; - private String timezone; - private String language; - private String culture; - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - - public String getTimezone() { - return timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public String getCulture() { - return culture; - } - - public void setCulture(String culture) { - this.culture = culture; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandler.java deleted file mode 100644 index f214182aa..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaletouched; - - -import gr.cite.notification.integrationevent.inbox.IntegrationEventHandler; - -public interface TenantDefaultLocaleTouchedIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java deleted file mode 100644 index c92aa288e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantdefaultlocaletouched/TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,129 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantdefaultlocaletouched; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; -import gr.cite.notification.integrationevent.inbox.InboxPrincipal; -import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.persist.tenantconfiguration.DefaultUserLocaleTenantConfigurationPersist; -import gr.cite.notification.model.persist.tenantconfiguration.TenantConfigurationPersist; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.service.tenantconfiguration.TenantConfigurationService; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.logging.LoggerService; -import gr.cite.tools.validation.Validator; -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 TenantDefaultLocaleTouchedIntegrationEventHandlerImpl implements TenantDefaultLocaleTouchedIntegrationEventHandler { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantDefaultLocaleTouchedIntegrationEventHandlerImpl.class)); - - private final JsonHandlingService jsonHandlingService; - private final CurrentPrincipalResolver currentPrincipalResolver; - private final ClaimExtractorProperties claimExtractorProperties; - private final TenantConfigurationService tenantConfigurationService; - private final AuditService auditService; - private final TenantEntityManager tenantEntityManager; - private final TenantScope tenantScope; - private final QueryFactory queryFactory; - private final ConventionService conventionService; - private final ValidatorFactory validatorFactory; - private final TenantDefaultLocaleTouchedConsistencyHandler tenantDefaultLocaleTouchedConsistencyHandler; - public TenantDefaultLocaleTouchedIntegrationEventHandlerImpl(JsonHandlingService jsonHandlingService, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, TenantConfigurationService tenantConfigurationService, AuditService auditService, TenantEntityManager tenantEntityManager, TenantScope tenantScope, QueryFactory queryFactory, ConventionService conventionService, ValidatorFactory validatorFactory, TenantDefaultLocaleTouchedConsistencyHandler tenantDefaultLocaleTouchedConsistencyHandler) { - this.jsonHandlingService = jsonHandlingService; - this.currentPrincipalResolver = currentPrincipalResolver; - this.claimExtractorProperties = claimExtractorProperties; - this.tenantConfigurationService = tenantConfigurationService; - this.auditService = auditService; - this.tenantEntityManager = tenantEntityManager; - this.tenantScope = tenantScope; - this.queryFactory = queryFactory; - this.conventionService = conventionService; - this.validatorFactory = validatorFactory; - this.tenantDefaultLocaleTouchedConsistencyHandler = tenantDefaultLocaleTouchedConsistencyHandler; - } - - @Override - public EventProcessingStatus handle(IntegrationEventProperties properties, String message) { - TenantDefaultLocaleTouchedIntegrationEvent event = this.jsonHandlingService.fromJsonSafe(TenantDefaultLocaleTouchedIntegrationEvent.class, message); - if (event == null) - return EventProcessingStatus.Error; - - EventProcessingStatus status = EventProcessingStatus.Success; - try { - - if (!(tenantDefaultLocaleTouchedConsistencyHandler.isConsistent(new TenantDefaultLocaleTouchedConsistencyPredicates(event.getTenantId())))) { - status = EventProcessingStatus.Postponed; - return status; - } - 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)); - - TenantConfigurationPersist persist = new TenantConfigurationPersist(); - persist.setType(TenantConfigurationType.DefaultUserLocale); - persist.setDefaultUserLocale(new DefaultUserLocaleTenantConfigurationPersist()); - persist.getDefaultUserLocale().setCulture(event.getCulture()); - persist.getDefaultUserLocale().setLanguage(event.getLanguage()); - persist.getDefaultUserLocale().setTimezone(event.getTimezone()); - - TenantConfigurationEntity tenantConfiguration = tenantConfigurationService.getTenantConfigurationEntityForType(TenantConfigurationType.DefaultUserLocale); - if (tenantConfiguration != null){ - persist.setId(tenantConfiguration.getId()); - persist.setHash(this.conventionService.hashValue(tenantConfiguration.getUpdatedAt())); - } - - Validator validator = this.validatorFactory.validator(TenantConfigurationPersist.TenantConfigurationPersistValidator.class); - validator.validate(persist); - if (!validator.result().isValid()) { - status = EventProcessingStatus.Error; - currentPrincipalResolver.pop(); - return status; - } - - tenantConfigurationService.persist(persist, new BaseFieldSet()); - - auditService.track(AuditableAction.Tenant_Configuration_DefaultUserLocale_Persist, Map.ofEntries( - new AbstractMap.SimpleEntry("tenantId", event.getTenantId() != null ? event.getTenantId() : "") - )); - //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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyHandler.java deleted file mode 100644 index 167443900..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantremoval; - -import gr.cite.notification.integrationevent.inbox.ConsistencyHandler; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyPredicates.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyPredicates.java deleted file mode 100644 index f55869126..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalConsistencyPredicates.java +++ /dev/null @@ -1,23 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantremoval; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEvent.java deleted file mode 100644 index cf1201688..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEvent.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantremoval; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandler.java deleted file mode 100644 index 7f4a6e121..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantremoval; - - -import gr.cite.notification.integrationevent.inbox.IntegrationEventHandler; - -public interface TenantRemovalIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java deleted file mode 100644 index c53db00f5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenantremoval/TenantRemovalIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenantremoval; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; -import gr.cite.notification.integrationevent.inbox.InboxPrincipal; -import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEvent.java deleted file mode 100644 index 03419f001..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEvent.java +++ /dev/null @@ -1,30 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenanttouched; - - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandler.java deleted file mode 100644 index f476601f3..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandler.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenanttouched; - -import gr.cite.notification.integrationevent.inbox.IntegrationEventHandler; - -public interface TenantTouchedIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java deleted file mode 100644 index deb8506d9..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/tenanttouched/TenantTouchedIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.tenanttouched; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; -import gr.cite.notification.integrationevent.inbox.InboxPrincipal; -import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.notification.model.persist.TenantTouchedIntegrationEventPersist; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalConsistencyHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalConsistencyHandler.java deleted file mode 100644 index 9cda19a0c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalConsistencyHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.userremoval; - -import gr.cite.notification.integrationevent.inbox.ConsistencyHandler; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalConsistencyPredicates.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalConsistencyPredicates.java deleted file mode 100644 index 6762a943c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalConsistencyPredicates.java +++ /dev/null @@ -1,24 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.userremoval; - - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEvent.java deleted file mode 100644 index 6e8a61805..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEvent.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.userremoval; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandler.java deleted file mode 100644 index 70a9504e5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.userremoval; - - -import gr.cite.notification.integrationevent.inbox.IntegrationEventHandler; - -public interface UserRemovalIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java deleted file mode 100644 index 62a256ad6..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/userremoval/UserRemovalIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,110 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.userremoval; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; -import gr.cite.notification.integrationevent.inbox.InboxPrincipal; -import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.service.user.UserService; -import gr.cite.tools.auditing.AuditService; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyValidationException; -import gr.cite.tools.fieldset.BaseFieldSet; -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 javax.management.InvalidApplicationException; -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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java deleted file mode 100644 index 18f90a147..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEvent.java +++ /dev/null @@ -1,327 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.usertouched; - -import gr.cite.notification.common.enums.ContactInfoType; -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandler.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandler.java deleted file mode 100644 index 38912cfce..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.usertouched; - - -import gr.cite.notification.integrationevent.inbox.IntegrationEventHandler; - -public interface UserTouchedIntegrationEventHandler extends IntegrationEventHandler { - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java deleted file mode 100644 index 2f08f5386..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/inbox/usertouched/UserTouchedIntegrationEventHandlerImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -package gr.cite.notification.integrationevent.inbox.usertouched; - -import gr.cite.commons.web.oidc.principal.CurrentPrincipalResolver; -import gr.cite.commons.web.oidc.principal.extractor.ClaimExtractorProperties; -import gr.cite.notification.audit.AuditableAction; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.integrationevent.inbox.EventProcessingStatus; -import gr.cite.notification.integrationevent.inbox.InboxPrincipal; -import gr.cite.notification.integrationevent.inbox.IntegrationEventProperties; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.service.user.UserService; -import gr.cite.tools.auditing.AuditService; -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.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 QueryFactory queryFactory; - private final TenantScope tenantScope; - 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, QueryFactory queryFactory, TenantScope tenantScope, CurrentPrincipalResolver currentPrincipalResolver, ClaimExtractorProperties claimExtractorProperties, UserService userService, AuditService auditService, TenantEntityManager tenantEntityManager) { - this.jsonHandlingService = jsonHandlingService; - this.validatorFactory = validatorFactory; - this.queryFactory = queryFactory; - this.tenantScope = tenantScope; - 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/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxIntegrationEvent.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxIntegrationEvent.java deleted file mode 100644 index 5961fe016..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxIntegrationEvent.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.notification.integrationevent.outbox; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import gr.cite.notification.integrationevent.TrackedEvent; -import gr.cite.rabbitmq.IntegrationEvent; - -@JsonIgnoreProperties(ignoreUnknown = true) -public class OutboxIntegrationEvent extends IntegrationEvent { - private TrackedEvent event; - - public TrackedEvent getEvent() { - return event; - } - - public void setEvent(TrackedEvent event) { - this.event = event; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxProperties.java deleted file mode 100644 index adeb3f62a..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxProperties.java +++ /dev/null @@ -1,19 +0,0 @@ -package gr.cite.notification.integrationevent.outbox; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "queue.task.publisher.options") -public class OutboxProperties { - - private final String exchange; - - - public OutboxProperties(String exchange - ) { - this.exchange = exchange; - } - - public String getExchange() { - return exchange; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java deleted file mode 100644 index 10848cb41..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxRepositoryImpl.java +++ /dev/null @@ -1,378 +0,0 @@ -package gr.cite.notification.integrationevent.outbox; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.fake.FakeRequestScope; -import gr.cite.notification.data.QueueOutboxEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.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; - - - public OutboxRepositoryImpl( - ApplicationContext applicationContext - ) { - this.applicationContext = applicationContext; - } - - @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()) { - default: { - logger.error("unrecognized outgoing integration event {}. Skipping...", event.getType()); - return null; - } - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxService.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxService.java deleted file mode 100644 index d63a85bf1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxService.java +++ /dev/null @@ -1,5 +0,0 @@ -package gr.cite.notification.integrationevent.outbox; - -public interface OutboxService { - void publish(OutboxIntegrationEvent event); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxServiceImpl.java deleted file mode 100644 index 677db1af5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/integrationevent/outbox/OutboxServiceImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleConfiguration.java b/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleConfiguration.java deleted file mode 100644 index b6699c02f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.notification.locale; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties(LocaleProperties.class) -public class LocaleConfiguration { -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleProperties.java deleted file mode 100644 index 296b55a92..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleProperties.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleService.java b/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleService.java deleted file mode 100644 index f2f54e6e7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleService.java +++ /dev/null @@ -1,18 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleServiceImpl.java deleted file mode 100644 index 71bdb83e7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/locale/LocaleServiceImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -package gr.cite.notification.locale; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/InAppNotification.java b/notification-service/notification/src/main/java/gr/cite/notification/model/InAppNotification.java deleted file mode 100644 index dc5569f72..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/InAppNotification.java +++ /dev/null @@ -1,155 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.common.enums.InAppNotificationPriority; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationInAppTracking; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; - -import jakarta.persistence.*; -import java.time.Instant; -import java.util.UUID; -public class InAppNotification { - public static class Field { - public static final String ID = "id"; - public static final String USER = "user"; - public static final String IS_ACTIVE = "isActive"; - public static final String TYPE = "type"; - public static final String READ_TIME = "readTime"; - public static final String TRACKING_STATE = "trackingState"; - public static final String PRIORITY = "priority"; - public static final String SUBJECT = "subject"; - public static final String BODY = "body"; - public static final String EXTRA_DATA = "extraData"; - public static final String CREATED_AT = "createdAt"; - public static final String UPDATED_AT = "updatedAt"; - public static final String TENANT = "tenant"; - public static final String HASH = "hash"; - } - - private UUID id; - private User user; - private IsActive isActive; - private UUID type; - private Instant readTime; - private NotificationInAppTracking trackingState; - private InAppNotificationPriority priority; - private String subject; - private String body; - private String extraData; - private Instant createdAt; - private Instant updatedAt; - private Tenant tenant; - private String hash; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public IsActive getIsActive() { - return isActive; - } - - public void setIsActive(IsActive isActive) { - this.isActive = isActive; - } - - public UUID getType() { - return type; - } - - public void setType(UUID type) { - this.type = type; - } - - public Instant getReadTime() { - return readTime; - } - - public void setReadTime(Instant readTime) { - this.readTime = readTime; - } - - public NotificationInAppTracking getTrackingState() { - return trackingState; - } - - public void setTrackingState(NotificationInAppTracking trackingState) { - this.trackingState = trackingState; - } - - public InAppNotificationPriority getPriority() { - return priority; - } - - public void setPriority(InAppNotificationPriority priority) { - this.priority = priority; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public String getExtraData() { - return extraData; - } - - public void setExtraData(String extraData) { - this.extraData = extraData; - } - - 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 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; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/Notification.java b/notification-service/notification/src/main/java/gr/cite/notification/model/Notification.java deleted file mode 100644 index 020a23ea7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/Notification.java +++ /dev/null @@ -1,225 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.common.enums.*; - -import java.time.Instant; -import java.util.UUID; - -public class Notification { - - private UUID id; - - public static final String _id = "id"; - - private Tenant tenant; - - public static final String _tenant = "tenant"; - - private User user; - - public static final String _user = "user"; - - private UUID type; - - public static final String _type = "type"; - - private NotificationContactType contactTypeHint; - - public static final String _contactTypeHint = "contactTypeHint"; - - private String contactHint; - - public static final String _contactHint = "contactHint"; - - private Instant notifiedAt; - - public static final String _notifiedAt = "notifiedAt"; - - private String data; - - public static final String _data = "data"; - - private NotificationNotifyState notifyState; - - public static final String _notifyState = "notifyState"; - - private NotificationContactType notifiedWith; - - public static final String _notifiedWith = "notifiedWith"; - - private Integer retryCount; - - public static final String _retryCount = "retryCount"; - - private NotificationTrackingState trackingState; - - public static final String _trackingState = "trackingState"; - - private NotificationTrackingProcess trackingProcess; - - public static final String _trackingProcess = "trackingProcess"; - - private String trackingData; - - public static final String _trackingData = "trackingData"; - - private String hash; - - public static final String _hash = "hash"; - - private IsActive isActive; - - public static final String _isActive = "isActive"; - - 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 Tenant getTenant() { - return tenant; - } - - public void setTenant(Tenant tenant) { - this.tenant = tenant; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public UUID getType() { - return type; - } - - public void setType(UUID type) { - this.type = type; - } - - public NotificationContactType getContactTypeHint() { - return contactTypeHint; - } - - public void setContactTypeHint(NotificationContactType contactTypeHint) { - this.contactTypeHint = contactTypeHint; - } - - public String getContactHint() { - return contactHint; - } - - public void setContactHint(String contactHint) { - this.contactHint = contactHint; - } - - public Instant getNotifiedAt() { - return notifiedAt; - } - - public void setNotifiedAt(Instant notifiedAt) { - this.notifiedAt = notifiedAt; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public NotificationNotifyState getNotifyState() { - return notifyState; - } - - public void setNotifyState(NotificationNotifyState notifyState) { - this.notifyState = notifyState; - } - - public NotificationContactType getNotifiedWith() { - return notifiedWith; - } - - public void setNotifiedWith(NotificationContactType notifiedWith) { - this.notifiedWith = notifiedWith; - } - - public Integer getRetryCount() { - return retryCount; - } - - public void setRetryCount(Integer retryCount) { - this.retryCount = retryCount; - } - - public NotificationTrackingState getTrackingState() { - return trackingState; - } - - public void setTrackingState(NotificationTrackingState trackingState) { - this.trackingState = trackingState; - } - - public NotificationTrackingProcess getTrackingProcess() { - return trackingProcess; - } - - public void setTrackingProcess(NotificationTrackingProcess trackingProcess) { - this.trackingProcess = trackingProcess; - } - - public String getTrackingData() { - return trackingData; - } - - public void setTrackingData(String trackingData) { - this.trackingData = trackingData; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } - - 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; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/NotificationTemplate.java b/notification-service/notification/src/main/java/gr/cite/notification/model/NotificationTemplate.java deleted file mode 100644 index 5a869d4a1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/NotificationTemplate.java +++ /dev/null @@ -1,134 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationTemplateChannel; -import gr.cite.notification.common.enums.NotificationTemplateKind; -import gr.cite.notification.model.notificationtemplate.NotificationTemplateValue; - - -import java.time.Instant; -import java.util.UUID; - -public class NotificationTemplate { - - private UUID id; - public static final String _id = "id"; - - private NotificationTemplateChannel channel; - public static final String _channel = "channel"; - - private UUID notificationType; - public static final String _notificationType = "notificationType"; - - private NotificationTemplateKind kind; - public static final String _kind = "kind"; - - private String languageCode; - public static final String _languageCode = "languageCode"; - - private NotificationTemplateValue value; - public static final String _value = "value"; - - private IsActive isActive; - public static final String _isActive = "isActive"; - - private Instant createdAt; - public static final String _createdAt = "createdAt"; - - private Instant updatedAt; - public static final String _updatedAt = "updatedAt"; - - private Tenant tenant; - public static final String _tenant = "tenant"; - - private String hash; - public static final String _hash = "hash"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public NotificationTemplateChannel getChannel() { - return channel; - } - - public void setChannel(NotificationTemplateChannel channel) { - this.channel = channel; - } - - public UUID getNotificationType() { - return notificationType; - } - - public void setNotificationType(UUID notificationType) { - this.notificationType = notificationType; - } - - public NotificationTemplateKind getKind() { - return kind; - } - - public void setKind(NotificationTemplateKind kind) { - this.kind = kind; - } - - public String getLanguageCode() { - return languageCode; - } - - public void setLanguageCode(String languageCode) { - this.languageCode = languageCode; - } - - public NotificationTemplateValue getValue() { - return value; - } - - public void setValue(NotificationTemplateValue value) { - this.value = value; - } - - 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 Tenant getTenant() { - return tenant; - } - - public void setTenant(Tenant tenant) { - this.tenant = tenant; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/SendNotificationResult.java b/notification-service/notification/src/main/java/gr/cite/notification/model/SendNotificationResult.java deleted file mode 100644 index b59a27807..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/SendNotificationResult.java +++ /dev/null @@ -1,47 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.common.enums.NotificationContactType; - -public class SendNotificationResult { - private Boolean success; - private NotificationContactType contactType; - private String trackingData; - - public SendNotificationResult() { - } - - public SendNotificationResult(Boolean success, NotificationContactType contactType) { - this.success = success; - this.contactType = contactType; - } - - public SendNotificationResult(Boolean success, NotificationContactType contactType, String trackingData) { - this.success = success; - this.contactType = contactType; - this.trackingData = trackingData; - } - - public Boolean getSuccess() { - return success; - } - - public void setSuccess(Boolean success) { - this.success = success; - } - - public NotificationContactType getContactType() { - return contactType; - } - - public void setContactType(NotificationContactType contactType) { - this.contactType = contactType; - } - - public String getTrackingData() { - return trackingData; - } - - public void setTrackingData(String trackingData) { - this.trackingData = trackingData; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/Tenant.java b/notification-service/notification/src/main/java/gr/cite/notification/model/Tenant.java deleted file mode 100644 index ab585cf72..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/Tenant.java +++ /dev/null @@ -1,82 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/TenantUser.java b/notification-service/notification/src/main/java/gr/cite/notification/model/TenantUser.java deleted file mode 100644 index 402356465..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/TenantUser.java +++ /dev/null @@ -1,98 +0,0 @@ -package gr.cite.notification.model; - - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/User.java b/notification-service/notification/src/main/java/gr/cite/notification/model/User.java deleted file mode 100644 index 7d3596491..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/User.java +++ /dev/null @@ -1,79 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.common.enums.IsActive; - -import java.time.Instant; -import java.util.List; -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 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/notification-service/notification/src/main/java/gr/cite/notification/model/UserContactInfo.java b/notification-service/notification/src/main/java/gr/cite/notification/model/UserContactInfo.java deleted file mode 100644 index cf899e095..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/UserContactInfo.java +++ /dev/null @@ -1,106 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.common.enums.ContactInfoType; -import gr.cite.notification.common.enums.IsActive; - -import java.time.Instant; -import java.util.UUID; - -public class UserContactInfo { - - private UUID id; - - public static final String _id = "id"; - - private User user; - - public static final String _user = "user"; - - 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"; - - 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 UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public Integer getOrdinal() { - return ordinal; - } - - public void setOrdinal(Integer ordinal) { - this.ordinal = ordinal; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - 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 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/notification-service/notification/src/main/java/gr/cite/notification/model/UserCredential.java b/notification-service/notification/src/main/java/gr/cite/notification/model/UserCredential.java deleted file mode 100644 index 7da0a716a..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/UserCredential.java +++ /dev/null @@ -1,69 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/UserNotificationPreference.java b/notification-service/notification/src/main/java/gr/cite/notification/model/UserNotificationPreference.java deleted file mode 100644 index 173016837..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/UserNotificationPreference.java +++ /dev/null @@ -1,119 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; - -import java.time.Instant; -import java.util.UUID; - -public class UserNotificationPreference { - - private UUID id; - - public static final String _id = "id"; - - private UUID userId; - - public static final String _userId = "userId"; - - private UUID type; - - public static final String _type = "type"; - - private UUID tenantId; - - public static final String _tenantId = "tenantId"; - - private NotificationContactType channel; - - public static final String _channel = "channel"; - - private Integer ordinal; - - public static final String _ordinal = "ordinal"; - - 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 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 UUID getType() { - return type; - } - - public void setType(UUID type) { - this.type = type; - } - - public UUID getTenantId() { - return tenantId; - } - - public void setTenantId(UUID tenantId) { - this.tenantId = tenantId; - } - - public NotificationContactType getChannel() { - return channel; - } - - public void setChannel(NotificationContactType channel) { - this.channel = channel; - } - - public Integer getOrdinal() { - return ordinal; - } - - public void setOrdinal(Integer ordinal) { - this.ordinal = ordinal; - } - - 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/notification-service/notification/src/main/java/gr/cite/notification/model/UserRole.java b/notification-service/notification/src/main/java/gr/cite/notification/model/UserRole.java deleted file mode 100644 index 7dc91d068..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/UserRole.java +++ /dev/null @@ -1,82 +0,0 @@ -package gr.cite.notification.model; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.conventers.IsActiveConverter; -import jakarta.persistence.Column; -import jakarta.persistence.Convert; - -import java.time.Instant; -import java.util.UUID; - -public class UserRole { - private UUID id; - public static final String _id = "id"; - - private String role; - public static final String _role = "role"; - - 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"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getRole() { - return role; - } - - public void setRole(String role) { - this.role = role; - } - - 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; - } - -} - diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java deleted file mode 100644 index ad1d29ada..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/BaseBuilder.java +++ /dev/null @@ -1,109 +0,0 @@ -package gr.cite.notification.model.builder; - -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -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 javax.management.InvalidApplicationException; -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 datas) 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(e -> e.size()).orElse(0)); - return this.asForeignKey(datas, directives, keySelector); - } - - public Map asForeignKey(List datas, FieldSet directives, Function keySelector) throws MyApplicationException { - this.logger.trace("building references"); - List models = this.build(directives, datas); - this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(e -> e.size()).orElse(0), Optional.ofNullable(datas).map(e -> e.size()).orElse(0)); - Map map = models.stream().collect(Collectors.toMap(o -> keySelector.apply(o), 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(e -> e.size()).orElse(0)); - return this.asMasterKey(datas, directives, keySelector); - } - - public Map> asMasterKey(List datas, FieldSet directives, Function keySelector) throws MyApplicationException { - this.logger.trace("building details"); - List models = this.build(directives, datas); - this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(e -> e.size()).orElse(0), Optional.ofNullable(datas).map(e -> e.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(x -> mapper.apply(x)).collect(Collectors.toList()); - this.logger.debug("mapping {} build items from {} requested", Optional.ofNullable(models).map(x -> x.size()).orElse(0), Optional.ofNullable(keys).map(x -> x.size())); - Map map = models.stream().collect(Collectors.toMap(o -> keySelector.apply(o), 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 boolean getBelongsToCurrentTenant(TenantScopedBaseEntity entity, TenantScope tenantScope){ - if (!tenantScope.isSet()) return true; - try { - if (entity.getTenantId() == null && tenantScope.getTenant() == null) return true; - if (entity.getTenantId() == null || tenantScope.getTenant() == null) return false; - - return entity.getTenantId().equals(tenantScope.getTenant()); - } catch (InvalidApplicationException e) { - return false; - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/InAppNotificationBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/InAppNotificationBuilder.java deleted file mode 100644 index cd6cc6acd..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/InAppNotificationBuilder.java +++ /dev/null @@ -1,141 +0,0 @@ -package gr.cite.notification.model.builder; - - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.InAppNotificationEntity; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.model.InAppNotification; -import gr.cite.notification.model.Notification; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.User; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.query.UserQuery; -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.annotation.Autowired; -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 InAppNotificationBuilder extends BaseBuilder { - - private final QueryFactory queryFactory; - private final BuilderFactory builderFactory; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public InAppNotificationBuilder( - ConventionService conventionService, - QueryFactory queryFactory, BuilderFactory builderFactory, JsonHandlingService jsonHandlingService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(InAppNotificationBuilder.class))); - this.queryFactory = queryFactory; - this.builderFactory = builderFactory; - } - - public InAppNotificationBuilder 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<>(); - - FieldSet tenantFields = fields.extractPrefixed(this.asPrefix(InAppNotification.Field.TENANT)); - Map tenantItemsMap = this.collectTenants(tenantFields, data); - - FieldSet userFields = fields.extractPrefixed(this.asPrefix(InAppNotification.Field.USER)); - Map userItemsMap = this.collectUsers(userFields, data); - - List models = new ArrayList<>(); - - for (InAppNotificationEntity d : data) { - InAppNotification m = new InAppNotification(); - if (fields.hasField(this.asIndexer(InAppNotification.Field.ID))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.TYPE))) m.setType(d.getType()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.IS_ACTIVE))) m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.CREATED_AT))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.UPDATED_AT))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.HASH))) m.setHash(this.hashValue(d.getUpdatedAt())); - if (fields.hasField(this.asIndexer(InAppNotification.Field.READ_TIME))) m.setReadTime(d.getReadTime()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.TRACKING_STATE))) m.setTrackingState(d.getTrackingState()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.BODY))) m.setBody(d.getBody()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.EXTRA_DATA))) m.setExtraData(d.getExtraData()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.PRIORITY))) m.setPriority(d.getPriority()); - if (fields.hasField(this.asIndexer(InAppNotification.Field.SUBJECT))) m.setSubject(d.getSubject()); - if (!tenantFields.isEmpty() && tenantItemsMap != null && tenantItemsMap.containsKey(d.getTenantId())) m.setTenant(tenantItemsMap.get(d.getTenantId())); - if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } - - private Map collectTenants(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", Tenant.class.getSimpleName()); - - Map itemMap; - if (!fields.hasOtherField(this.asIndexer(Tenant._id))) { - itemMap = this.asEmpty( - data.stream().map(InAppNotificationEntity::getTenantId).distinct().collect(Collectors.toList()), - x -> { - Tenant item = new Tenant(); - item.setId(x); - return item; - }, - Tenant::getId); - } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Tenant._id); - TenantQuery q = this.queryFactory.query(TenantQuery.class).disableTracking().authorize(this.authorize).ids(data.stream().map(InAppNotificationEntity::getTenantId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(TenantBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Tenant::getId); - } - if (!fields.hasField(Tenant._id)) { - itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); - } - - return itemMap; - } - - private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", User.class.getSimpleName()); - - Map itemMap; - if (!fields.hasOtherField(this.asIndexer(User._id))) { - itemMap = this.asEmpty( - data.stream().map(InAppNotificationEntity::getUserId).distinct().collect(Collectors.toList()), - x -> { - User item = new User(); - item.setId(x); - return item; - }, - User::getId); - } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); - UserQuery q = this.queryFactory.query(UserQuery.class).disableTracking().disableTracking().authorize(this.authorize).ids(data.stream().map(InAppNotificationEntity::getUserId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); - } - if (!fields.hasField(User._id)) { - itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); - } - - return itemMap; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/NotificationBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/NotificationBuilder.java deleted file mode 100644 index c870b0615..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/NotificationBuilder.java +++ /dev/null @@ -1,142 +0,0 @@ -package gr.cite.notification.model.builder; - - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.User; -import gr.cite.notification.model.Notification; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.query.UserQuery; -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.annotation.Autowired; -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 NotificationBuilder extends BaseBuilder { - - private final QueryFactory queryFactory; - private final BuilderFactory builderFactory; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public NotificationBuilder( - ConventionService conventionService, - QueryFactory queryFactory, BuilderFactory builderFactory, JsonHandlingService jsonHandlingService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(NotificationBuilder.class))); - this.queryFactory = queryFactory; - this.builderFactory = builderFactory; - } - - public NotificationBuilder 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<>(); - - FieldSet tenantFields = fields.extractPrefixed(this.asPrefix(Notification._tenant)); - Map tenantItemsMap = this.collectTenants(tenantFields, data); - - FieldSet userFields = fields.extractPrefixed(this.asPrefix(Notification._user)); - Map userItemsMap = this.collectUsers(userFields, data); - - List models = new ArrayList<>(); - - for (NotificationEntity d : data) { - Notification m = new Notification(); - if (fields.hasField(this.asIndexer(Notification._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(Notification._contactHint))) m.setContactHint(d.getContactHint()); - if (fields.hasField(this.asIndexer(Notification._contactTypeHint))) m.setContactTypeHint(d.getContactTypeHint()); - if (fields.hasField(this.asIndexer(Notification._notifiedAt))) m.setNotifiedAt(d.getNotifiedAt()); - if (fields.hasField(this.asIndexer(Notification._type))) m.setType(d.getType()); - if (fields.hasField(this.asIndexer(Notification._notifyState))) m.setNotifyState(d.getNotifyState()); - if (fields.hasField(this.asIndexer(Notification._notifiedWith))) m.setNotifiedWith(d.getNotifiedWith()); - if (fields.hasField(this.asIndexer(Notification._trackingState))) m.setTrackingState(d.getTrackingState()); - if (fields.hasField(this.asIndexer(Notification._trackingProcess))) m.setTrackingProcess(d.getTrackingProcess()); - if (fields.hasField(this.asIndexer(Notification._retryCount))) m.setRetryCount(d.getRetryCount()); - if (fields.hasField(this.asIndexer(Notification._isActive))) m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(Notification._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(Notification._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(Notification._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); - if (!tenantFields.isEmpty() && tenantItemsMap != null && tenantItemsMap.containsKey(d.getTenantId())) m.setTenant(tenantItemsMap.get(d.getTenantId())); - if (!userFields.isEmpty() && userItemsMap != null && userItemsMap.containsKey(d.getUserId())) m.setUser(userItemsMap.get(d.getUserId())); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } - - private Map collectTenants(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", Tenant.class.getSimpleName()); - - Map itemMap; - if (!fields.hasOtherField(this.asIndexer(Tenant._id))) { - itemMap = this.asEmpty( - data.stream().map(NotificationEntity::getTenantId).distinct().collect(Collectors.toList()), - x -> { - Tenant item = new Tenant(); - item.setId(x); - return item; - }, - Tenant::getId); - } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Tenant._id); - TenantQuery q = this.queryFactory.query(TenantQuery.class).disableTracking().authorize(this.authorize).ids(data.stream().map(NotificationEntity::getTenantId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(TenantBuilder.class).authorize(this.authorize).asForeignKey(q, clone, Tenant::getId); - } - if (!fields.hasField(Tenant._id)) { - itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); - } - - return itemMap; - } - - private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", User.class.getSimpleName()); - - Map itemMap; - if (!fields.hasOtherField(this.asIndexer(User._id))) { - itemMap = this.asEmpty( - data.stream().map(NotificationEntity::getUserId).filter(Objects::nonNull).distinct().collect(Collectors.toList()), - x -> { - User item = new User(); - item.setId(x); - return item; - }, - User::getId); - } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); - UserQuery q = this.queryFactory.query(UserQuery.class).disableTracking().authorize(this.authorize).ids(data.stream().map(NotificationEntity::getUserId).filter(Objects::nonNull).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); - } - if (!fields.hasField(User._id)) { - itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toList()); - } - - return itemMap; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/NotificationTemplateBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/NotificationTemplateBuilder.java deleted file mode 100644 index 810e4512f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/NotificationTemplateBuilder.java +++ /dev/null @@ -1,110 +0,0 @@ -package gr.cite.notification.model.builder; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.types.notificationtemplate.NotificationTemplateValueEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.NotificationTemplateEntity; -import gr.cite.notification.model.NotificationTemplate; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.builder.notificationtemplate.NotificationTemplateValueBuilder; -import gr.cite.notification.query.TenantQuery; -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.annotation.Autowired; -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 NotificationTemplateBuilder extends BaseBuilder { - - private final BuilderFactory builderFactory; - private final QueryFactory queryFactory; - private final JsonHandlingService jsonHandlingService; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - @Autowired - public NotificationTemplateBuilder(ConventionService conventionService, BuilderFactory builderFactory, QueryFactory queryFactory, JsonHandlingService jsonHandlingService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(NotificationTemplateBuilder.class))); - this.builderFactory = builderFactory; - this.queryFactory = queryFactory; - this.jsonHandlingService = jsonHandlingService; - } - - public NotificationTemplateBuilder 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<>(); - - FieldSet valueFields = fields.extractPrefixed(this.asPrefix(NotificationTemplate._value)); - - FieldSet tenantFields = fields.extractPrefixed(this.asPrefix(NotificationTemplate._tenant)); - Map tenantMap = this.collectTenants(tenantFields, data); - - List models = new ArrayList<>(); - for(NotificationTemplateEntity d : data){ - NotificationTemplate m = new NotificationTemplate(); - if(fields.hasField(this.asIndexer(NotificationTemplate._id))) m.setId(d.getId()); - if(fields.hasField(this.asIndexer(NotificationTemplate._channel))) m.setChannel(d.getChannel()); - if(fields.hasField(this.asIndexer(NotificationTemplate._notificationType))) m.setNotificationType(d.getNotificationType()); - if(fields.hasField(this.asIndexer(NotificationTemplate._kind))) m.setKind(d.getKind()); - if(fields.hasField(this.asIndexer(NotificationTemplate._languageCode))) m.setLanguageCode(d.getLanguageCode()); - if (!valueFields.isEmpty() && d.getValue() != null){ - NotificationTemplateValueEntity value = this.jsonHandlingService.fromJsonSafe(NotificationTemplateValueEntity.class, d.getValue()); - m.setValue(this.builderFactory.builder(NotificationTemplateValueBuilder.class).authorize(this.authorize).build(valueFields, value)); - } - if(fields.hasField(this.asIndexer(NotificationTemplate._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(NotificationTemplate._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); - if (!tenantFields.isEmpty() && tenantMap != null && tenantMap.containsKey(d.getTenantId())) m.setTenant(tenantMap.get(d.getTenantId())); - models.add(m); - } - this.logger.debug("build {} items",Optional.of(models).map(List::size).orElse(0)); - return models; - } - - private Map collectTenants(FieldSet fields, List datas) throws MyApplicationException { - if (fields.isEmpty() || datas.isEmpty()) return null; - this.logger.debug("checking related - {}", NotificationTemplate.class.getSimpleName()); - - Map itemMap = null; - if (!fields.hasOtherField(this.asIndexer(Tenant._id))) { - itemMap = this.asEmpty( - datas.stream().map(x -> x.getTenantId()).distinct().collect(Collectors.toList()), - x -> { - Tenant item = new Tenant(); - item.setId(x); - return item; - }, - x -> x.getId()); - } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(Tenant._id); - TenantQuery q = this.queryFactory.query(TenantQuery.class).disableTracking().authorize(this.authorize).ids(datas.stream().map(x -> x.getTenantId()).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(TenantBuilder.class).authorize(this.authorize).asForeignKey(q, clone, x -> x.getId()); - } - if (!fields.hasField(Tenant._id)) { - itemMap.values().stream().filter(x -> x != null).map(x -> { - x.setId(null); - return x; - }).collect(Collectors.toList()); - } - - return itemMap; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/TenantBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/TenantBuilder.java deleted file mode 100644 index b647a54e0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/TenantBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -package gr.cite.notification.model.builder; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.XmlHandlingService; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserBuilder.java deleted file mode 100644 index 6519c9f63..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserBuilder.java +++ /dev/null @@ -1,61 +0,0 @@ -package gr.cite.notification.model.builder; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.UserEntity; -import gr.cite.notification.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.*; -import java.util.stream.Collectors; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserBuilder extends BaseBuilder { - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public UserBuilder( - ConventionService conventionService - ) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(UserBuilder.class))); - } - - 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(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() || datas == null) 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", models.size()); - return models; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserContactInfoBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserContactInfoBuilder.java deleted file mode 100644 index be2377a6c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserContactInfoBuilder.java +++ /dev/null @@ -1,98 +0,0 @@ -package gr.cite.notification.model.builder; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.UserContactInfoEntity; -import gr.cite.notification.data.tenant.TenantScopedBaseEntity; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.User; -import gr.cite.notification.model.UserContactInfo; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.query.UserQuery; -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.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.util.*; -import java.util.function.Function; -import java.util.stream.Collectors; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserContactInfoBuilder extends BaseBuilder { - - private final BuilderFactory builderFactory; - private final QueryFactory queryFactory; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - public UserContactInfoBuilder(ConventionService conventionService, LoggerService logger, BuilderFactory builderFactory, QueryFactory queryFactory) { - super(conventionService, logger); - this.builderFactory = builderFactory; - this.queryFactory = queryFactory; - } - - public UserContactInfoBuilder 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<>(); - - FieldSet userFields = fields.extractPrefixed(this.asPrefix(UserContactInfo._user)); - Map userMap = this.collectUsers(userFields, data); - - List models = new ArrayList<>(); - - for (UserContactInfoEntity d : data) { - UserContactInfo m = new UserContactInfo(); - if (fields.hasField(this.asIndexer(UserContactInfo._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(UserContactInfo._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(UserContactInfo._ordinal))) m.setOrdinal(d.getOrdinal()); - if (fields.hasField(this.asIndexer(UserContactInfo._value))) m.setValue(d.getValue()); - if (fields.hasField(this.asIndexer(UserContactInfo._type))) m.setType(d.getType()); - if (!userFields.isEmpty() && userMap != null && userMap.containsKey(d.getUserId())) m.setUser(userMap.get(d.getUserId())); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } - - private Map collectUsers(FieldSet fields, List data) throws MyApplicationException { - if (fields.isEmpty() || data.isEmpty()) return null; - this.logger.debug("checking related - {}", User.class.getSimpleName()); - - Map itemMap; - if (!fields.hasOtherField(this.asIndexer(User._id))) { - itemMap = this.asEmpty( - data.stream().map(UserContactInfoEntity::getUserId).distinct().collect(Collectors.toList()), - x -> { - User item = new User(); - item.setId(x); - return item; - }, - User::getId); - } else { - FieldSet clone = new BaseFieldSet(fields.getFields()).ensure(User._id); - UserQuery q = this.queryFactory.query(UserQuery.class).disableTracking().authorize(this.authorize).ids(data.stream().map(UserContactInfoEntity::getUserId).distinct().collect(Collectors.toList())); - itemMap = this.builderFactory.builder(UserBuilder.class).authorize(this.authorize).asForeignKey(q, clone, User::getId); - } - if (!fields.hasField(User._id)) { - itemMap = itemMap.values().stream().filter(Objects::nonNull).peek(x -> x.setId(null)).collect(Collectors.toMap(User::getId, Function.identity())); - } - - return itemMap; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserNotificationPreferenceBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserNotificationPreferenceBuilder.java deleted file mode 100644 index 10a3fc3b5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/UserNotificationPreferenceBuilder.java +++ /dev/null @@ -1,57 +0,0 @@ -package gr.cite.notification.model.builder; - -import com.fasterxml.jackson.databind.ObjectMapper; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.UserNotificationPreferenceEntity; -import gr.cite.notification.model.tenantconfiguration.TenantConfiguration; -import gr.cite.notification.model.UserNotificationPreference; -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.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import java.util.*; - -@Component -@RequestScope -public class UserNotificationPreferenceBuilder extends BaseBuilder { - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - private final ObjectMapper mapper; - @Autowired - public UserNotificationPreferenceBuilder(ConventionService conventionService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(UserNotificationPreferenceBuilder.class))); - this.mapper = new ObjectMapper(); - } - - public UserNotificationPreferenceBuilder 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(UserNotificationPreferenceEntity d : data){ - UserNotificationPreference m = new UserNotificationPreference(); - if(fields.hasField(this.asIndexer(UserNotificationPreference._id))) m.setId(d.getId()); - if(fields.hasField(this.asIndexer(UserNotificationPreference._userId))) m.setUserId(d.getUserId()); - if(fields.hasField(this.asIndexer(UserNotificationPreference._tenantId))) m.setTenantId(d.getTenantId()); - if(fields.hasField(this.asIndexer(UserNotificationPreference._type))) m.setType(d.getType()); - if(fields.hasField(this.asIndexer(UserNotificationPreference._channel))) m.setChannel(d.getChannel()); - if(fields.hasField(this.asIndexer(UserNotificationPreference._ordinal))) m.setOrdinal(d.getOrdinal()); - if(fields.hasField(this.asIndexer(TenantConfiguration._createdAt))) m.setCreatedAt(d.getCreatedAt()); - models.add(m); - } - this.logger.debug("build {} items",Optional.of(models).map(List::size).orElse(0)); - return models; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/FieldInfoBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/FieldInfoBuilder.java deleted file mode 100644 index 339ef670f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/FieldInfoBuilder.java +++ /dev/null @@ -1,57 +0,0 @@ -package gr.cite.notification.model.builder.notificationtemplate; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.types.notification.FieldInfo; -import gr.cite.notification.common.types.notificationtemplate.FieldInfoEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.builder.BaseBuilder; -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 FieldInfoBuilder extends BaseBuilder { - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public FieldInfoBuilder( - ConventionService conventionService, BuilderFactory builderFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldInfoBuilder.class))); - } - - public FieldInfoBuilder 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 (FieldInfoEntity d : data) { - FieldInfo m = new FieldInfo(); - if (fields.hasField(this.asIndexer(FieldInfo._key))) m.setKey(d.getKey()); - if (fields.hasField(this.asIndexer(FieldInfo._value))) m.setValue(d.getValue()); - if (fields.hasField(this.asIndexer(FieldInfo._type))) m.setType(d.getType()); - - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/FieldOptionsBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/FieldOptionsBuilder.java deleted file mode 100644 index c213dc88b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/FieldOptionsBuilder.java +++ /dev/null @@ -1,64 +0,0 @@ -package gr.cite.notification.model.builder.notificationtemplate; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.types.notificationtemplate.FieldOptionsEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.builder.BaseBuilder; -import gr.cite.notification.model.notificationtemplate.FieldOptions; -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 FieldOptionsBuilder extends BaseBuilder { - - private final BuilderFactory builderFactory; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public FieldOptionsBuilder( - ConventionService conventionService, BuilderFactory builderFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(FieldOptionsBuilder.class))); - this.builderFactory = builderFactory; - } - - public FieldOptionsBuilder 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<>(); - - FieldSet optionalFields = fields.extractPrefixed(this.asPrefix(FieldOptions._optional)); - - List models = new ArrayList<>(); - for (FieldOptionsEntity d : data) { - FieldOptions m = new FieldOptions(); - if (fields.hasField(this.asIndexer(FieldOptions._mandatory))) m.setMandatory(d.getMandatory()); - if (!optionalFields.isEmpty() && d.getOptional() != null) { - m.setOptional(this.builderFactory.builder(FieldInfoBuilder.class).authorize(this.authorize).build(optionalFields, d.getOptional())); - } - if (fields.hasField(this.asIndexer(FieldOptions._formatting))) m.setFormatting(d.getFormatting()); - - - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/NotificationTemplateValueBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/NotificationTemplateValueBuilder.java deleted file mode 100644 index d5022d8dd..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/notificationtemplate/NotificationTemplateValueBuilder.java +++ /dev/null @@ -1,78 +0,0 @@ -package gr.cite.notification.model.builder.notificationtemplate; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.types.notificationtemplate.NotificationTemplateValueEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.builder.BaseBuilder; -import gr.cite.notification.model.notificationtemplate.FieldOptions; -import gr.cite.notification.model.notificationtemplate.NotificationTemplateValue; -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 NotificationTemplateValueBuilder extends BaseBuilder { - - private final BuilderFactory builderFactory; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public NotificationTemplateValueBuilder( - ConventionService conventionService, BuilderFactory builderFactory) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(NotificationTemplateValueBuilder.class))); - this.builderFactory = builderFactory; - } - - public NotificationTemplateValueBuilder 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<>(); - - FieldSet subjectFieldOptionsFields = fields.extractPrefixed(this.asPrefix(NotificationTemplateValue._subjectFieldOptions)); - FieldSet bodyFieldOptionsFields = fields.extractPrefixed(this.asPrefix(NotificationTemplateValue._bodyFieldOptions)); - - - List models = new ArrayList<>(); - for (NotificationTemplateValueEntity d : data) { - NotificationTemplateValue m = new NotificationTemplateValue(); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._subjectText))) m.setSubjectText(d.getSubjectText()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._subjectKey))) m.setSubjectKey(d.getSubjectKey()); - if (!subjectFieldOptionsFields.isEmpty() && d.getSubjectFieldOptions() != null) { - m.setSubjectFieldOptions(this.builderFactory.builder(FieldOptionsBuilder.class).authorize(this.authorize).build(subjectFieldOptionsFields, d.getSubjectFieldOptions())); - } - if (fields.hasField(this.asIndexer(NotificationTemplateValue._bodyText))) m.setBodyText(d.getBodyText()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._bodyKey))) m.setBodyKey(d.getBodyKey()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._priorityKey))) m.setPriorityKey(d.getPriorityKey()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._allowAttachments))) m.setAllowAttachments(d.getAllowAttachments()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._cc))) m.setCc(d.getCc()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._ccMode))) m.setCcMode(d.getCcMode()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._bcc))) m.setBcc(d.getBcc()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._bccMode))) m.setBccMode(d.getBccMode()); - if (fields.hasField(this.asIndexer(NotificationTemplateValue._extraDataKeys))) m.setExtraDataKeys(d.getExtraDataKeys()); - if (!bodyFieldOptionsFields.isEmpty() && d.getBodyFieldOptions() != null) { - m.setBodyFieldOptions(this.builderFactory.builder(FieldOptionsBuilder.class).authorize(this.authorize).build(bodyFieldOptionsFields, d.getBodyFieldOptions())); - } - - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/DefaultUserLocaleTenantConfigurationBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/DefaultUserLocaleTenantConfigurationBuilder.java deleted file mode 100644 index 8bd5916c0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/DefaultUserLocaleTenantConfigurationBuilder.java +++ /dev/null @@ -1,54 +0,0 @@ -package gr.cite.notification.model.builder.tenantconfiguration; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.types.tenantconfiguration.DefaultUserLocaleTenantConfigurationEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.builder.BaseBuilder; -import gr.cite.notification.model.tenantconfiguration.DefaultUserLocaleTenantConfiguration; -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 DefaultUserLocaleTenantConfigurationBuilder extends BaseBuilder { - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public DefaultUserLocaleTenantConfigurationBuilder( - ConventionService conventionService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(DefaultUserLocaleTenantConfigurationBuilder.class))); - } - - public DefaultUserLocaleTenantConfigurationBuilder 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 (DefaultUserLocaleTenantConfigurationEntity d : data) { - DefaultUserLocaleTenantConfiguration m = new DefaultUserLocaleTenantConfiguration(); - if (fields.hasField(this.asIndexer(DefaultUserLocaleTenantConfiguration._culture))) m.setCulture(d.getCulture()); - if (fields.hasField(this.asIndexer(DefaultUserLocaleTenantConfiguration._timezone))) m.setTimezone(d.getTimezone()); - if (fields.hasField(this.asIndexer(DefaultUserLocaleTenantConfiguration._language))) m.setLanguage(d.getLanguage()); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/NotifierListTenantConfigurationBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/NotifierListTenantConfigurationBuilder.java deleted file mode 100644 index 438a36dd1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/NotifierListTenantConfigurationBuilder.java +++ /dev/null @@ -1,52 +0,0 @@ -package gr.cite.notification.model.builder.tenantconfiguration; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.builder.BaseBuilder; -import gr.cite.notification.model.tenantconfiguration.NotifierListTenantConfiguration; -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 NotifierListTenantConfigurationBuilder extends BaseBuilder { - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public NotifierListTenantConfigurationBuilder( - ConventionService conventionService) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(NotifierListTenantConfigurationBuilder.class))); - } - - public NotifierListTenantConfigurationBuilder 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 (NotifierListTenantConfigurationEntity d : data) { - NotifierListTenantConfiguration m = new NotifierListTenantConfiguration(); - if (fields.hasField(this.asIndexer(NotifierListTenantConfiguration._notifiers))) m.setNotifiers(d.getNotifiers()); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/TenantConfigurationBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/TenantConfigurationBuilder.java deleted file mode 100644 index 8022c2c1d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/builder/tenantconfiguration/TenantConfigurationBuilder.java +++ /dev/null @@ -1,84 +0,0 @@ -package gr.cite.notification.model.builder.tenantconfiguration; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.types.tenantconfiguration.DefaultUserLocaleTenantConfigurationEntity; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.model.builder.BaseBuilder; -import gr.cite.notification.model.tenantconfiguration.TenantConfiguration; -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 TenantConfigurationBuilder extends BaseBuilder { - private final TenantScope tenantScope; - private final JsonHandlingService jsonHandlingService; - - private final BuilderFactory builderFactory; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - @Autowired - public TenantConfigurationBuilder( - ConventionService conventionService, - TenantScope tenantScope, JsonHandlingService jsonHandlingService, BuilderFactory builderFactory1) { - super(conventionService, new LoggerService(LoggerFactory.getLogger(TenantConfigurationBuilder.class))); - this.tenantScope = tenantScope; - this.jsonHandlingService = jsonHandlingService; - this.builderFactory = builderFactory1; - } - - public TenantConfigurationBuilder 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<>(); - - FieldSet notifierListFields = fields.extractPrefixed(this.asPrefix(TenantConfiguration._notifierList)); - FieldSet defaultUserLocaleFields = fields.extractPrefixed(this.asPrefix(TenantConfiguration._defaultUserLocale)); - - - List models = new ArrayList<>(); - for (TenantConfigurationEntity d : data) { - TenantConfiguration m = new TenantConfiguration(); - if (fields.hasField(this.asIndexer(TenantConfiguration._id))) m.setId(d.getId()); - if (fields.hasField(this.asIndexer(TenantConfiguration._type))) m.setType(d.getType()); - if (!notifierListFields.isEmpty() && !this.conventionService.isNullOrEmpty(d.getValue()) && TenantConfigurationType.NotifierList.equals(d.getType())){ - NotifierListTenantConfigurationEntity valueTyped = this.jsonHandlingService.fromJsonSafe(NotifierListTenantConfigurationEntity.class, d.getValue()); - m.setNotifierList(this.builderFactory.builder(NotifierListTenantConfigurationBuilder.class).authorize(this.authorize).build(notifierListFields, valueTyped)); - } - if (!defaultUserLocaleFields.isEmpty() && !this.conventionService.isNullOrEmpty(d.getValue()) && TenantConfigurationType.DefaultUserLocale.equals(d.getType())){ - DefaultUserLocaleTenantConfigurationEntity valueTyped = this.jsonHandlingService.fromJsonSafe(DefaultUserLocaleTenantConfigurationEntity.class, d.getValue()); - m.setDefaultUserLocale(this.builderFactory.builder(DefaultUserLocaleTenantConfigurationBuilder.class).authorize(this.authorize).build(defaultUserLocaleFields, valueTyped)); - } - if (fields.hasField(this.asIndexer(TenantConfiguration._createdAt))) m.setCreatedAt(d.getCreatedAt()); - if (fields.hasField(this.asIndexer(TenantConfiguration._updatedAt))) m.setUpdatedAt(d.getUpdatedAt()); - if (fields.hasField(this.asIndexer(TenantConfiguration._isActive))) m.setIsActive(d.getIsActive()); - if (fields.hasField(this.asIndexer(TenantConfiguration._hash))) m.setHash(this.hashValue(d.getUpdatedAt())); - if (fields.hasField(this.asIndexer(TenantConfiguration._belongsToCurrentTenant))) m.setBelongsToCurrentTenant(this.getBelongsToCurrentTenant(d, this.tenantScope)); - models.add(m); - } - this.logger.debug("build {} items", Optional.of(models).map(List::size).orElse(0)); - return models; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/BaseCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/BaseCensor.java deleted file mode 100644 index 12d1b9360..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/BaseCensor.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.notification.model.censorship; - -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/InAppNotificationCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/InAppNotificationCensor.java deleted file mode 100644 index 0bc1c06be..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/InAppNotificationCensor.java +++ /dev/null @@ -1,42 +0,0 @@ -package gr.cite.notification.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.OwnedResource; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.InAppNotification; -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.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 InAppNotificationCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InAppNotificationCensor.class)); - private final AuthorizationService authService; - protected final CensorFactory censorFactory; - - @Autowired - public InAppNotificationCensor(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 (this.isEmpty(fields)) return; - this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseInAppNotification); - FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(InAppNotification.Field.USER)); - this.censorFactory.censor(UserCensor.class).censor(userFields, userId); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/NotificationCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/NotificationCensor.java deleted file mode 100644 index 26be1e959..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/NotificationCensor.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.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 NotificationCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationCensor.class)); - private final AuthorizationService authService; - - @Autowired - public NotificationCensor(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.BrowseNotification); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/NotificationTemplateCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/NotificationTemplateCensor.java deleted file mode 100644 index 7112e41a4..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/NotificationTemplateCensor.java +++ /dev/null @@ -1,39 +0,0 @@ -package gr.cite.notification.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.NotificationTemplate; -import gr.cite.notification.model.censorship.notificationtemplate.NotificationTemplateValueCensor; -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.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 NotificationTemplateCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationTemplateCensor.class)); - protected final AuthorizationService authService; - protected final CensorFactory censorFactory; - - @Autowired - public NotificationTemplateCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { - super(conventionService); - this.authService = authService; - this.censorFactory = censorFactory; - } - - public void censor(FieldSet fields) { - logger.debug(new DataLogEntry("censoring fields", fields)); - if (this.isEmpty(fields)) return; - this.authService.authorizeForce(Permission.BrowseNotificationTemplate); - FieldSet valueFields = fields.extractPrefixed(this.asIndexerPrefix(NotificationTemplate._value)); - this.censorFactory.censor(NotificationTemplateValueCensor.class).censor(valueFields); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/TenantCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/TenantCensor.java deleted file mode 100644 index 4440362e2..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/TenantCensor.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserCensor.java deleted file mode 100644 index 11afb5a08..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserCensor.java +++ /dev/null @@ -1,47 +0,0 @@ -package gr.cite.notification.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.OwnedResource; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserContactInfoCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserContactInfoCensor.java deleted file mode 100644 index 0a009d8f7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserContactInfoCensor.java +++ /dev/null @@ -1,50 +0,0 @@ -package gr.cite.notification.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.OwnedResource; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.UserContactInfo; -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 UserContactInfoCensor extends BaseCensor { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserContactInfoCensor.class)); - - protected final AuthorizationService authService; - protected final CensorFactory censorFactory; - - @Autowired - public UserContactInfoCensor( - 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.BrowseUserContactInfo); - FieldSet userFields = fields.extractPrefixed(this.asIndexerPrefix(UserContactInfo._user)); - this.censorFactory.censor(UserCensor.class).censor(userFields, userId); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserNotificationPreferenceCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserNotificationPreferenceCensor.java deleted file mode 100644 index 13847a527..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/UserNotificationPreferenceCensor.java +++ /dev/null @@ -1,36 +0,0 @@ -package gr.cite.notification.model.censorship; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.OwnedResource; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.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; - -import java.util.List; -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class UserNotificationPreferenceCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserNotificationPreferenceCensor.class)); - private final AuthorizationService authService; - - @Autowired - public UserNotificationPreferenceCensor(ConventionService conventionService, AuthorizationService authService) { - super(conventionService); - this.authService = authService; - } - - public void censor(FieldSet fields, UUID userId) { - logger.debug(new DataLogEntry("censoring fields", fields)); - if (this.isEmpty(fields)) return; - this.authService.authorizeAtLeastOneForce(userId != null ? List.of(new OwnedResource(userId)) : null, Permission.BrowseUserNotificationPreference); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/FieldInfoCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/FieldInfoCensor.java deleted file mode 100644 index 7f8c93fb7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/FieldInfoCensor.java +++ /dev/null @@ -1,33 +0,0 @@ -package gr.cite.notification.model.censorship.notificationtemplate; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.censorship.BaseCensor; -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 FieldInfoCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FieldInfoCensor.class)); - private final AuthorizationService authService; - - @Autowired - public FieldInfoCensor(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.BrowseNotificationTemplate); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/FieldOptionsCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/FieldOptionsCensor.java deleted file mode 100644 index 44894dec9..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/FieldOptionsCensor.java +++ /dev/null @@ -1,39 +0,0 @@ -package gr.cite.notification.model.censorship.notificationtemplate; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.censorship.BaseCensor; -import gr.cite.notification.model.notificationtemplate.FieldOptions; -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.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 FieldOptionsCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(FieldOptionsCensor.class)); - protected final AuthorizationService authService; - protected final CensorFactory censorFactory; - - @Autowired - public FieldOptionsCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { - super(conventionService); - this.authService = authService; - this.censorFactory = censorFactory; - } - - public void censor(FieldSet fields) { - logger.debug(new DataLogEntry("censoring fields", fields)); - if (this.isEmpty(fields)) return; - this.authService.authorizeForce(Permission.BrowseNotificationTemplate); - FieldSet optionalFields = fields.extractPrefixed(this.asIndexerPrefix(FieldOptions._optional)); - this.censorFactory.censor(FieldInfoCensor.class).censor(optionalFields); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/NotificationTemplateValueCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/NotificationTemplateValueCensor.java deleted file mode 100644 index 38f6c104c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/notificationtemplate/NotificationTemplateValueCensor.java +++ /dev/null @@ -1,43 +0,0 @@ -package gr.cite.notification.model.censorship.notificationtemplate; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.NotificationTemplate; -import gr.cite.notification.model.censorship.BaseCensor; -import gr.cite.notification.model.notificationtemplate.FieldOptions; -import gr.cite.notification.model.notificationtemplate.NotificationTemplateValue; -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.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 NotificationTemplateValueCensor extends BaseCensor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationTemplateValueCensor.class)); - protected final AuthorizationService authService; - protected final CensorFactory censorFactory; - - @Autowired - public NotificationTemplateValueCensor(ConventionService conventionService, AuthorizationService authService, CensorFactory censorFactory) { - super(conventionService); - this.authService = authService; - this.censorFactory = censorFactory; - } - - public void censor(FieldSet fields) { - logger.debug(new DataLogEntry("censoring fields", fields)); - if (this.isEmpty(fields)) return; - this.authService.authorizeForce(Permission.BrowseNotificationTemplate); - FieldSet subjectFieldOptionsFields = fields.extractPrefixed(this.asIndexerPrefix(NotificationTemplateValue._subjectFieldOptions)); - this.censorFactory.censor(FieldOptionsCensor.class).censor(subjectFieldOptionsFields); - FieldSet bodyFieldOptionsFields = fields.extractPrefixed(this.asIndexerPrefix(NotificationTemplateValue._bodyFieldOptions)); - this.censorFactory.censor(FieldOptionsCensor.class).censor(bodyFieldOptionsFields); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/DefaultUserLocaleTenantConfigurationCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/DefaultUserLocaleTenantConfigurationCensor.java deleted file mode 100644 index 56b215ba7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/DefaultUserLocaleTenantConfigurationCensor.java +++ /dev/null @@ -1,38 +0,0 @@ -package gr.cite.notification.model.censorship.tenantconfiguration; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.censorship.BaseCensor; -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 DefaultUserLocaleTenantConfigurationCensor extends BaseCensor { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DefaultUserLocaleTenantConfigurationCensor.class)); - - protected final AuthorizationService authService; - - - public DefaultUserLocaleTenantConfigurationCensor(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.authorize(Permission.BrowseTenantConfiguration); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/NotifierListTenantConfigurationCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/NotifierListTenantConfigurationCensor.java deleted file mode 100644 index 9d396fe77..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/NotifierListTenantConfigurationCensor.java +++ /dev/null @@ -1,38 +0,0 @@ -package gr.cite.notification.model.censorship.tenantconfiguration; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.censorship.BaseCensor; -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 NotifierListTenantConfigurationCensor extends BaseCensor { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotifierListTenantConfigurationCensor.class)); - - protected final AuthorizationService authService; - - - public NotifierListTenantConfigurationCensor(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.authorize(Permission.BrowseTenantConfiguration); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/TenantConfigurationCensor.java b/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/TenantConfigurationCensor.java deleted file mode 100644 index 6dd0515b2..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/censorship/tenantconfiguration/TenantConfigurationCensor.java +++ /dev/null @@ -1,49 +0,0 @@ -package gr.cite.notification.model.censorship.tenantconfiguration; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.model.censorship.BaseCensor; -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 gr.cite.notification.model.tenantconfiguration.TenantConfiguration; - -import java.util.UUID; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class TenantConfigurationCensor extends BaseCensor { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantConfigurationCensor.class)); - - protected final AuthorizationService authService; - - protected final CensorFactory censorFactory; - - - public TenantConfigurationCensor(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.authorize(Permission.BrowseTenantConfiguration); - - FieldSet cssColorsFields = fields.extractPrefixed(this.asIndexerPrefix(TenantConfiguration._notifierList)); - this.censorFactory.censor(NotifierListTenantConfigurationCensor.class).censor(cssColorsFields, userId); - - FieldSet defaultUserLocaleFields = fields.extractPrefixed(this.asIndexerPrefix(TenantConfiguration._defaultUserLocale)); - this.censorFactory.censor(DefaultUserLocaleTenantConfigurationCensor.class).censor(defaultUserLocaleFields, userId); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/InAppNotificationDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/InAppNotificationDeleter.java deleted file mode 100644 index fc4551de2..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/InAppNotificationDeleter.java +++ /dev/null @@ -1,75 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.InAppNotificationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.query.InAppNotificationQuery; -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 InAppNotificationDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InAppNotificationDeleter.class)); - - private final TenantEntityManager entityManager; - protected final QueryFactory queryFactory; - - @Autowired - public InAppNotificationDeleter( - 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(InAppNotificationQuery.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; - - List ids = datas.stream().map(InAppNotificationEntity::getId).distinct().collect(Collectors.toList()); - - Instant now = Instant.now(); - - for (InAppNotificationEntity 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"); - } - - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/NotificationDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/NotificationDeleter.java deleted file mode 100644 index 1a743cc04..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/NotificationDeleter.java +++ /dev/null @@ -1,77 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.query.NotificationQuery; -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 NotificationDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationDeleter.class)); - - private final TenantEntityManager entityManager; - protected final QueryFactory queryFactory; - private final DeleterFactory deleterFactory; - - @Autowired - public NotificationDeleter( - 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(NotificationQuery.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; - - List ids = datas.stream().map(NotificationEntity::getId).distinct().collect(Collectors.toList()); - - Instant now = Instant.now(); - - for (NotificationEntity item : datas) { - logger.trace("deleting item {}", item.getId()); - item.setIsActive(IsActive.Inactive); - logger.trace("updating item"); - this.entityManager.merge(item); - logger.trace("updated item"); - } - - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/NotificationTemplateDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/NotificationTemplateDeleter.java deleted file mode 100644 index a69f060c8..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/NotificationTemplateDeleter.java +++ /dev/null @@ -1,78 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.NotificationTemplateEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.query.NotificationTemplateQuery; -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 NotificationTemplateDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationTemplateDeleter.class)); - - private final TenantEntityManager entityManager; - protected final QueryFactory queryFactory; - private final DeleterFactory deleterFactory; - - @Autowired - public NotificationTemplateDeleter( - 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(NotificationTemplateQuery.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; - - List ids = datas.stream().map(NotificationTemplateEntity::getId).distinct().collect(Collectors.toList()); - - Instant now = Instant.now(); - - for (NotificationTemplateEntity 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"); - } - - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantConfigurationDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantConfigurationDeleter.java deleted file mode 100644 index 36a6c2d26..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantConfigurationDeleter.java +++ /dev/null @@ -1,75 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.query.TenantConfigurationQuery; -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 TenantConfigurationDeleter implements Deleter { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantConfigurationDeleter.class)); - - private final TenantEntityManager entityManager; - protected final QueryFactory queryFactory; - - @Autowired - public TenantConfigurationDeleter( - 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(TenantConfigurationQuery.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; - - List ids = datas.stream().map(TenantConfigurationEntity::getId).distinct().toList(); - - Instant now = Instant.now(); - - for (TenantConfigurationEntity 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"); - } - - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantDeleter.java deleted file mode 100644 index 3c5338041..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantDeleter.java +++ /dev/null @@ -1,78 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.event.EventBroker; -import gr.cite.notification.event.TenantTouchedEvent; -import gr.cite.notification.event.UserRemovedFromTenantEvent; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantUserDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantUserDeleter.java deleted file mode 100644 index 64bf82a63..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/TenantUserDeleter.java +++ /dev/null @@ -1,76 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.TenantUserEntity; -import gr.cite.notification.event.EventBroker; -import gr.cite.notification.event.UserRemovedFromTenantEvent; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserContactInfoDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserContactInfoDeleter.java deleted file mode 100644 index a583d34fc..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserContactInfoDeleter.java +++ /dev/null @@ -1,75 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserContactInfoEntity; -import gr.cite.notification.query.UserContactInfoQuery; -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 UserContactInfoDeleter implements Deleter { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserContactInfoDeleter.class)); - - private final TenantEntityManager entityManager; - - private final QueryFactory queryFactory; - - @Autowired - public UserContactInfoDeleter( - 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(UserContactInfoQuery.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 (UserContactInfoEntity 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/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserCredentialDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserCredentialDeleter.java deleted file mode 100644 index a76206d90..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserCredentialDeleter.java +++ /dev/null @@ -1,69 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserCredentialEntity; -import gr.cite.notification.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; - - 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/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java b/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java deleted file mode 100644 index 9355ccea0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/deleter/UserDeleter.java +++ /dev/null @@ -1,97 +0,0 @@ -package gr.cite.notification.model.deleter; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserContactInfoEntity; -import gr.cite.notification.data.UserCredentialEntity; -import gr.cite.notification.data.UserEntity; -import gr.cite.notification.query.UserContactInfoQuery; -import gr.cite.notification.query.UserCredentialQuery; -import gr.cite.notification.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 - {}", UserContactInfoEntity.class.getSimpleName()); - List items = this.queryFactory.query(UserContactInfoQuery.class).userIds(ids).collect(); - UserContactInfoDeleter deleter = this.deleterFactory.deleter(UserContactInfoDeleter.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/notification-service/notification/src/main/java/gr/cite/notification/model/notificationtemplate/FieldOptions.java b/notification-service/notification/src/main/java/gr/cite/notification/model/notificationtemplate/FieldOptions.java deleted file mode 100644 index 48fd963ba..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/notificationtemplate/FieldOptions.java +++ /dev/null @@ -1,42 +0,0 @@ -package gr.cite.notification.model.notificationtemplate; - -import gr.cite.notification.common.types.notification.FieldInfo; - -import java.util.List; -import java.util.Map; - -public class FieldOptions { - - private List mandatory; - public static final String _mandatory = "mandatory"; - - private List optional; - public static final String _optional = "optional"; - - private Map formatting; - public static final String _formatting = "formatting"; - - public List getMandatory() { - return mandatory; - } - - public void setMandatory(List mandatory) { - this.mandatory = mandatory; - } - - public List getOptional() { - return optional; - } - - public void setOptional(List optional) { - this.optional = optional; - } - - public Map getFormatting() { - return formatting; - } - - public void setFormatting(Map formatting) { - this.formatting = formatting; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/notificationtemplate/NotificationTemplateValue.java b/notification-service/notification/src/main/java/gr/cite/notification/model/notificationtemplate/NotificationTemplateValue.java deleted file mode 100644 index 5abb42ef0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/notificationtemplate/NotificationTemplateValue.java +++ /dev/null @@ -1,139 +0,0 @@ -package gr.cite.notification.model.notificationtemplate; - -import gr.cite.notification.common.enums.EmailOverrideMode; - -import java.util.List; - -public class NotificationTemplateValue { - - private String subjectText; - public static final String _subjectText = "subjectText"; - private String subjectKey; - public static final String _subjectKey = "subjectKey"; - private FieldOptions subjectFieldOptions; - public static final String _subjectFieldOptions = "subjectFieldOptions"; - private String bodyText; - public static final String _bodyText = "bodyText"; - private String bodyKey; - public static final String _bodyKey = "bodyKey"; - private String priorityKey; - public static final String _priorityKey = "priorityKey"; - private Boolean allowAttachments; - public static final String _allowAttachments = "allowAttachments"; - private List cc; - public static final String _cc = "cc"; - private EmailOverrideMode ccMode; - public static final String _ccMode = "ccMode"; - private List bcc; - public static final String _bcc = "bcc"; - private EmailOverrideMode bccMode; - public static final String _bccMode = "bccMode"; - private List extraDataKeys; - public static final String _extraDataKeys = "extraDataKeys"; - private FieldOptions bodyFieldOptions; - public static final String _bodyFieldOptions = "bodyFieldOptions"; - - public String getSubjectText() { - return subjectText; - } - - public void setSubjectText(String subjectText) { - this.subjectText = subjectText; - } - - public String getSubjectKey() { - return subjectKey; - } - - public void setSubjectKey(String subjectKey) { - this.subjectKey = subjectKey; - } - - public FieldOptions getSubjectFieldOptions() { - return subjectFieldOptions; - } - - public void setSubjectFieldOptions(FieldOptions subjectFieldOptions) { - this.subjectFieldOptions = subjectFieldOptions; - } - - public String getBodyText() { - return bodyText; - } - - public void setBodyText(String bodyText) { - this.bodyText = bodyText; - } - - public String getBodyKey() { - return bodyKey; - } - - public void setBodyKey(String bodyKey) { - this.bodyKey = bodyKey; - } - - public String getPriorityKey() { - return priorityKey; - } - - public void setPriorityKey(String priorityKey) { - this.priorityKey = priorityKey; - } - - public Boolean getAllowAttachments() { - return allowAttachments; - } - - public void setAllowAttachments(Boolean allowAttachments) { - this.allowAttachments = allowAttachments; - } - - public List getCc() { - return cc; - } - - public void setCc(List cc) { - this.cc = cc; - } - - public EmailOverrideMode getCcMode() { - return ccMode; - } - - public void setCcMode(EmailOverrideMode ccMode) { - this.ccMode = ccMode; - } - - public List getBcc() { - return bcc; - } - - public void setBcc(List bcc) { - this.bcc = bcc; - } - - public EmailOverrideMode getBccMode() { - return bccMode; - } - - public void setBccMode(EmailOverrideMode bccMode) { - this.bccMode = bccMode; - } - - public List getExtraDataKeys() { - return extraDataKeys; - } - - public void setExtraDataKeys(List extraDataKeys) { - this.extraDataKeys = extraDataKeys; - } - - public FieldOptions getBodyFieldOptions() { - return bodyFieldOptions; - } - - public void setBodyFieldOptions(FieldOptions bodyFieldOptions) { - this.bodyFieldOptions = bodyFieldOptions; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/NotificationPersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/NotificationPersist.java deleted file mode 100644 index 80876abb0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/NotificationPersist.java +++ /dev/null @@ -1,239 +0,0 @@ -package gr.cite.notification.model.persist; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.enums.NotificationNotifyState; -import gr.cite.notification.common.enums.NotificationTrackingProcess; -import gr.cite.notification.common.enums.NotificationTrackingState; -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -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.time.Instant; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -public class NotificationPersist { - - public static class Field { - public static final String _id = "id"; - public static final String _userId = "userId"; - public static final String _type = "type"; - public static final String _contactTypeHint = "contactTypeHint"; - public static final String _contactHint = "contactHint"; - public static final String _notifiedAt = "notifiedAt"; - public static final String _notifyState = "notifyState"; - public static final String _notifiedWith = "notifiedWith"; - public static final String _data = "data"; - public static final String _retryCount = "retryCount"; - public static final String _trackingState = "trackingState"; - public static final String _trackingProcess = "trackingProcess"; - public static final String _trackingData = "trackingData"; - public static final String _provenanceRef = "provenanceRef"; - public static final String _hash = "hash"; - } - - private UUID id; - - private UUID userId; - - private UUID type; - - private NotificationContactType contactTypeHint; - - private String contactHint; - - private Instant notifiedAt; - - private NotificationNotifyState notifyState; - - private NotificationContactType notifiedWith; - - private String data; - - private Integer retryCount; - - private NotificationTrackingState trackingState; - - private NotificationTrackingProcess trackingProcess; - - private String trackingData; - - private String provenanceRef; - - private String hash; - - 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 UUID getType() { - return type; - } - - public void setType(UUID type) { - this.type = type; - } - - public NotificationContactType getContactTypeHint() { - return contactTypeHint; - } - - public void setContactTypeHint(NotificationContactType contactTypeHint) { - this.contactTypeHint = contactTypeHint; - } - - public String getContactHint() { - return contactHint; - } - - public void setContactHint(String contactHint) { - this.contactHint = contactHint; - } - - public Instant getNotifiedAt() { - return notifiedAt; - } - - public void setNotifiedAt(Instant notifiedAt) { - this.notifiedAt = notifiedAt; - } - - public NotificationNotifyState getNotifyState() { - return notifyState; - } - - public void setNotifyState(NotificationNotifyState notifyState) { - this.notifyState = notifyState; - } - - public NotificationContactType getNotifiedWith() { - return notifiedWith; - } - - public void setNotifiedWith(NotificationContactType notifiedWith) { - this.notifiedWith = notifiedWith; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public Integer getRetryCount() { - return retryCount; - } - - public void setRetryCount(Integer retryCount) { - this.retryCount = retryCount; - } - - public NotificationTrackingState getTrackingState() { - return trackingState; - } - - public void setTrackingState(NotificationTrackingState trackingState) { - this.trackingState = trackingState; - } - - public NotificationTrackingProcess getTrackingProcess() { - return trackingProcess; - } - - public void setTrackingProcess(NotificationTrackingProcess trackingProcess) { - this.trackingProcess = trackingProcess; - } - - public String getTrackingData() { - return trackingData; - } - - public void setTrackingData(String trackingData) { - this.trackingData = trackingData; - } - - public String getProvenanceRef() { - return provenanceRef; - } - - public void setProvenanceRef(String provenanceRef) { - this.provenanceRef = provenanceRef; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } - - @Component(NotificationPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class NotificationPersistValidator extends BaseValidator { - - public static final String ValidatorName = "NotificationPersistValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected NotificationPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return NotificationPersist.class; - } - - @Override - protected List specifications(NotificationPersist item) { - return Arrays.asList( - this.spec() - .iff(() -> this.isValidGuid(item.getId())) - .must(() -> this.isValidHash(item.getHash())) - .failOn(NotificationPersist.Field._hash).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationPersist.Field._hash}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isValidGuid(item.getId())) - .must(() -> !this.isValidHash(item.getHash())) - .failOn(NotificationPersist.Field._hash).failWith(messageSource.getMessage("Validation_OverPosting", new Object[]{}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getUserId())) - .failOn(NotificationPersist.Field._userId).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationPersist.Field._userId}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getType())) - .failOn(Field._type).failWith(messageSource.getMessage("Validation_Required", new Object[]{Field._type}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isEmpty(item.getContactHint())) - .must(() -> this.lessEqualLength(item.getContactHint(), NotificationEntity._contactHintLength)) - .failOn(Field._contactHint).failWith(messageSource.getMessage("Validation_MaxLength", new Object[]{Field._contactHint}, LocaleContextHolder.getLocale())) - ); - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/NotificationTemplatePersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/NotificationTemplatePersist.java deleted file mode 100644 index 6e7286dbd..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/NotificationTemplatePersist.java +++ /dev/null @@ -1,155 +0,0 @@ -package gr.cite.notification.model.persist; - -import gr.cite.notification.common.enums.NotificationTemplateChannel; -import gr.cite.notification.common.enums.NotificationTemplateKind; -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.persist.notificationtemplate.NotificationTemplateValuePersist; -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 NotificationTemplatePersist { - - private UUID id; - public static final String _id = "id"; - - private NotificationTemplateChannel channel; - public static final String _channel = "channel"; - - private UUID notificationType; - public static final String _notificationType = "notificationType"; - - private NotificationTemplateKind kind; - public static final String _kind = "kind"; - - private String languageCode; - public static final String _languageId = "languageId"; - - private NotificationTemplateValuePersist value; - public static final String _value = "value"; - - private String hash; - public static final String _hash = "hash"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public NotificationTemplateChannel getChannel() { - return channel; - } - - public void setChannel(NotificationTemplateChannel channel) { - this.channel = channel; - } - - public UUID getNotificationType() { - return notificationType; - } - - public void setNotificationType(UUID notificationType) { - this.notificationType = notificationType; - } - - public NotificationTemplateKind getKind() { - return kind; - } - - public void setKind(NotificationTemplateKind kind) { - this.kind = kind; - } - - public String getLanguageCode() { - return languageCode; - } - - public void setLanguageCode(String languageCode) { - this.languageCode = languageCode; - } - - public NotificationTemplateValuePersist getValue() { - return value; - } - - public void setValue(NotificationTemplateValuePersist value) { - this.value = value; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } - - @Component(NotificationTemplatePersist.NotificationTemplatePersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class NotificationTemplatePersistValidator extends BaseValidator { - - public static final String ValidatorName = "NotificationTemplatePersistValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected NotificationTemplatePersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return NotificationTemplatePersist.class; - } - - @Override - protected List specifications(NotificationTemplatePersist item) { - return Arrays.asList( - this.spec() - .iff(() -> this.isValidGuid(item.getId())) - .must(() -> this.isValidHash(item.getHash())) - .failOn(NotificationTemplatePersist._hash).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplatePersist._hash}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isValidGuid(item.getId())) - .must(() -> !this.isValidHash(item.getHash())) - .failOn(NotificationTemplatePersist._hash).failWith(messageSource.getMessage("Validation_OverPosting", new Object[]{}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getLanguageCode())) - .failOn(NotificationTemplatePersist._languageId).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplatePersist._languageId}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getNotificationType())) - .failOn(NotificationTemplatePersist._notificationType).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplatePersist._notificationType}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getKind())) - .failOn(NotificationTemplatePersist._kind).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplatePersist._kind}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getChannel())) - .failOn(NotificationTemplatePersist._channel).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplatePersist._channel}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getValue())) - .failOn(NotificationTemplatePersist._value).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplatePersist._value}, LocaleContextHolder.getLocale())), - this.refSpec() - .iff(() -> !this.isNull(item.getValue())) - .on(NotificationTemplatePersist._value) - .over(item.getValue()) - .using(() -> this.validatorFactory.validator(NotificationTemplateValuePersist.NotificationTemplateValuePersistValidator.class)) - ); - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/TenantTouchedIntegrationEventPersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/TenantTouchedIntegrationEventPersist.java deleted file mode 100644 index e8932c3de..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/TenantTouchedIntegrationEventPersist.java +++ /dev/null @@ -1,78 +0,0 @@ -package gr.cite.notification.model.persist; - -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/model/persist/UserNotificationPreferencePersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/UserNotificationPreferencePersist.java deleted file mode 100644 index cc2a6110e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/UserNotificationPreferencePersist.java +++ /dev/null @@ -1,72 +0,0 @@ -package gr.cite.notification.model.persist; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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.Map; -import java.util.UUID; - -public class UserNotificationPreferencePersist { - - private UUID userId; - public static final String _userId = "userId"; - private Map> notificationPreferences; - public static final String _notificationPreferences = "notificationPreferences"; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public Map> getNotificationPreferences() { - return notificationPreferences; - } - - public void setNotificationPreferences(Map> notificationPreferences) { - this.notificationPreferences = notificationPreferences; - } - - @Component(UserNotificationPreferencePersist.UserNotificationPreferencePersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class UserNotificationPreferencePersistValidator extends BaseValidator { - - public static final String ValidatorName = "UserNotificationPreferencePersistValidator"; - - private final MessageSource messageSource; - - protected UserNotificationPreferencePersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return UserNotificationPreferencePersist.class; - } - - @Override - protected List specifications(UserNotificationPreferencePersist item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isNull(item.getUserId())) - .failOn(UserNotificationPreferencePersist._userId).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserNotificationPreferencePersist._userId}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getNotificationPreferences())) - .failOn(UserNotificationPreferencePersist._notificationPreferences).failWith(messageSource.getMessage("Validation_Required", new Object[]{UserNotificationPreferencePersist._notificationPreferences}, LocaleContextHolder.getLocale())) - ); - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/UserTouchedIntegrationEventPersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/UserTouchedIntegrationEventPersist.java deleted file mode 100644 index 952eee89b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/UserTouchedIntegrationEventPersist.java +++ /dev/null @@ -1,81 +0,0 @@ -package gr.cite.notification.model.persist; - -import gr.cite.notification.common.validation.BaseValidator; - -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.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(UserTouchedIntegrationEventPersist.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/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/FieldInfoPersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/FieldInfoPersist.java deleted file mode 100644 index 0658f8852..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/FieldInfoPersist.java +++ /dev/null @@ -1,95 +0,0 @@ -package gr.cite.notification.model.persist.notificationtemplate; - -import gr.cite.notification.common.enums.NotificationDataType; -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -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; - -public class FieldInfoPersist { - - private String key; - public static final String _key = "key"; - - private NotificationDataType type; - public static final String _type = "type"; - - private String value; - public static final String _value = "value"; - - public FieldInfoPersist(String key, NotificationDataType type, String value) { - this.key = key; - this.type = type; - this.value = value; - } - - public FieldInfoPersist() { - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public NotificationDataType getType() { - return type; - } - - public void setType(NotificationDataType type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @Component(FieldInfoPersist.FieldInfoPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class FieldInfoPersistValidator extends BaseValidator { - - public static final String ValidatorName = " FieldInfoPersistValidator"; - - private final MessageSource messageSource; - - protected FieldInfoPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return FieldInfoPersist.class; - } - - @Override - protected List specifications(FieldInfoPersist item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isEmpty(item.getKey())) - .failOn(FieldInfoPersist._key).failWith(messageSource.getMessage("Validation_Required", new Object[]{FieldInfoPersist._key}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getType())) - .failOn(FieldInfoPersist._type).failWith(messageSource.getMessage("Validation_Required", new Object[]{FieldInfoPersist._type}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getValue())) - .failOn(FieldInfoPersist._value).failWith(messageSource.getMessage("Validation_Required", new Object[]{FieldInfoPersist._value}, LocaleContextHolder.getLocale())) - ); - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/FieldOptionsPersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/FieldOptionsPersist.java deleted file mode 100644 index dbe3c43c7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/FieldOptionsPersist.java +++ /dev/null @@ -1,91 +0,0 @@ -package gr.cite.notification.model.persist.notificationtemplate; - -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -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.Map; - -public class FieldOptionsPersist { - - private List mandatory; - public static final String _mandatory = "mandatory"; - - private List optional; - public static final String _optional = "optional"; - - private Map formatting; - public static final String _formatting = "formatting"; - - public List getMandatory() { - return mandatory; - } - - public void setMandatory(List mandatory) { - this.mandatory = mandatory; - } - - public List getOptional() { - return optional; - } - - public void setOptional(List optional) { - this.optional = optional; - } - - public Map getFormatting() { - return formatting; - } - - public void setFormatting(Map formatting) { - this.formatting = formatting; - } - - - @Component(FieldOptionsPersist.FieldOptionsPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class FieldOptionsPersistValidator extends BaseValidator { - - public static final String ValidatorName = " FieldOptionsPersistValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected FieldOptionsPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return FieldOptionsPersist.class; - } - - @Override - protected List specifications(FieldOptionsPersist item) { - return Arrays.asList( - this.navSpec() - .iff(() -> !this.isListNullOrEmpty(item.getOptional())) - .on(FieldOptionsPersist._optional) - .over(item.getOptional()) - .using((itm) -> this.validatorFactory.validator(FieldInfoPersist.FieldInfoPersistValidator.class)), - this.spec() - .iff(() -> !this.isListNullOrEmpty(item.getMandatory()) || !this.isNull(item.getOptional())) - .must(() -> !this.isNull(item.getFormatting())) - .failOn(FieldOptionsPersist._formatting).failWith(messageSource.getMessage("Validation_Required", new Object[]{FieldOptionsPersist._formatting}, LocaleContextHolder.getLocale())) - ); - - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/NotificationTemplateValuePersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/NotificationTemplateValuePersist.java deleted file mode 100644 index 028dc6fa7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/notificationtemplate/NotificationTemplateValuePersist.java +++ /dev/null @@ -1,219 +0,0 @@ -package gr.cite.notification.model.persist.notificationtemplate; - -import gr.cite.notification.common.enums.EmailOverrideMode; -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -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; - -public class NotificationTemplateValuePersist { - - private String subjectText; - public static final String _subjectText = "subjectText"; - - private String subjectKey; - public static final String _subjectKey = "subjectKey"; - - private FieldOptionsPersist subjectFieldOptions; - public static final String _subjectFieldOptions = "subjectFieldOptions"; - - private String bodyText; - public static final String _bodyText = "bodyText"; - - private String bodyKey; - public static final String _bodyKey = "bodyKey"; - private String priorityKey; - public static final String _priorityKey = "priorityKey"; - private Boolean allowAttachments = false; - public static final String _allowAttachments = "allowAttachments"; - private List cc; - public static final String _cc = "cc"; - - private EmailOverrideMode ccMode; - public static final String _ccMode = "ccMode"; - private List bcc; - public static final String _bcc = "bcc"; - - private EmailOverrideMode bccMode; - public static final String _bccMode = "bccMode"; - private List extraDataKeys; - public static final String _extraDataKeys = "extraDataKeys"; - - private FieldOptionsPersist bodyFieldOptions; - public static final String _bodyFieldOptions = "bodyFieldOptions"; - - public String getSubjectText() { - return subjectText; - } - - public void setSubjectText(String subjectText) { - this.subjectText = subjectText; - } - - public String getSubjectKey() { - return subjectKey; - } - - public void setSubjectKey(String subjectKey) { - this.subjectKey = subjectKey; - } - - public FieldOptionsPersist getSubjectFieldOptions() { - return subjectFieldOptions; - } - - public void setSubjectFieldOptions(FieldOptionsPersist subjectFieldOptions) { - this.subjectFieldOptions = subjectFieldOptions; - } - - public String getBodyText() { - return bodyText; - } - - public void setBodyText(String bodyText) { - this.bodyText = bodyText; - } - - public String getBodyKey() { - return bodyKey; - } - - public void setBodyKey(String bodyKey) { - this.bodyKey = bodyKey; - } - - public String getPriorityKey() { - return priorityKey; - } - - public void setPriorityKey(String priorityKey) { - this.priorityKey = priorityKey; - } - - public Boolean getAllowAttachments() { - return allowAttachments; - } - - public void setAllowAttachments(Boolean allowAttachments) { - this.allowAttachments = allowAttachments; - } - - public List getCc() { - return cc; - } - - public void setCc(List cc) { - this.cc = cc; - } - - public EmailOverrideMode getCcMode() { - return ccMode; - } - - public void setCcMode(EmailOverrideMode ccMode) { - this.ccMode = ccMode; - } - - public List getBcc() { - return bcc; - } - - public void setBcc(List bcc) { - this.bcc = bcc; - } - - public EmailOverrideMode getBccMode() { - return bccMode; - } - - public void setBccMode(EmailOverrideMode bccMode) { - this.bccMode = bccMode; - } - - public List getExtraDataKeys() { - return extraDataKeys; - } - - public void setExtraDataKeys(List extraDataKeys) { - this.extraDataKeys = extraDataKeys; - } - - public FieldOptionsPersist getBodyFieldOptions() { - return bodyFieldOptions; - } - - public void setBodyFieldOptions(FieldOptionsPersist bodyFieldOptions) { - this.bodyFieldOptions = bodyFieldOptions; - } - - @Component(NotificationTemplateValuePersist.NotificationTemplateValuePersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class NotificationTemplateValuePersistValidator extends BaseValidator { - - public static final String ValidatorName = "NotificationTemplateValuePersistValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected NotificationTemplateValuePersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return NotificationTemplateValuePersist.class; - } - - @Override - protected List specifications(NotificationTemplateValuePersist item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isEmpty(item.getSubjectKey())) - .failOn(NotificationTemplateValuePersist._subjectKey).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplateValuePersist._subjectKey}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getSubjectText())) - .failOn(NotificationTemplateValuePersist._subjectText).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplateValuePersist._subjectText}, LocaleContextHolder.getLocale())), - this.refSpec() - .iff(() -> !this.isNull(item.getSubjectFieldOptions())) - .on(NotificationTemplateValuePersist._subjectFieldOptions) - .over(item.getSubjectFieldOptions()) - .using(() -> this.validatorFactory.validator(FieldOptionsPersist.FieldOptionsPersistValidator.class)), - this.spec() - .must(() -> !this.isEmpty(item.getBodyKey())) - .failOn(NotificationTemplateValuePersist._bodyKey).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplateValuePersist._bodyKey}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getBodyText())) - .failOn(NotificationTemplateValuePersist._bodyText).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplateValuePersist._bodyText}, LocaleContextHolder.getLocale())), - this.refSpec() - .iff(() -> !this.isNull(item.getBodyFieldOptions())) - .on(NotificationTemplateValuePersist._bodyFieldOptions) - .over(item.getBodyFieldOptions()) - .using(() -> this.validatorFactory.validator(FieldOptionsPersist.FieldOptionsPersistValidator.class)), - this.spec() - .must(() -> !this.isNull(item.getAllowAttachments())) - .failOn(NotificationTemplateValuePersist._allowAttachments).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplateValuePersist._allowAttachments}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getPriorityKey())) - .failOn(NotificationTemplateValuePersist._priorityKey).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplateValuePersist._priorityKey}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getCcMode())) - .failOn(NotificationTemplateValuePersist._ccMode).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplateValuePersist._ccMode}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getBccMode())) - .failOn(NotificationTemplateValuePersist._bccMode).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotificationTemplateValuePersist._bccMode}, LocaleContextHolder.getLocale())) - ); - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/DefaultUserLocaleTenantConfigurationPersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/DefaultUserLocaleTenantConfigurationPersist.java deleted file mode 100644 index 52862fe28..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/DefaultUserLocaleTenantConfigurationPersist.java +++ /dev/null @@ -1,82 +0,0 @@ -package gr.cite.notification.model.persist.tenantconfiguration; - -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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; - -public class DefaultUserLocaleTenantConfigurationPersist { - private String timezone; - public static final String _timezone = "timezone"; - private String language; - public static final String _language = "language"; - private String culture; - public static final String _culture = "culture"; - - public String getTimezone() { - return timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public String getCulture() { - return culture; - } - - public void setCulture(String culture) { - this.culture = culture; - } - - @Component(DefaultUserLocaleTenantConfigurationPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class DefaultUserLocaleTenantConfigurationPersistValidator extends BaseValidator { - - public static final String ValidatorName = "DefaultUserLocaleTenantConfigurationPersistValidator"; - - private final MessageSource messageSource; - - protected DefaultUserLocaleTenantConfigurationPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return DefaultUserLocaleTenantConfigurationPersist.class; - } - - @Override - protected List specifications(DefaultUserLocaleTenantConfigurationPersist item) { - return Arrays.asList( - this.spec() - .must(() -> !this.isEmpty(item.getTimezone())) - .failOn(DefaultUserLocaleTenantConfigurationPersist._timezone).failWith(messageSource.getMessage("Validation_Required", new Object[]{DefaultUserLocaleTenantConfigurationPersist._timezone}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getLanguage())) - .failOn(DefaultUserLocaleTenantConfigurationPersist._language).failWith(messageSource.getMessage("Validation_Required", new Object[]{DefaultUserLocaleTenantConfigurationPersist._language}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isEmpty(item.getCulture())) - .failOn(DefaultUserLocaleTenantConfigurationPersist._culture).failWith(messageSource.getMessage("Validation_Required", new Object[]{DefaultUserLocaleTenantConfigurationPersist._culture}, LocaleContextHolder.getLocale())) - ); - } - } -} - diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/NotifierListTenantConfigurationPersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/NotifierListTenantConfigurationPersist.java deleted file mode 100644 index 81ee82997..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/NotifierListTenantConfigurationPersist.java +++ /dev/null @@ -1,54 +0,0 @@ -package gr.cite.notification.model.persist.tenantconfiguration; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.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.*; - -public class NotifierListTenantConfigurationPersist { - private Map> notifiers; - public static final String _notifiers = "notifiers"; - public Map> getNotifiers() { - return notifiers; - } - - public void setNotifiers(Map> notifiers) { - this.notifiers = notifiers; - } - - @Component(NotifierListTenantConfigurationPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class NotifierListTenantConfigurationPersistValidator extends BaseValidator { - - public static final String ValidatorName = "NotifierListTenantConfigurationPersistValidator"; - - private final MessageSource messageSource; - - protected NotifierListTenantConfigurationPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource) { - super(conventionService, errors); - this.messageSource = messageSource; - } - - @Override - protected Class modelClass() { - return NotifierListTenantConfigurationPersist.class; - } - - @Override - protected List specifications(NotifierListTenantConfigurationPersist item) { - return Collections.singletonList( - this.spec() - .must(() -> !this.isNull(item.getNotifiers())) - .failOn(NotifierListTenantConfigurationPersist._notifiers).failWith(messageSource.getMessage("Validation_Required", new Object[]{NotifierListTenantConfigurationPersist._notifiers}, LocaleContextHolder.getLocale())) - ); - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/TenantConfigurationPersist.java b/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/TenantConfigurationPersist.java deleted file mode 100644 index a40bb0750..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/persist/tenantconfiguration/TenantConfigurationPersist.java +++ /dev/null @@ -1,142 +0,0 @@ -package gr.cite.notification.model.persist.tenantconfiguration; - -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.validation.BaseValidator; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -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 TenantConfigurationPersist { - - private UUID id; - - public static final String _id = "id"; - - private TenantConfigurationType type; - - public static final String _type = "type"; - - private NotifierListTenantConfigurationPersist notifierList; - - public static final String _notifierList = "notifierList"; - - private DefaultUserLocaleTenantConfigurationPersist defaultUserLocale; - - public static final String _defaultUserLocale = "defaultUserLocale"; - - private String hash; - - public static final String _hash = "hash"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public NotifierListTenantConfigurationPersist getNotifierList() { - return notifierList; - } - - public void setNotifierList(NotifierListTenantConfigurationPersist notifierList) { - this.notifierList = notifierList; - } - - public DefaultUserLocaleTenantConfigurationPersist getDefaultUserLocale() { - return defaultUserLocale; - } - - public void setDefaultUserLocale(DefaultUserLocaleTenantConfigurationPersist defaultUserLocale) { - this.defaultUserLocale = defaultUserLocale; - } - - public String getHash() { - return hash; - } - - public void setHash(String hash) { - this.hash = hash; - } - - public TenantConfigurationType getType() { - return type; - } - - public void setType(TenantConfigurationType type) { - this.type = type; - } - - - - @Component(TenantConfigurationPersistValidator.ValidatorName) - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public static class TenantConfigurationPersistValidator extends BaseValidator { - - public static final String ValidatorName = "TenantConfigurationPersistValidator"; - - private final MessageSource messageSource; - - private final ValidatorFactory validatorFactory; - - protected TenantConfigurationPersistValidator(ConventionService conventionService, ErrorThesaurusProperties errors, MessageSource messageSource, ValidatorFactory validatorFactory) { - super(conventionService, errors); - this.messageSource = messageSource; - this.validatorFactory = validatorFactory; - } - - @Override - protected Class modelClass() { - return TenantConfigurationPersist.class; - } - - @Override - protected List specifications(TenantConfigurationPersist item) { - return Arrays.asList( - this.spec() - .iff(() -> this.isValidGuid(item.getId())) - .must(() -> this.isValidHash(item.getHash())) - .failOn(TenantConfigurationPersist._hash).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantConfigurationPersist._hash}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isValidGuid(item.getId())) - .must(() -> !this.isValidHash(item.getHash())) - .failOn(TenantConfigurationPersist._hash).failWith(messageSource.getMessage("Validation_OverPosting", new Object[]{}, LocaleContextHolder.getLocale())), - this.spec() - .must(() -> !this.isNull(item.getType())) - .failOn(TenantConfigurationPersist._type).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantConfigurationPersist._type}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isNull(item.getType()) && TenantConfigurationType.DefaultUserLocale.equals(item.getType())) - .must(() -> !this.isNull(item.getDefaultUserLocale())) - .failOn(TenantConfigurationPersist._defaultUserLocale).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantConfigurationPersist._defaultUserLocale}, LocaleContextHolder.getLocale())), - this.spec() - .iff(() -> !this.isNull(item.getType()) && TenantConfigurationType.NotifierList.equals(item.getType())) - .must(() -> !this.isNull(item.getNotifierList())) - .failOn(TenantConfigurationPersist._notifierList).failWith(messageSource.getMessage("Validation_Required", new Object[]{TenantConfigurationPersist._notifierList}, LocaleContextHolder.getLocale())), - - - this.refSpec() - .iff(() -> !this.isNull(item.getDefaultUserLocale()) && TenantConfigurationType.DefaultUserLocale.equals(item.getType())) - .on(TenantConfigurationPersist._defaultUserLocale) - .over(item.getDefaultUserLocale()) - .using(() -> this.validatorFactory.validator(DefaultUserLocaleTenantConfigurationPersist.DefaultUserLocaleTenantConfigurationPersistValidator.class)), - this.refSpec() - .iff(() -> !this.isNull(item.getNotifierList()) && TenantConfigurationType.NotifierList.equals(item.getType())) - .on(TenantConfigurationPersist._notifierList) - .over(item.getNotifierList()) - .using(() -> this.validatorFactory.validator(NotifierListTenantConfigurationPersist.NotifierListTenantConfigurationPersistValidator.class)) - - ); - } - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/DefaultUserLocaleTenantConfiguration.java b/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/DefaultUserLocaleTenantConfiguration.java deleted file mode 100644 index 24d068e61..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/DefaultUserLocaleTenantConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -package gr.cite.notification.model.tenantconfiguration; - -public class DefaultUserLocaleTenantConfiguration { - private String timezone; - public static final String _timezone = "timezone"; - private String language; - public static final String _language = "language"; - private String culture; - public static final String _culture = "culture"; - - public String getTimezone() { - return timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public String getCulture() { - return culture; - } - - public void setCulture(String culture) { - this.culture = culture; - } -} - diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/NotifierListTenantConfiguration.java b/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/NotifierListTenantConfiguration.java deleted file mode 100644 index 77a5618ee..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/NotifierListTenantConfiguration.java +++ /dev/null @@ -1,21 +0,0 @@ -package gr.cite.notification.model.tenantconfiguration; - -import gr.cite.notification.common.enums.NotificationContactType; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class NotifierListTenantConfiguration { - - private Map> notifiers; - public static final String _notifiers = "notifiers"; - - public Map> getNotifiers() { - return notifiers; - } - - public void setNotifiers(Map> notifiers) { - this.notifiers = notifiers; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/TenantConfiguration.java b/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/TenantConfiguration.java deleted file mode 100644 index c927cc7f1..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/tenantconfiguration/TenantConfiguration.java +++ /dev/null @@ -1,118 +0,0 @@ -package gr.cite.notification.model.tenantconfiguration; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; - -import java.time.Instant; -import java.util.UUID; - -public class TenantConfiguration { - - private UUID id; - - public static final String _id = "id"; - - private TenantConfigurationType type; - - public static final String _type = "type"; - - private Instant createdAt; - - public static final String _createdAt = "createdAt"; - - private NotifierListTenantConfiguration notifierList; - - public static final String _notifierList = "notifierList"; - - private DefaultUserLocaleTenantConfiguration defaultUserLocale; - - public static final String _defaultUserLocale = "defaultUserLocale"; - - 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 Boolean belongsToCurrentTenant; - public static final String _belongsToCurrentTenant = "belongsToCurrentTenant"; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public NotifierListTenantConfiguration getNotifierList() { - return notifierList; - } - - public void setNotifierList(NotifierListTenantConfiguration notifierList) { - this.notifierList = notifierList; - } - - public DefaultUserLocaleTenantConfiguration getDefaultUserLocale() { - return defaultUserLocale; - } - - public void setDefaultUserLocale(DefaultUserLocaleTenantConfiguration defaultUserLocale) { - this.defaultUserLocale = defaultUserLocale; - } - - 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 Boolean getBelongsToCurrentTenant() { - return belongsToCurrentTenant; - } - - public void setBelongsToCurrentTenant(Boolean belongsToCurrentTenant) { - this.belongsToCurrentTenant = belongsToCurrentTenant; - } - - public TenantConfigurationType getType() { - return type; - } - - public void setType(TenantConfigurationType type) { - this.type = type; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/model/user/PublicUser.java b/notification-service/notification/src/main/java/gr/cite/notification/model/user/PublicUser.java deleted file mode 100644 index 0e683ce0d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/model/user/PublicUser.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/query/InAppNotificationQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/InAppNotificationQuery.java deleted file mode 100644 index 1548c11cf..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/InAppNotificationQuery.java +++ /dev/null @@ -1,303 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.enums.InAppNotificationPriority; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationInAppTracking; -import gr.cite.notification.data.InAppNotificationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.model.InAppNotification; -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.BeanDefinition; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - -@Component -@Scope(BeanDefinition.SCOPE_PROTOTYPE) -public class InAppNotificationQuery extends QueryBase { - - private String like; - - private Collection ids; - - private List excludeIds; - - private List userId; - - private List type; - - private Collection isActives; - - private List tenantIds; - - private List trackingState; - - private Boolean isRead; - - private Instant from; - - private Instant to; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final TenantEntityManager tenantEntityManager; - - public InAppNotificationQuery(TenantEntityManager tenantEntityManager) { - this.tenantEntityManager = tenantEntityManager; - } - - public InAppNotificationQuery like(String value) { - this.like = value; - return this; - } - - public InAppNotificationQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public InAppNotificationQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public InAppNotificationQuery ids(Collection values) { - this.ids = values; - return this; - } - - public InAppNotificationQuery excludeIds(UUID... value) { - this.excludeIds = Arrays.asList(value); - return this; - } - - public InAppNotificationQuery excludeIds(List values) { - this.excludeIds = values; - return this; - } - - public InAppNotificationQuery userId(UUID... value) { - this.userId = Arrays.asList(value); - return this; - } - - public InAppNotificationQuery userId(List values) { - this.userId = values; - return this; - } - - public InAppNotificationQuery type(UUID... value) { - this.type = Arrays.asList(value); - return this; - } - - public InAppNotificationQuery type(List values) { - this.type = values; - return this; - } - - public InAppNotificationQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public InAppNotificationQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public InAppNotificationQuery Tenants(List value) { - this.tenantIds = value; - return this; - } - - public InAppNotificationQuery Tenants(UUID... value) { - this.tenantIds = Arrays.asList(value); - return this; - } - - public InAppNotificationQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public InAppNotificationQuery trackingState(List values) { - this.trackingState = values; - return this; - } - - public InAppNotificationQuery trackingState(NotificationInAppTracking... value) { - this.trackingState = List.of(value); - return this; - } - - public InAppNotificationQuery isRead(Boolean isRead) { - this.isRead = isRead; - return this; - } - - public InAppNotificationQuery isRead() { - this.isRead = true; - return this; - } - - public InAppNotificationQuery from(Instant from) { - this.from = from; - return this; - } - - public InAppNotificationQuery to(Instant to) { - this.to = to; - return this; - } - - public InAppNotificationQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public InAppNotificationQuery enableTracking() { - this.noTracking = false; - return this; - } - - public InAppNotificationQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Boolean isFalseQuery() { - return this.isNullOrEmpty(this.ids) - && this.isNullOrEmpty(this.isActives) - && this.isNullOrEmpty(this.type) - && this.isNullOrEmpty(this.excludeIds) - && this.isNullOrEmpty(this.userId) - && this.isNullOrEmpty(this.trackingState); - } - - @Override - protected Class entityClass() { - return InAppNotificationEntity.class; - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - predicates.add(queryContext.Root.get(InAppNotificationEntity._id).in(ids)); - } - - if (this.like != null && !this.like.isEmpty()) { - predicates.add(queryContext.CriteriaBuilder.like(queryContext.Root.get(InAppNotificationEntity._subject), this.like)); - } - - if (this.excludeIds != null) { - predicates.add(queryContext.CriteriaBuilder.not(queryContext.Root.get(InAppNotificationEntity._id).in(ids))); - } - - if (this.userId != null) { - predicates.add(queryContext.Root.get(InAppNotificationEntity._userId).in(userId)); - } - - if (this.isActives != null) { - predicates.add(queryContext.Root.get(InAppNotificationEntity._isActive).in(isActives)); - } - - if (this.tenantIds != null) { - predicates.add(queryContext.Root.get(InAppNotificationEntity._tenantId).in(tenantIds)); - } - - if (this.type != null) { - predicates.add(queryContext.Root.get(InAppNotificationEntity._type).in(this.type)); - } - - if (this.trackingState != null) { - predicates.add(queryContext.Root.get(InAppNotificationEntity._trackingState).in(trackingState)); - } - - if (isRead != null) { - predicates.add(isRead ? queryContext.CriteriaBuilder.isNotNull(queryContext.Root.get(InAppNotificationEntity._readTime)) : queryContext.CriteriaBuilder.isNull(queryContext.Root.get(InAppNotificationEntity._readTime))); - } - - if (from != null) { - predicates.add(queryContext.CriteriaBuilder.greaterThanOrEqualTo(queryContext.Root.get(InAppNotificationEntity._createdAt), from)); - } - - if (to != null) { - predicates.add(queryContext.CriteriaBuilder.lessThanOrEqualTo(queryContext.Root.get(InAppNotificationEntity._createdAt), from)); - } - - 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(InAppNotification.Field.ID)) - return InAppNotificationEntity._id; - else if (item.match(InAppNotification.Field.CREATED_AT)) - return InAppNotificationEntity._createdAt; - else if (item.match(InAppNotification.Field.USER)) - return InAppNotificationEntity._userId; - else if (item.match(InAppNotification.Field.IS_ACTIVE)) - return InAppNotificationEntity._isActive; - else if (item.match(InAppNotification.Field.READ_TIME)) - return InAppNotificationEntity._readTime; - else if (item.match(InAppNotification.Field.TRACKING_STATE)) - return InAppNotificationEntity._trackingState; - else if (item.match(InAppNotification.Field.BODY)) - return InAppNotificationEntity._body; - else if (item.match(InAppNotification.Field.EXTRA_DATA)) - return InAppNotificationEntity._extraData; - else if (item.match(InAppNotification.Field.PRIORITY)) - return InAppNotificationEntity._priority; - else if (item.match(InAppNotification.Field.SUBJECT)) - return InAppNotificationEntity._subject; - else if (item.match(InAppNotification.Field.TENANT)) - return InAppNotificationEntity._tenantId; - else if (item.match(InAppNotification.Field.TYPE)) - return InAppNotificationEntity._type; - else if (item.match(InAppNotification.Field.UPDATED_AT)) - return InAppNotificationEntity._updatedAt; - else - return null; - } - - @Override - protected InAppNotificationEntity convert(Tuple tuple, Set columns) { - InAppNotificationEntity item = new InAppNotificationEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._id, UUID.class)); - item.setType(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._type, UUID.class)); - item.setUserId(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._userId, UUID.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._tenantId, UUID.class)); - item.setTrackingState(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._trackingState, NotificationInAppTracking.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._isActive, IsActive.class)); - item.setExtraData(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._extraData, String.class)); - item.setBody(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._body, String.class)); - item.setSubject(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._subject, String.class)); - item.setPriority(QueryBase.convertSafe(tuple, columns, InAppNotificationEntity._priority, InAppNotificationPriority.class)); - return item; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/NotificationQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/NotificationQuery.java deleted file mode 100644 index 2bf4adfc3..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/NotificationQuery.java +++ /dev/null @@ -1,376 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.enums.*; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.model.Notification; -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.Predicate; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - -@Component -@Scope(BeanDefinition.SCOPE_PROTOTYPE) -public class NotificationQuery extends QueryBase { - - private Collection ids; - - private Collection isActives; - - private List tenantIds; - - private List notifyState; - - private List notifiedWith; - - private Boolean notifiedWithHasValue; - - private Boolean notifiedAtHasValue; - - private List type; - - private List contactType; - - private Integer retryThreshold; - - private Instant createdAfter; - - private List trackingState; - - private List trackingProgress; - - private Collection userIds; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final TenantEntityManager tenantEntityManager; - - public NotificationQuery(TenantEntityManager tenantEntityManager) { - this.tenantEntityManager = tenantEntityManager; - } - - public NotificationQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public NotificationQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public NotificationQuery ids(Collection values) { - this.ids = values; - return this; - } - - public NotificationQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public NotificationQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public NotificationQuery Tenants(List value) { - this.tenantIds = value; - return this; - } - - public NotificationQuery Tenants(UUID... value) { - this.tenantIds = Arrays.asList(value); - return this; - } - - public NotificationQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public NotificationQuery notifyState(NotificationNotifyState... notifyState) { - this.notifyState = List.of(notifyState); - return this; - } - - public NotificationQuery notifyState(List notifyState) { - this.notifyState = notifyState; - return this; - } - - public NotificationQuery notifiedWith(NotificationContactType... notifiedWith) { - this.notifiedWith = List.of(notifiedWith); - return this; - } - - public NotificationQuery notifiedWith(List notifiedWith) { - this.notifiedWith = notifiedWith; - return this; - } - - public NotificationQuery notifiedWithHasValue(Boolean notifiedWithHasValue) { - this.notifiedWithHasValue = notifiedWithHasValue; - return this; - } - - public NotificationQuery notifiedWithHasValue() { - this.notifiedWithHasValue = true; - return this; - } - - public NotificationQuery notifiedAtHasValue(Boolean notifiedAtHasValue) { - this.notifiedAtHasValue = notifiedAtHasValue; - return this; - } - - public NotificationQuery notifiedAtHasValue() { - this.notifiedAtHasValue = true; - return this; - } - - public NotificationQuery type(UUID... type) { - this.type = List.of(type); - return this; - } - - public NotificationQuery type(List type) { - this.type = type; - return this; - } - - public NotificationQuery contactType(NotificationContactType... contactType) { - this.contactType = List.of(contactType); - return this; - } - - public NotificationQuery contactType(List contactType) { - this.contactType = contactType; - return this; - } - - public NotificationQuery retryThreshold(Integer retryThreshold) { - this.retryThreshold = retryThreshold; - return this; - } - - public NotificationQuery createdAfter(Instant createdAfter) { - this.createdAfter = createdAfter; - return this; - } - - public NotificationQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public NotificationQuery trackingState(NotificationTrackingState... trackingState) { - this.trackingState = List.of(trackingState); - return this; - } - - public NotificationQuery trackingState(List trackingState) { - this.trackingState = trackingState; - return this; - } - - public NotificationQuery trackingProgress(NotificationTrackingProcess... trackingProgress) { - this.trackingProgress = List.of(trackingProgress); - return this; - } - - public NotificationQuery trackingProgress(List trackingProgress) { - this.trackingProgress = trackingProgress; - return this; - } - - public NotificationQuery userIds(UUID value) { - this.userIds = List.of(value); - return this; - } - - public NotificationQuery userIds(UUID... value) { - this.userIds = Arrays.asList(value); - return this; - } - - public NotificationQuery userIds(Collection values) { - this.userIds = values; - return this; - } - - public NotificationQuery ordering(Ordering ordering) { - this.setOrder(ordering); - return this; - } - - public NotificationQuery enableTracking() { - this.noTracking = false; - return this; - } - - public NotificationQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Boolean isFalseQuery() { - return this.isNullOrEmpty(this.ids) - && this.isNullOrEmpty(this.isActives) - && this.isNullOrEmpty(this.notifyState); - } - - @Override - protected Class entityClass() { - return NotificationEntity.class; - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - predicates.add(queryContext.Root.get(NotificationEntity._id).in(ids)); - } - - if (this.isActives != null) { - predicates.add(queryContext.Root.get(NotificationEntity._isActive).in(isActives)); - } - - if (this.tenantIds != null) { - predicates.add(queryContext.Root.get(NotificationEntity._tenantId).in(tenantIds)); - } - - if (this.notifyState != null) { - predicates.add(queryContext.Root.get(NotificationEntity._notifyState).in(notifyState)); - } - - if (this.notifiedWith != null) { - predicates.add(queryContext.Root.get(NotificationEntity._notifiedWith).in(notifiedWith)); - } - - if (notifiedWithHasValue != null) { - Predicate hasValuePredicate = notifiedWithHasValue ? queryContext.CriteriaBuilder.isNotNull(queryContext.Root.get(NotificationEntity._notifiedWith)) : queryContext.CriteriaBuilder.isNull(queryContext.Root.get(NotificationEntity._notifiedWith)); - predicates.add(hasValuePredicate); - } - - if (notifiedAtHasValue != null) { - Predicate hasValuePredicate = notifiedAtHasValue ? queryContext.CriteriaBuilder.isNotNull(queryContext.Root.get(NotificationEntity._notifiedAt)) : queryContext.CriteriaBuilder.isNull(queryContext.Root.get(NotificationEntity._notifiedAt)); - predicates.add(hasValuePredicate); - } - - if (this.type != null) { - predicates.add(queryContext.Root.get(NotificationEntity._type).in(this.type)); - } - - if (this.contactType != null) { - predicates.add(queryContext.Root.get(NotificationEntity._contactTypeHint).in(this.contactType)); - } - - if (this.retryThreshold != null) { - predicates.add(queryContext.CriteriaBuilder.le(queryContext.Root.get(NotificationEntity._retryCount), this.retryThreshold)); - } - - if (this.createdAfter != null) { - predicates.add(queryContext.CriteriaBuilder.greaterThan(queryContext.Root.get(NotificationEntity._createdAt), this.createdAfter)); - } - - if (this.trackingState != null) { - predicates.add(queryContext.Root.get(NotificationEntity._trackingState).in(trackingState)); - } - - if (this.trackingProgress != null) { - predicates.add(queryContext.Root.get(NotificationEntity._trackingProcess).in(trackingProgress)); - } - - if (this.userIds != null) { - predicates.add(queryContext.Root.get(NotificationEntity._userId).in(userIds)); - } - - 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(Notification._id)) - return NotificationEntity._id; - else if (item.match(Notification._contactHint)) - return NotificationEntity._contactHint; - else if (item.match(Notification._createdAt)) - return NotificationEntity._createdAt; - else if (item.match(Notification._isActive)) - return NotificationEntity._isActive; - else if (item.match(Notification._contactTypeHint)) - return NotificationEntity._contactTypeHint; - else if (item.match(Notification._updatedAt)) - return NotificationEntity._updatedAt; - else if (item.match(Notification._notifiedAt)) - return NotificationEntity._notifiedAt; - else if (item.match(Notification._data)) - return NotificationEntity._data; - else if (item.prefix(Notification._tenant)) - return NotificationEntity._tenantId; - else if (item.prefix(Notification._user)) - return NotificationEntity._userId; - else if (item.match(Notification._type)) - return NotificationEntity._type; - else if (item.match(Notification._notifyState)) - return NotificationEntity._notifyState; - else if (item.match(Notification._notifiedWith)) - return NotificationEntity._notifiedWith; - else if (item.match(Notification._trackingState)) - return NotificationEntity._trackingState; - else if (item.match(Notification._trackingProcess)) - return NotificationEntity._trackingProcess; - else if (item.match(Notification._trackingData)) - return NotificationEntity._trackingData; - else if (item.match(Notification._retryCount)) - return NotificationEntity._retryCount; - - else - return null; - } - - @Override - protected NotificationEntity convert(Tuple tuple, Set columns) { - NotificationEntity item = new NotificationEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, NotificationEntity._id, UUID.class)); - item.setContactHint(QueryBase.convertSafe(tuple, columns, NotificationEntity._contactHint, String.class)); - item.setContactTypeHint(QueryBase.convertSafe(tuple, columns, NotificationEntity._contactTypeHint, NotificationContactType.class)); - item.setNotifiedAt(QueryBase.convertSafe(tuple, columns, NotificationEntity._notifiedAt, Instant.class)); - item.setType(QueryBase.convertSafe(tuple, columns, NotificationEntity._type, UUID.class)); - item.setUserId(QueryBase.convertSafe(tuple, columns, NotificationEntity._userId, UUID.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, NotificationEntity._tenantId, UUID.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, NotificationEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, NotificationEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, NotificationEntity._isActive, IsActive.class)); - item.setNotifyState(QueryBase.convertSafe(tuple, columns, NotificationEntity._notifyState, NotificationNotifyState.class)); - item.setNotifiedWith(QueryBase.convertSafe(tuple, columns, NotificationEntity._notifiedWith, NotificationContactType.class)); - item.setTrackingState(QueryBase.convertSafe(tuple, columns, NotificationEntity._trackingState, NotificationTrackingState.class)); - item.setTrackingProcess(QueryBase.convertSafe(tuple, columns, NotificationEntity._trackingProcess, NotificationTrackingProcess.class)); - item.setRetryCount(QueryBase.convertSafe(tuple, columns, NotificationEntity._retryCount, Integer.class)); - - return item; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/NotificationTemplateQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/NotificationTemplateQuery.java deleted file mode 100644 index c3eaf35ad..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/NotificationTemplateQuery.java +++ /dev/null @@ -1,276 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.enums.*; -import gr.cite.notification.data.NotificationTemplateEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.model.NotificationTemplate; -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 org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; - -import java.time.Instant; -import java.util.*; - - -@Component -@Scope(BeanDefinition.SCOPE_PROTOTYPE) -public class NotificationTemplateQuery extends QueryBase { - private Collection ids; - - private Collection excludedIds; - private Collection isActives; - private Collection notificationTypes; - private Collection languageCodes; - - private List channels; - private List kinds; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final TenantEntityManager tenantEntityManager; - - public NotificationTemplateQuery(TenantEntityManager tenantEntityManager) { - this.tenantEntityManager = tenantEntityManager; - } - - public NotificationTemplateQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public NotificationTemplateQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public NotificationTemplateQuery ids(Collection values) { - this.ids = values; - return this; - } - - public NotificationTemplateQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public NotificationTemplateQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public NotificationTemplateQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public NotificationTemplateQuery notificationTypes(UUID value) { - this.notificationTypes = List.of(value); - return this; - } - - public NotificationTemplateQuery notificationTypes(UUID... value) { - this.notificationTypes = Arrays.asList(value); - return this; - } - - public NotificationTemplateQuery notificationTypes(Collection values) { - this.notificationTypes = values; - return this; - } - - public NotificationTemplateQuery languageCodes(String value) { - this.languageCodes = List.of(value); - return this; - } - - public NotificationTemplateQuery languageCodes(String... value) { - this.languageCodes = Arrays.asList(value); - return this; - } - - public NotificationTemplateQuery languageCodes(Collection values) { - this.languageCodes = values; - return this; - } - - - public NotificationTemplateQuery channels(NotificationTemplateChannel... channels) { - this.channels = List.of(channels); - return this; - } - - public NotificationTemplateQuery channels(NotificationTemplateChannel channels) { - this.channels = List.of(channels); - return this; - } - - public NotificationTemplateQuery channels(List channels) { - this.channels = channels; - return this; - } - - public NotificationTemplateQuery kinds(NotificationTemplateKind... kinds) { - this.kinds = List.of(kinds); - return this; - } - - public NotificationTemplateQuery kinds(NotificationTemplateKind kinds) { - this.kinds = List.of(kinds); - return this; - } - - public NotificationTemplateQuery kinds(List kinds) { - this.kinds = kinds; - return this; - } - - public NotificationTemplateQuery excludedIds(Collection values) { - this.excludedIds = values; - return this; - } - - public NotificationTemplateQuery excludedIds(UUID value) { - this.excludedIds = List.of(value); - return this; - } - - public NotificationTemplateQuery excludedIds(UUID... value) { - this.excludedIds = Arrays.asList(value); - return this; - } - - - public NotificationTemplateQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public NotificationTemplateQuery enableTracking() { - this.noTracking = false; - return this; - } - - public NotificationTemplateQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Boolean isFalseQuery() { - return this.isNullOrEmpty(this.ids) - && this.isNullOrEmpty(this.isActives) - && this.isNullOrEmpty(this.kinds) - && this.isNullOrEmpty(this.notificationTypes) - && this.isNullOrEmpty(this.languageCodes) - && this.isNullOrEmpty(this.channels); - } - - @Override - protected Class entityClass() { - return NotificationTemplateEntity.class; - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(NotificationTemplateEntity._id)); - for (UUID item : this.ids) - inClause.value(item); - predicates.add(inClause); - } - - if (this.isActives != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(NotificationTemplateEntity._isActive)); - for (IsActive item : this.isActives) - inClause.value(item); - predicates.add(inClause); - } - - if (this.notificationTypes != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(NotificationTemplateEntity._notificationType)); - for (UUID item : this.notificationTypes) - inClause.value(item); - predicates.add(inClause); - } - - if (this.languageCodes != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(NotificationTemplateEntity._languageCode)); - for (String item : this.languageCodes) - inClause.value(item); - predicates.add(inClause); - } - - if (this.channels != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(NotificationTemplateEntity._channel)); - for (NotificationTemplateChannel item : this.channels) - inClause.value(item); - predicates.add(inClause); } - - if (this.kinds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(NotificationTemplateEntity._kind)); - for (NotificationTemplateKind item : this.kinds) - inClause.value(item); - predicates.add(inClause); - } - - if (this.excludedIds != null) { - CriteriaBuilder.In notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(NotificationTemplateEntity._id)); - for (UUID item : this.excludedIds) - notInClause.value(item); - predicates.add(notInClause.not()); - } - - if (predicates.size() > 0) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(NotificationTemplate._id)) return NotificationTemplateEntity._id; - else if (item.match(NotificationTemplate._channel)) return NotificationTemplateEntity._channel; - else if (item.match(NotificationTemplate._kind)) return NotificationTemplateEntity._kind; - else if (item.match(NotificationTemplate._notificationType)) return NotificationTemplateEntity._notificationType; - else if (item.match(NotificationTemplate._languageCode)) return NotificationTemplateEntity._languageCode; - else if (item.prefix(NotificationTemplate._value)) return NotificationTemplateEntity._value; - else if (item.match(NotificationTemplate._createdAt)) return NotificationTemplateEntity._createdAt; - else if (item.match(NotificationTemplate._updatedAt)) return NotificationTemplateEntity._updatedAt; - else if (item.match(NotificationTemplate._isActive)) return NotificationTemplateEntity._isActive; - else if (item.prefix(NotificationTemplate._tenant)) return NotificationTemplateEntity._tenantId; - else return null; - } - - @Override - protected NotificationTemplateEntity convert(Tuple tuple, Set columns) { - NotificationTemplateEntity item = new NotificationTemplateEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._id, UUID.class)); - item.setChannel(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._channel, NotificationTemplateChannel.class)); - item.setKind(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._kind, NotificationTemplateKind.class)); - item.setNotificationType(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._notificationType, UUID.class)); - item.setValue(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._value, String.class)); - item.setLanguageCode(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._languageCode, String.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._isActive, IsActive.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, NotificationTemplateEntity._tenantId, UUID.class)); - return item; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/QueueInboxQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/QueueInboxQuery.java deleted file mode 100644 index 51a365de4..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/QueueInboxQuery.java +++ /dev/null @@ -1,263 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.QueueInboxEntity; -import gr.cite.notification.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 org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -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.isEmpty()) { - 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/notification-service/notification/src/main/java/gr/cite/notification/query/QueueOutboxQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/QueueOutboxQuery.java deleted file mode 100644 index a6fa0f7f0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/QueueOutboxQuery.java +++ /dev/null @@ -1,259 +0,0 @@ -package gr.cite.notification.query; - - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.QueueOutboxEntity; -import gr.cite.notification.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 org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -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/notification-service/notification/src/main/java/gr/cite/notification/query/TenantConfigurationQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/TenantConfigurationQuery.java deleted file mode 100644 index 31ac28b50..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/TenantConfigurationQuery.java +++ /dev/null @@ -1,228 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.model.tenantconfiguration.TenantConfiguration; -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.BeanDefinition; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - -@Component -@Scope(BeanDefinition.SCOPE_PROTOTYPE) -public class TenantConfigurationQuery extends QueryBase { - - private Collection ids; - private Collection tenantIds; - private Boolean tenantIsSet; - private Collection isActives; - private Collection types; - private Collection excludedIds; - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final TenantEntityManager tenantEntityManager; - - public TenantConfigurationQuery(TenantEntityManager tenantEntityManager) { - this.tenantEntityManager = tenantEntityManager; - } - - public TenantConfigurationQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public TenantConfigurationQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public TenantConfigurationQuery ids(Collection values) { - this.ids = values; - return this; - } - - public TenantConfigurationQuery tenantIds(UUID value) { - this.tenantIds = List.of(value); - return this; - } - - public TenantConfigurationQuery tenantIds(UUID... value) { - this.tenantIds = Arrays.asList(value); - return this; - } - - public TenantConfigurationQuery tenantIds(Collection values) { - this.tenantIds = values; - return this; - } - - public TenantConfigurationQuery tenantIsSet(Boolean values) { - this.tenantIsSet = values; - return this; - } - - public TenantConfigurationQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public TenantConfigurationQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public TenantConfigurationQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public TenantConfigurationQuery types(TenantConfigurationType value) { - this.types = List.of(value); - return this; - } - - public TenantConfigurationQuery types(TenantConfigurationType... value) { - this.types = Arrays.asList(value); - return this; - } - - public TenantConfigurationQuery types(Collection values) { - this.types = values; - return this; - } - - public TenantConfigurationQuery excludedIds(Collection values) { - this.excludedIds = values; - return this; - } - - public TenantConfigurationQuery excludedIds(UUID value) { - this.excludedIds = List.of(value); - return this; - } - - public TenantConfigurationQuery excludedIds(UUID... value) { - this.excludedIds = Arrays.asList(value); - return this; - } - - public TenantConfigurationQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public TenantConfigurationQuery enableTracking() { - this.noTracking = false; - return this; - } - - public TenantConfigurationQuery 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) ||this.isEmpty(this.types) || this.isEmpty(this.tenantIds); - } - - @Override - protected Class entityClass() { - return TenantConfigurationEntity.class; - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantConfigurationEntity._id)); - for (UUID item : this.ids) inClause.value(item); - predicates.add(inClause); - } - - if (this.tenantIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantConfigurationEntity._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(TenantConfigurationEntity._isActive)); - for (IsActive item : this.isActives) inClause.value(item); - predicates.add(inClause); - } - - if (this.tenantIsSet != null) { - if (this.tenantIsSet) predicates.add(queryContext.CriteriaBuilder.isNotNull(queryContext.Root.get(TenantConfigurationEntity._tenantId))); - else predicates.add(queryContext.CriteriaBuilder.isNull(queryContext.Root.get(TenantConfigurationEntity._tenantId))); - } - - - - if (this.types != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantConfigurationEntity._type)); - for (TenantConfigurationType item : this.types) inClause.value(item); - predicates.add(inClause); - } - - if (this.excludedIds != null) { - CriteriaBuilder.In notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(TenantConfigurationEntity._id)); - for (UUID item : this.excludedIds) - notInClause.value(item); - predicates.add(notInClause.not()); - } - - if (!predicates.isEmpty()) { - Predicate[] predicatesArray = predicates.toArray(new Predicate[0]); - return queryContext.CriteriaBuilder.and(predicatesArray); - } else { - return null; - } - - } - - @Override - protected TenantConfigurationEntity convert(Tuple tuple, Set columns) { - TenantConfigurationEntity item = new TenantConfigurationEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, TenantConfigurationEntity._id, UUID.class)); - item.setValue(QueryBase.convertSafe(tuple, columns, TenantConfigurationEntity._value, String.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, TenantConfigurationEntity._tenantId, UUID.class)); - item.setType(QueryBase.convertSafe(tuple, columns, TenantConfigurationEntity._type, TenantConfigurationType.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, TenantConfigurationEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, TenantConfigurationEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, TenantConfigurationEntity._isActive, IsActive.class)); - return item; - } - - @Override - protected String fieldNameOf(FieldResolver item) { - if (item.match(TenantConfiguration._id)) return TenantConfigurationEntity._id; - else if (item.match(TenantConfiguration._type)) return TenantConfigurationEntity._type; - else if (item.prefix(TenantConfiguration._notifierList)) return TenantConfigurationEntity._value; - else if (item.match(TenantConfiguration._notifierList)) return TenantConfigurationEntity._value; - else if (item.match(TenantConfiguration._createdAt)) return TenantConfigurationEntity._createdAt; - else if (item.match(TenantConfiguration._updatedAt)) return TenantConfigurationEntity._updatedAt; - else if (item.match(TenantConfiguration._isActive)) return TenantConfigurationEntity._isActive; - else if (item.match(TenantConfiguration._belongsToCurrentTenant)) return TenantConfigurationEntity._tenantId; - else if (item.match(TenantConfigurationEntity._tenantId)) return TenantConfigurationEntity._tenantId; - else return null; - } - -} \ No newline at end of file diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/TenantQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/TenantQuery.java deleted file mode 100644 index 119fa082c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/TenantQuery.java +++ /dev/null @@ -1,154 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.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 enableTracking() { - this.noTracking = false; - return this; - } - - public TenantQuery disableTracking() { - this.noTracking = true; - return this; - } - - public TenantQuery authorize(EnumSet values) { - this.authorize = values; - 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/notification-service/notification/src/main/java/gr/cite/notification/query/TenantUserQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/TenantUserQuery.java deleted file mode 100644 index 8439c7886..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/TenantUserQuery.java +++ /dev/null @@ -1,229 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserEntity; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.TenantUser; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.data.TenantUserEntity; -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/notification-service/notification/src/main/java/gr/cite/notification/query/UserContactInfoQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/UserContactInfoQuery.java deleted file mode 100644 index 7ff5211a9..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/UserContactInfoQuery.java +++ /dev/null @@ -1,291 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.ContactInfoType; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserContactInfoEntity; -import gr.cite.notification.data.UserEntity; -import gr.cite.notification.model.User; -import gr.cite.notification.model.UserContactInfo; -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 UserContactInfoQuery extends QueryBase { - - private Collection ids; - - private Collection userIds; - - private Collection excludedUserIds; - - private Collection isActives; - - private Collection type; - - private Collection values; - - private UserQuery userQuery; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final UserScope userScope; - - private final AuthorizationService authService; - - private final TenantEntityManager tenantEntityManager; - - public UserContactInfoQuery( - UserScope userScope, - AuthorizationService authService, TenantEntityManager tenantEntityManager - ) { - this.userScope = userScope; - this.authService = authService; - this.tenantEntityManager = tenantEntityManager; - } - - public UserContactInfoQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public UserContactInfoQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public UserContactInfoQuery ids(Collection values) { - this.ids = values; - return this; - } - - public UserContactInfoQuery userIds(UUID value) { - this.userIds = List.of(value); - return this; - } - - public UserContactInfoQuery userIds(UUID... value) { - this.userIds = Arrays.asList(value); - return this; - } - - public UserContactInfoQuery userIds(Collection values) { - this.userIds = values; - return this; - } - - public UserContactInfoQuery excludedUserIds(Collection values) { - this.excludedUserIds = values; - return this; - } - - public UserContactInfoQuery excludedUserIds(UUID value) { - this.excludedUserIds = List.of(value); - return this; - } - - public UserContactInfoQuery excludedUserIds(UUID... value) { - this.excludedUserIds = Arrays.asList(value); - return this; - } - - public UserContactInfoQuery isActive(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public UserContactInfoQuery isActive(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public UserContactInfoQuery isActive(Collection values) { - this.isActives = values; - return this; - } - - public UserContactInfoQuery type(ContactInfoType value) { - this.type = List.of(value); - return this; - } - - public UserContactInfoQuery type(ContactInfoType... value) { - this.type = Arrays.asList(value); - return this; - } - - public UserContactInfoQuery type(Collection values) { - this.type = values; - return this; - } - - public UserContactInfoQuery values(String value) { - this.values = List.of(value); - return this; - } - - public UserContactInfoQuery values(String... value) { - this.values = Arrays.asList(value); - return this; - } - - public UserContactInfoQuery values(Collection values) { - this.values = values; - return this; - } - - public UserContactInfoQuery userSubQuery(UserQuery subQuery) { - this.userQuery = subQuery; - return this; - } - - public UserContactInfoQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public UserContactInfoQuery enableTracking() { - this.noTracking = false; - return this; - } - - public UserContactInfoQuery disableTracking() { - this.noTracking = true; - return this; - } - - @Override - protected EntityManager entityManager(){ - return this.tenantEntityManager.getEntityManager(); - } - - @Override - protected Boolean isFalseQuery() { - return this.isEmpty(this.userIds) || this.isEmpty(this.excludedUserIds) || this.isEmpty(this.isActives) - || this.isEmpty(this.type) || this.isEmpty(this.excludedUserIds) || this.isFalseQuery(this.userQuery); - } - - @Override - protected Class entityClass() { - return UserContactInfoEntity.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.BrowseUserContactInfo)) - 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(UserContactInfoEntity._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.isActives != null) { - predicates.add(queryContext.Root.get(UserContactInfoEntity._isActive).in(isActives)); - } - if (this.userIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserContactInfoEntity._userId)); - for (UUID item : this.userIds) - inClause.value(item); - predicates.add(inClause); - } - if (this.excludedUserIds != null) { - CriteriaBuilder.In notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserContactInfoEntity._userId)); - for (UUID item : this.excludedUserIds) - notInClause.value(item); - predicates.add(notInClause.not()); - } - if (this.type != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserContactInfoEntity._type)); - for (ContactInfoType item : this.type) - inClause.value(item); - predicates.add(inClause); - } - if (this.values != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserContactInfoEntity._value)); - for (String item : this.values) - inClause.value(item); - predicates.add(inClause); - } - if (this.userQuery != null) { - QueryContext subQuery = this.applySubQuery(this.userQuery, queryContext, UUID.class, root -> root.get(UserContactInfoEntity._userId)); - predicates.add(queryContext.CriteriaBuilder.in(queryContext.Root.get(UserContactInfoEntity._userId)).value(subQuery.Query)); - } - - 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(UserContactInfo._id)) - return UserContactInfoEntity._id; - else if (item.match(UserContactInfo._type)) - return UserContactInfoEntity._type; - else if (item.match(UserContactInfo._value)) - return UserContactInfoEntity._value; - else if (item.match(UserContactInfo._ordinal)) - return UserContactInfoEntity._ordinal; - else if (item.match(UserContactInfo._createdAt)) - return UserContactInfoEntity._createdAt; - else if (item.match(UserContactInfo._updatedAt)) - return UserContactInfoEntity._updatedAt; - else if (item.match(UserContactInfo._isActive)) - return UserContactInfoEntity._isActive; - else if (item.match(UserContactInfo._user, User._id)) - return UserContactInfoEntity._userId; - else if (item.prefix(UserContactInfo._user)) - return UserContactInfoEntity._userId; - else - return null; - } - - @Override - protected UserContactInfoEntity convert(Tuple tuple, Set columns) { - UserContactInfoEntity item = new UserContactInfoEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, UserContactInfoEntity._id, UUID.class)); - item.setType(QueryBase.convertSafe(tuple, columns, UserContactInfoEntity._type, ContactInfoType.class)); - item.setValue(QueryBase.convertSafe(tuple, columns, UserContactInfoEntity._value, String.class)); - item.setOrdinal(QueryBase.convertSafe(tuple, columns, UserContactInfoEntity._ordinal, Integer.class)); - item.setUserId(QueryBase.convertSafe(tuple, columns, UserContactInfoEntity._userId, UUID.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, UserContactInfoEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, UserContactInfoEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, UserContactInfoEntity._isActive, IsActive.class)); - return item; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/UserCredentialQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/UserCredentialQuery.java deleted file mode 100644 index 2dec5a40c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/UserCredentialQuery.java +++ /dev/null @@ -1,233 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserCredentialEntity; -import gr.cite.notification.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 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 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/notification-service/notification/src/main/java/gr/cite/notification/query/UserNotificationPreferenceQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/UserNotificationPreferenceQuery.java deleted file mode 100644 index 9b4034842..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/UserNotificationPreferenceQuery.java +++ /dev/null @@ -1,257 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserCredentialEntity; -import gr.cite.notification.data.UserNotificationPreferenceEntity; -import gr.cite.notification.model.UserNotificationPreference; -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.BeanDefinition; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.*; - -@Component -@Scope(BeanDefinition.SCOPE_PROTOTYPE) -public class UserNotificationPreferenceQuery extends QueryBase { - - private Collection ids; - - private Collection excludedIds; - - private List userId; - - private List isActives; - - private List type; - - private List channel; - - private Collection tenantIds; - private Boolean tenantIsSet; - - private final TenantEntityManager tenantEntityManager; - - public UserNotificationPreferenceQuery(TenantEntityManager tenantEntityManager) { - this.tenantEntityManager = tenantEntityManager; - } - - public UserNotificationPreferenceQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public UserNotificationPreferenceQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public UserNotificationPreferenceQuery ids(Collection values) { - this.ids = values; - return this; - } - - public UserNotificationPreferenceQuery tenantIds(UUID value) { - this.tenantIds = List.of(value); - return this; - } - - public UserNotificationPreferenceQuery tenantIds(UUID... value) { - this.tenantIds = Arrays.asList(value); - return this; - } - - public UserNotificationPreferenceQuery tenantIds(Collection values) { - this.tenantIds = values; - return this; - } - - public UserNotificationPreferenceQuery tenantIsSet(Boolean values) { - this.tenantIsSet = values; - return this; - } - - public UserNotificationPreferenceQuery excludedIds(Collection values) { - this.excludedIds = values; - return this; - } - - public UserNotificationPreferenceQuery excludedIds(UUID value) { - this.excludedIds = List.of(value); - return this; - } - - public UserNotificationPreferenceQuery excludedIds(UUID... value) { - this.excludedIds = Arrays.asList(value); - return this; - } - - public UserNotificationPreferenceQuery userId(UUID... userId) { - this.userId = List.of(userId); - return this; - } - - public UserNotificationPreferenceQuery userId(List userId) { - this.userId = userId; - return this; - } - - public UserNotificationPreferenceQuery isActives(IsActive... isActives) { - this.isActives = List.of(isActives); - return this; - } - - public UserNotificationPreferenceQuery isActives(List isActives) { - this.isActives = isActives; - return this; - } - - public UserNotificationPreferenceQuery type(UUID... type) { - this.type = List.of(type); - return this; - } - - public UserNotificationPreferenceQuery type(List type) { - this.type = type; - return this; - } - - public UserNotificationPreferenceQuery channel(NotificationContactType... channel) { - this.channel = List.of(channel); - return this; - } - - public UserNotificationPreferenceQuery channel(List channel) { - this.channel = channel; - return this; - } - - public UserNotificationPreferenceQuery enableTracking() { - this.noTracking = false; - return this; - } - - public UserNotificationPreferenceQuery 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.tenantIds) ||this.isEmpty(this.excludedIds) ||this.isNullOrEmpty(this.userId) && this.isNullOrEmpty(this.type) && this.isNullOrEmpty(this.channel); - } - - @Override - protected Class entityClass() { - return UserNotificationPreferenceEntity.class; - } - - @Override - protected Predicate applyFilters(QueryContext queryContext) { - List predicates = new ArrayList<>(); - if (this.ids != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserNotificationPreferenceEntity._id)); - for (UUID item : this.ids) - inClause.value(item); - predicates.add(inClause); - } - if (this.excludedIds != null) { - CriteriaBuilder.In notInClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserNotificationPreferenceEntity._id)); - for (UUID item : this.excludedIds) - notInClause.value(item); - predicates.add(notInClause.not()); - } - if (this.tenantIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserNotificationPreferenceEntity._tenantId)); - for (UUID item : this.tenantIds) inClause.value(item); - predicates.add(inClause); - } - if (this.tenantIsSet != null) { - if (this.tenantIsSet) predicates.add(queryContext.CriteriaBuilder.isNotNull(queryContext.Root.get(UserNotificationPreferenceEntity._tenantId))); - else predicates.add(queryContext.CriteriaBuilder.isNull(queryContext.Root.get(UserNotificationPreferenceEntity._tenantId))); - } - - if (this.userId != null) { - predicates.add(queryContext.Root.get(UserNotificationPreferenceEntity._userId).in(this.userId)); - } - - if (this.isActives != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserNotificationPreferenceEntity._isActive)); - for (IsActive item : this.isActives) - inClause.value(item); - predicates.add(inClause); } - - if (this.type != null) { - predicates.add(queryContext.Root.get(UserNotificationPreferenceEntity._type).in(this.type)); - } - - if (this.channel != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserNotificationPreferenceEntity._channel)); - for (NotificationContactType item : this.channel) - 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(UserNotificationPreference._userId)) - return UserNotificationPreferenceEntity._userId; - else if (item.match(UserNotificationPreference._id)) - return UserNotificationPreferenceEntity._id; - else if (item.match(UserNotificationPreference._tenantId)) - return UserNotificationPreferenceEntity._tenantId; - else if (item.match(UserNotificationPreference._type)) - return UserNotificationPreferenceEntity._type; - else if (item.match(UserNotificationPreference._channel)) - return UserNotificationPreferenceEntity._channel; - else if (item.match(UserNotificationPreference._ordinal)) - return UserNotificationPreferenceEntity._ordinal; - else if (item.match(UserNotificationPreference._createdAt)) - return UserNotificationPreferenceEntity._createdAt; - else if (item.match(UserNotificationPreference._updatedAt)) - return UserNotificationPreferenceEntity._updatedAt; - else if (item.match(UserNotificationPreference._isActive)) - return UserNotificationPreferenceEntity._isActive; - else - return null; - } - - @Override - protected UserNotificationPreferenceEntity convert(Tuple tuple, Set columns) { - UserNotificationPreferenceEntity item = new UserNotificationPreferenceEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._id, UUID.class)); - item.setUserId(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._userId, UUID.class)); - item.setChannel(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._channel, NotificationContactType.class)); - item.setType(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._type, UUID.class)); - item.setTenantId(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._tenantId, UUID.class)); - item.setOrdinal(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._ordinal, Integer.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, UserNotificationPreferenceEntity._isActive, IsActive.class)); - return item; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/UserQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/UserQuery.java deleted file mode 100644 index 07ff953bd..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/UserQuery.java +++ /dev/null @@ -1,179 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserEntity; -import gr.cite.notification.model.user.PublicUser; -import gr.cite.notification.model.User; -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 org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import jakarta.persistence.Tuple; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.Predicate; -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 = true; - return this; - } - - public UserQuery disableTracking() { - this.noTracking = false; - 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.size() > 0) { - 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.size() > 0) { - 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/notification-service/notification/src/main/java/gr/cite/notification/query/UserRoleQuery.java b/notification-service/notification/src/main/java/gr/cite/notification/query/UserRoleQuery.java deleted file mode 100644 index 73cafd744..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/UserRoleQuery.java +++ /dev/null @@ -1,256 +0,0 @@ -package gr.cite.notification.query; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserRoleEntity; -import gr.cite.notification.model.UserRole; -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 UserRoleQuery extends QueryBase { - - private Collection ids; - - private Collection excludedIds; - - private Collection isActives; - - private Collection userIds; - - private Collection roles; - - private EnumSet authorize = EnumSet.of(AuthorizationFlags.None); - - private final UserScope userScope; - - private final AuthorizationService authService; - - private final TenantEntityManager tenantEntityManager; - - public UserRoleQuery(UserScope userScope, AuthorizationService authService, TenantEntityManager tenantEntityManager) { - this.userScope = userScope; - this.authService = authService; - this.tenantEntityManager = tenantEntityManager; - } - - public UserRoleQuery ids(UUID value) { - this.ids = List.of(value); - return this; - } - - public UserRoleQuery ids(UUID... value) { - this.ids = Arrays.asList(value); - return this; - } - - public UserRoleQuery ids(Collection values) { - this.ids = values; - return this; - } - - public UserRoleQuery excludedIds(Collection values) { - this.excludedIds = values; - return this; - } - - public UserRoleQuery excludedIds(UUID value) { - this.excludedIds = List.of(value); - return this; - } - - public UserRoleQuery excludedIds(UUID... value) { - this.excludedIds = Arrays.asList(value); - return this; - } - - public UserRoleQuery isActives(Collection values) { - this.isActives = values; - return this; - } - - public UserRoleQuery isActives(IsActive value) { - this.isActives = List.of(value); - return this; - } - - public UserRoleQuery isActives(IsActive... value) { - this.isActives = Arrays.asList(value); - return this; - } - - public UserRoleQuery userIds(UUID value) { - this.userIds = List.of(value); - return this; - } - - public UserRoleQuery userIds(UUID... value) { - this.userIds = Arrays.asList(value); - return this; - } - - public UserRoleQuery userIds(Collection values) { - this.userIds = values; - return this; - } - - public UserRoleQuery roles(String value) { - this.roles = List.of(value); - return this; - } - - public UserRoleQuery roles(String... value) { - this.roles = Arrays.asList(value); - return this; - } - - public UserRoleQuery roles(Collection values) { - this.roles = values; - return this; - } - - public UserRoleQuery authorize(EnumSet values) { - this.authorize = values; - return this; - } - - public UserRoleQuery enableTracking() { - this.noTracking = false; - return this; - } - - public UserRoleQuery 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.roles) || - this.isEmpty(this.excludedIds); - } - - @Override - protected Class entityClass() { - return UserRoleEntity.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(UserRoleEntity._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(UserRoleEntity._id)); - for (UUID item : this.ids) - inClause.value(item); - predicates.add(inClause); - } - if (this.isActives != null) { - predicates.add(queryContext.Root.get(UserRoleEntity._isActive).in(isActives)); - } - if (this.userIds != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserRoleEntity._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(UserRoleEntity._id)); - for (UUID item : this.excludedIds) - notInClause.value(item); - predicates.add(notInClause.not()); - } - if (this.roles != null) { - CriteriaBuilder.In inClause = queryContext.CriteriaBuilder.in(queryContext.Root.get(UserRoleEntity._role)); - for (String item : this.roles) - 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(UserRole._id)) - return UserRoleEntity._id; - else if (item.match(UserRole._role)) - return UserRoleEntity._role; - else if (item.prefix(UserRole._user)) - return UserRoleEntity._userId; - else if (item.match(UserRole._user)) - return UserRoleEntity._userId; - else if (item.match(UserRole._createdAt)) - return UserRoleEntity._createdAt; - else if (item.match(UserRole._updatedAt)) - return UserRoleEntity._updatedAt; - else if (item.match(UserRole._isActive)) - return UserRoleEntity._isActive; - else - return null; - } - - @Override - protected UserRoleEntity convert(Tuple tuple, Set columns) { - UserRoleEntity item = new UserRoleEntity(); - item.setId(QueryBase.convertSafe(tuple, columns, UserRoleEntity._id, UUID.class)); - item.setRole(QueryBase.convertSafe(tuple, columns, UserRoleEntity._role, String.class)); - item.setUserId(QueryBase.convertSafe(tuple, columns, UserRoleEntity._userId, UUID.class)); - item.setCreatedAt(QueryBase.convertSafe(tuple, columns, UserRoleEntity._createdAt, Instant.class)); - item.setUpdatedAt(QueryBase.convertSafe(tuple, columns, UserRoleEntity._updatedAt, Instant.class)); - item.setIsActive(QueryBase.convertSafe(tuple, columns, UserRoleEntity._isActive, IsActive.class)); - return item; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/InAppNotificationLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/InAppNotificationLookup.java deleted file mode 100644 index bafcf699d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/InAppNotificationLookup.java +++ /dev/null @@ -1,134 +0,0 @@ -package gr.cite.notification.query.lookup; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationInAppTracking; -import gr.cite.notification.query.InAppNotificationQuery; -import gr.cite.notification.query.NotificationQuery; -import gr.cite.tools.data.query.Lookup; -import gr.cite.tools.data.query.QueryFactory; - -import java.time.Instant; -import java.util.Collection; -import java.util.List; -import java.util.UUID; - -public class InAppNotificationLookup extends Lookup { - - private String like; - private Collection ids; - private List excludeIds; - private List userId; - private List type; - private Collection isActive; - private List tenantIds; - private List trackingState; - private Boolean isRead; - private Instant from; - private Instant to; - - public String getLike() { - return like; - } - - public void setLike(String like) { - this.like = like; - } - - public Collection getIds() { - return ids; - } - - public void setIds(Collection ids) { - this.ids = ids; - } - - public List getExcludeIds() { - return excludeIds; - } - - public void setExcludeIds(List excludeIds) { - this.excludeIds = excludeIds; - } - - public List getUserId() { - return userId; - } - - public void setUserId(List userId) { - this.userId = userId; - } - - public List getType() { - return type; - } - - public void setType(List type) { - this.type = type; - } - - public Collection getIsActive() { - return isActive; - } - - public void setIsActive(Collection isActive) { - this.isActive = isActive; - } - - public List getTenantIds() { - return tenantIds; - } - - public void setTenantIds(List tenantIds) { - this.tenantIds = tenantIds; - } - - public List getTrackingState() { - return trackingState; - } - - public void setTrackingState(List trackingState) { - this.trackingState = trackingState; - } - - public Boolean getRead() { - return isRead; - } - - public void setRead(Boolean read) { - isRead = read; - } - - public Instant getFrom() { - return from; - } - - public void setFrom(Instant from) { - this.from = from; - } - - public Instant getTo() { - return to; - } - - public void setTo(Instant to) { - this.to = to; - } - - public InAppNotificationQuery enrich(QueryFactory queryFactory) { - InAppNotificationQuery query = queryFactory.query(InAppNotificationQuery.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); - if (this.type != null) query.type(this.type); - if (this.isRead != null) query.isRead(this.isRead); - if (this.excludeIds != null) query.excludeIds(this.excludeIds); - if (this.to != null) query.to(this.to); - if (this.trackingState != null) query.trackingState(this.trackingState); - if (this.userId != null) query.userId(this.userId); - - this.enrichCommon(query); - - return query; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotificationLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotificationLookup.java deleted file mode 100644 index ca27d07f7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotificationLookup.java +++ /dev/null @@ -1,155 +0,0 @@ -package gr.cite.notification.query.lookup; - -import gr.cite.notification.common.enums.*; -import gr.cite.notification.query.NotificationQuery; -import gr.cite.notification.query.TenantQuery; -import gr.cite.tools.data.query.Lookup; -import gr.cite.tools.data.query.QueryFactory; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class NotificationLookup extends Lookup { - private List isActive; - private List ids; - private List notifyState; - private List notifiedWith; - private Boolean notifiedWithHasValue; - private Boolean notifiedAtHasValue; - private List type; - private List contactType; - private Integer retryThreshold; - private Instant createdAfter; - private List trackingState; - private List trackingProcess; - private List userIds; - - - 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 List getNotifyState() { - return notifyState; - } - - public void setNotifyState(List notifyState) { - this.notifyState = notifyState; - } - - public List getNotifiedWith() { - return notifiedWith; - } - - public void setNotifiedWith(List notifiedWith) { - this.notifiedWith = notifiedWith; - } - - public Boolean getNotifiedWithHasValue() { - return notifiedWithHasValue; - } - - public void setNotifiedWithHasValue(Boolean notifiedWithHasValue) { - this.notifiedWithHasValue = notifiedWithHasValue; - } - - public Boolean getNotifiedAtHasValue() { - return notifiedAtHasValue; - } - - public void setNotifiedAtHasValue(Boolean notifiedAtHasValue) { - this.notifiedAtHasValue = notifiedAtHasValue; - } - - public List getType() { - return type; - } - - public void setType(List type) { - this.type = type; - } - - public List getContactType() { - return contactType; - } - - public void setContactType(List contactType) { - this.contactType = contactType; - } - - public Integer getRetryThreshold() { - return retryThreshold; - } - - public void setRetryThreshold(Integer retryThreshold) { - this.retryThreshold = retryThreshold; - } - - public Instant getCreatedAfter() { - return createdAfter; - } - - public void setCreatedAfter(Instant createdAfter) { - this.createdAfter = createdAfter; - } - - public List getTrackingState() { - return trackingState; - } - - public void setTrackingState(List trackingState) { - this.trackingState = trackingState; - } - - public List getTrackingProcess() { - return trackingProcess; - } - - public void setTrackingProcess(List trackingProcess) { - this.trackingProcess = trackingProcess; - } - - public List getUserIds() { - return userIds; - } - - public void setUserIds(List userIds) { - this.userIds = userIds; - } - - public NotificationQuery enrich(QueryFactory queryFactory) { - NotificationQuery query = queryFactory.query(NotificationQuery.class); - if (this.isActive != null) query.isActive(this.isActive); - if (this.ids != null) query.ids(this.ids); - if (this.notifiedAtHasValue != null) query.notifiedAtHasValue(this.notifiedAtHasValue); - if (this.notifyState != null) query.notifyState(this.notifyState); - if (this.contactType != null) query.contactType(this.contactType); - if (this.createdAfter != null) query.createdAfter(this.createdAfter); - if (this.notifiedWithHasValue != null) query.notifiedWithHasValue(this.notifiedWithHasValue); - if (this.notifiedWith != null) query.notifiedWith(this.notifiedWith); - if (this.retryThreshold != null) query.retryThreshold(this.retryThreshold); - if (this.type != null) query.type(this.type); - if (this.trackingProcess != null) query.trackingProgress(this.trackingProcess); - if (this.trackingState != null) query.trackingState(this.trackingState); - if (this.userIds != null) query.userIds(this.userIds); - - this.enrichCommon(query); - - return query; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotificationTemplateLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotificationTemplateLookup.java deleted file mode 100644 index 938531dfb..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotificationTemplateLookup.java +++ /dev/null @@ -1,89 +0,0 @@ -package gr.cite.notification.query.lookup; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationTemplateChannel; -import gr.cite.notification.common.enums.NotificationTemplateKind; -import gr.cite.notification.query.NotificationTemplateQuery; -import gr.cite.tools.data.query.Lookup; -import gr.cite.tools.data.query.QueryFactory; - -import java.util.List; -import java.util.UUID; - -public class NotificationTemplateLookup extends Lookup { - - private List isActive; - - private List notificationTypes; - - private List channels; - - private List kinds; - - private List ids; - - private List excludedIds; - - public List getIsActive() { - return isActive; - } - - public List getNotificationTypes() { - return notificationTypes; - } - - public void setNotificationTypes(List notificationTypes) { - this.notificationTypes = notificationTypes; - } - - public void setIsActive(List isActive) { - this.isActive = isActive; - } - - public List getChannels() { - return channels; - } - - public void setChannels(List channels) { - this.channels = channels; - } - - public List getKinds() { - return kinds; - } - - public void setKinds(List kinds) { - this.kinds = kinds; - } - - 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 NotificationTemplateQuery enrich(QueryFactory queryFactory) { - NotificationTemplateQuery query = queryFactory.query(NotificationTemplateQuery.class); - if (this.ids != null) query.ids(this.ids); - if (this.excludedIds != null) query.excludedIds(this.excludedIds); - if (this.notificationTypes != null) query.notificationTypes(this.notificationTypes); - if (this.isActive != null) query.isActive(this.isActive); - if (this.channels != null) query.channels(this.channels); - if (this.kinds != null) query.kinds(this.kinds); - - this.enrichCommon(query); - - return query; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotifierListLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotifierListLookup.java deleted file mode 100644 index b3960b828..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/NotifierListLookup.java +++ /dev/null @@ -1,16 +0,0 @@ -package gr.cite.notification.query.lookup; - -import java.util.Set; -import java.util.UUID; - -public class NotifierListLookup { - private Set notificationTypes; - - public Set getNotificationTypes() { - return notificationTypes; - } - - public void setNotificationTypes(Set notificationTypes) { - this.notificationTypes = notificationTypes; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/TenantConfigurationLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/TenantConfigurationLookup.java deleted file mode 100644 index af35dd53d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/TenantConfigurationLookup.java +++ /dev/null @@ -1,84 +0,0 @@ -package gr.cite.notification.query.lookup; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.query.TenantConfigurationQuery; -import gr.cite.notification.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 TenantConfigurationLookup extends Lookup { - - private List isActive; - private List types; - private List ids; - private List tenantIds; - private List excludedIds; - private Boolean tenantIsSet; - - - 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 List getExcludedIds() { - return excludedIds; - } - - public void setExcludedIds(List excludeIds) { - this.excludedIds = excludeIds; - } - - public List getTypes() { - return types; - } - - public void setTypes(List types) { - this.types = types; - } - - public List getTenantIds() { - return tenantIds; - } - - public void setTenantIds(List tenantIds) { - this.tenantIds = tenantIds; - } - - public Boolean getTenantIsSet() { - return tenantIsSet; - } - - public void setTenantIsSet(Boolean tenantIsSet) { - this.tenantIsSet = tenantIsSet; - } - - public TenantConfigurationQuery enrich(QueryFactory queryFactory) { - TenantConfigurationQuery query = queryFactory.query(TenantConfigurationQuery.class); - if (this.types != null) query.types(this.types); - if (this.isActive != null) query.isActive(this.isActive); - if (this.ids != null) query.ids(this.ids); - if (this.excludedIds != null) query.excludedIds(this.excludedIds); - if (this.tenantIds != null) query.tenantIds(this.tenantIds); - if (this.tenantIsSet != null) query.tenantIsSet(this.tenantIsSet); - - this.enrichCommon(query); - - return query; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/TenantLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/TenantLookup.java deleted file mode 100644 index 21886546e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/TenantLookup.java +++ /dev/null @@ -1,51 +0,0 @@ -package gr.cite.notification.query.lookup; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserContactInfoLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserContactInfoLookup.java deleted file mode 100644 index abe7d14f0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserContactInfoLookup.java +++ /dev/null @@ -1,41 +0,0 @@ -package gr.cite.notification.query.lookup; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.query.UserContactInfoQuery; -import gr.cite.tools.data.query.Lookup; -import gr.cite.tools.data.query.QueryFactory; - -import java.util.List; -import java.util.UUID; - -public class UserContactInfoLookup extends Lookup { - - private List isActive; - private List userIds; - public List getIsActive() { - return isActive; - } - - public void setIsActive(List isActive) { - this.isActive = isActive; - } - - public List getUserIds() { - return userIds; - } - - public void setUserIds(List userIds) { - this.userIds = userIds; - } - - - public UserContactInfoQuery enrich(QueryFactory queryFactory) { - UserContactInfoQuery query = queryFactory.query(UserContactInfoQuery.class); - if (this.isActive != null) query.isActive(this.isActive); - if (this.userIds != null) query.userIds(this.userIds); - this.enrichCommon(query); - - return query; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserLookup.java deleted file mode 100644 index f96b12909..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserLookup.java +++ /dev/null @@ -1,52 +0,0 @@ -package gr.cite.notification.query.lookup; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserNotificationPreferenceLookup.java b/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserNotificationPreferenceLookup.java deleted file mode 100644 index d1567704b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/lookup/UserNotificationPreferenceLookup.java +++ /dev/null @@ -1,58 +0,0 @@ -package gr.cite.notification.query.lookup; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.query.TenantConfigurationQuery; -import gr.cite.notification.query.UserNotificationPreferenceQuery; -import gr.cite.tools.data.query.Lookup; -import gr.cite.tools.data.query.QueryFactory; - -import java.util.List; -import java.util.UUID; - -public class UserNotificationPreferenceLookup extends Lookup { - private List ids; - private List excludedIds; - private List userId; - private List type; - private List channel; - - public List getUserId() { - return userId; - } - - public void setUserId(List userId) { - this.userId = userId; - } - - public List getType() { - return type; - } - - public void setType(List type) { - this.type = type; - } - - public List getChannel() { - return channel; - } - - public void setChannel(List channel) { - this.channel = channel; - } - - public UserNotificationPreferenceQuery enrich(QueryFactory queryFactory) { - UserNotificationPreferenceQuery query = queryFactory.query(UserNotificationPreferenceQuery.class); - if (this.userId != null) query.userId(this.userId); - if (this.channel != null) query.channel(this.channel); - if (this.type != null) query.type(this.type); - if (this.ids != null) query.ids(this.ids); - if (this.excludedIds != null) query.excludedIds(this.excludedIds); - - this.enrichCommon(query); - - return query; - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/utils/BuildSubQueryInput.java b/notification-service/notification/src/main/java/gr/cite/notification/query/utils/BuildSubQueryInput.java deleted file mode 100644 index 28c8be2ed..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/utils/BuildSubQueryInput.java +++ /dev/null @@ -1,90 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/query/utils/QueryUtilsService.java b/notification-service/notification/src/main/java/gr/cite/notification/query/utils/QueryUtilsService.java deleted file mode 100644 index eda7c1eff..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/utils/QueryUtilsService.java +++ /dev/null @@ -1,7 +0,0 @@ -package gr.cite.notification.query.utils; - -import jakarta.persistence.criteria.Subquery; - -public interface QueryUtilsService { - Subquery buildSubQuery(BuildSubQueryInput parameters); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/query/utils/QueryUtilsServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/query/utils/QueryUtilsServiceImpl.java deleted file mode 100644 index fd179178c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/query/utils/QueryUtilsServiceImpl.java +++ /dev/null @@ -1,18 +0,0 @@ -package gr.cite.notification.query.utils; - -import jakarta.persistence.criteria.Root; -import jakarta.persistence.criteria.Subquery; -import org.springframework.stereotype.Component; - -@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/notification-service/notification/src/main/java/gr/cite/notification/schedule/NotificationScheduleTask.java b/notification-service/notification/src/main/java/gr/cite/notification/schedule/NotificationScheduleTask.java deleted file mode 100644 index 80b50e14f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/schedule/NotificationScheduleTask.java +++ /dev/null @@ -1,158 +0,0 @@ -package gr.cite.notification.schedule; - -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.config.notification.NotificationProperties; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.query.NotificationQuery; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.schedule.model.CandidateInfo; -import gr.cite.notification.schedule.model.MiniTenant; -import gr.cite.notification.service.notification.NotificationService; -import gr.cite.notification.service.notificationscheduling.NotificationSchedulingService; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.ApplicationContext; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -public class NotificationScheduleTask { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationScheduleTask.class)); - - private final ApplicationContext applicationContext; - public NotificationScheduleTask(ApplicationContext applicationContext, NotificationProperties properties) { - this.applicationContext = applicationContext; - long intervalSeconds = properties.getTask().getProcessor().getIntervalSeconds(); - if (properties.getTask().getProcessor().getEnable() && intervalSeconds > 0) { - logger.info("Notification task will be scheduled to run every {} seconds", intervalSeconds); - - ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); - //GK: Fixed rate is heavily unpredictable and it will not scale well on a very heavy workload - scheduler.scheduleWithFixedDelay(this::process, 10, intervalSeconds, TimeUnit.SECONDS); - } - } - - public void process() { - try { - Instant lastCandidateNotificationCreationTimestamp = null; - while (true) { - CandidateInfo candidateInfo = this.candidateToNotify(lastCandidateNotificationCreationTimestamp); - if (candidateInfo == null) break; - - lastCandidateNotificationCreationTimestamp = candidateInfo.getNotificationCreatedAt(); - Boolean shouldOmit = this.shouldOmitNotify(candidateInfo); - if (shouldOmit) { - continue; - } - Boolean shouldAwait = this.shouldWait(candidateInfo); - if (shouldAwait) { - continue; - } - this.notify(candidateInfo.getNotificationId()); - } - - lastCandidateNotificationCreationTimestamp = null; - while(true) { - CandidateInfo candidateInfo = this.candidateToTrack(lastCandidateNotificationCreationTimestamp); - if (candidateInfo == null) break; - - lastCandidateNotificationCreationTimestamp = candidateInfo.getNotificationCreatedAt(); - Boolean shouldOmit = this.shouldOmitTracking(candidateInfo); - if (shouldOmit) { - continue; - } - this.track(candidateInfo.getNotificationId()); - } - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - } - - private CandidateInfo candidateToNotify(Instant lastCandidateNotificationCreationTimestamp) { - CandidateInfo candidateInfo = null; - try { - NotificationSchedulingService schedulingService = this.applicationContext.getBean(NotificationSchedulingService.class); - candidateInfo = schedulingService.candidateToNotify(lastCandidateNotificationCreationTimestamp); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - return candidateInfo; - } - - private Boolean shouldWait(CandidateInfo candidateInfo) { - Boolean shouldWait = false; - try { - NotificationSchedulingService schedulingService = applicationContext.getBean(NotificationSchedulingService.class); - shouldWait = schedulingService.shouldWait(candidateInfo); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - return shouldWait; - } - - private Boolean shouldOmitNotify(CandidateInfo candidateInfo) { - Boolean shouldOmit = false; - try { - NotificationSchedulingService schedulingService = applicationContext.getBean(NotificationSchedulingService.class); - shouldOmit = schedulingService.shouldOmitNotify(candidateInfo.getNotificationId()); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - return shouldOmit; - } - - private Boolean notify(UUID notificationId) { - Boolean success = null; - try { - NotificationSchedulingService schedulingService = applicationContext.getBean(NotificationSchedulingService.class); - success = schedulingService.notify(notificationId); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - - return success; - } - - private CandidateInfo candidateToTrack(Instant lastCandidateNotificationCreationTimestamp) { - CandidateInfo candidateInfo = null; - try { - NotificationSchedulingService schedulingService = this.applicationContext.getBean(NotificationSchedulingService.class); - candidateInfo = schedulingService.candidateToTrack(lastCandidateNotificationCreationTimestamp); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - return candidateInfo; - } - - private Boolean shouldOmitTracking(CandidateInfo candidateInfo) { - Boolean shouldOmit = false; - try { - NotificationSchedulingService schedulingService = applicationContext.getBean(NotificationSchedulingService.class); - shouldOmit = schedulingService.shouldOmitTracking(candidateInfo.getNotificationId()); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - return shouldOmit; - } - - private Boolean track(UUID notificationId) { - Boolean success = null; - try { - NotificationSchedulingService schedulingService = applicationContext.getBean(NotificationSchedulingService.class); - success = schedulingService.track(notificationId); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - } - - return success; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/schedule/model/CandidateInfo.java b/notification-service/notification/src/main/java/gr/cite/notification/schedule/model/CandidateInfo.java deleted file mode 100644 index f8ffe4e1b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/schedule/model/CandidateInfo.java +++ /dev/null @@ -1,45 +0,0 @@ -package gr.cite.notification.schedule.model; - -import gr.cite.notification.common.enums.NotificationNotifyState; - -import java.time.Instant; -import java.util.UUID; - -public class CandidateInfo { - private UUID notificationId; - private NotificationNotifyState previousState; - private Instant notificationCreatedAt; - - public CandidateInfo() { - } - - public CandidateInfo(UUID notificationId, NotificationNotifyState previousState, Instant notificationCreatedAt) { - this.notificationId = notificationId; - this.previousState = previousState; - this.notificationCreatedAt = notificationCreatedAt; - } - - public UUID getNotificationId() { - return notificationId; - } - - public void setNotificationId(UUID notificationId) { - this.notificationId = notificationId; - } - - public NotificationNotifyState getPreviousState() { - return previousState; - } - - public void setPreviousState(NotificationNotifyState previousState) { - this.previousState = previousState; - } - - public Instant getNotificationCreatedAt() { - return notificationCreatedAt; - } - - public void setNotificationCreatedAt(Instant notificationCreatedAt) { - this.notificationCreatedAt = notificationCreatedAt; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/schedule/model/MiniTenant.java b/notification-service/notification/src/main/java/gr/cite/notification/schedule/model/MiniTenant.java deleted file mode 100644 index 09ed0592f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/schedule/model/MiniTenant.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.schedule.model; - -import java.util.UUID; - -public class MiniTenant { - private UUID id; - private String tenantCode; - - public MiniTenant() { - } - - public MiniTenant(UUID id, String tenantCode) { - this.id = id; - this.tenantCode = tenantCode; - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTenantCode() { - return tenantCode; - } - - public void setTenantCode(String tenantCode) { - this.tenantCode = tenantCode; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/AuthnSandbox.java b/notification-service/notification/src/main/java/gr/cite/notification/service/AuthnSandbox.java deleted file mode 100644 index 3e5a408b3..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/AuthnSandbox.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.notification.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/notification-service/notification/src/main/java/gr/cite/notification/service/channelResolution/ChannelResolutionService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/channelResolution/ChannelResolutionService.java deleted file mode 100644 index 18ec2085b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/channelResolution/ChannelResolutionService.java +++ /dev/null @@ -1,14 +0,0 @@ -package gr.cite.notification.service.channelResolution; - -import gr.cite.notification.common.enums.NotificationContactType; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public interface ChannelResolutionService { - - List resolve(UUID type); - List resolve(UUID type, UUID userId); - Map> resolve(UUID type, List userIds); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/channelResolution/ChannelResolutionServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/channelResolution/ChannelResolutionServiceImpl.java deleted file mode 100644 index a01b259d0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/channelResolution/ChannelResolutionServiceImpl.java +++ /dev/null @@ -1,120 +0,0 @@ -package gr.cite.notification.service.channelResolution; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.config.notification.NotificationConfig; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.UserNotificationPreference; -import gr.cite.notification.service.tenantconfiguration.TenantConfigurationService; -import gr.cite.notification.service.userNotificationPreference.UserNotificationPreferenceService; -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.annotation.Qualifier; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.util.*; -import java.util.stream.Collectors; - -@Component -@RequestScope -public class ChannelResolutionServiceImpl implements ChannelResolutionService{ - private static final LoggerService loggerService = new LoggerService(LoggerFactory.getLogger(ChannelResolutionServiceImpl.class)); - - private final ErrorThesaurusProperties errors; - private final Map> globalPoliciesMap; - private final TenantConfigurationService tenantConfigurationService; - private final UserNotificationPreferenceService userNotificationPreferenceService; - - @Autowired - public ChannelResolutionServiceImpl(ErrorThesaurusProperties errors, - @Qualifier(NotificationConfig.BeanQualifier.GLOBAL_POLICIES_MAP) - Map> globalPoliciesMap, - TenantConfigurationService tenantConfigurationService, UserNotificationPreferenceService userNotificationPreferenceService) { - this.errors = errors; - this.globalPoliciesMap = globalPoliciesMap; - this.tenantConfigurationService = tenantConfigurationService; - this.userNotificationPreferenceService = userNotificationPreferenceService; - } - - private List lookupGlobalPolicy(UUID type) { - if (!this.globalPoliciesMap.containsKey(type)) throw new MyApplicationException(this.errors.getSystemError().getCode(), this.errors.getSystemError().getMessage()); - return this.globalPoliciesMap.get(type); - } - - @Override - public List resolve(UUID type) { - return this.lookupGlobalPolicy(type); - } - - @Override - public List resolve(UUID type, UUID userId) { - if (userId == null) return this.resolve(type); - - Map> resolved = this.resolve(type, List.of(userId)); - if (resolved == null || !resolved.containsKey(userId)) return new ArrayList<>(); - return resolved.get(userId); - } - - @Override - public Map> resolve(UUID type, List userIds) { - List users = userIds.stream().distinct().collect(Collectors.toList()); - - List globals = this.lookupGlobalPolicy(type); - List tenantPolicies = this.lookupOrCollectTenantPolicies(type); - Map> userPolicies = this.lookupOrCollectUserPolicies(users, type); - Map> curatedUserPolicies = new HashMap<>(); - for (UUID userId: users) - { - List curatedTypes = null; - if (userPolicies == null || !userPolicies.containsKey(userId)) - { - if (tenantPolicies != null) - { - curatedTypes = tenantPolicies; - } - else - { - curatedTypes = globals; - } - } - else - { - curatedTypes = new ArrayList<>(); - for (NotificationContactType userPolicy : userPolicies.get(userId)) - { - if (globals == null || !globals.contains(userPolicy)) continue; - if (tenantPolicies != null && !tenantPolicies.contains(userPolicy)) continue; - curatedTypes.add(userPolicy); - } - } - curatedUserPolicies.put(userId, curatedTypes); - } - - return curatedUserPolicies; - } - - private List lookupOrCollectTenantPolicies(UUID type) { - NotifierListTenantConfigurationEntity container = this.tenantConfigurationService.collectTenantNotifierList(); - if (container == null || container.getNotifiers() == null) return null; - return container.getNotifiers().get(type); - } - - private Map> lookupOrCollectUserPolicies(List users, UUID type) { - Map> contactsByUser = new HashMap<>(); - Map> userNotificationPreferences = null; - try { - userNotificationPreferences = this.userNotificationPreferenceService.collectUserNotificationPreferences(users); - } catch (InvalidApplicationException e) { - throw new RuntimeException(e); - } - for (Map.Entry> notificationPreference: userNotificationPreferences.entrySet()) - { - contactsByUser.put(notificationPreference.getKey(), notificationPreference.getValue().stream().filter(x -> x.getType() != null && x.getType() == type && x.getChannel() != null).sorted(Comparator.comparingInt(x -> x.getOrdinal())).map(x -> x.getChannel()).collect(Collectors.toList())); - } - return contactsByUser; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/ContactExtractor.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/ContactExtractor.java deleted file mode 100644 index 4fed2e792..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/ContactExtractor.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.notification.service.contact.extractor; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.service.contact.model.Contact; - -public interface ContactExtractor { - - Contact extract(NotificationEntity notification); - - NotificationContactType supports(); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/ContactExtractorFactory.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/ContactExtractorFactory.java deleted file mode 100644 index 01780a6cb..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/ContactExtractorFactory.java +++ /dev/null @@ -1,25 +0,0 @@ -package gr.cite.notification.service.contact.extractor; - -import gr.cite.notification.common.enums.NotificationContactType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Component -public class ContactExtractorFactory { - - private final Map contactExtractorMap; - - - @Autowired - public ContactExtractorFactory(List contactExtractorList) { - this.contactExtractorMap = contactExtractorList.stream().collect(Collectors.toMap(ContactExtractor::supports, contactExtractor -> contactExtractor)); - } - - public ContactExtractor fromContactType(NotificationContactType type) { - return this.contactExtractorMap.getOrDefault(type, null); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java deleted file mode 100644 index 5ef5a6d65..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/EmailContactExtractor.java +++ /dev/null @@ -1,117 +0,0 @@ -package gr.cite.notification.service.contact.extractor; - -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.StringUtils; -import gr.cite.notification.common.enums.ContactInfoType; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.types.notification.ContactPair; -import gr.cite.notification.common.enums.EmailOverrideMode; -import gr.cite.notification.common.types.notification.NotificationContactData; -import gr.cite.notification.config.notification.NotificationConfig; -import gr.cite.notification.config.notification.NotificationProperties; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.data.UserContactInfoEntity; -import gr.cite.notification.model.UserContactInfo; -import gr.cite.notification.query.UserContactInfoQuery; -import gr.cite.notification.service.contact.model.Contact; -import gr.cite.notification.service.contact.model.EmailContact; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -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.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -@Component -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class EmailContactExtractor implements ContactExtractor { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(EmailContactExtractor.class)); - - private final JsonHandlingService jsonHandlingService; - private final QueryFactory queryFactory; - private final Map> flowMap; - - @Autowired - public EmailContactExtractor(JsonHandlingService jsonHandlingService, - @Qualifier(NotificationConfig.BeanQualifier.FLOW_MAP) - Map> flowMap, - QueryFactory queryFactory - ) { - this.jsonHandlingService = jsonHandlingService; - this.queryFactory = queryFactory; - this.flowMap = flowMap; - } - - @Override - public Contact extract(NotificationEntity notification) { - EmailContact emailContact = new EmailContact(); - NotificationContactData data = this.jsonHandlingService.fromJsonSafe(NotificationContactData.class, notification.getContactHint()); - - List contactPairs = data != null && data.getContacts() != null ? data.getContacts().stream().filter(contactPair -> contactPair.getType().equals(ContactInfoType.Email) && !StringUtils.isNullOrEmpty(contactPair.getContact())).collect(Collectors.toList()) : null; - - if (contactPairs != null && !contactPairs.isEmpty()) { - emailContact.setEmails(contactPairs.stream().map(ContactPair::getContact).collect(Collectors.toList())); - } - else if (notification.getUserId() != null) { - logger.trace("extracting from user"); - UserContactInfoEntity userContactInfo = this.queryFactory.query(UserContactInfoQuery.class).disableTracking() - .userIds(notification.getUserId()) - .isActive(IsActive.Active) - .type(ContactInfoType.Email).firstAs(new BaseFieldSet().ensure(UserContactInfo._value)); - - if (userContactInfo != null && userContactInfo.getValue() != null && !userContactInfo.getValue().isBlank()) emailContact.setEmails(List.of(userContactInfo.getValue())); - } - else { - logger.warn("Could not retrieve contact information for notification {}", notification.getId()); - } - NotificationProperties.Flow options = this.locateFlowOptions(notification.getType()); - - List defaultCCs = options.getCc() != null ? options.getCc().stream().filter(x -> x != null && !x.isBlank()).collect(Collectors.toList()) : new ArrayList<>(); - List defaultBCCs = options.getBcc() != null ? options.getBcc().stream().filter(x -> x != null && !x.isBlank()).collect(Collectors.toList()) : new ArrayList<>(); - - List ccContacts = data != null && data.getCc() != null ? data.getCc().stream().filter(contactPair -> contactPair.getType().equals(ContactInfoType.Email) && !StringUtils.isNullOrEmpty(contactPair.getContact())).map(ContactPair::getContact).collect(Collectors.toList()) : new ArrayList<>(); - List bccContacts = data != null && data.getBcc() != null ? data.getBcc().stream().filter(contactPair -> contactPair.getType().equals(ContactInfoType.Email) && !StringUtils.isNullOrEmpty(contactPair.getContact())).map(ContactPair::getContact).collect(Collectors.toList()) : new ArrayList<>(); - - emailContact.setCcEmails(this.mergeContacts(options.getCcMode(), defaultCCs, ccContacts).stream().distinct().collect(Collectors.toList())); - emailContact.setBccEmails(this.mergeContacts(options.getBccMode(), defaultBCCs, bccContacts).stream().distinct().collect(Collectors.toList())); - - return emailContact; - } - - private List mergeContacts(EmailOverrideMode overrideMode, List defaultContacts, List messageContacts) { - switch (overrideMode) { - case NotOverride: - return defaultContacts; - case Replace: - return messageContacts != null && !messageContacts.isEmpty() ? messageContacts : defaultContacts; - case Additive: { - List contacts = new ArrayList<>(); - if (messageContacts != null) contacts.addAll(messageContacts); - if (defaultContacts != null) contacts.addAll(defaultContacts); - return contacts; - } - default: - throw new MyApplicationException("Invalid type " + overrideMode); - } - } - - private NotificationProperties.Flow locateFlowOptions(UUID type) { - return this.flowMap.get("email").getOrDefault(type, null); - } - - @Override - public NotificationContactType supports() { - return NotificationContactType.EMAIL; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/InAppContactExtractor.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/InAppContactExtractor.java deleted file mode 100644 index a68520def..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/extractor/InAppContactExtractor.java +++ /dev/null @@ -1,29 +0,0 @@ -package gr.cite.notification.service.contact.extractor; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.service.contact.model.Contact; -import gr.cite.notification.service.contact.model.InAppContact; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class InAppContactExtractor implements ContactExtractor{ - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InAppContactExtractor.class)); - @Override - public Contact extract(NotificationEntity notification) { - if (notification.getUserId() == null) - { - logger.error("Could not retrieve contact information for notification " + notification.getId()); - return null; - } - logger.trace("extracting from notification"); - return new InAppContact(notification.getUserId()); - } - - @Override - public NotificationContactType supports() { - return NotificationContactType.IN_APP; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/Contact.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/Contact.java deleted file mode 100644 index 4117ffea0..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/Contact.java +++ /dev/null @@ -1,4 +0,0 @@ -package gr.cite.notification.service.contact.model; - -public interface Contact { -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/EmailContact.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/EmailContact.java deleted file mode 100644 index 55d5d4a61..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/EmailContact.java +++ /dev/null @@ -1,42 +0,0 @@ -package gr.cite.notification.service.contact.model; - -import java.util.List; - -public class EmailContact implements Contact{ - private List emails; - private List ccEmails; - private List bccEmails; - - public EmailContact() { - } - - public EmailContact(List emails, List ccEmails, List bccEmails) { - this.emails = emails; - this.ccEmails = ccEmails; - this.bccEmails = bccEmails; - } - - public List getEmails() { - return emails; - } - - public void setEmails(List emails) { - this.emails = emails; - } - - public List getCcEmails() { - return ccEmails; - } - - public void setCcEmails(List ccEmails) { - this.ccEmails = ccEmails; - } - - public List getBccEmails() { - return bccEmails; - } - - public void setBccEmails(List bccEmails) { - this.bccEmails = bccEmails; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/InAppContact.java b/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/InAppContact.java deleted file mode 100644 index ccb43834e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/contact/model/InAppContact.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.notification.service.contact.model; - -import java.util.UUID; - -public class InAppContact implements Contact{ - private UUID userId; - - public InAppContact() { - } - - public InAppContact(UUID userId) { - this.userId = userId; - } - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingService.java deleted file mode 100644 index eb4ddb426..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingService.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.notification.service.formatting; - -import java.time.Instant; -import java.util.Locale; -import java.util.TimeZone; -import java.util.UUID; - -public interface FormattingService { - - String format(int value, UUID userId, String format, Locale locale); - - String format(int value, String format, Locale locale); - - String format(long value, UUID userId, String format, Locale locale); - - String format(long value, String format, Locale locale); - - String format(double value, UUID userId, Integer decimals, String format, Locale locale); - - String format(double value, Integer decimals, String format, Locale locale); - - String format(Instant value, UUID userId, TimeZone timezone, String format, Locale locale); - - String format(Instant value, TimeZone timeZone, String format, Locale locale); -} - diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceConfiguration.java b/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceConfiguration.java deleted file mode 100644 index 8b4530743..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.notification.service.formatting; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties(FormattingServiceProperties.class) -public class FormattingServiceConfiguration { -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceImpl.java deleted file mode 100644 index 22266bdb3..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceImpl.java +++ /dev/null @@ -1,169 +0,0 @@ -package gr.cite.notification.service.formatting; - -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.locale.LocaleService; -import gr.cite.tools.data.query.QueryFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.NumberFormat; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.Locale; -import java.util.TimeZone; -import java.util.UUID; - -@Component -@RequestScope -public class FormattingServiceImpl implements FormattingService { - - private final QueryFactory queryFactory; - private final ConventionService conventionService; - private final LocaleService localeService; - private final FormattingServiceProperties properties; - private final FormattingUserprofileCacheCacheService formattingUserprofileCacheCacheService; - - @Autowired - public FormattingServiceImpl(QueryFactory queryFactory, - ConventionService conventionService, - LocaleService localeService, - FormattingServiceProperties properties, - FormattingUserprofileCacheCacheService formattingUserprofileCacheCacheService - ) { - this.queryFactory = queryFactory; - this.conventionService = conventionService; - this.localeService = localeService; - this.properties = properties; - this.formattingUserprofileCacheCacheService = formattingUserprofileCacheCacheService; - } - - public String format(int value, UUID userId, String format, Locale locale) { - return this.formatNonDecimal(value, userId, format, locale); - } - - private String formatNonDecimal(Number value,UUID userId, String format, Locale locale) { - Locale localeToUse = this.localeService.culture(); - if (locale != null) { - localeToUse = locale; - } else if (userId != null) { - FormattingUserprofileCacheCacheService.UserFormattingProfileCacheValue profile = this.getUserProfile(userId); - if (profile != null) { - localeToUse = this.localeService.cultureSafe(profile.getCulture()); - } - } - - String formatToUse = !this.conventionService.isNullOrEmpty(format) ? format : this.properties.getIntegerFormat(); - return this.formatNonDecimal(value, formatToUse, localeToUse); - } - - public String format(int value, String format, Locale locale) { - return this.formatNonDecimal(value, format, locale); - } - - private String formatNonDecimal(Number value, String format, Locale locale) { - if (this.conventionService.isNullOrEmpty(format) && locale != null) return NumberFormat.getInstance(locale).format(value); - else if (!this.conventionService.isNullOrEmpty(format) && locale == null) return String.format(format, value); - else if (!this.conventionService.isNullOrEmpty(format) && locale != null) return String.format(locale, format, value); - - return NumberFormat.getInstance(Locale.ROOT).format(value); - } - - public String format(long value, UUID userId, String format, Locale locale) { - return this.formatNonDecimal(value, userId, format, locale); - } - - public String format(long value, String format, Locale locale) { - return this.formatNonDecimal(value, format, locale); - } - - public String format(double value, UUID userId, Integer decimals, String format, Locale locale) { - Locale localeToUse = this.localeService.culture(); - if (locale != null) { - localeToUse = locale; - } else if (userId != null) { - FormattingUserprofileCacheCacheService.UserFormattingProfileCacheValue profile = this.getUserProfile(userId); - if (profile != null) { - localeToUse = this.localeService.cultureSafe(profile.getCulture()); - } - } - - String formatToUse = !this.conventionService.isNullOrEmpty(format) ? format : this.properties.getDecimalFormat(); - int decimalsToUse = decimals != null ? decimals : this.properties.getDecimalDigitsRound(); - return this.format(value, decimalsToUse, formatToUse, localeToUse); - } - - public String format(double value, Integer decimals, String format, Locale locale) { - double val = value; - if (decimals != null) { - BigDecimal bd = new BigDecimal(Double.toString(value)); - bd = bd.setScale(decimals, RoundingMode.HALF_UP); - val = bd.doubleValue(); - } - - if (this.conventionService.isNullOrEmpty(format) && locale != null) return NumberFormat.getInstance(locale).format(val); - else if (!this.conventionService.isNullOrEmpty(format) && locale == null) return new DecimalFormat(format).format(val); - else if (!this.conventionService.isNullOrEmpty(format) && locale != null) return new DecimalFormat(format, new DecimalFormatSymbols(locale)).format(val); - - return NumberFormat.getInstance(Locale.ROOT).format(val); - } - - public String format(Instant value, UUID userId, TimeZone timezone, String format, Locale locale) { - FormattingUserprofileCacheCacheService.UserFormattingProfileCacheValue profile = null; - if (userId != null && (locale == null || timezone == null)) { - profile = this.getUserProfile(userId); - } - - Locale localeToUse = this.localeService.culture(); - if (locale != null) { - localeToUse = locale; - } else if (userId != null) { - localeToUse = this.localeService.cultureSafe(profile.getCulture()); - } - - TimeZone timezoneToUse = this.localeService.timezone(); - if (timezone != null) { - timezoneToUse = timezone; - } else if (userId != null) { - timezoneToUse = this.localeService.timezoneSafe(profile.getZone()); - } - - String formatToUse = !this.conventionService.isNullOrEmpty(format) ? format : this.properties.getDateTimeFormat(); - return this.format(value, timezoneToUse, formatToUse, localeToUse); - } - - public String format(Instant value, TimeZone timeZone, String format, Locale locale) { - ZoneId zoneId = ZoneId.from(ZoneOffset.UTC); - - if (timeZone != null) { - zoneId = timeZone.toZoneId(); - } - if (this.conventionService.isNullOrEmpty(format) && locale != null) DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM).withLocale(locale).withZone(zoneId).format(value); - else if (!this.conventionService.isNullOrEmpty(format) && locale == null) return DateTimeFormatter.ofPattern(format).withZone(zoneId).format(value); - else if (!this.conventionService.isNullOrEmpty(format) && locale != null) return DateTimeFormatter.ofPattern(format, locale).withZone(zoneId).format(value); - - return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM).withZone(zoneId).format(value); - } - - private FormattingUserprofileCacheCacheService.UserFormattingProfileCacheValue getUserProfile(UUID userId) { - FormattingUserprofileCacheCacheService.UserFormattingProfileCacheValue cacheValue = this.formattingUserprofileCacheCacheService.lookup(this.formattingUserprofileCacheCacheService.buildKey(userId)); - if (cacheValue != null) { - return cacheValue; - } else { -// UserEntity user = this.queryFactory.query(UserQuery.class).ids(userId).firstAs(new BaseFieldSet().ensure(User._culture).ensure(User._language).ensure(User._timezone).ensure(User._id)); -// if (user == null) return null; -// cacheValue = new FormattingUserprofileCacheCacheService.UserFormattingProfileCacheValue(userId, user.getTimezone(), user.getCulture(), user.getLanguage()); -// this.formattingUserprofileCacheCacheService.put(cacheValue); - - return cacheValue; - } - } -} - diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceProperties.java deleted file mode 100644 index 48126d18f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingServiceProperties.java +++ /dev/null @@ -1,38 +0,0 @@ -package gr.cite.notification.service.formatting; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "formatting.options") -public class FormattingServiceProperties { - - private final String integerFormat; - - private final String decimalFormat; - - private final String dateTimeFormat; - - private final Integer decimalDigitsRound; - - public FormattingServiceProperties(String integerFormat, String decimalFormat, String dateTimeFormat, Integer decimalDigitsRound) { - this.integerFormat = integerFormat; - this.decimalFormat = decimalFormat; - this.dateTimeFormat = dateTimeFormat; - this.decimalDigitsRound = decimalDigitsRound; - } - - public String getIntegerFormat() { - return integerFormat; - } - - public String getDecimalFormat() { - return decimalFormat; - } - - public String getDateTimeFormat() { - return dateTimeFormat; - } - - public Integer getDecimalDigitsRound() { - return decimalDigitsRound; - } -} \ No newline at end of file diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingUserprofileCacheCacheService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingUserprofileCacheCacheService.java deleted file mode 100644 index d07091aa9..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingUserprofileCacheCacheService.java +++ /dev/null @@ -1,92 +0,0 @@ -package gr.cite.notification.service.formatting; - -import gr.cite.notification.event.UserTouchedEvent; -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 FormattingUserprofileCacheCacheService extends CacheService { - - public static class UserFormattingProfileCacheValue { - - public UserFormattingProfileCacheValue() { - } - - public UserFormattingProfileCacheValue(UUID userId, String zone, String culture, String language) { - this.userId = userId; - this.zone = zone; - this.culture = culture; - this.language = language; - } - - private UUID userId; - private String zone; - private String culture; - private String language; - - public String getZone() { - return zone; - } - - public void setZone(String zone) { - this.zone = zone; - } - - 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 getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - } - - @Autowired - public FormattingUserprofileCacheCacheService(FormattingUserprofileCacheOptions options) { - super(options); - } - - @EventListener - public void handleUserTouchedEvent(UserTouchedEvent event) { - if (event.getUserId() != null) this.evict(this.buildKey(event.getUserId())); - } - - @Override - protected Class valueClass() { - return UserFormattingProfileCacheValue.class; - } - - @Override - public String keyOf(UserFormattingProfileCacheValue value) { - return this.buildKey(value.getUserId()); - } - - - public String buildKey(UUID userId) { - return this.generateKey(new HashMap<>() {{ - put("$user_id$", userId.toString().toLowerCase(Locale.ROOT)); - }}); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingUserprofileCacheOptions.java b/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingUserprofileCacheOptions.java deleted file mode 100644 index 199d98d3d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/formatting/FormattingUserprofileCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.notification.service.formatting; - -import gr.cite.tools.cache.CacheOptions; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "cache.formatting-user-profile-cache") -public class FormattingUserprofileCacheOptions extends CacheOptions { -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/inappnotification/InAppNotificationService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/inappnotification/InAppNotificationService.java deleted file mode 100644 index fb0129b8a..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/inappnotification/InAppNotificationService.java +++ /dev/null @@ -1,13 +0,0 @@ -package gr.cite.notification.service.inappnotification; - -import javax.management.InvalidApplicationException; -import java.util.List; -import java.util.UUID; - -public interface InAppNotificationService { - - void markAsRead(List ids); - void markAsRead(UUID id); - void deleteAndSave(UUID id) throws InvalidApplicationException; - void markAsReadAllUserNotification(UUID userId); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/inappnotification/InAppNotificationServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/inappnotification/InAppNotificationServiceImpl.java deleted file mode 100644 index 7e56decef..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/inappnotification/InAppNotificationServiceImpl.java +++ /dev/null @@ -1,98 +0,0 @@ -package gr.cite.notification.service.inappnotification; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.OwnedResource; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.NotificationInAppTracking; -import gr.cite.notification.common.scope.user.UserScope; -import gr.cite.notification.data.InAppNotificationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.model.deleter.InAppNotificationDeleter; -import gr.cite.notification.query.InAppNotificationQuery; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.logging.DataLogEntry; -import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.Query; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.List; -import java.util.UUID; - -@Service -@RequestScope -public class InAppNotificationServiceImpl implements InAppNotificationService { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InAppNotificationServiceImpl.class)); - - private final QueryFactory queryFactory; - - private final TenantEntityManager entityManager; - - private final AuthorizationService authService; - - private final DeleterFactory deleterFactory; - private final UserScope userScope; - - @Autowired - public InAppNotificationServiceImpl(QueryFactory queryFactory, TenantEntityManager entityManager, AuthorizationService authService, DeleterFactory deleterFactory, UserScope userScope) { - this.queryFactory = queryFactory; - this.entityManager = entityManager; - this.authService = authService; - this.deleterFactory = deleterFactory; - this.userScope = userScope; - } - - public void markAsRead(UUID id) { - this.markAsRead(List.of(id)); - } - - public void markAsRead(List ids) { - try { - logger.debug(new DataLogEntry("marking as read in-app notifications", ids)); - UUID userId = this.userScope.getUserId(); - List items = this.queryFactory.query(InAppNotificationQuery.class).disableTracking() - .ids(ids) - .userId(userId) - .collect(); - - Instant now = Instant.now(); - for (InAppNotificationEntity item : items) { - item.setTrackingState(NotificationInAppTracking.DELIVERED); - item.setUpdatedAt(now); - item.setReadTime(now); - this.entityManager.merge(item); - } - } catch (InvalidApplicationException e) { - logger.error(e.getMessage(), e); - } - } - - public void markAsReadAllUserNotification(UUID userId) { - String entity = InAppNotificationEntity.class.getSimpleName(); - - String sqlQuery = "UPDATE " + entity + " as e SET " + InAppNotificationEntity._trackingState + " = :trackingState, " + InAppNotificationEntity._updatedAt + "= :updatedAt, " + InAppNotificationEntity._readTime + " = :readTime " + - "WHERE e." + InAppNotificationEntity._trackingState + " = :trackingStateCondition AND e." + InAppNotificationEntity._userId + " = :userId"; - - Query query = this.entityManager.getEntityManager().createQuery(sqlQuery) - .setParameter("trackingState", NotificationInAppTracking.DELIVERED) - .setParameter("updatedAt", Instant.now()) - .setParameter("readTime", Instant.now()) - .setParameter("userId", userId) - .setParameter("trackingStateCondition", NotificationInAppTracking.STORED); - - int updateCount = query.executeUpdate(); - } - - public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug("deleting in-app notification: {}", id); - this.authService.authorizeAtLeastOneForce(this.userScope.getUserId() != null ? List.of(new OwnedResource(this.userScope.getUserId())) : null, Permission.DeleteInAppNotification); - this.deleterFactory.deleter(InAppNotificationDeleter.class).deleteAndSaveByIds(List.of(id)); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/EmailMessageBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/EmailMessageBuilder.java deleted file mode 100644 index 8cbe09c2f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/EmailMessageBuilder.java +++ /dev/null @@ -1,121 +0,0 @@ -package gr.cite.notification.service.message.builder; - -import gr.cite.notification.service.message.cache.NotificationTemplateCache; -import gr.cite.notification.common.StringUtils; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.enums.NotificationTemplateChannel; -import gr.cite.notification.common.types.notification.FieldInfo; -import gr.cite.notification.config.notification.NotificationConfig; -import gr.cite.notification.config.notification.NotificationProperties; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.NotificationTemplate; -import gr.cite.notification.service.formatting.FormattingService; -import gr.cite.notification.service.message.common.MessageBuilderBase; -import gr.cite.notification.service.message.infobuilder.MessageInfoBuilderService; -import gr.cite.notification.service.message.model.EmailMessage; -import gr.cite.notification.service.message.model.Message; -import gr.cite.notification.service.message.model.MessageInfo; -import gr.cite.notification.service.notificationtemplate.NotificationTemplateService; -import gr.cite.tools.cipher.CipherService; -import gr.cite.tools.cipher.config.CipherProfileProperties; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import java.util.Map; -import java.util.UUID; - -@Component -@RequestScope -public class EmailMessageBuilder extends MessageBuilderBase implements MessageBuilder{ - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(EmailMessageBuilder.class)); - private final NotificationProperties properties; - private final Map> flowMap; - private final MessageInfoBuilderService messageInfoBuilderService; - private final Map cipherFields; - private final NotificationTemplateService notificationTemplateService; - @Autowired - public EmailMessageBuilder(NotificationProperties properties, - @Qualifier(NotificationConfig.BeanQualifier.FLOW_MAP) - Map> flowMap, - MessageInfoBuilderService messageInfoBuilderService, - ErrorThesaurusProperties errors, - @Qualifier(NotificationConfig.BeanQualifier.CIPHER_FIELDS) - Map cipherFields, - CipherService cipherService, - CipherProfileProperties cipherProfileProperties, - FormattingService formattingService, - NotificationTemplateCache cache, NotificationTemplateService notificationTemplateService) { - super(logger, errors, cipherService, cipherProfileProperties, formattingService, cache); - this.properties = properties; - this.flowMap = flowMap; - this.messageInfoBuilderService = messageInfoBuilderService; - this.cipherFields = cipherFields; - this.notificationTemplateService = notificationTemplateService; - } - - @Override - public Message buildMessage(NotificationEntity notification) { - MessageInfo messageInfo = this.messageInfoBuilderService.buildMessageInfo(notification); - if (messageInfo == null) { - logger.error("Could not retrieve message info for notification " + notification.getId()); - return null; - } - NotificationProperties.Flow options = this.flowMap.get("email").getOrDefault(notification.getType(), null); - NotificationTemplate template = notificationTemplateService.lookupOverriddenTemplates(notification.getType(), NotificationTemplateChannel.Email,messageInfo.getLanguage()); - - if (options == null && template == null) { - logger.error("Could not retrieve flow options for notification " + notification.getId() + " of type " + notification.getType()); - return null; - } - String subjectTemplate = null; - ReplaceResult subjectResult = null; - String bodyTemplate = null; - ReplaceResult bodyResult = null; - - // fallback - if (template != null && template.getValue() != null){ - if (!StringUtils.isNullOrEmpty(template.getValue().getSubjectKey())) subjectTemplate = messageInfo.getFields().stream().filter(fieldInfo -> fieldInfo.getKey().equals(template.getValue().getSubjectKey())).findFirst().orElse(new FieldInfo()).getValue(); - if (StringUtils.isNullOrEmpty(subjectTemplate)) subjectTemplate = template.getValue().getSubjectText(); - FieldFormatting subjectFormatting = this.buildFieldFormatting(template.getValue().getSubjectFieldOptions()); - subjectResult = this.buildTemplate(notification.getId(), subjectTemplate, messageInfo, template.getValue().getSubjectFieldOptions(), subjectFormatting, cipherFields.get(notification.getType())); - - if(!StringUtils.isNullOrEmpty(template.getValue().getBodyKey())) bodyTemplate = messageInfo.getFields().stream().filter(fieldInfo -> fieldInfo.getKey().equals(template.getValue().getBodyKey())).findFirst().orElse(new FieldInfo()).getValue(); - if (StringUtils.isNullOrEmpty(bodyTemplate)) bodyTemplate = template.getValue().getBodyText(); - FieldFormatting bodyFormatting = this.buildFieldFormatting(template.getValue().getBodyFieldOptions()); - bodyResult = this.buildTemplate(notification.getId(), bodyTemplate, messageInfo, template.getValue().getBodyFieldOptions(), bodyFormatting, cipherFields.get(notification.getType())); - }else { - if(!StringUtils.isNullOrEmpty(options.getSubjectKey())) subjectTemplate = messageInfo.getFields().stream().filter(fieldInfo -> fieldInfo.getKey().equals(options.getSubjectKey())).findFirst().orElse(new FieldInfo()).getValue(); - if (StringUtils.isNullOrEmpty(subjectTemplate)) subjectTemplate = this.lookupOrReadLocalizedFile(this.getTemplate().getTemplateCache(), options.getSubjectPath(), messageInfo.getLanguage()); - FieldFormatting subjectFormatting = this.buildFieldFormatting(options.getSubjectFieldOptions()); - subjectResult = this.buildTemplate(notification.getId(), subjectTemplate, messageInfo, options.getSubjectFieldOptions(), subjectFormatting, cipherFields.get(notification.getType())); - - if(!StringUtils.isNullOrEmpty(options.getBodyKey())) bodyTemplate = messageInfo.getFields().stream().filter(fieldInfo -> fieldInfo.getKey().equals(options.getBodyKey())).findFirst().orElse(new FieldInfo()).getValue(); - if (StringUtils.isNullOrEmpty(bodyTemplate)) bodyTemplate = this.lookupOrReadLocalizedFile(this.getTemplate().getTemplateCache(), options.getBodyPath(), messageInfo.getLanguage()); - FieldFormatting bodyFormatting = this.buildFieldFormatting(options.getBodyFieldOptions()); - bodyResult = this.buildTemplate(notification.getId(), bodyTemplate, messageInfo, options.getBodyFieldOptions(), bodyFormatting, cipherFields.get(notification.getType())); - - } - if (bodyResult != null && subjectResult != null) { - EmailMessage emailMessage = new EmailMessage(); - emailMessage.setBody(bodyResult.getText()); - emailMessage.setSubject(subjectResult.getText()); - - return emailMessage; - } - return null; - } - - private NotificationProperties.Template getTemplate() { - return this.properties.getMessage().get("email"); - } - - @Override - public NotificationContactType supports() { - return NotificationContactType.EMAIL; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/InAppMessageBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/InAppMessageBuilder.java deleted file mode 100644 index 2523731f3..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/InAppMessageBuilder.java +++ /dev/null @@ -1,139 +0,0 @@ -package gr.cite.notification.service.message.builder; - -import gr.cite.notification.service.message.cache.NotificationTemplateCache; -import gr.cite.notification.common.StringUtils; -import gr.cite.notification.common.enums.InAppNotificationPriority; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.enums.NotificationTemplateChannel; -import gr.cite.notification.common.types.notification.FieldInfo; -import gr.cite.notification.config.notification.NotificationConfig; -import gr.cite.notification.config.notification.NotificationProperties; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.NotificationTemplate; -import gr.cite.notification.service.formatting.FormattingService; -import gr.cite.notification.service.message.common.MessageBuilderBase; -import gr.cite.notification.service.message.infobuilder.MessageInfoBuilderService; -import gr.cite.notification.service.message.model.InAppMessage; -import gr.cite.notification.service.message.model.Message; -import gr.cite.notification.service.message.model.MessageInfo; -import gr.cite.notification.service.notificationtemplate.NotificationTemplateService; -import gr.cite.tools.cipher.CipherService; -import gr.cite.tools.cipher.config.CipherProfileProperties; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -@Component -@RequestScope -public class InAppMessageBuilder extends MessageBuilderBase implements MessageBuilder{ - private final static LoggerService logger = new LoggerService(LoggerFactory.getLogger(InAppMessageBuilder.class)); - private final MessageInfoBuilderService messageInfoBuilderService; - private final Map> flowMap; - private final NotificationProperties properties; - private final NotificationTemplateService notificationTemplateService; - private final QueryFactory queryFactory; - - @Autowired - public InAppMessageBuilder(MessageInfoBuilderService messageInfoBuilderService, - @Qualifier(NotificationConfig.BeanQualifier.FLOW_MAP) - Map> flowMap, - ErrorThesaurusProperties errors, NotificationProperties properties, - CipherService cipherService, - CipherProfileProperties cipherProfileProperties, - FormattingService formattingService, - NotificationTemplateCache cache, NotificationTemplateService notificationTemplateService, QueryFactory queryFactory) { - super(logger, errors, cipherService, cipherProfileProperties, formattingService, cache); - this.messageInfoBuilderService = messageInfoBuilderService; - this.flowMap = flowMap; - this.properties = properties; - this.notificationTemplateService = notificationTemplateService; - this.queryFactory = queryFactory; - } - - @Override - public Message buildMessage(NotificationEntity notification) { - MessageInfo messageInfo = this.messageInfoBuilderService.buildMessageInfo(notification); - if (messageInfo == null) { - logger.error("Could not retrieve message info for notification " + notification.getId()); - return null; - } - - NotificationProperties.Flow options = this.flowMap.get("in-app").getOrDefault(notification.getType(), null); - NotificationTemplate template = notificationTemplateService.lookupOverriddenTemplates(notification.getType(), NotificationTemplateChannel.InApp, messageInfo.getLanguage()); - - if (options == null && template == null) { - logger.error("Could not retrieve flow options for notification " + notification.getId() + " of type " + notification.getType()); - return null; - } - - MessageBuilderBase.FieldCiphering ciphering = options.getCipherFields() == null || options.getCipherFields().isEmpty() ? new MessageBuilderBase.FieldCiphering() : new MessageBuilderBase.FieldCiphering(options.getCipherFields()); - String subjectTemplate = null; - ReplaceResult subjectResult = null; - String bodyTemplate = null; - ReplaceResult bodyResult = null; - - // fallback - if ( template != null && template.getValue() != null){ - if (!StringUtils.isNullOrEmpty(template.getValue().getSubjectKey())) subjectTemplate = messageInfo.getFields().stream().filter(fieldInfo -> fieldInfo.getKey().equals(template.getValue().getSubjectKey())).findFirst().orElse(new FieldInfo()).getValue(); - if (StringUtils.isNullOrEmpty(subjectTemplate)) subjectTemplate = template.getValue().getSubjectText(); - FieldFormatting subjectFormatting = this.buildFieldFormatting(template.getValue().getSubjectFieldOptions()); - subjectResult = this.buildTemplate(notification.getId(), subjectTemplate, messageInfo, template.getValue().getSubjectFieldOptions(), subjectFormatting, ciphering); - - if(!StringUtils.isNullOrEmpty(template.getValue().getBodyKey())) bodyTemplate = messageInfo.getFields().stream().filter(fieldInfo -> fieldInfo.getKey().equals(template.getValue().getBodyKey())).findFirst().orElse(new FieldInfo()).getValue(); - if (StringUtils.isNullOrEmpty(bodyTemplate)) bodyTemplate = template.getValue().getBodyText(); - FieldFormatting bodyFormatting = this.buildFieldFormatting(template.getValue().getBodyFieldOptions()); - bodyResult = this.buildTemplate(notification.getId(), bodyTemplate, messageInfo, template.getValue().getBodyFieldOptions(), bodyFormatting, ciphering); - }else{ - if (!StringUtils.isNullOrEmpty(options.getSubjectKey())) subjectTemplate = messageInfo.getFields().stream().filter(x -> x.getKey().equals(options.getSubjectKey())).findFirst().orElse(new FieldInfo()).getValue(); - if (StringUtils.isNullOrEmpty(subjectTemplate)) subjectTemplate = this.lookupOrReadLocalizedFile(this.getTemplate().getTemplateCache(), options.getSubjectPath(), messageInfo.getLanguage()); - FieldFormatting subjectFormatting = this.buildFieldFormatting(options.getSubjectFieldOptions()); - subjectResult = this.buildTemplate(notification.getId(), subjectTemplate, messageInfo, options.getSubjectFieldOptions(), subjectFormatting, ciphering); - - if (!StringUtils.isNullOrEmpty(options.getBodyKey())) bodyTemplate = messageInfo.getFields().stream().filter(x -> x.getKey().equals(options.getBodyKey())).findFirst().orElse(new FieldInfo()).getValue(); - if (StringUtils.isNullOrEmpty(bodyTemplate)) bodyTemplate = this.lookupOrReadLocalizedFile(this.getTemplate().getTemplateCache(), options.getBodyPath(), messageInfo.getLanguage()); - FieldFormatting bodyFormatting = this.buildFieldFormatting(options.getBodyFieldOptions()); - bodyResult = this.buildTemplate(notification.getId(), bodyTemplate, messageInfo, options.getBodyFieldOptions(), bodyFormatting, ciphering); - } - - String priorityString = ""; - if ( template != null && template.getValue() != null){ - if (!StringUtils.isNullOrEmpty(template.getValue().getPriorityKey())) priorityString = messageInfo.getFields().stream().filter(x -> x.getKey().equals(template.getValue().getPriorityKey())).findFirst().orElse(new FieldInfo()).getValue(); - }else { - if (!StringUtils.isNullOrEmpty(options.getPriorityKey())) priorityString = messageInfo.getFields().stream().filter(x -> x.getKey().equals(options.getPriorityKey())).findFirst().orElse(new FieldInfo()).getValue(); - } - - InAppNotificationPriority inAppNotificationPriority = InAppNotificationPriority.NORMAL; - - if (!StringUtils.isNullOrEmpty(priorityString)) { - inAppNotificationPriority = InAppNotificationPriority.valueOf(priorityString.toLowerCase()); - } - - List extraData = null; - if (template != null && template.getValue() != null){ - if (template.getValue().getExtraDataKeys() != null && !template.getValue().getExtraDataKeys().isEmpty()) extraData = messageInfo.getFields().stream().filter(x -> template.getValue().getExtraDataKeys().contains(x.getKey())).collect(Collectors.toList()); - }else { - if (options.getExtraDataKeys() != null && !options.getExtraDataKeys().isEmpty()) extraData = messageInfo.getFields().stream().filter(x -> options.getExtraDataKeys().contains(x.getKey())).collect(Collectors.toList()); - } - - return new InAppMessage(subjectResult.getText(), bodyResult.getText(), notification.getType(), inAppNotificationPriority, extraData); - } - - private NotificationProperties.Template getTemplate() { - return this.properties.getMessage().get("in-app"); - } - - @Override - public NotificationContactType supports() { - return NotificationContactType.IN_APP; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/MessageBuilder.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/MessageBuilder.java deleted file mode 100644 index bfad76832..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/MessageBuilder.java +++ /dev/null @@ -1,11 +0,0 @@ -package gr.cite.notification.service.message.builder; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.service.message.model.Message; - -public interface MessageBuilder { - Message buildMessage(NotificationEntity notification); - - NotificationContactType supports(); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/MessageBuilderFactory.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/MessageBuilderFactory.java deleted file mode 100644 index 1958bebee..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/builder/MessageBuilderFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -package gr.cite.notification.service.message.builder; - -import gr.cite.notification.common.enums.NotificationContactType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Component -@RequestScope -public class MessageBuilderFactory { - - private final Map messageBuilders; - - @Autowired - public MessageBuilderFactory(List messageBuilders) { - this.messageBuilders = messageBuilders.stream().collect(Collectors.toMap(MessageBuilder::supports, messageBuilder -> messageBuilder)); - } - - public MessageBuilder getFromType(NotificationContactType contactType) { - return messageBuilders.getOrDefault(contactType, null); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/cache/NotificationTemplateCache.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/cache/NotificationTemplateCache.java deleted file mode 100644 index 05538492c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/cache/NotificationTemplateCache.java +++ /dev/null @@ -1,79 +0,0 @@ -package gr.cite.notification.service.message.cache; - -import gr.cite.tools.cache.CacheService; -import org.springframework.cache.Cache; -import org.springframework.stereotype.Component; - -@Component -public class NotificationTemplateCache extends CacheService { - - public static class NotificationTemplateCacheValue { - private String prefix; - private String key; - private String pattern; - - public NotificationTemplateCacheValue() { - } - - public NotificationTemplateCacheValue(String prefix, String key, String pattern) { - this.prefix = prefix; - this.key = key; - this.pattern = pattern; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getPattern() { - return pattern; - } - - public void setPattern(String pattern) { - this.pattern = pattern; - } - } - - public NotificationTemplateCache(NotificationTemplateCacheOptions options) { - super(options); - } - - private Cache cache(){ - return this.cacheManager.getCache(this.options.getName()); - } - - public String lookup(NotificationTemplateCacheValue key) { - return this.cache().get(this.keyOf(key), String.class); - } - - public void put(NotificationTemplateCacheValue key, String value) { - this.cache().put(this.keyOf(key), value); - } - @Override - protected Class valueClass() { - return NotificationTemplateCacheValue.class; - } - - @Override - public String keyOf(NotificationTemplateCacheValue value) { - return this.buildKey(value); - } - - private String buildKey(NotificationTemplateCacheValue value) { - return value.getPattern() - .replace("{prefix}", value.getPrefix()) - .replace("{key}", value.getKey()); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/cache/NotificationTemplateCacheOptions.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/cache/NotificationTemplateCacheOptions.java deleted file mode 100644 index eee0d9134..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/cache/NotificationTemplateCacheOptions.java +++ /dev/null @@ -1,10 +0,0 @@ -package gr.cite.notification.service.message.cache; - -import gr.cite.tools.cache.CacheOptions; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "cache.template") -public class NotificationTemplateCacheOptions extends CacheOptions { -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/common/MessageBuilderBase.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/common/MessageBuilderBase.java deleted file mode 100644 index 32864b6f4..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/common/MessageBuilderBase.java +++ /dev/null @@ -1,305 +0,0 @@ -package gr.cite.notification.service.message.common; - -import gr.cite.notification.service.message.cache.NotificationTemplateCache; -import gr.cite.notification.common.StringUtils; -import gr.cite.notification.common.types.notification.FieldInfo; -import gr.cite.notification.config.notification.NotificationProperties; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.notificationtemplate.FieldOptions; -import gr.cite.notification.service.formatting.FormattingService; -import gr.cite.notification.service.message.model.MessageInfo; -import gr.cite.tools.cipher.CipherService; -import gr.cite.tools.cipher.config.CipherProfileProperties; -import gr.cite.tools.exception.MyApplicationException; -import gr.cite.tools.logging.LoggerService; -import org.springframework.util.ResourceUtils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.time.Instant; -import java.util.*; - -public abstract class MessageBuilderBase { - private final LoggerService logger; - private final ErrorThesaurusProperties errors; - private final CipherService cipherService; - private final CipherProfileProperties cipherProfileProperties; - - private final FormattingService formattingService; - private final NotificationTemplateCache cache; - - public MessageBuilderBase(LoggerService logger, ErrorThesaurusProperties errors, CipherService cipherService, CipherProfileProperties cipherProfileProperties, FormattingService formattingService, NotificationTemplateCache cache) { - this.logger = logger; - this.errors = errors; - this.cipherService = cipherService; - this.cipherProfileProperties = cipherProfileProperties; - this.formattingService = formattingService; - this.cache = cache; - } - - //GK: Unlike in C# in Java Map is just an interface - protected static class FieldFormatting extends HashMap { - public Boolean isSet(String key) { - return this.containsKey(key) && (this.get(key) != null && !this.get(key).isEmpty()); - } - } - - public static class FieldCiphering extends HashSet { - public FieldCiphering(List cipherFields) { - super(cipherFields); - } - - public FieldCiphering() { - } - - public Boolean isSet(String key) { - return this.contains(key); - } - } - - protected static class ReplaceResult { - private String text; - private Set replacedKeys; - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public Set getReplacedKeys() { - return replacedKeys; - } - - public void setReplacedKeys(Set replacedKeys) { - this.replacedKeys = replacedKeys; - } - } - - protected ReplaceResult applyFieldReplace(String text, MessageInfo messageInfo, FieldFormatting fieldFormatting, FieldCiphering fieldCiphering) { - ReplaceResult result = new ReplaceResult(); - result.setReplacedKeys(new HashSet<>()); - - if (messageInfo.getUserId() != null && (fieldCiphering != null && !fieldCiphering.isSet("{user-id}"))) { - String txtValue = fieldFormatting.isSet("{user-id}") ? String.format(fieldFormatting.get("{user-id}"), messageInfo.getUserId().toString()) : messageInfo.getUserId().toString(); - text = text.replace("{user-id}", txtValue); - result.getReplacedKeys().add("{user-id}"); - } - //GOTCHA: fieldCiphering not supported for language-code. will not replace - if (!StringUtils.isNullOrEmpty(messageInfo.getLanguage()) && (fieldCiphering != null && !fieldCiphering.isSet("{language-code}"))) { - String txtValue = fieldFormatting.isSet("{language-code}") ? String.format(fieldFormatting.get("{language-code}"), messageInfo.getLanguage()) : messageInfo.getLanguage(); - text = text.replace("{language-code}", txtValue); - result.getReplacedKeys().add("{language-code}"); - } - //GOTCHA: fieldCiphering not supported for language-code. will not replace - if (!StringUtils.isNullOrEmpty(messageInfo.getCulture()) && (fieldCiphering != null && !fieldCiphering.isSet("{culture-code}"))) { - String txtValue = fieldFormatting.isSet("{culture-code}") ? String.format(fieldFormatting.get("{culture-code}"), messageInfo.getCulture()) : messageInfo.getCulture(); - text = text.replace("{culture-code}", txtValue); - result.getReplacedKeys().add("{culture-code}"); - } - //GOTCHA: fieldCiphering not supported for timezone-code. will not replace - if (!StringUtils.isNullOrEmpty(messageInfo.getTimeZone()) && (fieldCiphering != null && !fieldCiphering.isSet("{timezone-code}"))) { - String txtValue = fieldFormatting.isSet("{timezone-code}") ? String.format(fieldFormatting.get("{timezone-code}"), messageInfo.getTimeZone()) : messageInfo.getTimeZone(); - text = text.replace("{timezone-code}", txtValue); - result.getReplacedKeys().add("{timezone-code}"); - } - //GOTCHA: fieldCiphering not supported for tenant-id. will not replace - if (messageInfo.getTenantId() !=null && !messageInfo.getTenantId().equals(new UUID(0L, 0L)) && (fieldCiphering != null && !fieldCiphering.isSet("{tenant-id}"))) { - String txtValue = fieldFormatting.isSet("{tenant-id}") ? String.format(fieldFormatting.get("{tenant-id}"), messageInfo.getTenantId().toString()) : messageInfo.getTenantId().toString(); - text = text.replace("{tenant-id}", txtValue); - result.getReplacedKeys().add("{tenant-id}"); - } - //GOTCHA: fieldCiphering not supported for tenant-code. will not replace - if (!StringUtils.isNullOrEmpty(messageInfo.getTenantCode()) && (fieldCiphering != null && !fieldCiphering.isSet("{tenant-code}"))) { - String txtValue = fieldFormatting.isSet("{tenant-code}") ? String.format(fieldFormatting.get("{tenant-code}"), messageInfo.getTenantCode()) : messageInfo.getTenantCode(); - text = text.replace("{tenant-code}", txtValue); - result.getReplacedKeys().add("{tenant-code}"); - } - - for (FieldInfo field : messageInfo.getFields()) { - FieldInfo theField = field; - if ((fieldCiphering != null && fieldCiphering.isSet(field.getKey())) && !StringUtils.isNullOrEmpty(field.getValue())) { - theField = new FieldInfo(); - theField.setKey(field.getKey()); - theField.setType(field.getType()); - theField.setValue(this.decipherValue(field)); - } - - if (fieldFormatting != null){ - String format = fieldFormatting.isSet(theField.getKey()) ? fieldFormatting.get(theField.getKey()) : null; - String value = this.format(messageInfo.getUserId(), theField, format); - if (StringUtils.isNullOrEmpty(value)) continue; - text = text.replace(theField.getKey(), value); - result.getReplacedKeys().add(theField.getKey()); - } - } - - result.setText(text); - - return result; - } - - protected FieldFormatting buildFieldFormatting(NotificationProperties.Flow.FieldOption options) { - FieldFormatting formatting = new FieldFormatting(); - if (options == null || options.getFormatting() == null) return formatting; - - for (Map.Entry pair : options.getFormatting().entrySet()) { - if (StringUtils.isNullOrEmpty(pair.getValue())) continue; - formatting.put(pair.getKey(), pair.getValue()); - } - return formatting; - } - - protected FieldFormatting buildFieldFormatting(FieldOptions options) { - FieldFormatting formatting = new FieldFormatting(); - if (options == null || options.getFormatting() == null) return formatting; - - for (Map.Entry pair : options.getFormatting().entrySet()) { - if (StringUtils.isNullOrEmpty(pair.getValue())) continue; - formatting.put(pair.getKey(), pair.getValue()); - } - return formatting; - } - - protected String lookupOrReadLocalizedFile(NotificationProperties.Template.TemplateCache templateCache, String path, String language) { - String filename = path.replace("{language}", language); - File file = null; - NotificationTemplateCache.NotificationTemplateCacheValue cacheKey = - new NotificationTemplateCache.NotificationTemplateCacheValue(templateCache.getPrefix(), - filename, - templateCache.getKeyPattern()); - String content = this.cache.lookup(cacheKey); - - if (!StringUtils.isNullOrEmpty(content)) return content; - try { - file = ResourceUtils.getFile(filename); - - } catch (FileNotFoundException e) { - throw new MyApplicationException(this.errors.getSystemError().getCode(), this.errors.getSystemError().getMessage()); - } - try { - content = new String(new FileInputStream(file).readAllBytes()); - } catch (IOException e) { - throw new RuntimeException(e); - } - - this.cache.put(cacheKey, content); - - return content; - } - - protected String decipherValue(FieldInfo field) { - try { - return this.cipherService.decryptSymetricAes(field.getValue(), this.cipherProfileProperties.getProfileMap().get("notification-profile-name")); - } catch (Exception ex) { - this.logger.error("could not decipher value " + field.getValue() + " of key " + field.getKey() + ". no value for key", ex); - return null; - } - } - - protected ReplaceResult buildTemplate(UUID notificationId, String template, MessageInfo messageInfo, NotificationProperties.Flow.FieldOption options, FieldFormatting formatting, FieldCiphering ciphering) { - ReplaceResult result = this.applyFieldReplace(template, messageInfo, formatting, ciphering); - if (options != null) { - Boolean allMandatory = this.ensureMandatoryFields(result, options.getMandatory() != null ? options.getMandatory() : new ArrayList<>()); - if (!allMandatory) { - logger.error("Could not replace all subject mandatory field for notification {}", notificationId); - return null; - } - if (options.getOptional() != null) { - for (FieldInfo field : options.getOptional()) { - result.setText(this.applyFieldReplace(result.getText(), field, "", formatting)); - } - } - } - return result; - } - - protected ReplaceResult buildTemplate(UUID notificationId, String template, MessageInfo messageInfo, FieldOptions options, FieldFormatting formatting, FieldCiphering ciphering) { - ReplaceResult result = this.applyFieldReplace(template, messageInfo, formatting, ciphering); - if (options != null) { - Boolean allMandatory = this.ensureMandatoryFields(result, options.getMandatory() != null ? options.getMandatory() : new ArrayList<>()); - if (!allMandatory) { - logger.error("Could not replace all subject mandatory field for notification {}", notificationId); - return null; - } - if (options.getOptional() != null) { - for (FieldInfo field : options.getOptional()) { - result.setText(this.applyFieldReplace(result.getText(), field, "", formatting)); - } - } - } - return result; - } - - protected Boolean ensureMandatoryFields(ReplaceResult result, List mandatory) { - for (String field : mandatory) { - if (!result.getReplacedKeys().contains(field)) { - logger.warn("Mandatory field {} was not replaced in message", field); - return false; - } - } - return true; - } - - protected String applyFieldReplace(String text, FieldInfo field, String defaultValue, FieldFormatting formatting) { - String txtVal = defaultValue; - if (!StringUtils.isNullOrEmpty(field.getValue())) { - if (formatting.isSet(field.getKey())) txtVal = String.format(formatting.get(field.getKey()), field.getValue()); - else txtVal = field.getValue(); - } - - text = text.replace(field.getKey(), txtVal); - - return text; - } - - protected String format(UUID userId, FieldInfo field, String format) { - switch (field.getType()) { - case DateTime: - return this.dateTimeFormat(userId, field.getValue(), format); - case Decimal: - return this.decimalFormat(userId, field.getValue(), format); - case Double: - return this.doubleFormat(userId, field.getValue(), format); - case Integer: - return this.integerFormat(userId, field.getValue(), format); - case String: - default: - return this.stringFormat(field.getValue(), format); - } - } - - private String stringFormat(String value, String format) { - String val; - if (!StringUtils.isNullOrEmpty(format)) val = String.format(format, value); - else val = value; - - return val; - } - - private String dateTimeFormat(UUID userId, String value, String format) { - if (StringUtils.isNullOrEmpty(value)) return ""; - Instant time = Instant.parse(value); - return formattingService.format(time, userId, null, format, null); - } - - private String decimalFormat(UUID userId, String value, String format) { - if (StringUtils.isNullOrEmpty(value)) return ""; - Double aDouble = Double.parseDouble(value); - return formattingService.format(aDouble, userId, null, format, null); - } - - private String doubleFormat(UUID userId, String value, String format) { - return this.decimalFormat(userId, value, format); - } - - private String integerFormat(UUID userId, String value, String format) { - if (StringUtils.isNullOrEmpty(value)) return ""; - Integer aInteger = Integer.parseInt(value); - return formattingService.format(aInteger, userId, format, null); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/infobuilder/MessageBuilderServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/infobuilder/MessageBuilderServiceImpl.java deleted file mode 100644 index 06d4bda4e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/infobuilder/MessageBuilderServiceImpl.java +++ /dev/null @@ -1,134 +0,0 @@ -package gr.cite.notification.service.message.infobuilder; - -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.StringUtils; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.enums.NotificationDataType; -import gr.cite.notification.common.types.notification.FieldInfo; -import gr.cite.notification.common.types.notification.NotificationFieldData; -import gr.cite.notification.common.types.tenantconfiguration.DefaultUserLocaleTenantConfigurationEntity; -import gr.cite.notification.common.types.user.AdditionalInfoEntity; -import gr.cite.notification.config.notification.NotificationConfig; -import gr.cite.notification.config.notification.NotificationProperties; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.UserEntity; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.locale.LocaleService; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.query.UserQuery; -import gr.cite.notification.service.contact.extractor.EmailContactExtractor; -import gr.cite.notification.service.message.model.MessageInfo; -import gr.cite.notification.service.tenantconfiguration.TenantConfigurationService; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyForbiddenException; -import gr.cite.tools.fieldset.BaseFieldSet; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.util.List; -import java.util.stream.Collectors; - -@Component -@RequestScope -public class MessageBuilderServiceImpl implements MessageInfoBuilderService { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(EmailContactExtractor.class)); - - private final List staticFieldList; - private final JsonHandlingService jsonHandlingService; - private final QueryFactory queryFactory; - private final TenantConfigurationService tenantConfigurationService; - private final TenantScope scope; - private final ErrorThesaurusProperties errors; - private final LocaleService localeService; - - @Autowired - public MessageBuilderServiceImpl(@Qualifier(NotificationConfig.BeanQualifier.STATIC_FIELD_LIST) - List staticFieldList, - JsonHandlingService jsonHandlingService, - QueryFactory queryFactory, - TenantConfigurationService tenantConfigurationService, - TenantScope scope, ErrorThesaurusProperties errors, - LocaleService localeService) { - this.staticFieldList = staticFieldList; - this.jsonHandlingService = jsonHandlingService; - this.queryFactory = queryFactory; - this.tenantConfigurationService = tenantConfigurationService; - this.scope = scope; - this.errors = errors; - this.localeService = localeService; - } - - @Override - public MessageInfo buildMessageInfo(NotificationEntity notification) { - MessageInfo messageInfo = new MessageInfo(); - messageInfo.setUserId(notification.getUserId()); - messageInfo.setFields(staticFieldList.stream() - .filter(field -> !StringUtils.isNullOrEmpty(field.getKey()) && !StringUtils.isNullOrEmpty(field.getValue())) - .map(field -> { - FieldInfo fieldInfo = new FieldInfo(); - fieldInfo.setKey(field.getKey()); - fieldInfo.setType(NotificationDataType.valueOf(field.getType())); - fieldInfo.setValue(field.getValue()); - return fieldInfo; - }).collect(Collectors.toList())); - NotificationFieldData data = this.jsonHandlingService.fromJsonSafe(NotificationFieldData.class, notification.getData()); - if (data != null && data.getFields() != null) messageInfo.getFields().addAll(data.getFields()); - - UserEntity userProfile = null; - if (notification.getUserId() != null) { - userProfile = this.queryFactory.query(UserQuery.class).disableTracking() - .ids(notification.getUserId()) - .isActive(IsActive.Active).first(); - } - - AdditionalInfoEntity additionalInfoEntity = userProfile == null ? null : this.jsonHandlingService.fromJsonSafe(AdditionalInfoEntity.class, userProfile.getAdditionalInfo()); - - if (additionalInfoEntity != null) { - messageInfo.setLanguage(additionalInfoEntity.getLanguage()); - messageInfo.setCulture(additionalInfoEntity.getCulture()); - messageInfo.setTimeZone(additionalInfoEntity.getTimezone()); - } else { - DefaultUserLocaleTenantConfigurationEntity defaultUserLocaleConfiguration = this.tenantConfigurationService.collectTenantUserLocale(); - if (defaultUserLocaleConfiguration != null) { - messageInfo.setLanguage(defaultUserLocaleConfiguration.getLanguage()); - messageInfo.setCulture(defaultUserLocaleConfiguration.getCulture()); - messageInfo.setTimeZone(defaultUserLocaleConfiguration.getTimezone()); - } - } - - if (messageInfo.getLanguage() == null || messageInfo.getLanguage().isBlank()) messageInfo.setLanguage(this.localeService.language()); - if (messageInfo.getCulture() == null || messageInfo.getCulture().isBlank()) messageInfo.setCulture(this.localeService.cultureName()); - if (messageInfo.getTimeZone() == null || messageInfo.getTimeZone().isBlank()) messageInfo.setTimeZone(this.localeService.timezoneName()); - - if (this.scope.isMultitenant()) { - if (!this.scope.isDefaultTenant()) { - TenantEntity tenantInfo = this.queryFactory.query(TenantQuery.class).disableTracking() - .isActive(IsActive.Active).firstAs(new BaseFieldSet(TenantEntity._id, TenantEntity._code)); - - if (tenantInfo == null) { - try { - logger.error("Could not retrieve tenant info for notification {} in tenant {}", notification.getId(), scope.getTenant()); - } catch (InvalidApplicationException e) { - throw new RuntimeException(e); - } - throw new MyForbiddenException(this.errors.getMissingTenant().getCode(), this.errors.getMissingTenant().getMessage()); - } - - messageInfo.setTenantId(tenantInfo.getId()); - messageInfo.setTenantCode(tenantInfo.getCode()); - } else { - messageInfo.setTenantId(null); - messageInfo.setTenantCode(this.scope.getDefaultTenantCode()); - } - } - - return messageInfo; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/infobuilder/MessageInfoBuilderService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/infobuilder/MessageInfoBuilderService.java deleted file mode 100644 index 619a78316..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/infobuilder/MessageInfoBuilderService.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.notification.service.message.infobuilder; - -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.service.message.model.MessageInfo; - -public interface MessageInfoBuilderService { - - MessageInfo buildMessageInfo(NotificationEntity notification); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/EmailMessage.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/EmailMessage.java deleted file mode 100644 index 8c0e5d5dc..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/EmailMessage.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.notification.service.message.model; - -public class EmailMessage implements Message{ - private String subject; - private String body; - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/InAppMessage.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/InAppMessage.java deleted file mode 100644 index bf6b6ec5b..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/InAppMessage.java +++ /dev/null @@ -1,66 +0,0 @@ -package gr.cite.notification.service.message.model; - -import gr.cite.notification.common.enums.InAppNotificationPriority; -import gr.cite.notification.common.types.notification.FieldInfo; - -import java.util.List; -import java.util.UUID; - -public class InAppMessage implements Message{ - private String subject; - private String body; - private UUID type; - private InAppNotificationPriority priority; - private List ExtraData; - - public InAppMessage() { - } - - public InAppMessage(String subject, String body, UUID type, InAppNotificationPriority priority, List extraData) { - this.subject = subject; - this.body = body; - this.type = type; - this.priority = priority; - ExtraData = extraData; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public UUID getType() { - return type; - } - - public void setType(UUID type) { - this.type = type; - } - - public InAppNotificationPriority getPriority() { - return priority; - } - - public void setPriority(InAppNotificationPriority priority) { - this.priority = priority; - } - - public List getExtraData() { - return ExtraData; - } - - public void setExtraData(List extraData) { - ExtraData = extraData; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/Message.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/Message.java deleted file mode 100644 index 116ebea8d..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/Message.java +++ /dev/null @@ -1,4 +0,0 @@ -package gr.cite.notification.service.message.model; - -public interface Message { -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/MessageInfo.java b/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/MessageInfo.java deleted file mode 100644 index d7fc78c98..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/message/model/MessageInfo.java +++ /dev/null @@ -1,72 +0,0 @@ -package gr.cite.notification.service.message.model; - -import gr.cite.notification.common.types.notification.FieldInfo; - -import java.util.List; -import java.util.UUID; - -public class MessageInfo { - private UUID userId; - private String language; - private String culture; - private String timeZone; - private UUID tenantId; - private String tenantCode; - private List fields; - - public UUID getUserId() { - return userId; - } - - public void setUserId(UUID userId) { - this.userId = userId; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public String getCulture() { - return culture; - } - - public void setCulture(String culture) { - this.culture = culture; - } - - public String getTimeZone() { - return timeZone; - } - - public void setTimeZone(String timeZone) { - this.timeZone = timeZone; - } - - 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; - } - - public List getFields() { - return fields; - } - - public void setFields(List fields) { - this.fields = fields; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationService.java deleted file mode 100644 index 3cf6b5c29..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationService.java +++ /dev/null @@ -1,21 +0,0 @@ -package gr.cite.notification.service.notification; - -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.model.Notification; -import gr.cite.notification.model.SendNotificationResult; -import gr.cite.notification.model.persist.NotificationPersist; -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 NotificationService{ - - Notification persist(NotificationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException; - void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; - SendNotificationResult doNotify(NotificationEntity notification); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java deleted file mode 100644 index 0dd30f452..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notification/NotificationServiceImpl.java +++ /dev/null @@ -1,223 +0,0 @@ -package gr.cite.notification.service.notification; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.data.UserNotificationPreferenceEntity; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.SendNotificationResult; -import gr.cite.notification.model.UserNotificationPreference; -import gr.cite.notification.model.builder.NotificationBuilder; -import gr.cite.notification.model.Notification; -import gr.cite.notification.model.deleter.NotificationDeleter; -import gr.cite.notification.model.persist.NotificationPersist; -import gr.cite.notification.query.NotificationQuery; -import gr.cite.notification.query.UserNotificationPreferenceQuery; -import gr.cite.notification.service.channelResolution.ChannelResolutionService; -import gr.cite.notification.service.contact.extractor.ContactExtractorFactory; -import gr.cite.notification.service.contact.model.Contact; -import gr.cite.notification.service.message.builder.MessageBuilderFactory; -import gr.cite.notification.service.message.model.Message; -import gr.cite.notification.service.notify.NotifierFactory; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.deleter.DeleterFactory; -import gr.cite.tools.data.query.Ordering; -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.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Service; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -@Service -@RequestScope -public class NotificationServiceImpl implements NotificationService { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationServiceImpl.class)); - private final TenantEntityManager entityManager; - private final AuthorizationService authService; - private final DeleterFactory deleterFactory; - private final BuilderFactory builderFactory; - private final ConventionService conventionService; - private final ErrorThesaurusProperties errors; - private final MessageSource messageSource; - private final ChannelResolutionService channelResolutionService; - private final MessageBuilderFactory messageBuilderFactory; - private final ContactExtractorFactory contactExtractorFactory; - private final NotifierFactory notifierFactory; - private final ApplicationContext applicationContext; - private final QueryFactory queryFactory; - private final TenantScope tenantScope; - - @Autowired - public NotificationServiceImpl( - TenantEntityManager entityManager, - AuthorizationService authService, - DeleterFactory deleterFactory, - BuilderFactory builderFactory, - ConventionService conventionService, - ErrorThesaurusProperties errors, - MessageSource messageSource, - ChannelResolutionService channelResolutionService, MessageBuilderFactory messageBuilderFactory, ContactExtractorFactory contactExtractorFactory, NotifierFactory notifierFactory, ApplicationContext applicationContext, QueryFactory queryFactory, TenantScope tenantScope) { - this.entityManager = entityManager; - this.authService = authService; - this.deleterFactory = deleterFactory; - this.builderFactory = builderFactory; - this.conventionService = conventionService; - this.errors = errors; - this.messageSource = messageSource; - this.channelResolutionService = channelResolutionService; - this.messageBuilderFactory = messageBuilderFactory; - this.contactExtractorFactory = contactExtractorFactory; - this.notifierFactory = notifierFactory; - this.applicationContext = applicationContext; - this.queryFactory = queryFactory; - this.tenantScope = tenantScope; - } - - @Override - public Notification persist(NotificationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("persisting notification").And("model", model).And("fields", fields)); - -// this.authorizationService.authorizeForce(Permission.EditNotification); - - Boolean isUpdate = this.conventionService.isValidGuid(model.getId()); - - NotificationEntity data = null; - if (isUpdate) { - data = this.entityManager.find(NotificationEntity.class, model.getId()); - if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), Notification.class.getSimpleName()}, LocaleContextHolder.getLocale())); - if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); - } else { - data = new NotificationEntity(); - data.setId(UUID.randomUUID()); - data.setIsActive(IsActive.Active); - data.setCreatedAt(Instant.now()); - } - - data.setNotifiedAt(model.getNotifiedAt()); - data.setContactHint(model.getContactHint()); - data.setContactTypeHint(model.getContactTypeHint()); - data.setType(model.getType()); - data.setUserId(model.getUserId()); - data.setNotifyState(model.getNotifyState()); - data.setTrackingProcess(model.getTrackingProcess()); - data.setNotifiedWith(model.getNotifiedWith()); - data.setTrackingData(model.getTrackingData()); - data.setTrackingState(model.getTrackingState()); - data.setNotifiedAt(model.getNotifiedAt()); - data.setRetryCount(model.getRetryCount()); - data.setData(model.getData()); - data.setUpdatedAt(Instant.now()); - - if (isUpdate) this.entityManager.merge(data); - else this.entityManager.persist(data); - - this.entityManager.flush(); - - return this.builderFactory.builder(NotificationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(BaseFieldSet.build(fields, Notification._id, Notification._hash), data); - } - - public SendNotificationResult doNotify(NotificationEntity notification) { - List contactTypes = this.orderContactTypesFromPreferences(notification); - if (this.conventionService.isListNullOrEmpty(contactTypes)) contactTypes = this.orderContactTypes(notification); - if (contactTypes == null) return null; - - for (NotificationContactType contactType: contactTypes) { - SendNotificationResult result = this.sendNotification(notification, contactType); - if (result.getSuccess()) return result; - } - return null; - } - - private List orderContactTypesFromPreferences(NotificationEntity notification) { - if (notification.getUserId() == null) return null; - Ordering ordering = new Ordering(); - ordering.addAscending(UserNotificationPreference._ordinal); - UserNotificationPreferenceQuery query = this.queryFactory.query(UserNotificationPreferenceQuery.class).disableTracking().userId(notification.getUserId()).type(notification.getType()).isActives(IsActive.Active); - query.setOrder(ordering); - - List preferences = query.collectAs(new BaseFieldSet().ensure(UserNotificationPreference._channel).ensure(UserNotificationPreference._tenantId).ensure(UserNotificationPreference._id)); - if (!this.conventionService.isListNullOrEmpty(preferences)) return preferences.stream().filter(x -> { - try { - return !this.tenantScope.isMultitenant() || this.tenantScope.isDefaultTenant() ? x.getTenantId() == null : x.getTenantId() == this.tenantScope.getTenant(); - } catch (InvalidApplicationException e) { - throw new RuntimeException(e); - } - }).map(UserNotificationPreferenceEntity::getChannel).collect(Collectors.toList()); - return null; - } - - private List orderContactTypes(NotificationEntity notification) { - List contactTypes = notification.getUserId() == null ? this.channelResolutionService.resolve(notification.getType()): this.channelResolutionService.resolve(notification.getType(), notification.getUserId()); - if (notification.getContactTypeHint() == null) return contactTypes; - - List ordered = new ArrayList<>(Collections.singleton(notification.getContactTypeHint())); - for (NotificationContactType type: contactTypes) - { - if (type == notification.getContactTypeHint()) continue; - ordered.add(type); - } - - return ordered; - } - - private SendNotificationResult sendNotification(NotificationEntity notification, NotificationContactType contactType) { - String tracking = null; - try { - Message message = this.messageBuilderFactory.getFromType(contactType).buildMessage(notification); - if (message == null) { - return new SendNotificationResult(false, contactType); - } - Contact contact = contactExtractorFactory.fromContactType(contactType).extract(notification); - if (contact == null) { - return new SendNotificationResult(false, contactType); - } - TenantScope tenantScoped = applicationContext.getBean(TenantScope.class); - if (notification.getTenantId() != null){ - TenantEntity tenant = this.entityManager.find(TenantEntity.class, notification.getTenantId()); - tenantScoped.setTenant(tenant.getId(), tenant.getCode()); - } - - tracking = notifierFactory.fromContactType(contactType).notify(contact, message); - }catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - return new SendNotificationResult(false, contactType); - } - - return new SendNotificationResult(true, contactType, tracking); - } - - @Override - public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug("deleting notification: {}", id); - this.authService.authorizeForce(Permission.DeleteNotification); - this.deleterFactory.deleter(NotificationDeleter.class).deleteAndSaveByIds(List.of(id)); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingService.java deleted file mode 100644 index b1fc7e35f..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingService.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.notification.service.notificationscheduling; - -import gr.cite.notification.schedule.model.CandidateInfo; -import gr.cite.notification.schedule.model.MiniTenant; - -import java.time.Instant; -import java.util.List; -import java.util.UUID; - -public interface NotificationSchedulingService { - - CandidateInfo candidateToNotify(Instant lastCandidateNotificationCreationTimestamp); - Boolean shouldWait(CandidateInfo candidateInfo); - Boolean shouldOmitNotify(UUID notificationId); - Boolean notify(UUID notificationId); - - CandidateInfo candidateToTrack(Instant lastCandidateNotificationCreationTimestamp); - Boolean shouldOmitTracking(UUID notificationId); - Boolean track(UUID notificationId); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java deleted file mode 100644 index cf69bb785..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationscheduling/NotificationSchedulingServiceImpl.java +++ /dev/null @@ -1,419 +0,0 @@ -package gr.cite.notification.service.notificationscheduling; - -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationNotifyState; -import gr.cite.notification.common.enums.NotificationTrackingProcess; -import gr.cite.notification.common.enums.NotificationTrackingState; -import gr.cite.notification.common.scope.fake.FakeRequestScope; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.config.notification.NotificationProperties; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.model.SendNotificationResult; -import gr.cite.notification.query.NotificationQuery; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.schedule.model.CandidateInfo; -import gr.cite.notification.service.notification.NotificationService; -import gr.cite.notification.service.track.TrackingFactory; -import gr.cite.notification.service.track.model.TrackerResponse; -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.UUID; -import java.util.concurrent.ThreadLocalRandom; - -public class NotificationSchedulingServiceImpl implements NotificationSchedulingService { - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationSchedulingServiceImpl.class)); - private final ApplicationContext applicationContext; - private final NotificationProperties properties; - @PersistenceUnit - private EntityManagerFactory entityManagerFactory; - - public NotificationSchedulingServiceImpl(ApplicationContext applicationContext, NotificationProperties properties) { - this.applicationContext = applicationContext; - this.properties = properties; - } - - @Override - public CandidateInfo candidateToNotify(Instant lastCandidateNotificationCreationTimestamp) { - EntityTransaction transaction = null; - CandidateInfo candidateInfo = null; - try (FakeRequestScope fakeRequestScope = 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); - NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); - NotificationEntity candidates; - - notificationQuery = notificationQuery - .isActive(IsActive.Active) - .notifyState(NotificationNotifyState.PENDING, NotificationNotifyState.ERROR) - .retryThreshold(Math.toIntExact(this.properties.getTask().getProcessor().getOptions().getRetryThreshold())) - .createdAfter(lastCandidateNotificationCreationTimestamp) - .ordering(new Ordering().addAscending(NotificationEntity._createdAt)); - candidates = notificationQuery.first(); - if (candidates != null) { - NotificationNotifyState previousState = candidates.getNotifyState(); - candidates.setNotifyState(NotificationNotifyState.PROCESSING); - //candidates.setUpdatedAt(Instant.now()); - candidates = entityManager.merge(candidates); - entityManager.persist(candidates); - entityManager.flush(); - - candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt()); - } - transaction.commit(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (OptimisticLockException e) { - logger.error("Optimistic Lock Error occurred on Notification persist"); - if (transaction != null) transaction.rollback(); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - if (transaction != null) transaction.rollback(); - } - return candidateInfo; - } - - @Override - public Boolean shouldWait(CandidateInfo candidateInfo) { - EntityTransaction transaction = null; - boolean shouldWait = false; - try (FakeRequestScope fakeRequestScope = 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(); - NotificationEntity notification = entityManager.find(NotificationEntity.class, candidateInfo.getNotificationId()); - if (notification.getRetryCount() != null && notification.getRetryCount() >= 1) { - int accumulatedRetry = 0; - int pastAccumulateRetry = 0; - NotificationProperties.Task.Processor.Options options = properties.getTask().getProcessor().getOptions(); - for (int i = 1; i <= notification.getRetryCount() + 1; i += 1) - accumulatedRetry += (int) (i * options.getRetryThreshold()); - for (int i = 1; i <= notification.getRetryCount(); i += 1) - pastAccumulateRetry += (int) (i * options.getRetryThreshold()); - int randAccumulatedRetry = ThreadLocalRandom.current().nextInt(accumulatedRetry / 2, accumulatedRetry + 1); - long additionalTime = randAccumulatedRetry > options.getMaxRetryDelaySeconds() ? options.getMaxRetryDelaySeconds() : randAccumulatedRetry; - long retry = pastAccumulateRetry + additionalTime; - - Instant retryOn = notification.getCreatedAt().plusSeconds(retry); - boolean itIsTime = retryOn.isBefore(Instant.now()); - - if (!itIsTime) { - notification.setNotifyState(candidateInfo.getPreviousState()); - //notification.setUpdatedAt(Instant.now()); - - entityManager.merge(notification); - entityManager.flush(); - } - shouldWait = !itIsTime; - } - transaction.commit(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (OptimisticLockException e) { - logger.error("Optimistic Lock Error occurred on Notification persist"); - if (transaction != null) transaction.rollback(); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - if (transaction != null) transaction.rollback(); - } - return shouldWait; - } - - @Override - public Boolean shouldOmitNotify(UUID notificationId) { - EntityTransaction transaction = null; - boolean shouldOmit = false; - try (FakeRequestScope fakeRequestScope = 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(); - - NotificationEntity notification = entityManager.find(NotificationEntity.class, notificationId); - long age = Instant.now().getEpochSecond() - notification.getCreatedAt().getEpochSecond(); - long omitSeconds = properties.getTask().getProcessor().getOptions().getTooOldToSendSeconds(); - if (age >= omitSeconds) { - notification.setNotifyState(NotificationNotifyState.OMITTED); - //notification.setUpdatedAt(Instant.now()); - - notification = entityManager.merge(notification); - entityManager.persist(notification); - entityManager.flush(); - - shouldOmit = true; - } - transaction.commit(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (OptimisticLockException e) { - logger.error("Optimistic Lock Error occurred on Notification persist"); - if (transaction != null) transaction.rollback(); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - if (transaction != null) transaction.rollback(); - } - return shouldOmit; - - } - - @Override - public Boolean notify(UUID notificationId) { - boolean success; - NotificationEntity notification; - - try (FakeRequestScope fakeRequestScope = new FakeRequestScope()) { - - EntityTransaction transaction = null; - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - transaction.begin(); - - QueryFactory queryFactory = this.applicationContext.getBean(QueryFactory.class); - notification = queryFactory.query(NotificationQuery.class).ids(notificationId).first(); - if (notification == null) throw new IllegalArgumentException("notification is null"); - - TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); - - SendNotificationResult result; - try { - if (notification.getTenantId() != null) { - TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); - } else { - tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); - } - tenantEntityManager.reloadTenantFilters(); - - NotificationService notificationService = this.applicationContext.getBean(NotificationService.class); - result = notificationService.doNotify(notification); - - if (result != null && result.getSuccess()) { - notification.setNotifyState(NotificationNotifyState.SUCCESSFUL); - notification.setTrackingData(result.getTrackingData()); - notification.setNotifiedWith(result.getContactType()); - notification.setNotifiedAt(Instant.now()); - } else { - notification.setNotifyState(NotificationNotifyState.ERROR); - notification.setRetryCount(notification.getRetryCount() != null ? notification.getRetryCount() + 1 : 0); - notification.setNotifiedWith(null); - notification.setNotifiedAt(null); - } - //notification.setUpdatedAt(Instant.now()); - - NotificationEntity notification1 = entityManager.merge(notification); - entityManager.persist(notification1); - entityManager.flush(); - } finally { - tenantScope.removeTempTenant(tenantEntityManager); - tenantEntityManager.reloadTenantFilters(); - } - //we want to return false for notification we want to add in the skip bag - success = result != null && result.getSuccess(); - transaction.commit(); - } catch (OptimisticLockException e) { - logger.error("Optimistic Lock Error occurred on Notification persist"); - if (transaction != null) transaction.rollback(); - success = false; - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - if (transaction != null) transaction.rollback(); - success = false; - } - } - return success; - } - - @Override - public CandidateInfo candidateToTrack(Instant lastCandidateNotificationCreationTimestamp) { - EntityTransaction transaction = null; - CandidateInfo candidateInfo = null; - try (FakeRequestScope fakeRequestScope = 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(); - NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); - NotificationEntity candidates; - - notificationQuery = notificationQuery - .isActive(IsActive.Active) - .notifyState(NotificationNotifyState.SUCCESSFUL) - .notifiedWithHasValue() - .notifiedWithHasValue() - .createdAfter(lastCandidateNotificationCreationTimestamp) - .trackingState(NotificationTrackingState.QUEUED, NotificationTrackingState.SENT, NotificationTrackingState.UNDEFINED) - .trackingProgress(NotificationTrackingProcess.PENDING); - candidates = notificationQuery.first(); - if (candidates != null) { - NotificationNotifyState previousState = candidates.getNotifyState(); - candidates.setTrackingProcess(NotificationTrackingProcess.PROCESSING); - //candidates.setUpdatedAt(Instant.now()); - - candidates = entityManager.merge(candidates); - entityManager.persist(candidates); - entityManager.flush(); - - candidateInfo = new CandidateInfo(candidates.getId(), previousState, candidates.getCreatedAt()); - } - transaction.commit(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (OptimisticLockException e) { - logger.error("Optimistic Lock Error occurred on Notification persist"); - if (transaction != null) transaction.rollback(); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - if (transaction != null) transaction.rollback(); - } - return candidateInfo; - } - - @Override - public Boolean shouldOmitTracking(UUID notificationId) { - EntityTransaction transaction = null; - boolean shouldOmit = false; - try (FakeRequestScope fakeRequestScope = 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(); - - NotificationEntity notification = entityManager.find(NotificationEntity.class, notificationId); - long age = Instant.now().getEpochSecond() - notification.getNotifiedAt().getEpochSecond(); - long omitSeconds = properties.getTask().getProcessor().getOptions().getTooOldToTrackSeconds(); - if (age >= omitSeconds) { - notification.setTrackingProcess(NotificationTrackingProcess.OMITTED); - //notification.setUpdatedAt(Instant.now()); - - notification = entityManager.merge(notification); - entityManager.persist(notification); - entityManager.flush(); - - shouldOmit = true; - } - transaction.commit(); - } finally { - tenantEntityManager.reloadTenantFilters(); - } - } catch (OptimisticLockException e) { - logger.error("Optimistic Lock Error occurred on Notification persist"); - if (transaction != null) transaction.rollback(); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - if (transaction != null) transaction.rollback(); - } - return shouldOmit; - - } - - @Override - public Boolean track(UUID notificationId) { - EntityTransaction transaction = null; - Boolean success = null; - try (FakeRequestScope fakeRequestScope = 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); - NotificationQuery notificationQuery = queryFactory.query(NotificationQuery.class); - NotificationEntity notification = notificationQuery.ids(notificationId).first(); - if (notification == null) throw new IllegalArgumentException("notification is null"); - if (notification.getNotifiedWith() == null) throw new IllegalArgumentException("Notification's Notified With is null"); - if (notification.getNotifiedAt() == null) throw new IllegalArgumentException("Notification's Notified At is null"); - - TenantScope tenantScope = this.applicationContext.getBean(TenantScope.class); - TrackerResponse result = null; - try { - if (notification.getTenantId() != null) { - TenantEntity tenant = queryFactory.query(TenantQuery.class).ids(notification.getTenantId()).first(); - tenantScope.setTempTenant(tenantEntityManager, tenant.getId(), tenant.getCode()); - } else { - tenantScope.setTempTenant(tenantEntityManager, null, tenantScope.getDefaultTenantCode()); - } - tenantEntityManager.reloadTenantFilters(); - - try { - TrackingFactory trackingFactory = applicationContext.getBean(TrackingFactory.class); - result = trackingFactory.fromContactType(notification.getNotifiedWith()).track(notification); - } catch (Exception e) { - logger.error("Could not complete track for notification {}", notification.getId(), e); - } - - if (result != null && notification.getTrackingProcess().equals(result.getTrackingProgress()) && notification.getTrackingState().equals(result.getTrackingState())) { - return false; - } - - if (result != null) { - notification.setTrackingState(result.getTrackingState()); - notification.setTrackingProcess(result.getTrackingProgress()); - notification.setTrackingData(result.getTrackingData()); - } else { - notification.setTrackingProcess(NotificationTrackingProcess.ERROR); - } - //notification.setUpdatedAt(Instant.now()); - - NotificationEntity notification1 = entityManager.merge(notification); - entityManager.persist(notification1); - entityManager.flush(); - - //we want to return false for notification we want to add in the skip bag - success = result != null && !notification.getTrackingProcess().equals(NotificationTrackingProcess.ERROR); - transaction.commit(); - } finally { - tenantScope.removeTempTenant(tenantEntityManager); - tenantEntityManager.reloadTenantFilters(); - } - } - } catch (OptimisticLockException e) { - logger.error("Optimistic Lock Error occurred on Notification persist"); - if (transaction != null) transaction.rollback(); - } catch (Exception e) { - logger.error(e.getLocalizedMessage(), e); - if (transaction != null) transaction.rollback(); - } - return success; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationtemplate/NotificationServiceTemplateImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notificationtemplate/NotificationServiceTemplateImpl.java deleted file mode 100644 index ee2f2021e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationtemplate/NotificationServiceTemplateImpl.java +++ /dev/null @@ -1,236 +0,0 @@ -package gr.cite.notification.service.notificationtemplate; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationTemplateChannel; -import gr.cite.notification.common.enums.NotificationTemplateKind; -import gr.cite.notification.common.types.notification.FieldInfo; -import gr.cite.notification.common.types.notificationtemplate.FieldInfoEntity; -import gr.cite.notification.common.types.notificationtemplate.FieldOptionsEntity; -import gr.cite.notification.common.types.notificationtemplate.NotificationTemplateValueEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.NotificationTemplateEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.NotificationTemplate; -import gr.cite.notification.model.builder.NotificationTemplateBuilder; -import gr.cite.notification.model.deleter.NotificationTemplateDeleter; -import gr.cite.notification.model.notificationtemplate.FieldOptions; -import gr.cite.notification.model.notificationtemplate.NotificationTemplateValue; -import gr.cite.notification.model.persist.NotificationTemplatePersist; -import gr.cite.notification.model.persist.notificationtemplate.FieldInfoPersist; -import gr.cite.notification.model.persist.notificationtemplate.FieldOptionsPersist; -import gr.cite.notification.model.persist.notificationtemplate.NotificationTemplateValuePersist; -import gr.cite.notification.query.NotificationTemplateQuery; -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.jetbrains.annotations.NotNull; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Service; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -@Service -@RequestScope -public class NotificationServiceTemplateImpl implements NotificationTemplateService { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationServiceTemplateImpl.class)); - private final TenantEntityManager entityManager; - private final AuthorizationService authService; - private final AuthorizationService authorizationService; - private final DeleterFactory deleterFactory; - private final BuilderFactory builderFactory; - private final QueryFactory queryFactory; - private final ConventionService conventionService; - private final ErrorThesaurusProperties errors; - private final MessageSource messageSource; - private final JsonHandlingService jsonHandlingService; - - @Autowired - public NotificationServiceTemplateImpl( - TenantEntityManager entityManager, - AuthorizationService authService, AuthorizationService authorizationService, - DeleterFactory deleterFactory, - BuilderFactory builderFactory, - QueryFactory queryFactory, ConventionService conventionService, - ErrorThesaurusProperties errors, - MessageSource messageSource, - JsonHandlingService jsonHandlingService) { - this.entityManager = entityManager; - this.authService = authService; - this.authorizationService = authorizationService; - this.deleterFactory = deleterFactory; - this.builderFactory = builderFactory; - this.queryFactory = queryFactory; - this.conventionService = conventionService; - this.errors = errors; - this.messageSource = messageSource; - this.jsonHandlingService = jsonHandlingService; - } - - @Override - public NotificationTemplate persist(NotificationTemplatePersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { - logger.debug(new MapLogEntry("persisting notification template").And("model", model).And("fields", fields)); - - this.authorizationService.authorizeForce(Permission.EditNotificationTemplate); - - Boolean isUpdate = this.conventionService.isValidGuid(model.getId()); - - NotificationTemplateEntity data = null; - if (isUpdate) { - data = this.entityManager.find(NotificationTemplateEntity.class, model.getId()); - if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), NotificationTemplate.class.getSimpleName()}, LocaleContextHolder.getLocale())); - if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); - } else { - data = new NotificationTemplateEntity(); - data.setId(UUID.randomUUID()); - data.setIsActive(IsActive.Active); - data.setCreatedAt(Instant.now()); - } - - data.setNotificationType(model.getNotificationType()); - data.setChannel(model.getChannel()); - data.setKind(model.getKind()); - data.setLanguageCode(model.getLanguageCode()); - data.setValue(this.jsonHandlingService.toJsonSafe(this.buildNotificationTemplateValueEntity(model.getValue()))); - data.setUpdatedAt(Instant.now()); - - if (isUpdate) this.entityManager.merge(data); - else this.entityManager.persist(data); - - this.entityManager.flush(); - - return this.builderFactory.builder(NotificationTemplateBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(BaseFieldSet.build(fields, NotificationTemplate._id, NotificationTemplate._hash), data); - } - - private @NotNull NotificationTemplateValueEntity buildNotificationTemplateValueEntity(NotificationTemplateValuePersist persist) { - NotificationTemplateValueEntity data = new NotificationTemplateValueEntity(); - if (persist == null) return data; - - data.setSubjectText(persist.getSubjectText()); - data.setSubjectKey(persist.getSubjectKey()); - if (!this.conventionService.isListNullOrEmpty(List.of(persist.getSubjectFieldOptions()))) { - data.setSubjectFieldOptions(this.buildFieldOptionsEntity(persist.getSubjectFieldOptions())); - } - data.setBodyText(persist.getBodyText()); - data.setBodyKey(persist.getBodyKey()); - data.setPriorityKey(persist.getPriorityKey()); - data.setAllowAttachments(persist.getAllowAttachments()); - data.setCc(persist.getCc()); - data.setCcMode(persist.getCcMode()); - data.setBcc(persist.getBcc()); - data.setBccMode(persist.getBccMode()); - data.setExtraDataKeys(persist.getExtraDataKeys()); - if (!this.conventionService.isListNullOrEmpty(List.of(persist.getBodyFieldOptions()))) { - data.setBodyFieldOptions(this.buildFieldOptionsEntity(persist.getBodyFieldOptions())); - } - - return data; - } - - private @NotNull FieldOptionsEntity buildFieldOptionsEntity(FieldOptionsPersist persist) { - FieldOptionsEntity data = new FieldOptionsEntity(); - if (persist == null) return data; - - data.setMandatory(persist.getMandatory()); - if (!this.conventionService.isListNullOrEmpty(persist.getOptional())) { - data.setOptional(new ArrayList<>()); - for (FieldInfoPersist optionalPersist : persist.getOptional()) { - data.getOptional().add(this.buildFieldInfoEntity(optionalPersist)); - } - } - data.setFormatting(persist.getFormatting()); - - return data; - } - - private @NotNull FieldInfoEntity buildFieldInfoEntity(FieldInfoPersist persist) { - FieldInfoEntity data = new FieldInfoEntity(); - if (persist == null) return data; - - data.setKey(persist.getKey()); - data.setType(persist.getType()); - data.setValue(persist.getValue()); - - return data; - } - - @Override - public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug("deleting notification template: {}", id); - this.authService.authorizeForce(Permission.DeleteNotificationTemplate); - this.deleterFactory.deleter(NotificationTemplateDeleter.class).deleteAndSaveByIds(List.of(id)); - } - - @Override - public NotificationTemplate lookupOverriddenTemplates(UUID notificationType, NotificationTemplateChannel channel, String language) { - NotificationTemplateQuery query = this.queryFactory.query(NotificationTemplateQuery.class).disableTracking() - .notificationTypes(notificationType) - .channels(channel) - .languageCodes(language) - .kinds(NotificationTemplateKind.Primary) - .isActive(IsActive.Active); - - if (query.first() == null){ - return null; - } - FieldSet fieldSet = new BaseFieldSet( - NotificationTemplate._id, - NotificationTemplate._channel, - NotificationTemplate._notificationType, - NotificationTemplate._kind, - NotificationTemplate._languageCode, - - NotificationTemplate._value + "." + NotificationTemplateValue._subjectKey, - NotificationTemplate._value + "." + NotificationTemplateValue._subjectText, - NotificationTemplate._value + "." + NotificationTemplateValue._subjectFieldOptions, - NotificationTemplate._value + "." + NotificationTemplateValue._subjectFieldOptions + "." + FieldOptions._mandatory, - NotificationTemplate._value + "." + NotificationTemplateValue._subjectFieldOptions + "." + FieldOptions._optional + "." + FieldInfo._key, - NotificationTemplate._value + "." + NotificationTemplateValue._subjectFieldOptions + "." + FieldOptions._optional + "." +FieldInfo._type, - NotificationTemplate._value + "." + NotificationTemplateValue._subjectFieldOptions + "." + FieldOptions._optional + "." + FieldInfo._value, - NotificationTemplate._value + "." + NotificationTemplateValue._subjectFieldOptions + "." + FieldOptions._formatting, - NotificationTemplate._value + "." + NotificationTemplateValue._bodyKey, - NotificationTemplate._value + "." + NotificationTemplateValue._bodyText, - NotificationTemplate._value + "." + NotificationTemplateValue._bodyFieldOptions, - NotificationTemplate._value + "." + NotificationTemplateValue._bodyFieldOptions + "." + FieldOptions._mandatory, - NotificationTemplate._value + "." + NotificationTemplateValue._bodyFieldOptions + "." + FieldOptions._optional + "." + FieldInfo._key, - NotificationTemplate._value + "." + NotificationTemplateValue._bodyFieldOptions + "." + FieldOptions._optional + "." + FieldInfo._type, - NotificationTemplate._value + "." + NotificationTemplateValue._bodyFieldOptions + "." + FieldOptions._optional + "." + FieldInfo._value, - NotificationTemplate._value + "." + NotificationTemplateValue._bodyFieldOptions + "." + FieldOptions._formatting, - NotificationTemplate._value + "." + NotificationTemplateValue._priorityKey, - NotificationTemplate._value + "." + NotificationTemplateValue._allowAttachments, - NotificationTemplate._value + "." + NotificationTemplateValue._cc, - NotificationTemplate._value + "." + NotificationTemplateValue._ccMode, - NotificationTemplate._value + "." + NotificationTemplateValue._bcc, - NotificationTemplate._value + "." + NotificationTemplateValue._bccMode, - NotificationTemplate._value + "." + NotificationTemplateValue._extraDataKeys, - - NotificationTemplate._createdAt, - NotificationTemplate._updatedAt, - NotificationTemplate._hash, - NotificationTemplate._isActive - ); - return this.builderFactory.builder(NotificationTemplateBuilder.class).build(fieldSet, query.first()); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationtemplate/NotificationTemplateService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notificationtemplate/NotificationTemplateService.java deleted file mode 100644 index a64200aa7..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notificationtemplate/NotificationTemplateService.java +++ /dev/null @@ -1,21 +0,0 @@ -package gr.cite.notification.service.notificationtemplate; - -import gr.cite.notification.common.enums.NotificationTemplateChannel; -import gr.cite.notification.model.NotificationTemplate; -import gr.cite.notification.model.persist.NotificationTemplatePersist; -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 NotificationTemplateService { - - NotificationTemplate persist(NotificationTemplatePersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException; - void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; - NotificationTemplate lookupOverriddenTemplates(UUID notificationType, NotificationTemplateChannel channel, String language); - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailConfig.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailConfig.java deleted file mode 100644 index ccd8a9a0e..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package gr.cite.notification.service.notify; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties(EmailProperties.class) -public class EmailConfig { -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailNotifier.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailNotifier.java deleted file mode 100644 index f56e603fa..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailNotifier.java +++ /dev/null @@ -1,62 +0,0 @@ -package gr.cite.notification.service.notify; - -import gr.cite.notification.common.StringUtils; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.service.contact.model.Contact; -import gr.cite.notification.service.contact.model.EmailContact; -import gr.cite.notification.service.message.model.EmailMessage; -import gr.cite.notification.service.message.model.Message; -import gr.cite.tools.logging.LoggerService; -import jakarta.mail.MessagingException; -import jakarta.mail.internet.MimeMessage; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.mail.javamail.MimeMessageHelper; -import org.springframework.stereotype.Component; - -import static java.nio.charset.StandardCharsets.UTF_8; - -@Component -public class EmailNotifier implements Notify{ - private final static LoggerService logger = new LoggerService(LoggerFactory.getLogger(EmailNotifier.class)); - - private final JavaMailSender javaMailSender; - private final EmailProperties emailProperties; - - @Autowired - public EmailNotifier(JavaMailSender javaMailSender, EmailProperties emailProperties) { - this.javaMailSender = javaMailSender; - this.emailProperties = emailProperties; - } - - @Override - public String notify(Contact contact, Message message) { - EmailContact emailContact = (EmailContact) contact; - EmailMessage emailMessage = (EmailMessage) message; - - if (emailContact == null || emailContact.getEmails() == null || emailContact.getEmails().stream().allMatch(StringUtils::isNullOrEmpty)) throw new IllegalArgumentException("contact not provided"); - if (emailMessage == null) throw new IllegalArgumentException("message not provided"); - - try { - MimeMessage mailMessage = javaMailSender.createMimeMessage(); - MimeMessageHelper helper = new MimeMessageHelper(mailMessage, UTF_8.name()); - helper.setTo(emailContact.getEmails().toArray(new String[0])); - helper.setCc(emailContact.getCcEmails().toArray(new String[0])); - helper.setBcc(emailContact.getBccEmails().toArray(new String[0])); - helper.setSubject(emailMessage.getSubject()); - helper.setText(emailMessage.getBody(), true); - helper.setFrom(emailProperties.getAddress()); - javaMailSender.send(mailMessage); - } catch (MessagingException e) { - logger.error(e.getLocalizedMessage(), e); - throw new RuntimeException(e); - } - return null; - } - - @Override - public NotificationContactType supports() { - return NotificationContactType.EMAIL; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailProperties.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailProperties.java deleted file mode 100644 index ac24b2a99..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/EmailProperties.java +++ /dev/null @@ -1,17 +0,0 @@ -package gr.cite.notification.service.notify; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "email") -public class EmailProperties { - - private final String address; - - public EmailProperties(String address) { - this.address = address; - } - - public String getAddress() { - return address; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java deleted file mode 100644 index 3759c1a99..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/InAppNotifier.java +++ /dev/null @@ -1,101 +0,0 @@ -package gr.cite.notification.service.notify; - -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.enums.NotificationInAppTracking; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.types.notification.InAppTrackingData; -import gr.cite.notification.data.InAppNotificationEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.service.contact.model.Contact; -import gr.cite.notification.service.contact.model.InAppContact; -import gr.cite.notification.service.message.model.InAppMessage; -import gr.cite.notification.service.message.model.Message; -import gr.cite.tools.logging.LoggerService; -import jakarta.persistence.PersistenceUnit; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; - -import jakarta.persistence.EntityManager; -import jakarta.persistence.EntityManagerFactory; -import jakarta.persistence.EntityTransaction; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.UUID; - -@Component -public class InAppNotifier implements Notify{ - private final static LoggerService logger = new LoggerService(LoggerFactory.getLogger(InAppNotifier.class)); - - private final JsonHandlingService jsonHandlingService; - private final ApplicationContext applicationContext; - @PersistenceUnit - private EntityManagerFactory entityManagerFactory; - - @Autowired - public InAppNotifier(JsonHandlingService jsonHandlingService, ApplicationContext applicationContext) { - this.jsonHandlingService = jsonHandlingService; - this.applicationContext = applicationContext; - } - - @Override - public String notify(Contact contact, Message message) { - String data = null; - EntityTransaction transaction = null; - TenantEntityManager tenantEntityManager = this.applicationContext.getBean(TenantEntityManager.class); - try (EntityManager entityManager = this.entityManagerFactory.createEntityManager()) { - tenantEntityManager.setEntityManager(entityManager); - tenantEntityManager.disableTenantFilters(); - - transaction = entityManager.getTransaction(); - transaction.begin(); - InAppContact inAppContact = (InAppContact) contact; - if (inAppContact == null) throw new IllegalArgumentException("contact not provided"); - - InAppMessage inAppMessage = (InAppMessage) message; - if (inAppMessage == null) throw new IllegalArgumentException("message not provided"); - - TenantScope tenantScope = applicationContext.getBean(TenantScope.class); - InAppNotificationEntity inApp = new InAppNotificationEntity(); - - inApp.setId(UUID.randomUUID()); - inApp.setUserId(inAppContact.getUserId()); - inApp.setIsActive(IsActive.Active); - inApp.setType(inAppMessage.getType()); - inApp.setTrackingState(NotificationInAppTracking.STORED); - inApp.setPriority(inAppMessage.getPriority()); - inApp.setSubject(inAppMessage.getSubject()); - inApp.setBody(inAppMessage.getBody()); - inApp.setExtraData(inAppMessage.getExtraData() != null ? this.jsonHandlingService.toJsonSafe(inAppMessage.getExtraData()) : null); - inApp.setCreatedAt(Instant.now()); - inApp.setUpdatedAt(Instant.now()); - inApp.setTenantId(tenantScope.getTenant()); - - entityManager.persist(inApp); - entityManager.flush(); - - InAppTrackingData trackingData = new InAppTrackingData(inApp.getId()); - data = this.jsonHandlingService.toJsonSafe(trackingData); - transaction.commit(); - } catch (Exception e) { - if (transaction != null) transaction.rollback(); - logger.error(e.getMessage(), e); - } finally { - try { - tenantEntityManager.reloadTenantFilters(); - } catch (InvalidApplicationException e) { - logger.error(e.getMessage(), e); - } - } - return data; - } - - @Override - public NotificationContactType supports() { - return NotificationContactType.IN_APP; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java deleted file mode 100644 index 92a70d190..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/NotifierFactory.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.notification.service.notify; - -import gr.cite.notification.common.enums.NotificationContactType; -import org.springframework.stereotype.Component; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Component -public class NotifierFactory { - - private final Map notifyMap; - - public NotifierFactory(List notifies) { - this.notifyMap = notifies.stream().collect(Collectors.toMap(Notify::supports, notify -> notify)); - } - - public Notify fromContactType(NotificationContactType type) { - return this.notifyMap.getOrDefault(type, null); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/Notify.java b/notification-service/notification/src/main/java/gr/cite/notification/service/notify/Notify.java deleted file mode 100644 index b1b2082de..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/notify/Notify.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.notification.service.notify; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.service.contact.model.Contact; -import gr.cite.notification.service.message.model.Message; - -public interface Notify { - - String notify(Contact contact, Message message); - - NotificationContactType supports(); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/tenant/TenantService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/tenant/TenantService.java deleted file mode 100644 index 5e20f9f22..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/tenant/TenantService.java +++ /dev/null @@ -1,23 +0,0 @@ -package gr.cite.notification.service.tenant; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.User; -import gr.cite.notification.model.persist.TenantTouchedIntegrationEventPersist; -import gr.cite.notification.model.persist.UserTouchedIntegrationEventPersist; -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/notification-service/notification/src/main/java/gr/cite/notification/service/tenant/TenantServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/tenant/TenantServiceImpl.java deleted file mode 100644 index 7441361ae..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/tenant/TenantServiceImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -package gr.cite.notification.service.tenant; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.event.EventBroker; -import gr.cite.notification.event.TenantTouchedEvent; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.builder.TenantBuilder; -import gr.cite.notification.model.deleter.TenantDeleter; -import gr.cite.notification.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); - this.authorizationService.authorizeForce(Permission.DeleteTenant); - - 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.deleterFactory.deleter(TenantDeleter.class).deleteAndSaveByIds(List.of(id)); - - this.eventBroker.emit(new TenantTouchedEvent(data.getId(), data.getCode())); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/tenantconfiguration/TenantConfigurationService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/tenantconfiguration/TenantConfigurationService.java deleted file mode 100644 index b83d943e5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/tenantconfiguration/TenantConfigurationService.java +++ /dev/null @@ -1,38 +0,0 @@ -package gr.cite.notification.service.tenantconfiguration; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.types.tenantconfiguration.DefaultUserLocaleTenantConfigurationEntity; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.model.persist.tenantconfiguration.TenantConfigurationPersist; -import gr.cite.notification.model.tenantconfiguration.TenantConfiguration; -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.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.management.InvalidApplicationException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.Set; -import java.util.UUID; - -public interface TenantConfigurationService { - - TenantConfiguration persist(TenantConfigurationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException; - - void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; - - NotifierListTenantConfigurationEntity collectTenantNotifierList(); - DefaultUserLocaleTenantConfigurationEntity collectTenantUserLocale(); - - TenantConfigurationEntity getTenantConfigurationEntityForType(TenantConfigurationType type); - - NotifierListTenantConfigurationEntity collectTenantAvailableNotifierList(Set notificationTypes); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/tenantconfiguration/TenantConfigurationServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/tenantconfiguration/TenantConfigurationServiceImpl.java deleted file mode 100644 index 6916cc8fc..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/tenantconfiguration/TenantConfigurationServiceImpl.java +++ /dev/null @@ -1,238 +0,0 @@ -package gr.cite.notification.service.tenantconfiguration; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.enums.TenantConfigurationType; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.types.tenantconfiguration.DefaultUserLocaleTenantConfigurationEntity; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.TenantConfigurationEntity; -import gr.cite.notification.data.TenantEntity; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.event.EventBroker; -import gr.cite.notification.event.TenantConfigurationTouchedEvent; -import gr.cite.notification.model.builder.tenantconfiguration.TenantConfigurationBuilder; -import gr.cite.notification.model.deleter.TenantConfigurationDeleter; -import gr.cite.notification.model.persist.tenantconfiguration.DefaultUserLocaleTenantConfigurationPersist; -import gr.cite.notification.model.persist.tenantconfiguration.NotifierListTenantConfigurationPersist; -import gr.cite.notification.model.persist.tenantconfiguration.TenantConfigurationPersist; -import gr.cite.notification.model.tenantconfiguration.TenantConfiguration; -import gr.cite.notification.query.TenantConfigurationQuery; -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.jetbrains.annotations.NotNull; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.stereotype.Service; -import gr.cite.notification.authorization.AuthorizationFlags; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.management.InvalidApplicationException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; - -@Service -public class TenantConfigurationServiceImpl implements TenantConfigurationService { - - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(TenantConfigurationServiceImpl.class)); - - private final TenantEntityManager entityManager; - - private final AuthorizationService authorizationService; - - private final DeleterFactory deleterFactory; - - private final BuilderFactory builderFactory; - - private final ConventionService conventionService; - - private final ErrorThesaurusProperties errors; - - private final MessageSource messageSource; - - private final JsonHandlingService jsonHandlingService; - - private final QueryFactory queryFactory; - private final EventBroker eventBroker; - private final TenantScope tenantScope; - private final Map> globalPoliciesMap; - @Autowired - public TenantConfigurationServiceImpl( - TenantEntityManager entityManager, - AuthorizationService authorizationService, - DeleterFactory deleterFactory, - BuilderFactory builderFactory, - ConventionService conventionService, - ErrorThesaurusProperties errors, - MessageSource messageSource, JsonHandlingService jsonHandlingService, QueryFactory queryFactory, EventBroker eventBroker, TenantScope tenantScope, Map> globalPoliciesMap) { - this.entityManager = entityManager; - this.authorizationService = authorizationService; - this.deleterFactory = deleterFactory; - this.builderFactory = builderFactory; - this.conventionService = conventionService; - this.errors = errors; - this.messageSource = messageSource; - this.jsonHandlingService = jsonHandlingService; - this.queryFactory = queryFactory; - this.eventBroker = eventBroker; - this.tenantScope = tenantScope; - this.globalPoliciesMap = globalPoliciesMap; - } - - public TenantConfiguration persist(TenantConfigurationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException { - logger.debug(new MapLogEntry("persisting data TenantConfiguration").And("model", model).And("fields", fields)); - - this.authorizationService.authorizeForce(Permission.EditTenantConfiguration); - - Boolean isUpdate = this.conventionService.isValidGuid(model.getId()); - - TenantConfigurationEntity data; - if (isUpdate) { - data = this.entityManager.find(TenantConfigurationEntity.class, model.getId()); - if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), TenantConfiguration.class.getSimpleName()}, LocaleContextHolder.getLocale())); - if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); - if (!data.getType().equals(model.getType())) throw new MyValidationException(this.errors.getTenantConfigurationTypeCanNotChange().getCode(), this.errors.getTenantConfigurationTypeCanNotChange().getMessage()); - } else { - data = new TenantConfigurationEntity(); - data.setId(UUID.randomUUID()); - data.setIsActive(IsActive.Active); - data.setCreatedAt(Instant.now()); - data.setType(model.getType()); - } - - TenantConfigurationQuery tenantConfigurationQuery = this.queryFactory.query(TenantConfigurationQuery.class).excludedIds(data.getId()).isActive(IsActive.Active).types(data.getType()); - if (data.getTenantId() == null) tenantConfigurationQuery.tenantIsSet(false); - else tenantConfigurationQuery.tenantIsSet(true).tenantIds(data.getTenantId()); - if (tenantConfigurationQuery.count() > 0)throw new MyValidationException(this.errors.getMultipleTenantConfigurationTypeNotAllowed().getCode(), this.errors.getMultipleTenantConfigurationTypeNotAllowed().getMessage()); - - switch (data.getType()){ - case NotifierList -> data.setValue(this.jsonHandlingService.toJson(this.buildNotifierListTenantConfigurationEntity(model.getNotifierList()))); - case DefaultUserLocale -> data.setValue(this.jsonHandlingService.toJson(this.buildDefaultUserLocaleTenantConfigurationEntity(model.getDefaultUserLocale()))); - default -> throw new InternalError("unknown type: " + data.getType()); - } - data.setUpdatedAt(Instant.now()); - if (isUpdate) - this.entityManager.merge(data); - else - this.entityManager.persist(data); - - this.entityManager.flush(); - - if (data.getTenantId() != null) { - TenantEntity tenant = this.entityManager.find(TenantEntity.class, data.getTenantId()); - if (tenant == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{data.getTenantId(), TenantEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); - this.eventBroker.emit(new TenantConfigurationTouchedEvent(tenant.getId(), tenant.getCode(), data.getType())); - } else { - this.eventBroker.emit(new TenantConfigurationTouchedEvent(data.getId(), this.tenantScope.getDefaultTenantCode(), data.getType())); - } - - return this.builderFactory.builder(TenantConfigurationBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(BaseFieldSet.build(fields, TenantConfiguration._id), data); - } - - private @NotNull DefaultUserLocaleTenantConfigurationEntity buildDefaultUserLocaleTenantConfigurationEntity(DefaultUserLocaleTenantConfigurationPersist persist){ - DefaultUserLocaleTenantConfigurationEntity data = new DefaultUserLocaleTenantConfigurationEntity(); - if (persist == null) return data; - data.setCulture(persist.getCulture()); - data.setLanguage(persist.getLanguage()); - data.setTimezone(persist.getTimezone()); - return data; - } - - private @NotNull NotifierListTenantConfigurationEntity buildNotifierListTenantConfigurationEntity(NotifierListTenantConfigurationPersist persist){ - NotifierListTenantConfigurationEntity data = new NotifierListTenantConfigurationEntity(); - if (persist == null) return data; - data.setNotifiers(persist.getNotifiers()); - return data; - } - - - public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException { - logger.debug("deleting dataset: {}", id); - - this.authorizationService.authorizeForce(Permission.DeleteTenantConfiguration); - - TenantConfigurationEntity data = this.entityManager.find(TenantConfigurationEntity.class, id); - if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{id, TenantConfiguration.class.getSimpleName()}, LocaleContextHolder.getLocale())); - - this.deleterFactory.deleter(TenantConfigurationDeleter.class).deleteAndSaveByIds(List.of(id)); - - if (data.getTenantId() != null) { - TenantEntity tenant = this.entityManager.find(TenantEntity.class, data.getTenantId()); - if (tenant == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{data.getTenantId(), TenantEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); - this.eventBroker.emit(new TenantConfigurationTouchedEvent(tenant.getId(), tenant.getCode(), data.getType())); - } else { - this.eventBroker.emit(new TenantConfigurationTouchedEvent(data.getId(), this.tenantScope.getDefaultTenantCode(), data.getType())); - } - } - - @Override - public NotifierListTenantConfigurationEntity collectTenantNotifierList() { - TenantConfigurationEntity data = this.getTenantConfigurationEntityForType(TenantConfigurationType.NotifierList); - if (data == null || this.conventionService.isNullOrEmpty(data.getValue())) return null; - return this.jsonHandlingService.fromJsonSafe(NotifierListTenantConfigurationEntity.class, data.getValue()); - } - - @Override - public DefaultUserLocaleTenantConfigurationEntity collectTenantUserLocale() { - TenantConfigurationEntity data = this.getTenantConfigurationEntityForType(TenantConfigurationType.DefaultUserLocale); - if (data == null || this.conventionService.isNullOrEmpty(data.getValue())) return null; - return this.jsonHandlingService.fromJsonSafe(DefaultUserLocaleTenantConfigurationEntity.class, data.getValue()); - } - - @Override - public TenantConfigurationEntity getTenantConfigurationEntityForType(TenantConfigurationType type){ - TenantConfigurationQuery query = this.queryFactory.query(TenantConfigurationQuery.class).disableTracking().authorize(AuthorizationFlags.OwnerOrPermission).isActive(IsActive.Active).types(type); - if (this.tenantScope.isDefaultTenant()) query.tenantIsSet(false); - else { - try { - query.tenantIsSet(true).tenantIds(this.tenantScope.getTenant()); - } catch (InvalidApplicationException e) { - throw new RuntimeException(e); - } - } - - return query.first(); - } - - @Override - public NotifierListTenantConfigurationEntity collectTenantAvailableNotifierList(Set notificationTypes) { - this.authorizationService.authorizeForce(Permission.BrowseTenantConfiguration); - Map> currentNotificationListPolicies = this.globalPoliciesMap; - - if (notificationTypes != null && !notificationTypes.isEmpty()) - { - return new NotifierListTenantConfigurationEntity(currentNotificationListPolicies - .entrySet().stream() - .filter(x -> notificationTypes.contains(x.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); - } - else return new NotifierListTenantConfigurationEntity(currentNotificationListPolicies); - } - -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java deleted file mode 100644 index 4608c0092..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/EmailTracker.java +++ /dev/null @@ -1,32 +0,0 @@ -package gr.cite.notification.service.track; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.enums.NotificationTrackingProcess; -import gr.cite.notification.common.enums.NotificationTrackingState; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.service.track.model.TrackerResponse; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class EmailTracker implements Track { - private final static LoggerService logger = new LoggerService(LoggerFactory.getLogger(EmailTracker.class)); - - @Override - public TrackerResponse track(NotificationEntity notification) { -// if (notification.getTrackingProgress() != NotificationTrackingProgress.PROCESSING) - if(1==1) - { - logger.warn("notification " + notification.getId() + " was send for tracking but it is not locked for processing"); - return null; - } - - return new TrackerResponse(NotificationTrackingState.NA, NotificationTrackingProcess.COMPLETED, null); - } - - @Override - public NotificationContactType supports() { - return NotificationContactType.EMAIL; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/InAppTracker.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/InAppTracker.java deleted file mode 100644 index 85431023a..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/InAppTracker.java +++ /dev/null @@ -1,115 +0,0 @@ -package gr.cite.notification.service.track; - -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.*; -import gr.cite.notification.common.types.notification.InAppTrackingData; -import gr.cite.notification.common.types.notification.TrackingTrace; -import gr.cite.notification.data.InAppNotificationEntity; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.query.InAppNotificationQuery; -import gr.cite.notification.service.track.model.TrackerResponse; -import gr.cite.notification.service.track.model.TrackingTraceData; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.logging.LoggerService; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - -@Component -public class InAppTracker implements Track{ - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(InAppTracker.class)); - - private final JsonHandlingService jsonHandlingService; - private final QueryFactory queryFactory; - - @Autowired - public InAppTracker(JsonHandlingService jsonHandlingService, QueryFactory queryFactory) { - this.jsonHandlingService = jsonHandlingService; - this.queryFactory = queryFactory; - } - - @Override - public TrackerResponse track(NotificationEntity notification) { -// if (notification.getTrackingProgress() != NotificationTrackingProgress.PROCESSING) - if (1==1) - { - logger.warn("notification " + notification.getId() + " was send for tracking but it is not locked for processing"); - return null; - } - -// InAppTrackingData data = this.jsonHandlingService.fromJsonSafe(InAppTrackingData.class, notification.getTrackingData()); - InAppTrackingData data = null; - if (data == null) - { - logger.warn("could not find tracking info in notification " + notification.getId()); - return null; - } - - InAppNotificationEntity inApp = this.queryFactory.query(InAppNotificationQuery.class) - .ids(data.getInAppNotificationId()).first(); - - NotificationTrackingProcess completed = NotificationTrackingProcess.PENDING; - NotificationTrackingState state = this.evaluateState(inApp); - switch (state) - { - case DELIVERED: - case UNDELIVERED: - case FAILED: - case UNSENT: { completed = NotificationTrackingProcess.COMPLETED; break; } - case QUEUED: - case SENT: { completed = NotificationTrackingProcess.PENDING; break; } - //Something went wrong - case NA: - case UNDEFINED: - default: { completed = NotificationTrackingProcess.ERROR; break; } - } - - TrackingTraceData traceData = new TrackingTraceData (inApp.getTrackingState().toString(), inApp.getReadTime(), inApp.getIsActive() == IsActive.Active); - List traces = data.getTraces() != null ? data.getTraces() : new ArrayList<>(); - TrackingTrace lastTrace = traces.stream().max(Comparator.comparing(TrackingTrace::getAt)).orElse(null); - - Boolean hasTrackingChanges = false; - if (lastTrace != null) - { - TrackingTraceData lastTrackingTraceData = this.jsonHandlingService.fromJsonSafe(TrackingTraceData.class, lastTrace.getData()); - hasTrackingChanges = lastTrackingTraceData == null || !lastTrackingTraceData.equals(traceData); - } - else - { - hasTrackingChanges = true; - } - - if (hasTrackingChanges) - { - traces.add(new TrackingTrace(Instant.now(), this.jsonHandlingService.toJsonSafe(traceData))); - } - InAppTrackingData newData = new InAppTrackingData(data.getInAppNotificationId(), traces); - - TrackerResponse trackerResponse = new TrackerResponse(state, completed, this.jsonHandlingService.toJsonSafe(newData)); - - return trackerResponse; - } - - private NotificationTrackingState evaluateState(InAppNotificationEntity notification) - { - if (notification == null) return NotificationTrackingState.FAILED; - if (notification.getIsActive() == IsActive.Inactive && notification.getTrackingState() == NotificationInAppTracking.STORED) return NotificationTrackingState.UNDELIVERED; - - switch (notification.getTrackingState()) - { - case DELIVERED: return NotificationTrackingState.DELIVERED; - case STORED: return NotificationTrackingState.SENT; - default: return NotificationTrackingState.UNDELIVERED; - } - } - - @Override - public NotificationContactType supports() { - return NotificationContactType.IN_APP; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/Track.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/Track.java deleted file mode 100644 index 9231168f5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/Track.java +++ /dev/null @@ -1,12 +0,0 @@ -package gr.cite.notification.service.track; - -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.data.NotificationEntity; -import gr.cite.notification.service.track.model.TrackerResponse; - -public interface Track { - - TrackerResponse track(NotificationEntity notification); - - NotificationContactType supports(); -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java deleted file mode 100644 index 13cfa4577..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/TrackingFactory.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.notification.service.track; - -import gr.cite.notification.common.enums.NotificationContactType; -import org.springframework.stereotype.Component; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Component -public class TrackingFactory { - - private final Map trackMap; - - public TrackingFactory(List notifies) { - this.trackMap = notifies.stream().collect(Collectors.toMap(Track::supports, track -> track)); - } - - public Track fromContactType(NotificationContactType type) { - return this.trackMap.getOrDefault(type, null); - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/model/TrackerResponse.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/model/TrackerResponse.java deleted file mode 100644 index d289d36f5..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/model/TrackerResponse.java +++ /dev/null @@ -1,43 +0,0 @@ -package gr.cite.notification.service.track.model; - -import gr.cite.notification.common.enums.NotificationTrackingProcess; -import gr.cite.notification.common.enums.NotificationTrackingState; - -public class TrackerResponse { - private NotificationTrackingState trackingState; - private NotificationTrackingProcess trackingProgress; - private String trackingData; - - public TrackerResponse() { - } - - public TrackerResponse(NotificationTrackingState trackingState, NotificationTrackingProcess trackingProgress, String trackingData) { - this.trackingState = trackingState; - this.trackingProgress = trackingProgress; - this.trackingData = trackingData; - } - - public NotificationTrackingState getTrackingState() { - return trackingState; - } - - public void setTrackingState(NotificationTrackingState trackingState) { - this.trackingState = trackingState; - } - - public NotificationTrackingProcess getTrackingProgress() { - return trackingProgress; - } - - public void setTrackingProgress(NotificationTrackingProcess trackingProgress) { - this.trackingProgress = trackingProgress; - } - - public String getTrackingData() { - return trackingData; - } - - public void setTrackingData(String trackingData) { - this.trackingData = trackingData; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/track/model/TrackingTraceData.java b/notification-service/notification/src/main/java/gr/cite/notification/service/track/model/TrackingTraceData.java deleted file mode 100644 index 4da338e23..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/track/model/TrackingTraceData.java +++ /dev/null @@ -1,62 +0,0 @@ -package gr.cite.notification.service.track.model; - -import java.time.Instant; - -public class TrackingTraceData { - private String state; - private Instant readTime; - private Boolean isActive; - - public TrackingTraceData() { - } - - public TrackingTraceData(String state, Instant readTime, Boolean isActive) { - this.state = state; - this.readTime = readTime; - this.isActive = isActive; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public Instant getReadTime() { - return readTime; - } - - public void setReadTime(Instant readTime) { - this.readTime = readTime; - } - - public Boolean getActive() { - return isActive; - } - - public void setActive(Boolean active) { - isActive = active; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - TrackingTraceData that = (TrackingTraceData) o; - - if (!state.equals(that.state)) return false; - if (!readTime.equals(that.readTime)) return false; - return isActive.equals(that.isActive); - } - - @Override - public int hashCode() { - int result = state.hashCode(); - result = 31 * result + readTime.hashCode(); - result = 31 * result + isActive.hashCode(); - return result; - } -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserService.java deleted file mode 100644 index d08b9cfab..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserService.java +++ /dev/null @@ -1,22 +0,0 @@ -package gr.cite.notification.service.user; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.notification.integrationevent.inbox.usertouched.UserTouchedIntegrationEvent; -import gr.cite.notification.model.User; -import gr.cite.notification.model.persist.UserTouchedIntegrationEventPersist; -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/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java deleted file mode 100644 index 4c5a78b91..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java +++ /dev/null @@ -1,259 +0,0 @@ -package gr.cite.notification.service.user; - -import com.fasterxml.jackson.core.JsonProcessingException; -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.AuthorizationFlags; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.JsonHandlingService; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.types.user.AdditionalInfoEntity; -import gr.cite.notification.convention.ConventionService; -import gr.cite.notification.data.*; -import gr.cite.notification.event.EventBroker; -import gr.cite.notification.event.UserAddedToTenantEvent; -import gr.cite.notification.event.UserCredentialTouchedEvent; -import gr.cite.notification.event.UserTouchedEvent; -import gr.cite.notification.integrationevent.inbox.usertouched.UserTouchedIntegrationEvent; -import gr.cite.notification.model.Tenant; -import gr.cite.notification.model.User; -import gr.cite.notification.model.builder.UserBuilder; -import gr.cite.notification.model.deleter.TenantUserDeleter; -import gr.cite.notification.model.deleter.UserContactInfoDeleter; -import gr.cite.notification.model.deleter.UserCredentialDeleter; -import gr.cite.notification.model.deleter.UserDeleter; -import gr.cite.notification.query.TenantQuery; -import gr.cite.notification.query.TenantUserQuery; -import gr.cite.notification.query.UserContactInfoQuery; -import gr.cite.notification.query.UserCredentialQuery; -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.jetbrains.annotations.NotNull; -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.*; -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.authorize(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(this.buildAdditionalInfoEntity(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(this.buildAdditionalInfoEntity(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.persistContactInfo(model.getUserContactInfo(), data.getId()); - 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); - } - - private @NotNull AdditionalInfoEntity buildAdditionalInfoEntity(UserTouchedIntegrationEvent.UserProfile persist){ - AdditionalInfoEntity data = new AdditionalInfoEntity(); - if (persist == null) return data; - data.setCulture(persist.getCulture()); - data.setTimezone(persist.getTimezone()); - data.setLanguage(persist.getLanguage()); - return 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 persistContactInfo(List models, UUID userId) throws InvalidApplicationException { - List items = this.queryFactory.query(UserContactInfoQuery.class) - .userIds(userId) - .collect(); - List updatedCreatedIds = new ArrayList<>(); - if (models != null) { - for (UserTouchedIntegrationEvent.UserContactInfo model : models) { - UserContactInfoEntity data = items.stream().filter(x -> x.getType().equals(model.getType()) && x.getValue().equals(model.getValue())).findFirst().orElse(null); - if (data == null) { - data = new UserContactInfoEntity(); - data.setId(UUID.randomUUID()); - data.setUserId(userId); - data.setType(model.getType()); - data.setValue(model.getValue()); - data.setOrdinal(model.getOrdinal()); - data.setCreatedAt(Instant.now()); - data.setUpdatedAt(Instant.now()); - data.setIsActive(IsActive.Active); - entityManager.persist(data); - } else { - data.setOrdinal(model.getOrdinal()); - entityManager.merge(data); - } - updatedCreatedIds.add(data.getId()); - } - } - List toDelete = items.stream().filter(x -> updatedCreatedIds.stream().noneMatch(y -> y.equals(x.getId()))).collect(Collectors.toList()); - deleterFactory.deleter(UserContactInfoDeleter.class).delete(toDelete); - - entityManager.flush(); - } - - private void persistUserCredential(List models, UUID userId) throws InvalidApplicationException { - List items = this.queryFactory.query(UserCredentialQuery.class) - .userIds(userId) - .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(); - } - -} \ No newline at end of file diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/userNotificationPreference/UserNotificationPreferenceService.java b/notification-service/notification/src/main/java/gr/cite/notification/service/userNotificationPreference/UserNotificationPreferenceService.java deleted file mode 100644 index c76f00716..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/userNotificationPreference/UserNotificationPreferenceService.java +++ /dev/null @@ -1,20 +0,0 @@ -package gr.cite.notification.service.userNotificationPreference; - -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.model.UserNotificationPreference; -import gr.cite.notification.model.persist.UserNotificationPreferencePersist; -import gr.cite.tools.fieldset.FieldSet; - -import javax.management.InvalidApplicationException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -public interface UserNotificationPreferenceService { - - List persist(UserNotificationPreferencePersist model, FieldSet fieldSet); - NotifierListTenantConfigurationEntity collectUserAvailableNotifierList(Set notificationTypes); - List collectUserNotificationPreferences(UUID id) throws InvalidApplicationException; - Map> collectUserNotificationPreferences(List ids) throws InvalidApplicationException; -} diff --git a/notification-service/notification/src/main/java/gr/cite/notification/service/userNotificationPreference/UserNotificationPreferenceServiceImpl.java b/notification-service/notification/src/main/java/gr/cite/notification/service/userNotificationPreference/UserNotificationPreferenceServiceImpl.java deleted file mode 100644 index b6418da0c..000000000 --- a/notification-service/notification/src/main/java/gr/cite/notification/service/userNotificationPreference/UserNotificationPreferenceServiceImpl.java +++ /dev/null @@ -1,232 +0,0 @@ -package gr.cite.notification.service.userNotificationPreference; - -import gr.cite.commons.web.authz.service.AuthorizationService; -import gr.cite.notification.authorization.OwnedResource; -import gr.cite.notification.authorization.Permission; -import gr.cite.notification.common.enums.IsActive; -import gr.cite.notification.common.enums.NotificationContactType; -import gr.cite.notification.common.scope.tenant.TenantScope; -import gr.cite.notification.common.types.tenantconfiguration.NotifierListTenantConfigurationEntity; -import gr.cite.notification.config.notification.NotificationConfig; -import gr.cite.notification.data.TenantEntityManager; -import gr.cite.notification.data.UserNotificationPreferenceEntity; -import gr.cite.notification.errorcode.ErrorThesaurusProperties; -import gr.cite.notification.model.UserNotificationPreference; -import gr.cite.notification.model.builder.UserNotificationPreferenceBuilder; -import gr.cite.notification.model.persist.UserNotificationPreferencePersist; -import gr.cite.notification.query.UserNotificationPreferenceQuery; -import gr.cite.notification.service.tenantconfiguration.TenantConfigurationService; -import gr.cite.tools.data.builder.BuilderFactory; -import gr.cite.tools.data.query.QueryFactory; -import gr.cite.tools.exception.MyApplicationException; -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.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; -import org.springframework.web.context.annotation.RequestScope; - -import javax.management.InvalidApplicationException; -import java.time.Instant; -import java.util.*; -import java.util.stream.Collectors; - -@Service -@RequestScope -public class UserNotificationPreferenceServiceImpl implements UserNotificationPreferenceService{ - private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserNotificationPreferenceServiceImpl.class)); - - private final QueryFactory queryFactory; - private final BuilderFactory builderFactory; - private final AuthorizationService authService; - private final TenantConfigurationService tenantConfigurationService; - private final Map> globalPoliciesMap; - private final ErrorThesaurusProperties errors; - private final TenantEntityManager entityManager; - private final TenantScope tenantScope; - - @Autowired - public UserNotificationPreferenceServiceImpl(QueryFactory queryFactory, - BuilderFactory builderFactory, - AuthorizationService authService, - TenantConfigurationService tenantConfigurationService, - @Qualifier(NotificationConfig.BeanQualifier.GLOBAL_POLICIES_MAP) - Map> globalPoliciesMap, - ErrorThesaurusProperties errors, TenantEntityManager entityManager, TenantScope tenantScope) { - this.queryFactory = queryFactory; - this.builderFactory = builderFactory; - this.authService = authService; - this.tenantConfigurationService = tenantConfigurationService; - this.globalPoliciesMap = globalPoliciesMap; - this.errors = errors; - this.entityManager = entityManager; - this.tenantScope = tenantScope; - } - - @Override - public List persist(UserNotificationPreferencePersist model, FieldSet fieldSet) { - logger.debug(new MapLogEntry("persisting").And("model", model).And("fields", fieldSet)); - - this.authService.authorizeAtLeastOneForce(model.getUserId() != null ? List.of(new OwnedResource(model.getUserId())) : null, Permission.EditUserNotificationPreference); - - Map> currentNotificationListPolicies; - NotifierListTenantConfigurationEntity tenantNotifierListPolicies = this.tenantConfigurationService.collectTenantNotifierList(); - if (tenantNotifierListPolicies != null) - { - currentNotificationListPolicies = mergeNotifierPolicies(tenantNotifierListPolicies.getNotifiers(), this.globalPoliciesMap); - } - else - { - currentNotificationListPolicies = this.globalPoliciesMap; - } - - if (model.getNotificationPreferences().entrySet().stream().anyMatch(entry -> model.getNotificationPreferences().get(entry.getKey()).stream().anyMatch(contactType -> !currentNotificationListPolicies.get(entry.getKey()).contains(contactType)))) - { - throw new MyValidationException(this.errors.getOverlappingTenantConfigurationNotifierList().getCode(), this.errors.getOverlappingTenantConfigurationNotifierList().getMessage()); - } - - List datas = this.patchAndSave(List.of(model)); - return this.builderFactory.builder(UserNotificationPreferenceBuilder.class).build(fieldSet, datas); - } - - @Override - public NotifierListTenantConfigurationEntity collectUserAvailableNotifierList(Set notificationTypes) { - Map> currentNotificationListPolicies; - NotifierListTenantConfigurationEntity tenantNotifierListPolicies = this.tenantConfigurationService.collectTenantNotifierList(); - if (tenantNotifierListPolicies != null) - { - currentNotificationListPolicies = mergeNotifierPolicies(tenantNotifierListPolicies.getNotifiers(), this.globalPoliciesMap); - } - else - { - currentNotificationListPolicies = this.globalPoliciesMap; - } - - if (notificationTypes != null && !notificationTypes.isEmpty()) - { - return new NotifierListTenantConfigurationEntity(currentNotificationListPolicies - .entrySet().stream() - .filter(x -> notificationTypes.contains(x.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); - } - else return new NotifierListTenantConfigurationEntity(currentNotificationListPolicies); - } - - @Override - public List collectUserNotificationPreferences(UUID id) throws InvalidApplicationException { - Map> result = this.collectUserNotificationPreferences(List.of(id)); - if (result != null) { - return result.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); - } - logger.error("failed to collect user notification preferences for user " + id); - return new ArrayList<>(); - } - - @Override - public Map> collectUserNotificationPreferences(List ids) throws InvalidApplicationException { - UserNotificationPreferenceQuery query = this.queryFactory - .query(UserNotificationPreferenceQuery.class) - .userId(ids); - if (this.tenantScope.isMultitenant() && this.tenantScope.isSet()) { - if (!this.tenantScope.isDefaultTenant()) { - query.tenantIsSet(true).tenantIds(this.tenantScope.getTenant()); - } else { - query.tenantIsSet(false); - } - } - return this.builderFactory.builder(UserNotificationPreferenceBuilder.class) - .build(new BaseFieldSet(UserNotificationPreference._userId, UserNotificationPreference._type, - UserNotificationPreference._channel, UserNotificationPreference._ordinal, UserNotificationPreference._tenantId, UserNotificationPreference._id), query.collect()).stream() - .collect(Collectors.groupingBy(UserNotificationPreference::getUserId)); //GK: Yep that exist on JAVA Streams - } - - private Map> mergeNotifierPolicies(Map> overrides, Map> bases) - { - Map> mergedPolicies = new HashMap<>(); - for(Map.Entry> policyEntry: bases.entrySet()) - { - if (overrides.containsKey(policyEntry.getKey())) - { - List notifierList = overrides.get(policyEntry.getKey()); - if(notifierList == null) throw new MyApplicationException(this.errors.getSystemError().getCode(), this.errors.getSystemError().getMessage()); - mergedPolicies.put(policyEntry.getKey(), notifierList); - } - else - { - mergedPolicies.put(policyEntry.getKey(), policyEntry.getValue()); - } - } - return mergedPolicies; - } - - private List patchAndSave(List models) - { - List datas = new ArrayList<>(); - for (UserNotificationPreferencePersist model: models) - { - for (Map.Entry> notificationPreference: model.getNotificationPreferences().entrySet()) - { - this.patchAndSave(model.getUserId(), notificationPreference.getKey(), notificationPreference.getValue()); - } - } - return datas; - } - - private List patchAndSave(UUID userId, UUID type, List contactTypes) - { - List preferences = null; - try { - UserNotificationPreferenceQuery query = this.queryFactory - .query(UserNotificationPreferenceQuery.class) - .type(type) - .isActives(IsActive.Active) - .userId(userId); - if (this.tenantScope.isMultitenant() && this.tenantScope.isSet()) { - if (!this.tenantScope.isDefaultTenant()) { - query.tenantIsSet(true).tenantIds(this.tenantScope.getTenant()); - } else { - query.tenantIsSet(false); - } - } - preferences = query.collect(); - int ordinal = 0; - - List updatedPreferences = new ArrayList<>(); - for (NotificationContactType contactType : contactTypes) { - UserNotificationPreferenceEntity preference = preferences.stream().filter(x -> x.getChannel() == contactType).findFirst().orElse(null); - - boolean isUpdate = preference != null; - if (preference != null) { - preference.setOrdinal(ordinal); - - } else { - preference = new UserNotificationPreferenceEntity(); - preference.setId(UUID.randomUUID()); - preference.setUserId(userId); - preference.setType(type); - preference.setOrdinal(ordinal); - preference.setChannel(contactType); - preference.setCreatedAt(Instant.now()); - preference.setIsActive(IsActive.Active); - } - preference.setUpdatedAt(Instant.now()); - - if(isUpdate) this.entityManager.merge(preference); - else this.entityManager.persist(preference); - updatedPreferences.add(preference); - ordinal++; - } - List toDelete = preferences.stream().filter(x -> !updatedPreferences.stream().map(UserNotificationPreferenceEntity::getChannel).toList().contains(x.getChannel())).toList(); - for (UserNotificationPreferenceEntity deletable: toDelete) { - this.entityManager.remove(deletable); - } - } catch (InvalidApplicationException e) { - logger.error(e.getMessage(), e); - } - return preferences; - } -} diff --git a/notification-service/pom.xml b/notification-service/pom.xml deleted file mode 100644 index 4dd88371d..000000000 --- a/notification-service/pom.xml +++ /dev/null @@ -1,192 +0,0 @@ - - - - 4.0.0 - gr.cite - notification-service-parent - Notification Parent - ${revision} - pom - - - org.springframework.boot - spring-boot-starter-parent - 3.2.5 - - - - notification - notification-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/notification-service/settings.xml b/notification-service/settings.xml deleted file mode 100644 index 2aae21a89..000000000 --- a/notification-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} - - - - - \ No newline at end of file