org.hibernate
diff --git a/sonar-project.properties b/sonar-project.properties
index 4bf3ba5..fdcdfce 100644
--- a/sonar-project.properties
+++ b/sonar-project.properties
@@ -1,25 +1,25 @@
-sonar.projectKey=org.securityrat.casemanagement
-sonar.projectName=case Management
-sonar.projectVersion=0.0.1-SNAPSHOT
+sonar.projectKey=caseManagement
+sonar.projectName=caseManagement generated by jhipster
+sonar.projectVersion=1.0
sonar.sources=src/main/
sonar.host.url=http://localhost:9001
sonar.tests=src/test/
-sonar.coverage.jacoco.xmlReportPaths=target/jacoco/test/jacoco.xml,target/jacoco/integrationTest/jacoco.xml
+sonar.coverage.jacoco.xmlReportPaths=target/site/**/jacoco*.xml
sonar.java.codeCoveragePlugin=jacoco
-sonar.junit.reportPaths=target/test-results/test,target/test-results/integrationTest
+sonar.junit.reportPaths=target/surefire-reports,target/failsafe-reports
sonar.sourceEncoding=UTF-8
sonar.exclusions=src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/classes/static/**/*.*
sonar.issue.ignore.multicriteria=S3437,S4684,UndocumentedApi
-# Rule https://sonarcloud.io/coding_rules?open=squid%3AS3437&rule_key=squid%3AS3437 is ignored, as a JPA-managed field cannot be transient
+# Rule https://rules.sonarsource.com/java/RSPEC-3437 is ignored, as a JPA-managed field cannot be transient
sonar.issue.ignore.multicriteria.S3437.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.S3437.ruleKey=squid:S3437
-# Rule https://sonarcloud.io/coding_rules?open=squid%3AUndocumentedApi&rule_key=squid%3AUndocumentedApi is ignored, as we want to follow "clean code" guidelines and classes, methods and arguments names should be self-explanatory
+# Rule https://rules.sonarsource.com/java/RSPEC-1176 is ignored, as we want to follow "clean code" guidelines and classes, methods and arguments names should be self-explanatory
sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey=squid:UndocumentedApi
-# Rule https://sonarcloud.io/coding_rules?open=squid%3AS4684&rule_key=squid%3AS4684
+# Rule https://rules.sonarsource.com/java/RSPEC-4684
sonar.issue.ignore.multicriteria.S4684.resourceKey=src/main/java/**/*
-sonar.issue.ignore.multicriteria.S4684.ruleKey=squid:S4684
+sonar.issue.ignore.multicriteria.S4684.ruleKey=java:S4684
diff --git a/src/main/docker/app.yml b/src/main/docker/app.yml
index 9f766b3..eed6a30 100644
--- a/src/main/docker/app.yml
+++ b/src/main/docker/app.yml
@@ -1,28 +1,52 @@
-version: '2'
+# This configuration is intended for development purpose, it's **your** responsibility to harden it for production
+version: '3.8'
services:
casemanagement-app:
image: casemanagement
environment:
- _JAVA_OPTIONS=-Xmx512m -Xms256m
- - SPRING_PROFILES_ACTIVE=prod,swagger
+ - SPRING_PROFILES_ACTIVE=prod,api-docs
- MANAGEMENT_METRICS_EXPORT_PROMETHEUS_ENABLED=true
- SPRING_CLOUD_CONSUL_HOST=consul
- SPRING_CLOUD_CONSUL_PORT=8500
- - SPRING_DATASOURCE_URL=jdbc:mariadb://casemanagement-mariadb:3306/casemanagement
+ - SPRING_DATASOURCE_URL=jdbc:mariadb://casemanagement-mariadb:3306/casemanagement?useLegacyDatetimeCode=false&serverTimezone=UTC
+ - SPRING_LIQUIBASE_URL=jdbc:mariadb://casemanagement-mariadb:3306/casemanagement?useLegacyDatetimeCode=false&serverTimezone=UTC
- SPRING_SECURITY_OAUTH2_CLIENT_PROVIDER_OIDC_ISSUER_URI=http://keycloak:9080/auth/realms/jhipster
- SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_OIDC_CLIENT_ID=internal
- SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_OIDC_CLIENT_SECRET=internal
- JHIPSTER_SLEEP=120 # gives time for mariadb server to start
casemanagement-mariadb:
- extends:
- file: mariadb.yml
- service: casemanagement-mariadb
+ image: mariadb:10.5.9
+ # volumes:
+ # - ~/volumes/jhipster/caseManagement/mysql/:/var/lib/mysql/
+ environment:
+ - MYSQL_USER=root
+ - MYSQL_ALLOW_EMPTY_PASSWORD=yes
+ - MYSQL_DATABASE=casemanagement
+ # If you want to expose these ports outside your dev PC,
+ # remove the "127.0.0.1:" prefix
+ ports:
+ - 127.0.0.1:3306:3306
+ command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8mb4 --explicit_defaults_for_timestamp
consul:
- extends:
- file: consul.yml
- service: consul
+ image: consul:1.9.4
+ # If you want to expose these ports outside your dev PC,
+ # remove the "127.0.0.1:" prefix
+ ports:
+ - 127.0.0.1:8300:8300
+ - 127.0.0.1:8500:8500
+ - 127.0.0.1:8600:8600
+ command: consul agent -dev -ui -client 0.0.0.0 -log-level=INFO
consul-config-loader:
- extends:
- file: consul.yml
- service: consul-config-loader
+ image: jhipster/consul-config-loader:v0.4.1
+ volumes:
+ - ./central-server-config:/config
+ environment:
+ - INIT_SLEEP_SECONDS=5
+ - CONSUL_URL=consul
+ - CONSUL_PORT=8500
+ # Uncomment to load configuration into Consul from a Git repository
+ # as configured in central-server-config/git2consul.json
+ # Also set SPRING_CLOUD_CONSUL_CONFIG_FORMAT=files on your apps
+ # - CONFIG_MODE=git
diff --git a/src/main/docker/central-server-config/application.yml b/src/main/docker/central-server-config/application.yml
index e2398f0..af04448 100644
--- a/src/main/docker/central-server-config/application.yml
+++ b/src/main/docker/central-server-config/application.yml
@@ -6,4 +6,5 @@ jhipster:
security:
authentication:
jwt:
- secret: my-secret-key-which-should-be-changed-in-production-and-be-base64-encoded
+ # secret key which should be base64 encoded and changed in production
+ base64-secret: ebcc96a1801b3e946498deeae1c992287d454acc
diff --git a/src/main/docker/config/git2consul.json b/src/main/docker/config/git2consul.json
index dcb9f6b..000854d 100644
--- a/src/main/docker/config/git2consul.json
+++ b/src/main/docker/config/git2consul.json
@@ -4,7 +4,7 @@
{
"name": "config",
"url": "https://github.com/jhipster/generator-jhipster.git",
- "branches": ["master"],
+ "branches": ["main"],
"include_branch_name": false,
"source_root": "generators/server/src/main/docker/config/consul-config/",
"hooks": [
diff --git a/src/main/docker/consul.yml b/src/main/docker/consul.yml
index 2aa4598..546ac4b 100644
--- a/src/main/docker/consul.yml
+++ b/src/main/docker/consul.yml
@@ -1,15 +1,18 @@
-version: '2'
+# This configuration is intended for development purpose, it's **your** responsibility to harden it for production
+version: '3.8'
services:
consul:
- image: consul:1.6.2
+ image: consul:1.9.4
+ # If you want to expose these ports outside your dev PC,
+ # remove the "127.0.0.1:" prefix
ports:
- - 8300:8300
- - 8500:8500
- - 8600:8600
- command: consul agent -dev -ui -client 0.0.0.0
+ - 127.0.0.1:8300:8300
+ - 127.0.0.1:8500:8500
+ - 127.0.0.1:8600:8600
+ command: consul agent -dev -ui -client 0.0.0.0 -log-level=INFO
consul-config-loader:
- image: jhipster/consul-config-loader:v0.3.0
+ image: jhipster/consul-config-loader:v0.4.1
volumes:
- ./central-server-config:/config
environment:
diff --git a/src/main/docker/jhipster-control-center.yml b/src/main/docker/jhipster-control-center.yml
new file mode 100644
index 0000000..7d0d9a9
--- /dev/null
+++ b/src/main/docker/jhipster-control-center.yml
@@ -0,0 +1,54 @@
+## How to use JHCC docker compose
+# To allow JHCC to reach JHipster application from a docker container note that we set the host as host.docker.internal
+# To reach the application from a browser, you need to add '127.0.0.1 host.docker.internal' to your hosts file.
+### Discovery mode
+# JHCC support 3 kinds of discovery mode: Consul, Eureka and static
+# In order to use one, please set SPRING_PROFILES_ACTIVE to one (and only one) of this values: consul,eureka,static
+### Discovery properties
+# According to the discovery mode choose as Spring profile, you have to set the right properties
+# please note that current properties are set to run JHCC with default values, personalize them if needed
+# and remove those from other modes. You can only have one mode active.
+#### Eureka
+# - EUREKA_CLIENT_SERVICE_URL_DEFAULTZONE=http://admin:admin@host.docker.internal:8761/eureka/
+#### Consul
+# - SPRING_CLOUD_CONSUL_HOST=host.docker.internal
+# - SPRING_CLOUD_CONSUL_PORT=8500
+#### Static
+# Add instances to "MyApp"
+# - SPRING_CLOUD_DISCOVERY_CLIENT_SIMPLE_INSTANCES_MYAPP_0_URI=http://host.docker.internal:8081
+# - SPRING_CLOUD_DISCOVERY_CLIENT_SIMPLE_INSTANCES_MYAPP_1_URI=http://host.docker.internal:8082
+# Or add a new application named MyNewApp
+# - SPRING_CLOUD_DISCOVERY_CLIENT_SIMPLE_INSTANCES_MYNEWAPP_0_URI=http://host.docker.internal:8080
+# This configuration is intended for development purpose, it's **your** responsibility to harden it for production
+
+#### IMPORTANT
+# If you choose Consul or Eureka mode:
+# Do not forget to remove the prefix "127.0.0.1" in front of their port in order to expose them.
+# This is required because JHCC need to communicate with Consul or Eureka.
+# - In Consul mode, the ports are in the consul.yml file.
+# - In Eureka mode, the ports are in the jhipster-registry.yml file.
+
+version: '3.8'
+services:
+ jhipster-control-center:
+ image: 'jhipster/jhipster-control-center:v0.4.1'
+ command:
+ - /bin/sh
+ - -c
+ # Patch /etc/hosts to support resolving host.docker.internal to the internal IP address used by the host in all OSes
+ - echo "`ip route | grep default | cut -d ' ' -f3` host.docker.internal" | tee -a /etc/hosts > /dev/null && java -jar /jhipster-control-center.jar
+ environment:
+ - _JAVA_OPTIONS=-Xmx512m -Xms256m
+ - SPRING_PROFILES_ACTIVE=prod,api-docs,consul,oauth2
+ - JHIPSTER_SLEEP=30 # gives time for other services to boot before the application
+ # For keycloak to work, you need to add '127.0.0.1 keycloak' to your hosts file
+ - SPRING_SECURITY_OAUTH2_CLIENT_PROVIDER_OIDC_ISSUER_URI=http://keycloak:9080/auth/realms/jhipster
+ - SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_OIDC_CLIENT_ID=jhipster-control-center
+ - SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_OIDC_CLIENT_SECRET=jhipster-control-center
+ - SPRING_CLOUD_CONSUL_HOST=host.docker.internal
+ - SPRING_CLOUD_CONSUL_PORT=8500
+ - LOGGING_FILE_NAME=/tmp/jhipster-control-center.log
+ # If you want to expose these ports outside your dev PC,
+ # remove the "127.0.0.1:" prefix
+ ports:
+ - 127.0.0.1:7419:7419
diff --git a/src/main/jib/entrypoint.sh b/src/main/docker/jib/entrypoint.sh
similarity index 100%
rename from src/main/jib/entrypoint.sh
rename to src/main/docker/jib/entrypoint.sh
diff --git a/src/main/docker/mariadb.yml b/src/main/docker/mariadb.yml
index ea2b077..9a96c98 100644
--- a/src/main/docker/mariadb.yml
+++ b/src/main/docker/mariadb.yml
@@ -1,13 +1,16 @@
-version: '2'
+# This configuration is intended for development purpose, it's **your** responsibility to harden it for production
+version: '3.8'
services:
casemanagement-mariadb:
- image: mariadb:10.4.10
+ image: mariadb:10.5.9
# volumes:
- # - ~/volumes/jhipster/caseManagement/mysql/:/var/lib/mysql/
+ # - ~/volumes/jhipster/caseManagement/mysql/:/var/lib/mysql/
environment:
- MYSQL_USER=root
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
- MYSQL_DATABASE=casemanagement
+ # If you want to expose these ports outside your dev PC,
+ # remove the "127.0.0.1:" prefix
ports:
- - 3306:3306
+ - 127.0.0.1:3306:3306
command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8mb4 --explicit_defaults_for_timestamp
diff --git a/src/main/docker/monitoring.yml b/src/main/docker/monitoring.yml
index c1ac16e..1c7c1e2 100644
--- a/src/main/docker/monitoring.yml
+++ b/src/main/docker/monitoring.yml
@@ -1,26 +1,31 @@
-version: '2'
+# This configuration is intended for development purpose, it's **your** responsibility to harden it for production
+version: '3.8'
services:
casemanagement-prometheus:
- image: prom/prometheus:v2.14.0
+ image: prom/prometheus:v2.25.0
volumes:
- ./prometheus/:/etc/prometheus/
command:
- '--config.file=/etc/prometheus/prometheus.yml'
+ # If you want to expose these ports outside your dev PC,
+ # remove the "127.0.0.1:" prefix
ports:
- - 9090:9090
+ - 127.0.0.1:9090:9090
# On MacOS, remove next line and replace localhost by host.docker.internal in prometheus/prometheus.yml and
# grafana/provisioning/datasources/datasource.yml
network_mode: 'host' # to test locally running service
casemanagement-grafana:
- image: grafana/grafana:6.5.1
+ image: grafana/grafana:7.4.3
volumes:
- ./grafana/provisioning/:/etc/grafana/provisioning/
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
- GF_USERS_ALLOW_SIGN_UP=false
- GF_INSTALL_PLUGINS=grafana-piechart-panel
+ # If you want to expose these ports outside your dev PC,
+ # remove the "127.0.0.1:" prefix
ports:
- - 3000:3000
+ - 127.0.0.1:3000:3000
# On MacOS, remove next line and replace localhost by host.docker.internal in prometheus/prometheus.yml and
# grafana/provisioning/datasources/datasource.yml
network_mode: 'host' # to test locally running service
diff --git a/src/main/docker/sonar.yml b/src/main/docker/sonar.yml
index 622d796..8104715 100644
--- a/src/main/docker/sonar.yml
+++ b/src/main/docker/sonar.yml
@@ -1,7 +1,13 @@
-version: '2'
+# This configuration is intended for development purpose, it's **your** responsibility to harden it for production
+version: '3.8'
services:
casemanagement-sonar:
- image: sonarqube:7.9.1-community
+ image: sonarqube:8.7.0-community
+ # Authentication is turned off for out of the box experience while trying out SonarQube
+ # For real use cases delete sonar.forceAuthentication variable or set sonar.forceAuthentication=true
+ environment:
+ - sonar.forceAuthentication=false
+ # If you want to expose these ports outside your dev PC,
+ # remove the "127.0.0.1:" prefix
ports:
- - 9001:9000
- - 9092:9092
+ - 127.0.0.1:9001:9000
diff --git a/src/main/java/org/securityrat/casemanagement/ApplicationWebXml.java b/src/main/java/org/securityrat/casemanagement/ApplicationWebXml.java
index 2346a2a..a0a82fd 100644
--- a/src/main/java/org/securityrat/casemanagement/ApplicationWebXml.java
+++ b/src/main/java/org/securityrat/casemanagement/ApplicationWebXml.java
@@ -1,9 +1,8 @@
package org.securityrat.casemanagement;
-import io.github.jhipster.config.DefaultProfileUtil;
-
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
+import tech.jhipster.config.DefaultProfileUtil;
/**
* This is a helper Java class that provides an alternative to creating a {@code web.xml}.
@@ -13,9 +12,7 @@ public class ApplicationWebXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- /**
- * set a default to use when no profile is configured.
- */
+ // set a default to use when no profile is configured.
DefaultProfileUtil.addDefaultProfile(application.application());
return application.sources(CaseManagementApp.class);
}
diff --git a/src/main/java/org/securityrat/casemanagement/CaseManagementApp.java b/src/main/java/org/securityrat/casemanagement/CaseManagementApp.java
index 46f1405..60793e8 100644
--- a/src/main/java/org/securityrat/casemanagement/CaseManagementApp.java
+++ b/src/main/java/org/securityrat/casemanagement/CaseManagementApp.java
@@ -1,30 +1,26 @@
package org.securityrat.casemanagement;
-import org.securityrat.casemanagement.config.ApplicationProperties;
-
-import io.github.jhipster.config.DefaultProfileUtil;
-import io.github.jhipster.config.JHipsterConstants;
-
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Optional;
+import javax.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
+import org.securityrat.casemanagement.config.ApplicationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.core.env.Environment;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Arrays;
-import java.util.Collection;
+import tech.jhipster.config.DefaultProfileUtil;
+import tech.jhipster.config.JHipsterConstants;
@SpringBootApplication
-@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
-@EnableDiscoveryClient
-public class CaseManagementApp implements InitializingBean {
+@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class })
+public class CaseManagementApp {
private static final Logger log = LoggerFactory.getLogger(CaseManagementApp.class);
@@ -41,16 +37,24 @@ public CaseManagementApp(Environment env) {
*
* You can find more information on how profiles work with JHipster on https://www.jhipster.tech/profiles/.
*/
- @Override
- public void afterPropertiesSet() throws Exception {
+ @PostConstruct
+ public void initApplication() {
Collection activeProfiles = Arrays.asList(env.getActiveProfiles());
- if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
- log.error("You have misconfigured your application! It should not run " +
- "with both the 'dev' and 'prod' profiles at the same time.");
+ if (
+ activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) &&
+ activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)
+ ) {
+ log.error(
+ "You have misconfigured your application! It should not run " + "with both the 'dev' and 'prod' profiles at the same time."
+ );
}
- if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
- log.error("You have misconfigured your application! It should not " +
- "run with both the 'dev' and 'cloud' profiles at the same time.");
+ if (
+ activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) &&
+ activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)
+ ) {
+ log.error(
+ "You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time."
+ );
}
}
@@ -67,26 +71,24 @@ public static void main(String[] args) {
}
private static void logApplicationStartup(Environment env) {
- String protocol = "http";
- if (env.getProperty("server.ssl.key-store") != null) {
- protocol = "https";
- }
+ String protocol = Optional.ofNullable(env.getProperty("server.ssl.key-store")).map(key -> "https").orElse("http");
String serverPort = env.getProperty("server.port");
- String contextPath = env.getProperty("server.servlet.context-path");
- if (StringUtils.isBlank(contextPath)) {
- contextPath = "/";
- }
+ String contextPath = Optional
+ .ofNullable(env.getProperty("server.servlet.context-path"))
+ .filter(StringUtils::isNotBlank)
+ .orElse("/");
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
- log.info("\n----------------------------------------------------------\n\t" +
- "Application '{}' is running! Access URLs:\n\t" +
- "Local: \t\t{}://localhost:{}{}\n\t" +
- "External: \t{}://{}:{}{}\n\t" +
- "Profile(s): \t{}\n----------------------------------------------------------",
+ log.info(
+ "\n----------------------------------------------------------\n\t" +
+ "Application '{}' is running! Access URLs:\n\t" +
+ "Local: \t\t{}://localhost:{}{}\n\t" +
+ "External: \t{}://{}:{}{}\n\t" +
+ "Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
@@ -95,13 +97,17 @@ private static void logApplicationStartup(Environment env) {
hostAddress,
serverPort,
contextPath,
- env.getActiveProfiles());
+ env.getActiveProfiles()
+ );
String configServerStatus = env.getProperty("configserver.status");
if (configServerStatus == null) {
configServerStatus = "Not found or not setup for this application";
}
- log.info("\n----------------------------------------------------------\n\t" +
- "Config Server: \t{}\n----------------------------------------------------------", configServerStatus);
+ log.info(
+ "\n----------------------------------------------------------\n\t" +
+ "Config Server: \t{}\n----------------------------------------------------------",
+ configServerStatus
+ );
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/GeneratedByJHipster.java b/src/main/java/org/securityrat/casemanagement/GeneratedByJHipster.java
new file mode 100644
index 0000000..2119628
--- /dev/null
+++ b/src/main/java/org/securityrat/casemanagement/GeneratedByJHipster.java
@@ -0,0 +1,13 @@
+package org.securityrat.casemanagement;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import javax.annotation.Generated;
+
+@Generated(value = "JHipster", comments = "Generated by JHipster 7.0.0")
+@Retention(RetentionPolicy.SOURCE)
+@Target({ ElementType.TYPE })
+public @interface GeneratedByJHipster {
+}
diff --git a/src/main/java/org/securityrat/casemanagement/aop/logging/LoggingAspect.java b/src/main/java/org/securityrat/casemanagement/aop/logging/LoggingAspect.java
index e065893..b73510b 100644
--- a/src/main/java/org/securityrat/casemanagement/aop/logging/LoggingAspect.java
+++ b/src/main/java/org/securityrat/casemanagement/aop/logging/LoggingAspect.java
@@ -1,7 +1,6 @@
package org.securityrat.casemanagement.aop.logging;
-import io.github.jhipster.config.JHipsterConstants;
-
+import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
@@ -12,8 +11,7 @@
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
-
-import java.util.Arrays;
+import tech.jhipster.config.JHipsterConstants;
/**
* Aspect for logging execution of service and repository Spring components.
@@ -23,8 +21,6 @@
@Aspect
public class LoggingAspect {
- private final Logger log = LoggerFactory.getLogger(this.getClass());
-
private final Environment env;
public LoggingAspect(Environment env) {
@@ -34,9 +30,11 @@ public LoggingAspect(Environment env) {
/**
* Pointcut that matches all repositories, services and Web REST endpoints.
*/
- @Pointcut("within(@org.springframework.stereotype.Repository *)" +
+ @Pointcut(
+ "within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
- " || within(@org.springframework.web.bind.annotation.RestController *)")
+ " || within(@org.springframework.web.bind.annotation.RestController *)"
+ )
public void springBeanPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
@@ -44,13 +42,25 @@ public void springBeanPointcut() {
/**
* Pointcut that matches all Spring beans in the application's main packages.
*/
- @Pointcut("within(org.securityrat.casemanagement.repository..*)"+
- " || within(org.securityrat.casemanagement.service..*)"+
- " || within(org.securityrat.casemanagement.web.rest..*)")
+ @Pointcut(
+ "within(org.securityrat.casemanagement.repository..*)" +
+ " || within(org.securityrat.casemanagement.service..*)" +
+ " || within(org.securityrat.casemanagement.web.rest..*)"
+ )
public void applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
+ /**
+ * Retrieves the {@link Logger} associated to the given {@link JoinPoint}.
+ *
+ * @param joinPoint join point we want the logger for.
+ * @return {@link Logger} associated to the given {@link JoinPoint}.
+ */
+ private Logger logger(JoinPoint joinPoint) {
+ return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
+ }
+
/**
* Advice that logs methods throwing exceptions.
*
@@ -60,12 +70,21 @@ public void applicationPackagePointcut() {
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
- log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
- joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
-
+ logger(joinPoint)
+ .error(
+ "Exception in {}() with cause = \'{}\' and exception = \'{}\'",
+ joinPoint.getSignature().getName(),
+ e.getCause() != null ? e.getCause() : "NULL",
+ e.getMessage(),
+ e
+ );
} else {
- log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
- joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
+ logger(joinPoint)
+ .error(
+ "Exception in {}() with cause = {}",
+ joinPoint.getSignature().getName(),
+ e.getCause() != null ? e.getCause() : "NULL"
+ );
}
}
@@ -78,21 +97,18 @@ public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
+ Logger log = logger(joinPoint);
if (log.isDebugEnabled()) {
- log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
- joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
+ log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
- log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
- joinPoint.getSignature().getName(), result);
+ log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
- log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
- joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
-
+ log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName());
throw e;
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/client/AuthorizedFeignClient.java b/src/main/java/org/securityrat/casemanagement/client/AuthorizedFeignClient.java
index d589ae4..31d75f1 100644
--- a/src/main/java/org/securityrat/casemanagement/client/AuthorizedFeignClient.java
+++ b/src/main/java/org/securityrat/casemanagement/client/AuthorizedFeignClient.java
@@ -1,17 +1,15 @@
package org.securityrat.casemanagement.client;
+import java.lang.annotation.*;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.core.annotation.AliasFor;
-import java.lang.annotation.*;
-
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@FeignClient
public @interface AuthorizedFeignClient {
-
@AliasFor(annotation = FeignClient.class, attribute = "name")
String name() default "";
@@ -48,7 +46,7 @@
Class> fallback() default void.class;
/**
- * Path prefix to be used by all method-level mappings. Can be used with or without {@code @RibbonClient}.
+ * Path prefix to be used by all method-level mappings.
* @return the path prefix to be used by all method-level mappings.
*/
String path() default "";
diff --git a/src/main/java/org/securityrat/casemanagement/client/OAuth2InterceptedFeignConfiguration.java b/src/main/java/org/securityrat/casemanagement/client/OAuth2InterceptedFeignConfiguration.java
index 659d076..f304ec9 100644
--- a/src/main/java/org/securityrat/casemanagement/client/OAuth2InterceptedFeignConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/client/OAuth2InterceptedFeignConfiguration.java
@@ -1,10 +1,8 @@
package org.securityrat.casemanagement.client;
-import org.springframework.context.annotation.Bean;
-
import feign.RequestInterceptor;
-
import org.securityrat.casemanagement.security.oauth2.AuthorizationHeaderUtil;
+import org.springframework.context.annotation.Bean;
public class OAuth2InterceptedFeignConfiguration {
diff --git a/src/main/java/org/securityrat/casemanagement/client/RequirementManagementServiceClient.java b/src/main/java/org/securityrat/casemanagement/client/RequirementManagementServiceClient.java
deleted file mode 100644
index 0f988b1..0000000
--- a/src/main/java/org/securityrat/casemanagement/client/RequirementManagementServiceClient.java
+++ /dev/null
@@ -1,127 +0,0 @@
-package org.securityrat.casemanagement.client;
-
-import java.util.List;
-
-import org.securityrat.casemanagement.service.dto.*;
-import org.springframework.web.bind.annotation.*;
-
-@AuthorizedFeignClient(name = "requirementManagement")
-public interface RequirementManagementServiceClient {
-
- /**
- * Get a list of RequirementSets from requirement management.
- *
- * @param active
- * Add the given value of type Boolean as a filter for the field
- * 'active' to the request to requirement management
- * @return List of RequirementSets as returned by requirement management.
- */
- @RequestMapping(value = "/api/requirement-sets")
- List getRequirementSetsFromRequirementManagement(
- @RequestParam(value = "active.equals") Boolean active);
-
- /**
- * Get a list of Attributes from requirement management, filter by active.
- *
- * @param active
- * Add the given value of type Boolean as a filter for the field
- * 'active' to the request to requirement management
- * @return List of Attributes as returned by requirement management.
- */
- @RequestMapping(value = "/api/attributes")
- List getAttributesFromRequirementManagement(@RequestParam(value = "active.equals") Boolean active);
-
- /**
- * Get a list of all Attributes from requirement management.
- *
- * @return List of Attributes as returned by requirement management.
- */
- @RequestMapping(value = "/api/attributes")
- List getAllAttributesFromRequirementManagement();
-
- /**
- * Get a list of all ExtensionKeys from requirement management.
- *
- * param active Add the given value of type Boolean as a filter for the field
- * 'active' to the request to requirement management
- *
- * @return List of ExtensionKeys as returned by requirement management.
- */
- @RequestMapping(value = "/api/extension-keys")
- List getAllExtensionKeysFromRequirementManagement(
- @RequestParam(value = "active.equals") Boolean active);
-
- /**
- * Get a list of all Skeletons from requirement management.
- *
- * param active Add the given value of type Boolean as a filter for the field
- * 'active' to the request to requirement management
- *
- * @return List of Skeletons as returned by requirement management.
- */
- @RequestMapping(value = "/api/skeletons")
- List getAllSkeletonsFromRequirementManagement(@RequestParam(value = "active.equals") Boolean active);
-
- /**
- * Get a list of all Extensions from requirement management.
- *
- * param active Add the given value of type Boolean as a filter for the field
- * 'active' to the request to requirement management
- *
- * @return List of Extensions as returned by requirement management.
- */
- @RequestMapping(value = "/api/extensions")
- List getAllExtensionsFromRequirementManagement(@RequestParam(value = "active.equals") Boolean active);
-
- /**
- * Get a list of all SkAtEx from requirement management.
- *
- * param active Add the given value of type Boolean as a filter for the field
- * 'active' to the request to requirement management
- *
- * @return List of SkAtEx as returned by requirement management.
- */
- @RequestMapping(value = "/api/sk-at-exes")
- List getAllSkAtExFromRequirementManagement(@RequestParam(value = "active.equals") Boolean active);
-
- /**
- * Get a list of all AttributeKeys from requirement management.
- *
- * param active Add the given value of type Boolean as a filter for the field
- * 'active' to the request to requirement management
- *
- * @return List of AttributeKeys as returned by requirement management.
- */
- @RequestMapping(value = "/api/attribute-keys")
- List getAttributeKeysFromRequirementManagement(
- @RequestParam(value = "active.equals") Boolean active);
-
- /**
- * Get a list of all AttributeKeys from requirement management.
- *
- * @param active
- * Add the given value of type Boolean as a filter for the field
- * 'active' to the request to requirement management
- * @param attributeKeyType
- * type of the attribute Keys to be requested.
- *
- * @return List of AttributeKeys as returned by requirement management.
- */
- @RequestMapping(value = "/api/attribute-keys")
- List getAttributeKeysFromRequirementManagement(
- @RequestParam(value = "active.equals") Boolean active,
- @RequestParam(value = "type.equals") String attributeKeyType);
-
- @RequestMapping(value = "/api/sk-at-exes/{id}")
- SkAtExDTO getSkAtExById(@RequestParam(value = "id") Integer id);
-
- @RequestMapping(value = "/api/attributes/{id}")
- AttributeDTO getAttributeById(@RequestParam(value = "id") Integer id);
-
- @RequestMapping(value = "/api/skeletons/{id}")
- SkeletonDTO getSkeletonById(@RequestParam(value = "id") Integer id);
-
- @RequestMapping(value = "/api/extension-keys/{id}")
- ExtensionKeyDTO getExtensionKeyById(@RequestParam(value = "id") Integer id);
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/client/TokenRelayRequestInterceptor.java b/src/main/java/org/securityrat/casemanagement/client/TokenRelayRequestInterceptor.java
index 5104c0a..acff2ec 100644
--- a/src/main/java/org/securityrat/casemanagement/client/TokenRelayRequestInterceptor.java
+++ b/src/main/java/org/securityrat/casemanagement/client/TokenRelayRequestInterceptor.java
@@ -1,11 +1,9 @@
package org.securityrat.casemanagement.client;
-import org.securityrat.casemanagement.security.oauth2.AuthorizationHeaderUtil;
-
import feign.RequestInterceptor;
import feign.RequestTemplate;
-
import java.util.Optional;
+import org.securityrat.casemanagement.security.oauth2.AuthorizationHeaderUtil;
public class TokenRelayRequestInterceptor implements RequestInterceptor {
diff --git a/src/main/java/org/securityrat/casemanagement/config/ApplicationProperties.java b/src/main/java/org/securityrat/casemanagement/config/ApplicationProperties.java
index edac8d7..51dbea4 100644
--- a/src/main/java/org/securityrat/casemanagement/config/ApplicationProperties.java
+++ b/src/main/java/org/securityrat/casemanagement/config/ApplicationProperties.java
@@ -6,8 +6,7 @@
* Properties specific to Case Management.
*
* Properties are configured in the {@code application.yml} file.
- * See {@link io.github.jhipster.config.JHipsterProperties} for a good example.
+ * See {@link tech.jhipster.config.JHipsterProperties} for a good example.
*/
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
-public class ApplicationProperties {
-}
+public class ApplicationProperties {}
diff --git a/src/main/java/org/securityrat/casemanagement/config/AsyncConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/AsyncConfiguration.java
index 30010be..119228b 100644
--- a/src/main/java/org/securityrat/casemanagement/config/AsyncConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/AsyncConfiguration.java
@@ -1,6 +1,6 @@
package org.securityrat.casemanagement.config;
-import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
+import java.util.concurrent.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
@@ -12,8 +12,7 @@
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-
-import java.util.concurrent.Executor;
+import tech.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
@Configuration
@EnableAsync
diff --git a/src/main/java/org/securityrat/casemanagement/config/CloudDatabaseConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/CloudDatabaseConfiguration.java
deleted file mode 100644
index 61bb763..0000000
--- a/src/main/java/org/securityrat/casemanagement/config/CloudDatabaseConfiguration.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package org.securityrat.casemanagement.config;
-
-import io.github.jhipster.config.JHipsterConstants;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.cloud.config.java.AbstractCloudConfig;
-import org.springframework.context.annotation.*;
-
-import javax.sql.DataSource;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-
-
-@Configuration
-@Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
-public class CloudDatabaseConfiguration extends AbstractCloudConfig {
-
- private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
-
- private static final String CLOUD_CONFIGURATION_HIKARI_PREFIX = "spring.datasource.hikari";
-
- @Bean
- @ConfigurationProperties(CLOUD_CONFIGURATION_HIKARI_PREFIX)
- public DataSource dataSource() {
- log.info("Configuring JDBC datasource from a cloud provider");
- return connectionFactory().dataSource();
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/config/Constants.java b/src/main/java/org/securityrat/casemanagement/config/Constants.java
index 8559954..2213540 100644
--- a/src/main/java/org/securityrat/casemanagement/config/Constants.java
+++ b/src/main/java/org/securityrat/casemanagement/config/Constants.java
@@ -6,12 +6,10 @@
public final class Constants {
// Regex for acceptable logins
- public static final String LOGIN_REGEX = "^[_.@A-Za-z0-9-]*$";
-
- public static final String SYSTEM_ACCOUNT = "system";
+ public static final String LOGIN_REGEX = "^(?>[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*)|(?>[_.@A-Za-z0-9-]+)$";
+
+ public static final String SYSTEM = "system";
public static final String DEFAULT_LANGUAGE = "en";
- public static final String ANONYMOUS_USER = "anonymoususer";
- private Constants() {
- }
+ private Constants() {}
}
diff --git a/src/main/java/org/securityrat/casemanagement/config/DatabaseConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/DatabaseConfiguration.java
index 78fa2d3..1f6c240 100644
--- a/src/main/java/org/securityrat/casemanagement/config/DatabaseConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/DatabaseConfiguration.java
@@ -1,19 +1,17 @@
package org.securityrat.casemanagement.config;
-import io.github.jhipster.config.JHipsterConstants;
-import io.github.jhipster.config.h2.H2ConfigurationHelper;
+import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
-
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
-
-import java.sql.SQLException;
+import tech.jhipster.config.JHipsterConstants;
+import tech.jhipster.config.h2.H2ConfigurationHelper;
@Configuration
@EnableJpaRepositories("org.securityrat.casemanagement.repository")
diff --git a/src/main/java/org/securityrat/casemanagement/config/FeignConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/FeignConfiguration.java
index 5dd7837..94cdd4d 100644
--- a/src/main/java/org/securityrat/casemanagement/config/FeignConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/FeignConfiguration.java
@@ -18,5 +18,4 @@ public class FeignConfiguration {
feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.BASIC;
}
-
}
diff --git a/src/main/java/org/securityrat/casemanagement/config/JacksonConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/JacksonConfiguration.java
index a83db54..b11a73e 100644
--- a/src/main/java/org/securityrat/casemanagement/config/JacksonConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/JacksonConfiguration.java
@@ -3,8 +3,6 @@
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
-import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
-
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.ProblemModule;
@@ -35,19 +33,11 @@ public Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
- /*
- * Jackson Afterburner module to speed up serialization/deserialization.
- */
- @Bean
- public AfterburnerModule afterburnerModule() {
- return new AfterburnerModule();
- }
-
/*
* Module for serialization/deserialization of RFC7807 Problem.
*/
@Bean
- ProblemModule problemModule() {
+ public ProblemModule problemModule() {
return new ProblemModule();
}
@@ -55,7 +45,7 @@ ProblemModule problemModule() {
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
@Bean
- ConstraintViolationProblemModule constraintViolationProblemModule() {
+ public ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/config/LiquibaseConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/LiquibaseConfiguration.java
index 16d770f..ce7ce72 100644
--- a/src/main/java/org/securityrat/casemanagement/config/LiquibaseConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/LiquibaseConfiguration.java
@@ -1,7 +1,7 @@
package org.securityrat.casemanagement.config;
-import io.github.jhipster.config.JHipsterConstants;
-import io.github.jhipster.config.liquibase.SpringLiquibaseUtil;
+import java.util.concurrent.Executor;
+import javax.sql.DataSource;
import liquibase.integration.spring.SpringLiquibase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -14,9 +14,8 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
-
-import javax.sql.DataSource;
-import java.util.concurrent.Executor;
+import tech.jhipster.config.JHipsterConstants;
+import tech.jhipster.config.liquibase.SpringLiquibaseUtil;
@Configuration
public class LiquibaseConfiguration {
@@ -30,13 +29,23 @@ public LiquibaseConfiguration(Environment env) {
}
@Bean
- public SpringLiquibase liquibase(@Qualifier("taskExecutor") Executor executor,
- @LiquibaseDataSource ObjectProvider liquibaseDataSource, LiquibaseProperties liquibaseProperties,
- ObjectProvider dataSource, DataSourceProperties dataSourceProperties) {
-
+ public SpringLiquibase liquibase(
+ @Qualifier("taskExecutor") Executor executor,
+ @LiquibaseDataSource ObjectProvider liquibaseDataSource,
+ LiquibaseProperties liquibaseProperties,
+ ObjectProvider dataSource,
+ DataSourceProperties dataSourceProperties
+ ) {
// If you don't want Liquibase to start asynchronously, substitute by this:
// SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties);
- SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(this.env, executor, liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties);
+ SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(
+ this.env,
+ executor,
+ liquibaseDataSource.getIfAvailable(),
+ liquibaseProperties,
+ dataSource.getIfUnique(),
+ dataSourceProperties
+ );
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
diff --git a/src/main/java/org/securityrat/casemanagement/config/LocaleConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/LocaleConfiguration.java
index a29995e..bbac062 100644
--- a/src/main/java/org/securityrat/casemanagement/config/LocaleConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/LocaleConfiguration.java
@@ -1,17 +1,16 @@
package org.securityrat.casemanagement.config;
-import io.github.jhipster.config.locale.AngularCookieLocaleResolver;
-
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
+import tech.jhipster.config.locale.AngularCookieLocaleResolver;
@Configuration
public class LocaleConfiguration implements WebMvcConfigurer {
- @Bean(name = "localeResolver")
+ @Bean
public LocaleResolver localeResolver() {
AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver();
cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY");
diff --git a/src/main/java/org/securityrat/casemanagement/config/LoggingAspectConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/LoggingAspectConfiguration.java
index 868191f..1d3b842 100644
--- a/src/main/java/org/securityrat/casemanagement/config/LoggingAspectConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/LoggingAspectConfiguration.java
@@ -1,11 +1,9 @@
package org.securityrat.casemanagement.config;
import org.securityrat.casemanagement.aop.logging.LoggingAspect;
-
-import io.github.jhipster.config.JHipsterConstants;
-
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
+import tech.jhipster.config.JHipsterConstants;
@Configuration
@EnableAspectJAutoProxy
diff --git a/src/main/java/org/securityrat/casemanagement/config/LoggingConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/LoggingConfiguration.java
index d315346..562ce6e 100644
--- a/src/main/java/org/securityrat/casemanagement/config/LoggingConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/LoggingConfiguration.java
@@ -1,9 +1,12 @@
package org.securityrat.casemanagement.config;
+import static tech.jhipster.config.logging.LoggingUtils.*;
+
import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import io.github.jhipster.config.JHipsterProperties;
+import java.util.HashMap;
+import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
@@ -11,11 +14,7 @@
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import static io.github.jhipster.config.logging.LoggingUtils.*;
+import tech.jhipster.config.JHipsterProperties;
/*
* Configures the console and Logstash log appenders from the app properties
@@ -24,13 +23,14 @@
@RefreshScope
public class LoggingConfiguration {
- public LoggingConfiguration(@Value("${spring.application.name}") String appName,
- @Value("${server.port}") String serverPort,
- JHipsterProperties jHipsterProperties,
- ObjectProvider consulRegistration,
- ObjectProvider buildProperties,
- ObjectMapper mapper) throws JsonProcessingException {
-
+ public LoggingConfiguration(
+ @Value("${spring.application.name}") String appName,
+ @Value("${server.port}") String serverPort,
+ JHipsterProperties jHipsterProperties,
+ ObjectProvider consulRegistration,
+ ObjectProvider buildProperties,
+ ObjectMapper mapper
+ ) throws JsonProcessingException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Map map = new HashMap<>();
@@ -52,8 +52,5 @@ public LoggingConfiguration(@Value("${spring.application.name}") String appName,
if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) {
addContextListener(context, customFields, loggingProperties);
}
- if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
- setMetricsMarkerLogbackFilter(context, loggingProperties.isUseJsonFormat());
- }
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/config/MethodSecurityConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/MethodSecurityConfiguration.java
deleted file mode 100644
index 088d156..0000000
--- a/src/main/java/org/securityrat/casemanagement/config/MethodSecurityConfiguration.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package org.securityrat.casemanagement.config;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
-import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
-import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
-import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;
-
-@Configuration
-@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
-public class MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
- @Override
- protected MethodSecurityExpressionHandler createExpressionHandler() {
- return new OAuth2MethodSecurityExpressionHandler();
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/config/SecurityConfiguration.java b/src/main/java/org/securityrat/casemanagement/config/SecurityConfiguration.java
index 64170e8..e1525b9 100644
--- a/src/main/java/org/securityrat/casemanagement/config/SecurityConfiguration.java
+++ b/src/main/java/org/securityrat/casemanagement/config/SecurityConfiguration.java
@@ -1,28 +1,32 @@
package org.securityrat.casemanagement.config;
+import java.util.*;
import org.securityrat.casemanagement.security.*;
-
-import io.github.jhipster.config.JHipsterProperties;
+import org.securityrat.casemanagement.security.SecurityUtils;
+import org.securityrat.casemanagement.security.oauth2.AudienceValidator;
+import org.securityrat.casemanagement.security.oauth2.JwtGrantedAuthorityConverter;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
+import org.springframework.core.convert.converter.Converter;
+import org.springframework.security.authentication.AbstractAuthenticationToken;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
-import org.securityrat.casemanagement.security.oauth2.AudienceValidator;
-import org.securityrat.casemanagement.security.SecurityUtils;
+import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.*;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.security.core.GrantedAuthority;
-import java.util.*;
-import org.securityrat.casemanagement.security.oauth2.JwtAuthorityExtractor;
+import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
+import tech.jhipster.config.JHipsterProperties;
@EnableWebSecurity
+@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@@ -30,18 +34,16 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private String issuerUri;
private final JHipsterProperties jHipsterProperties;
- private final JwtAuthorityExtractor jwtAuthorityExtractor;
private final SecurityProblemSupport problemSupport;
- public SecurityConfiguration(JwtAuthorityExtractor jwtAuthorityExtractor, JHipsterProperties jHipsterProperties, SecurityProblemSupport problemSupport) {
+ public SecurityConfiguration(JHipsterProperties jHipsterProperties, SecurityProblemSupport problemSupport) {
this.problemSupport = problemSupport;
- this.jwtAuthorityExtractor = jwtAuthorityExtractor;
this.jHipsterProperties = jHipsterProperties;
}
+
@Override
public void configure(WebSecurity web) {
- web.ignoring()
- .antMatchers("/h2-console/**");
+ web.ignoring().antMatchers("/h2-console/**");
}
@Override
@@ -59,7 +61,7 @@ public void configure(HttpSecurity http) throws Exception {
.and()
.referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
.and()
- .featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'")
+ .featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; fullscreen 'self'; payment 'none'")
.and()
.frameOptions()
.deny()
@@ -69,26 +71,32 @@ public void configure(HttpSecurity http) throws Exception {
.and()
.authorizeRequests()
.antMatchers("/api/auth-info").permitAll()
+ .antMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
+ .antMatchers("/management/health/**").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.oauth2ResourceServer()
.jwt()
- .jwtAuthenticationConverter(jwtAuthorityExtractor)
+ .jwtAuthenticationConverter(authenticationConverter())
.and()
.and()
.oauth2Client();
// @formatter:on
}
+ Converter authenticationConverter() {
+ JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
+ jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(new JwtGrantedAuthorityConverter());
+ return jwtAuthenticationConverter;
+ }
@Bean
JwtDecoder jwtDecoder() {
- NimbusJwtDecoderJwkSupport jwtDecoder = (NimbusJwtDecoderJwkSupport)
- JwtDecoders.fromOidcIssuerLocation(issuerUri);
+ NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(issuerUri);
OAuth2TokenValidator audienceValidator = new AudienceValidator(jHipsterProperties.getSecurity().getOauth2().getAudience());
OAuth2TokenValidator withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
diff --git a/src/main/java/org/securityrat/casemanagement/config/WebConfigurer.java b/src/main/java/org/securityrat/casemanagement/config/WebConfigurer.java
index 1abc415..3a652ec 100644
--- a/src/main/java/org/securityrat/casemanagement/config/WebConfigurer.java
+++ b/src/main/java/org/securityrat/casemanagement/config/WebConfigurer.java
@@ -1,8 +1,6 @@
package org.securityrat.casemanagement.config;
-import io.github.jhipster.config.JHipsterConstants;
-import io.github.jhipster.config.JHipsterProperties;
-import io.github.jhipster.config.h2.H2ConfigurationHelper;
+import javax.servlet.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.*;
@@ -12,11 +10,13 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
+import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
-
-import javax.servlet.*;
+import tech.jhipster.config.JHipsterConstants;
+import tech.jhipster.config.JHipsterProperties;
+import tech.jhipster.config.h2.H2ConfigurationHelper;
/**
* Configuration of web application with Servlet 3.0 APIs.
@@ -40,6 +40,7 @@ public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
+
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
@@ -50,11 +51,14 @@ public void onStartup(ServletContext servletContext) throws ServletException {
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
- if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
+ if (!CollectionUtils.isEmpty(config.getAllowedOrigins())) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
+ source.registerCorsConfiguration("/v3/api-docs", config);
+ source.registerCorsConfiguration("/swagger-resources", config);
+ source.registerCorsConfiguration("/swagger-ui/**", config);
}
return new CorsFilter(source);
}
@@ -66,5 +70,4 @@ private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
H2ConfigurationHelper.initH2Console(servletContext);
}
-
}
diff --git a/src/main/java/org/securityrat/casemanagement/config/audit/AuditEventConverter.java b/src/main/java/org/securityrat/casemanagement/config/audit/AuditEventConverter.java
deleted file mode 100644
index a049c52..0000000
--- a/src/main/java/org/securityrat/casemanagement/config/audit/AuditEventConverter.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package org.securityrat.casemanagement.config.audit;
-
-import org.securityrat.casemanagement.domain.PersistentAuditEvent;
-
-import org.springframework.boot.actuate.audit.AuditEvent;
-import org.springframework.security.web.authentication.WebAuthenticationDetails;
-import org.springframework.stereotype.Component;
-
-import java.util.*;
-
-@Component
-public class AuditEventConverter {
-
- /**
- * Convert a list of {@link PersistentAuditEvent}s to a list of {@link AuditEvent}s.
- *
- * @param persistentAuditEvents the list to convert.
- * @return the converted list.
- */
- public List convertToAuditEvent(Iterable persistentAuditEvents) {
- if (persistentAuditEvents == null) {
- return Collections.emptyList();
- }
- List auditEvents = new ArrayList<>();
- for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
- auditEvents.add(convertToAuditEvent(persistentAuditEvent));
- }
- return auditEvents;
- }
-
- /**
- * Convert a {@link PersistentAuditEvent} to an {@link AuditEvent}.
- *
- * @param persistentAuditEvent the event to convert.
- * @return the converted list.
- */
- public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) {
- if (persistentAuditEvent == null) {
- return null;
- }
- return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(),
- persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
- }
-
- /**
- * Internal conversion. This is needed to support the current SpringBoot actuator {@code AuditEventRepository} interface.
- *
- * @param data the data to convert.
- * @return a map of {@link String}, {@link Object}.
- */
- public Map convertDataToObjects(Map data) {
- Map results = new HashMap<>();
-
- if (data != null) {
- for (Map.Entry entry : data.entrySet()) {
- results.put(entry.getKey(), entry.getValue());
- }
- }
- return results;
- }
-
- /**
- * Internal conversion. This method will allow to save additional data.
- * By default, it will save the object as string.
- *
- * @param data the data to convert.
- * @return a map of {@link String}, {@link String}.
- */
- public Map convertDataToStrings(Map data) {
- Map results = new HashMap<>();
-
- if (data != null) {
- for (Map.Entry entry : data.entrySet()) {
- // Extract the data that will be saved.
- if (entry.getValue() instanceof WebAuthenticationDetails) {
- WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue();
- results.put("remoteAddress", authenticationDetails.getRemoteAddress());
- results.put("sessionId", authenticationDetails.getSessionId());
- } else {
- results.put(entry.getKey(), Objects.toString(entry.getValue()));
- }
- }
- }
- return results;
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/config/audit/package-info.java b/src/main/java/org/securityrat/casemanagement/config/audit/package-info.java
deleted file mode 100644
index 033145f..0000000
--- a/src/main/java/org/securityrat/casemanagement/config/audit/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Audit specific code.
- */
-package org.securityrat.casemanagement.config.audit;
diff --git a/src/main/java/org/securityrat/casemanagement/domain/AbstractAuditingEntity.java b/src/main/java/org/securityrat/casemanagement/domain/AbstractAuditingEntity.java
index 6a5e210..14f1725 100644
--- a/src/main/java/org/securityrat/casemanagement/domain/AbstractAuditingEntity.java
+++ b/src/main/java/org/securityrat/casemanagement/domain/AbstractAuditingEntity.java
@@ -1,21 +1,20 @@
package org.securityrat.casemanagement.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
-import org.springframework.data.annotation.CreatedBy;
-import org.springframework.data.annotation.CreatedDate;
-import org.springframework.data.annotation.LastModifiedBy;
-import org.springframework.data.annotation.LastModifiedDate;
-import org.springframework.data.jpa.domain.support.AuditingEntityListener;
-
import java.io.Serializable;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
+import org.springframework.data.annotation.CreatedBy;
+import org.springframework.data.annotation.CreatedDate;
+import org.springframework.data.annotation.LastModifiedBy;
+import org.springframework.data.annotation.LastModifiedDate;
+import org.springframework.data.jpa.domain.support.AuditingEntityListener;
/**
- * Base abstract class for entities which will hold definitions for created, last modified by and created,
- * last modified by date.
+ * Base abstract class for entities which will hold definitions for created, last modified, created by,
+ * last modified by attributes.
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
diff --git a/src/main/java/org/securityrat/casemanagement/domain/AccessToken.java b/src/main/java/org/securityrat/casemanagement/domain/AccessToken.java
index 8ee1182..c5fe969 100644
--- a/src/main/java/org/securityrat/casemanagement/domain/AccessToken.java
+++ b/src/main/java/org/securityrat/casemanagement/domain/AccessToken.java
@@ -1,11 +1,10 @@
package org.securityrat.casemanagement.domain;
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import javax.persistence.*;
-import javax.validation.constraints.*;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import java.time.ZonedDateTime;
+import javax.persistence.*;
+import javax.validation.constraints.*;
/**
* A AccessToken.
@@ -17,7 +16,8 @@ public class AccessToken implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
+ @SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@@ -27,15 +27,21 @@ public class AccessToken implements Serializable {
@Column(name = "expiration_date")
private ZonedDateTime expirationDate;
+ @NotNull
+ @Column(name = "salt", nullable = false)
+ private String salt;
+
+ @Column(name = "refresh_token")
+ private String refreshToken;
+
@ManyToOne
- @JsonIgnoreProperties("accessTokens")
private User user;
@ManyToOne
- @JsonIgnoreProperties("accessTokens")
+ @JsonIgnoreProperties(value = { "accessTokens" }, allowSetters = true)
private TicketSystemInstance ticketInstance;
- // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
+ // jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
@@ -44,8 +50,13 @@ public void setId(Long id) {
this.id = id;
}
+ public AccessToken id(Long id) {
+ this.id = id;
+ return this;
+ }
+
public String getToken() {
- return token;
+ return this.token;
}
public AccessToken token(String token) {
@@ -58,7 +69,7 @@ public void setToken(String token) {
}
public ZonedDateTime getExpirationDate() {
- return expirationDate;
+ return this.expirationDate;
}
public AccessToken expirationDate(ZonedDateTime expirationDate) {
@@ -70,12 +81,38 @@ public void setExpirationDate(ZonedDateTime expirationDate) {
this.expirationDate = expirationDate;
}
+ public String getSalt() {
+ return this.salt;
+ }
+
+ public AccessToken salt(String salt) {
+ this.salt = salt;
+ return this;
+ }
+
+ public void setSalt(String salt) {
+ this.salt = salt;
+ }
+
+ public String getRefreshToken() {
+ return this.refreshToken;
+ }
+
+ public AccessToken refreshToken(String refreshToken) {
+ this.refreshToken = refreshToken;
+ return this;
+ }
+
+ public void setRefreshToken(String refreshToken) {
+ this.refreshToken = refreshToken;
+ }
+
public User getUser() {
- return user;
+ return this.user;
}
public AccessToken user(User user) {
- this.user = user;
+ this.setUser(user);
return this;
}
@@ -84,18 +121,19 @@ public void setUser(User user) {
}
public TicketSystemInstance getTicketInstance() {
- return ticketInstance;
+ return this.ticketInstance;
}
public AccessToken ticketInstance(TicketSystemInstance ticketSystemInstance) {
- this.ticketInstance = ticketSystemInstance;
+ this.setTicketInstance(ticketSystemInstance);
return this;
}
public void setTicketInstance(TicketSystemInstance ticketSystemInstance) {
this.ticketInstance = ticketSystemInstance;
}
- // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
+
+ // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
@@ -110,15 +148,19 @@ public boolean equals(Object o) {
@Override
public int hashCode() {
- return 31;
+ // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
+ return getClass().hashCode();
}
+ // prettier-ignore
@Override
public String toString() {
return "AccessToken{" +
"id=" + getId() +
", token='" + getToken() + "'" +
", expirationDate='" + getExpirationDate() + "'" +
+ ", salt='" + getSalt() + "'" +
+ ", refreshToken='" + getRefreshToken() + "'" +
"}";
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/domain/Authority.java b/src/main/java/org/securityrat/casemanagement/domain/Authority.java
index 4d7ada1..0d4cce0 100644
--- a/src/main/java/org/securityrat/casemanagement/domain/Authority.java
+++ b/src/main/java/org/securityrat/casemanagement/domain/Authority.java
@@ -1,13 +1,13 @@
package org.securityrat.casemanagement.domain;
+import java.io.Serializable;
+import java.util.Objects;
+import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
-import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
-import java.io.Serializable;
-import java.util.Objects;
/**
* An authority (a security role) used by Spring Security.
@@ -48,6 +48,7 @@ public int hashCode() {
return Objects.hashCode(name);
}
+ // prettier-ignore
@Override
public String toString() {
return "Authority{" +
diff --git a/src/main/java/org/securityrat/casemanagement/domain/PersistentAuditEvent.java b/src/main/java/org/securityrat/casemanagement/domain/PersistentAuditEvent.java
deleted file mode 100644
index bf997bf..0000000
--- a/src/main/java/org/securityrat/casemanagement/domain/PersistentAuditEvent.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package org.securityrat.casemanagement.domain;
-
-import javax.persistence.*;
-import javax.validation.constraints.NotNull;
-import java.io.Serializable;
-import java.time.Instant;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Persist AuditEvent managed by the Spring Boot actuator.
- *
- * @see org.springframework.boot.actuate.audit.AuditEvent
- */
-@Entity
-@Table(name = "jhi_persistent_audit_event")
-public class PersistentAuditEvent implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "event_id")
- private Long id;
-
- @NotNull
- @Column(nullable = false)
- private String principal;
-
- @Column(name = "event_date")
- private Instant auditEventDate;
-
- @Column(name = "event_type")
- private String auditEventType;
-
- @ElementCollection
- @MapKeyColumn(name = "name")
- @Column(name = "value")
- @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id"))
- private Map data = new HashMap<>();
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getPrincipal() {
- return principal;
- }
-
- public void setPrincipal(String principal) {
- this.principal = principal;
- }
-
- public Instant getAuditEventDate() {
- return auditEventDate;
- }
-
- public void setAuditEventDate(Instant auditEventDate) {
- this.auditEventDate = auditEventDate;
- }
-
- public String getAuditEventType() {
- return auditEventType;
- }
-
- public void setAuditEventType(String auditEventType) {
- this.auditEventType = auditEventType;
- }
-
- public Map getData() {
- return data;
- }
-
- public void setData(Map data) {
- this.data = data;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof PersistentAuditEvent)) {
- return false;
- }
- return id != null && id.equals(((PersistentAuditEvent) o).id);
- }
-
- @Override
- public int hashCode() {
- return 31;
- }
-
- @Override
- public String toString() {
- return "PersistentAuditEvent{" +
- "principal='" + principal + '\'' +
- ", auditEventDate=" + auditEventDate +
- ", auditEventType='" + auditEventType + '\'' +
- '}';
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/domain/TicketSystemInstance.java b/src/main/java/org/securityrat/casemanagement/domain/TicketSystemInstance.java
index 851118d..0028fd6 100644
--- a/src/main/java/org/securityrat/casemanagement/domain/TicketSystemInstance.java
+++ b/src/main/java/org/securityrat/casemanagement/domain/TicketSystemInstance.java
@@ -1,12 +1,11 @@
package org.securityrat.casemanagement.domain;
-import javax.persistence.*;
-import javax.validation.constraints.*;
-
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
-
+import javax.persistence.*;
+import javax.validation.constraints.*;
import org.securityrat.casemanagement.domain.enumeration.TicketSystem;
/**
@@ -19,7 +18,8 @@ public class TicketSystemInstance implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
+ @SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "name")
@@ -34,10 +34,20 @@ public class TicketSystemInstance implements Serializable {
@Column(name = "url", nullable = false)
private String url;
+ @Column(name = "consumer_key")
+ private String consumerKey;
+
+ @Column(name = "client_id")
+ private String clientId;
+
+ @Column(name = "client_secret")
+ private String clientSecret;
+
@OneToMany(mappedBy = "ticketInstance")
+ @JsonIgnoreProperties(value = { "user", "ticketInstance" }, allowSetters = true)
private Set accessTokens = new HashSet<>();
- // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
+ // jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
@@ -46,8 +56,13 @@ public void setId(Long id) {
this.id = id;
}
+ public TicketSystemInstance id(Long id) {
+ this.id = id;
+ return this;
+ }
+
public String getName() {
- return name;
+ return this.name;
}
public TicketSystemInstance name(String name) {
@@ -60,7 +75,7 @@ public void setName(String name) {
}
public TicketSystem getType() {
- return type;
+ return this.type;
}
public TicketSystemInstance type(TicketSystem type) {
@@ -73,7 +88,7 @@ public void setType(TicketSystem type) {
}
public String getUrl() {
- return url;
+ return this.url;
}
public TicketSystemInstance url(String url) {
@@ -85,12 +100,51 @@ public void setUrl(String url) {
this.url = url;
}
+ public String getConsumerKey() {
+ return this.consumerKey;
+ }
+
+ public TicketSystemInstance consumerKey(String consumerKey) {
+ this.consumerKey = consumerKey;
+ return this;
+ }
+
+ public void setConsumerKey(String consumerKey) {
+ this.consumerKey = consumerKey;
+ }
+
+ public String getClientId() {
+ return this.clientId;
+ }
+
+ public TicketSystemInstance clientId(String clientId) {
+ this.clientId = clientId;
+ return this;
+ }
+
+ public void setClientId(String clientId) {
+ this.clientId = clientId;
+ }
+
+ public String getClientSecret() {
+ return this.clientSecret;
+ }
+
+ public TicketSystemInstance clientSecret(String clientSecret) {
+ this.clientSecret = clientSecret;
+ return this;
+ }
+
+ public void setClientSecret(String clientSecret) {
+ this.clientSecret = clientSecret;
+ }
+
public Set getAccessTokens() {
- return accessTokens;
+ return this.accessTokens;
}
public TicketSystemInstance accessTokens(Set accessTokens) {
- this.accessTokens = accessTokens;
+ this.setAccessTokens(accessTokens);
return this;
}
@@ -107,9 +161,16 @@ public TicketSystemInstance removeAccessToken(AccessToken accessToken) {
}
public void setAccessTokens(Set accessTokens) {
+ if (this.accessTokens != null) {
+ this.accessTokens.forEach(i -> i.setTicketInstance(null));
+ }
+ if (accessTokens != null) {
+ accessTokens.forEach(i -> i.setTicketInstance(this));
+ }
this.accessTokens = accessTokens;
}
- // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
+
+ // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
@@ -124,9 +185,11 @@ public boolean equals(Object o) {
@Override
public int hashCode() {
- return 31;
+ // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
+ return getClass().hashCode();
}
+ // prettier-ignore
@Override
public String toString() {
return "TicketSystemInstance{" +
@@ -134,6 +197,9 @@ public String toString() {
", name='" + getName() + "'" +
", type='" + getType() + "'" +
", url='" + getUrl() + "'" +
+ ", consumerKey='" + getConsumerKey() + "'" +
+ ", clientId='" + getClientId() + "'" +
+ ", clientSecret='" + getClientSecret() + "'" +
"}";
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/domain/User.java b/src/main/java/org/securityrat/casemanagement/domain/User.java
index 3a08af7..b781fe4 100644
--- a/src/main/java/org/securityrat/casemanagement/domain/User.java
+++ b/src/main/java/org/securityrat/casemanagement/domain/User.java
@@ -1,23 +1,21 @@
package org.securityrat.casemanagement.domain;
-import org.securityrat.casemanagement.config.Constants;
-
import com.fasterxml.jackson.annotation.JsonIgnore;
-import org.apache.commons.lang3.StringUtils;
-import org.hibernate.annotations.BatchSize;
-
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Locale;
-import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
+import org.hibernate.annotations.BatchSize;
+import org.securityrat.casemanagement.config.Constants;
/**
- * A appUser.
+ * A user.
*/
@Entity
@Table(name = "jhi_user")
@@ -63,9 +61,9 @@ public class User extends AbstractAuditingEntity implements Serializable {
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
- joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
- inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
-
+ joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") },
+ inverseJoinColumns = { @JoinColumn(name = "authority_name", referencedColumnName = "name") }
+ )
@BatchSize(size = 20)
private Set authorities = new HashSet<>();
@@ -118,7 +116,7 @@ public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
- public boolean getActivated() {
+ public boolean isActivated() {
return activated;
}
@@ -155,9 +153,11 @@ public boolean equals(Object o) {
@Override
public int hashCode() {
- return 31;
+ // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
+ return getClass().hashCode();
}
+ // prettier-ignore
@Override
public String toString() {
return "User{" +
diff --git a/src/main/java/org/securityrat/casemanagement/domain/enumeration/AttributeType.java b/src/main/java/org/securityrat/casemanagement/domain/enumeration/AttributeType.java
deleted file mode 100644
index 9993bcf..0000000
--- a/src/main/java/org/securityrat/casemanagement/domain/enumeration/AttributeType.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package org.securityrat.casemanagement.domain.enumeration;
-
-/**
- * The AttributeType enumeration.
- */
-public enum AttributeType {
- FE_TAG, PARAMETER, CATEGORY
-}
diff --git a/src/main/java/org/securityrat/casemanagement/domain/enumeration/ExtensionSection.java b/src/main/java/org/securityrat/casemanagement/domain/enumeration/ExtensionSection.java
deleted file mode 100644
index 1c2ea65..0000000
--- a/src/main/java/org/securityrat/casemanagement/domain/enumeration/ExtensionSection.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.securityrat.casemanagement.domain.enumeration;
-
-public enum ExtensionSection {
- STATUS, ENHANCEMENT
-}
diff --git a/src/main/java/org/securityrat/casemanagement/domain/enumeration/ExtensionType.java b/src/main/java/org/securityrat/casemanagement/domain/enumeration/ExtensionType.java
deleted file mode 100644
index d8258a2..0000000
--- a/src/main/java/org/securityrat/casemanagement/domain/enumeration/ExtensionType.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package org.securityrat.casemanagement.domain.enumeration;
-
-/**
- * The extension type enumeration
- *
- */
-public enum ExtensionType {
- ENUM,FREETEXT
-}
diff --git a/src/main/java/org/securityrat/casemanagement/domain/enumeration/TicketSystem.java b/src/main/java/org/securityrat/casemanagement/domain/enumeration/TicketSystem.java
index 3bd33ee..cb80891 100644
--- a/src/main/java/org/securityrat/casemanagement/domain/enumeration/TicketSystem.java
+++ b/src/main/java/org/securityrat/casemanagement/domain/enumeration/TicketSystem.java
@@ -4,5 +4,5 @@
* The TicketSystem enumeration.
*/
public enum TicketSystem {
- JIRA
+ JIRA,
}
diff --git a/src/main/java/org/securityrat/casemanagement/repository/AccessTokenRepository.java b/src/main/java/org/securityrat/casemanagement/repository/AccessTokenRepository.java
index c0676fa..ba81e06 100644
--- a/src/main/java/org/securityrat/casemanagement/repository/AccessTokenRepository.java
+++ b/src/main/java/org/securityrat/casemanagement/repository/AccessTokenRepository.java
@@ -1,15 +1,16 @@
package org.securityrat.casemanagement.repository;
+import java.util.List;
import org.securityrat.casemanagement.domain.AccessToken;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
-
/**
- * Spring Data repository for the AccessToken entity.
+ * Spring Data SQL repository for the AccessToken entity.
*/
@SuppressWarnings("unused")
@Repository
public interface AccessTokenRepository extends JpaRepository {
-
+ @Query("select accessToken from AccessToken accessToken where accessToken.user.login = ?#{principal.preferredUsername}")
+ List findByUserIsCurrentUser();
}
diff --git a/src/main/java/org/securityrat/casemanagement/repository/AuthorityRepository.java b/src/main/java/org/securityrat/casemanagement/repository/AuthorityRepository.java
index aa346eb..93d350c 100644
--- a/src/main/java/org/securityrat/casemanagement/repository/AuthorityRepository.java
+++ b/src/main/java/org/securityrat/casemanagement/repository/AuthorityRepository.java
@@ -1,11 +1,9 @@
package org.securityrat.casemanagement.repository;
import org.securityrat.casemanagement.domain.Authority;
-
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Spring Data JPA repository for the {@link Authority} entity.
*/
-public interface AuthorityRepository extends JpaRepository {
-}
+public interface AuthorityRepository extends JpaRepository {}
diff --git a/src/main/java/org/securityrat/casemanagement/repository/CustomAuditEventRepository.java b/src/main/java/org/securityrat/casemanagement/repository/CustomAuditEventRepository.java
deleted file mode 100644
index 3da6fc0..0000000
--- a/src/main/java/org/securityrat/casemanagement/repository/CustomAuditEventRepository.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package org.securityrat.casemanagement.repository;
-
-import org.securityrat.casemanagement.config.Constants;
-import org.securityrat.casemanagement.config.audit.AuditEventConverter;
-import org.securityrat.casemanagement.domain.PersistentAuditEvent;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.boot.actuate.audit.AuditEvent;
-import org.springframework.boot.actuate.audit.AuditEventRepository;
-import org.springframework.stereotype.Repository;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.time.Instant;
-import java.util.*;
-
-/**
- * An implementation of Spring Boot's {@link AuditEventRepository}.
- */
-@Repository
-public class CustomAuditEventRepository implements AuditEventRepository {
-
- private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";
-
- /**
- * Should be the same as in Liquibase migration.
- */
- protected static final int EVENT_DATA_COLUMN_MAX_LENGTH = 255;
-
- private final PersistenceAuditEventRepository persistenceAuditEventRepository;
-
- private final AuditEventConverter auditEventConverter;
-
- private final Logger log = LoggerFactory.getLogger(getClass());
-
- public CustomAuditEventRepository(PersistenceAuditEventRepository persistenceAuditEventRepository,
- AuditEventConverter auditEventConverter) {
-
- this.persistenceAuditEventRepository = persistenceAuditEventRepository;
- this.auditEventConverter = auditEventConverter;
- }
-
- @Override
- public List find(String principal, Instant after, String type) {
- Iterable persistentAuditEvents =
- persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type);
- return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
- }
-
- @Override
- @Transactional(propagation = Propagation.REQUIRES_NEW)
- public void add(AuditEvent event) {
- if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
- !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) {
-
- PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
- persistentAuditEvent.setPrincipal(event.getPrincipal());
- persistentAuditEvent.setAuditEventType(event.getType());
- persistentAuditEvent.setAuditEventDate(event.getTimestamp());
- Map eventData = auditEventConverter.convertDataToStrings(event.getData());
- persistentAuditEvent.setData(truncate(eventData));
- persistenceAuditEventRepository.save(persistentAuditEvent);
- }
- }
-
- /**
- * Truncate event data that might exceed column length.
- */
- private Map truncate(Map data) {
- Map results = new HashMap<>();
-
- if (data != null) {
- for (Map.Entry entry : data.entrySet()) {
- String value = entry.getValue();
- if (value != null) {
- int length = value.length();
- if (length > EVENT_DATA_COLUMN_MAX_LENGTH) {
- value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH);
- log.warn("Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.",
- entry.getKey(), length, EVENT_DATA_COLUMN_MAX_LENGTH);
- }
- }
- results.put(entry.getKey(), value);
- }
- }
- return results;
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/repository/PersistenceAuditEventRepository.java b/src/main/java/org/securityrat/casemanagement/repository/PersistenceAuditEventRepository.java
deleted file mode 100644
index 702baaa..0000000
--- a/src/main/java/org/securityrat/casemanagement/repository/PersistenceAuditEventRepository.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package org.securityrat.casemanagement.repository;
-
-import org.securityrat.casemanagement.domain.PersistentAuditEvent;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.Pageable;
-import org.springframework.data.jpa.repository.JpaRepository;
-
-import java.time.Instant;
-import java.util.List;
-
-/**
- * Spring Data JPA repository for the {@link PersistentAuditEvent} entity.
- */
-public interface PersistenceAuditEventRepository extends JpaRepository {
-
- List findByPrincipal(String principal);
-
- List findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principal, Instant after, String type);
-
- Page findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable);
-
- List findByAuditEventDateBefore(Instant before);
-}
diff --git a/src/main/java/org/securityrat/casemanagement/repository/TicketSystemInstanceRepository.java b/src/main/java/org/securityrat/casemanagement/repository/TicketSystemInstanceRepository.java
index 0fbeb99..9973246 100644
--- a/src/main/java/org/securityrat/casemanagement/repository/TicketSystemInstanceRepository.java
+++ b/src/main/java/org/securityrat/casemanagement/repository/TicketSystemInstanceRepository.java
@@ -4,12 +4,9 @@
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
-
/**
- * Spring Data repository for the TicketSystemInstance entity.
+ * Spring Data SQL repository for the TicketSystemInstance entity.
*/
@SuppressWarnings("unused")
@Repository
-public interface TicketSystemInstanceRepository extends JpaRepository {
-
-}
+public interface TicketSystemInstanceRepository extends JpaRepository {}
diff --git a/src/main/java/org/securityrat/casemanagement/repository/UserRepository.java b/src/main/java/org/securityrat/casemanagement/repository/UserRepository.java
index 0b10459..e5c28c7 100644
--- a/src/main/java/org/securityrat/casemanagement/repository/UserRepository.java
+++ b/src/main/java/org/securityrat/casemanagement/repository/UserRepository.java
@@ -1,36 +1,23 @@
package org.securityrat.casemanagement.repository;
+import java.util.List;
+import java.util.Optional;
import org.securityrat.casemanagement.domain.User;
-
import org.springframework.data.domain.Page;
-
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
-import java.util.List;
-import java.util.Optional;
-import java.time.Instant;
-
/**
* Spring Data JPA repository for the {@link User} entity.
*/
@Repository
public interface UserRepository extends JpaRepository {
-
- Optional findOneByEmailIgnoreCase(String email);
-
Optional findOneByLogin(String login);
- @EntityGraph(attributePaths = "authorities")
- Optional findOneWithAuthoritiesById(Long id);
-
@EntityGraph(attributePaths = "authorities")
Optional findOneWithAuthoritiesByLogin(String login);
- @EntityGraph(attributePaths = "authorities")
- Optional findOneWithAuthoritiesByEmailIgnoreCase(String email);
-
- Page findAllByLoginNot(Pageable pageable, String login);
+ Page findAllByIdNotNullAndActivatedIsTrue(Pageable pageable);
}
diff --git a/src/main/java/org/securityrat/casemanagement/security/AuthoritiesConstants.java b/src/main/java/org/securityrat/casemanagement/security/AuthoritiesConstants.java
index 924381d..a6a3a3c 100644
--- a/src/main/java/org/securityrat/casemanagement/security/AuthoritiesConstants.java
+++ b/src/main/java/org/securityrat/casemanagement/security/AuthoritiesConstants.java
@@ -11,6 +11,5 @@ public final class AuthoritiesConstants {
public static final String ANONYMOUS = "ROLE_ANONYMOUS";
- private AuthoritiesConstants() {
- }
+ private AuthoritiesConstants() {}
}
diff --git a/src/main/java/org/securityrat/casemanagement/security/SecurityUtils.java b/src/main/java/org/securityrat/casemanagement/security/SecurityUtils.java
index 19aab77..e1f2f84 100644
--- a/src/main/java/org/securityrat/casemanagement/security/SecurityUtils.java
+++ b/src/main/java/org/securityrat/casemanagement/security/SecurityUtils.java
@@ -1,5 +1,8 @@
package org.securityrat.casemanagement.security;
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
@@ -9,92 +12,80 @@
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
-import java.util.*;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
/**
* Utility class for Spring Security.
*/
public final class SecurityUtils {
- private SecurityUtils() {
- }
+ private SecurityUtils() {}
/**
- * Get the login of the current appUser.
+ * Get the login of the current user.
*
- * @return the login of the current appUser.
+ * @return the login of the current user.
*/
public static Optional getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
- return Optional.ofNullable(securityContext.getAuthentication())
- .map(authentication -> {
- if (authentication.getPrincipal() instanceof UserDetails) {
- UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
- return springSecurityUser.getUsername();
- } else if (authentication instanceof JwtAuthenticationToken) {
- return (String) ((JwtAuthenticationToken)authentication).getToken().getClaims().get("preferred_username");
- } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
- Map attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
- if (attributes.containsKey("preferred_username")) {
- return (String) attributes.get("preferred_username");
- }
- } else if (authentication.getPrincipal() instanceof String) {
- return (String) authentication.getPrincipal();
- }
- return null;
- });
+ return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication()));
+ }
+
+ private static String extractPrincipal(Authentication authentication) {
+ if (authentication == null) {
+ return null;
+ } else if (authentication.getPrincipal() instanceof UserDetails) {
+ UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
+ return springSecurityUser.getUsername();
+ } else if (authentication instanceof JwtAuthenticationToken) {
+ return (String) ((JwtAuthenticationToken) authentication).getToken().getClaims().get("preferred_username");
+ } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
+ Map attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
+ if (attributes.containsKey("preferred_username")) {
+ return (String) attributes.get("preferred_username");
+ }
+ } else if (authentication.getPrincipal() instanceof String) {
+ return (String) authentication.getPrincipal();
+ }
+ return null;
}
/**
- * Check if a appUser is authenticated.
+ * Check if a user is authenticated.
*
- * @return true if the appUser is authenticated, false otherwise.
+ * @return true if the user is authenticated, false otherwise.
*/
public static boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- return authentication != null &&
- getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals);
+ return authentication != null && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals);
}
/**
- * If the current appUser has a specific authority (security role).
- *
- * The name of this method comes from the {@code isUserInRole()} method in the Servlet API.
+ * Checks if the current user has a specific authority.
*
* @param authority the authority to check.
- * @return true if the current appUser has the authority, false otherwise.
+ * @return true if the current user has the authority, false otherwise.
*/
- public static boolean isCurrentUserInRole(String authority) {
+ public static boolean hasCurrentUserThisAuthority(String authority) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- return authentication != null &&
- getAuthorities(authentication).anyMatch(authority::equals);
+ return authentication != null && getAuthorities(authentication).anyMatch(authority::equals);
}
private static Stream getAuthorities(Authentication authentication) {
- Collection extends GrantedAuthority> authorities = authentication instanceof JwtAuthenticationToken ?
- extractAuthorityFromClaims(((JwtAuthenticationToken) authentication).getToken().getClaims())
+ Collection extends GrantedAuthority> authorities = authentication instanceof JwtAuthenticationToken
+ ? extractAuthorityFromClaims(((JwtAuthenticationToken) authentication).getToken().getClaims())
: authentication.getAuthorities();
- return authorities.stream()
- .map(GrantedAuthority::getAuthority);
+ return authorities.stream().map(GrantedAuthority::getAuthority);
}
public static List extractAuthorityFromClaims(Map claims) {
- return mapRolesToGrantedAuthorities(
- getRolesFromClaims(claims));
+ return mapRolesToGrantedAuthorities(getRolesFromClaims(claims));
}
@SuppressWarnings("unchecked")
private static Collection getRolesFromClaims(Map claims) {
- return (Collection) claims.getOrDefault("groups",
- claims.getOrDefault("roles", new ArrayList<>()));
+ return (Collection) claims.getOrDefault("groups", claims.getOrDefault("roles", new ArrayList<>()));
}
private static List mapRolesToGrantedAuthorities(Collection roles) {
- return roles.stream()
- .filter(role -> role.startsWith("ROLE_"))
- .map(SimpleGrantedAuthority::new)
- .collect(Collectors.toList());
+ return roles.stream().filter(role -> role.startsWith("ROLE_")).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/security/SpringSecurityAuditorAware.java b/src/main/java/org/securityrat/casemanagement/security/SpringSecurityAuditorAware.java
index 02b0056..c9e8f34 100644
--- a/src/main/java/org/securityrat/casemanagement/security/SpringSecurityAuditorAware.java
+++ b/src/main/java/org/securityrat/casemanagement/security/SpringSecurityAuditorAware.java
@@ -1,9 +1,7 @@
package org.securityrat.casemanagement.security;
-import org.securityrat.casemanagement.config.Constants;
-
import java.util.Optional;
-
+import org.securityrat.casemanagement.config.Constants;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
@@ -15,6 +13,6 @@ public class SpringSecurityAuditorAware implements AuditorAware {
@Override
public Optional getCurrentAuditor() {
- return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT));
+ return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM));
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/security/oauth2/AudienceValidator.java b/src/main/java/org/securityrat/casemanagement/security/oauth2/AudienceValidator.java
index d403a6b..58c3d9b 100644
--- a/src/main/java/org/securityrat/casemanagement/security/oauth2/AudienceValidator.java
+++ b/src/main/java/org/securityrat/casemanagement/security/oauth2/AudienceValidator.java
@@ -1,5 +1,6 @@
package org.securityrat.casemanagement.security.oauth2;
+import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.core.OAuth2Error;
@@ -8,11 +9,10 @@
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.Assert;
-import java.util.List;
-
public class AudienceValidator implements OAuth2TokenValidator {
+
private final Logger log = LoggerFactory.getLogger(AudienceValidator.class);
- private OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
+ private final OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
private final List allowedAudience;
@@ -23,7 +23,7 @@ public AudienceValidator(List allowedAudience) {
public OAuth2TokenValidatorResult validate(Jwt jwt) {
List audience = jwt.getAudience();
- if(audience.stream().anyMatch(aud -> allowedAudience.contains(aud))) {
+ if (audience.stream().anyMatch(allowedAudience::contains)) {
return OAuth2TokenValidatorResult.success();
} else {
log.warn("Invalid audience: {}", audience);
diff --git a/src/main/java/org/securityrat/casemanagement/security/oauth2/AuthorizationHeaderUtil.java b/src/main/java/org/securityrat/casemanagement/security/oauth2/AuthorizationHeaderUtil.java
index 11cdda4..02a10c1 100644
--- a/src/main/java/org/securityrat/casemanagement/security/oauth2/AuthorizationHeaderUtil.java
+++ b/src/main/java/org/securityrat/casemanagement/security/oauth2/AuthorizationHeaderUtil.java
@@ -6,7 +6,8 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
-
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import org.securityrat.casemanagement.security.oauth2.OAuthIdpTokenResponseDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,9 +32,6 @@
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
@Component
public class AuthorizationHeaderUtil {
@@ -52,9 +50,7 @@ public Optional getAuthorizationHeader() {
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
String name = oauthToken.getName();
String registrationId = oauthToken.getAuthorizedClientRegistrationId();
- OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
- registrationId,
- name);
+ OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(registrationId, name);
if (null == client) {
throw new OAuth2AuthorizationException(new OAuth2Error("access_denied", "The token is expired", null));
@@ -75,7 +71,6 @@ public Optional getAuthorizationHeader() {
String authorizationHeaderValue = String.format("%s %s", tokenType, accessTokenValue);
return Optional.of(authorizationHeaderValue);
}
-
} else if (authentication instanceof JwtAuthenticationToken) {
JwtAuthenticationToken accessToken = (JwtAuthenticationToken) authentication;
String tokenValue = accessToken.getToken().getTokenValue();
@@ -88,11 +83,11 @@ public Optional getAuthorizationHeader() {
private String refreshToken(OAuth2AuthorizedClient client, OAuth2AuthenticationToken oauthToken) {
OAuth2AccessTokenResponse atr = refreshTokenClient(client);
if (atr == null || atr.getAccessToken() == null) {
- log.info("Failed to refresh token for appUser");
+ log.info("Failed to refresh token for user");
return null;
}
- OAuth2RefreshToken refreshToken = atr.getRefreshToken() != null ? atr.getRefreshToken(): client.getRefreshToken();
+ OAuth2RefreshToken refreshToken = atr.getRefreshToken() != null ? atr.getRefreshToken() : client.getRefreshToken();
OAuth2AuthorizedClient updatedClient = new OAuth2AuthorizedClient(
client.getClientRegistration(),
client.getPrincipalName(),
@@ -105,7 +100,6 @@ private String refreshToken(OAuth2AuthorizedClient client, OAuth2AuthenticationT
}
private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) {
-
MultiValueMap formParameters = new LinkedMultiValueMap<>();
formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue());
formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue());
@@ -115,7 +109,10 @@ private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient curr
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(formParameters);
try {
- RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret());
+ RestTemplate r = restTemplate(
+ currentClient.getClientRegistration().getClientId(),
+ currentClient.getClientRegistration().getClientSecret()
+ );
ResponseEntity responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class);
return toOAuth2AccessTokenResponse(responseEntity.getBody());
} catch (OAuth2AuthorizationException e) {
@@ -130,7 +127,8 @@ private OAuth2AccessTokenResponse toOAuth2AccessTokenResponse(OAuthIdpTokenRespo
additionalParameters.put("not-before-policy", oAuthIdpResponse.getNotBefore());
additionalParameters.put("refresh_expires_in", oAuthIdpResponse.getRefreshExpiresIn());
additionalParameters.put("session_state", oAuthIdpResponse.getSessionState());
- return OAuth2AccessTokenResponse.withToken(oAuthIdpResponse.getAccessToken())
+ return OAuth2AccessTokenResponse
+ .withToken(oAuthIdpResponse.getAccessToken())
.expiresIn(oAuthIdpResponse.getExpiresIn())
.refreshToken(oAuthIdpResponse.getRefreshToken())
.scopes(Pattern.compile("\\s").splitAsStream(oAuthIdpResponse.getScope()).collect(Collectors.toSet()))
@@ -141,9 +139,7 @@ private OAuth2AccessTokenResponse toOAuth2AccessTokenResponse(OAuthIdpTokenRespo
private RestTemplate restTemplate(String clientId, String clientSecret) {
return restTemplateBuilder
- .additionalMessageConverters(
- new FormHttpMessageConverter(),
- new OAuth2AccessTokenResponseHttpMessageConverter())
+ .additionalMessageConverters(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter())
.errorHandler(new OAuth2ErrorResponseErrorHandler())
.basicAuthentication(clientId, clientSecret)
.build();
diff --git a/src/main/java/org/securityrat/casemanagement/security/oauth2/JwtAuthorityExtractor.java b/src/main/java/org/securityrat/casemanagement/security/oauth2/JwtGrantedAuthorityConverter.java
similarity index 58%
rename from src/main/java/org/securityrat/casemanagement/security/oauth2/JwtAuthorityExtractor.java
rename to src/main/java/org/securityrat/casemanagement/security/oauth2/JwtGrantedAuthorityConverter.java
index 41cbc55..0d1225f 100644
--- a/src/main/java/org/securityrat/casemanagement/security/oauth2/JwtAuthorityExtractor.java
+++ b/src/main/java/org/securityrat/casemanagement/security/oauth2/JwtGrantedAuthorityConverter.java
@@ -1,21 +1,21 @@
package org.securityrat.casemanagement.security.oauth2;
+import java.util.Collection;
import org.securityrat.casemanagement.security.SecurityUtils;
+import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
-import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.stereotype.Component;
-import java.util.Collection;
-
@Component
-public class JwtAuthorityExtractor extends JwtAuthenticationConverter {
+public class JwtGrantedAuthorityConverter implements Converter> {
- public JwtAuthorityExtractor() {
+ public JwtGrantedAuthorityConverter() {
+ // Bean extracting authority.
}
@Override
- protected Collection extractAuthorities(Jwt jwt) {
+ public Collection convert(Jwt jwt) {
return SecurityUtils.extractAuthorityFromClaims(jwt.getClaims());
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/security/oauth2/OAuthIdpTokenResponseDTO.java b/src/main/java/org/securityrat/casemanagement/security/oauth2/OAuthIdpTokenResponseDTO.java
index f6d1b4d..4dc0a9a 100644
--- a/src/main/java/org/securityrat/casemanagement/security/oauth2/OAuthIdpTokenResponseDTO.java
+++ b/src/main/java/org/securityrat/casemanagement/security/oauth2/OAuthIdpTokenResponseDTO.java
@@ -1,7 +1,6 @@
package org.securityrat.casemanagement.security.oauth2;
import com.fasterxml.jackson.annotation.JsonProperty;
-
import java.io.Serializable;
import java.util.UUID;
@@ -41,7 +40,9 @@ public class OAuthIdpTokenResponseDTO implements Serializable {
@JsonProperty("refresh_expires_in")
private String refreshExpiresIn;
- public OAuthIdpTokenResponseDTO() {}
+ public OAuthIdpTokenResponseDTO() {
+ // Empty constructor for serialization.
+ }
public String getRefreshExpiresIn() {
return refreshExpiresIn;
diff --git a/src/main/java/org/securityrat/casemanagement/service/AuditEventService.java b/src/main/java/org/securityrat/casemanagement/service/AuditEventService.java
deleted file mode 100644
index 4969ab2..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/AuditEventService.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package org.securityrat.casemanagement.service;
-
-import io.github.jhipster.config.JHipsterProperties;
-import org.securityrat.casemanagement.config.audit.AuditEventConverter;
-import org.securityrat.casemanagement.repository.PersistenceAuditEventRepository;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.boot.actuate.audit.AuditEvent;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.Pageable;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.time.Instant;
-import java.time.temporal.ChronoUnit;
-import java.util.Optional;
-
-/**
- * Service for managing audit events.
- *
- * This is the default implementation to support SpringBoot Actuator {@code AuditEventRepository}.
- */
-@Service
-@Transactional
-public class AuditEventService {
-
- private final Logger log = LoggerFactory.getLogger(AuditEventService.class);
-
- private final JHipsterProperties jHipsterProperties;
-
- private final PersistenceAuditEventRepository persistenceAuditEventRepository;
-
- private final AuditEventConverter auditEventConverter;
-
- public AuditEventService(
- PersistenceAuditEventRepository persistenceAuditEventRepository,
- AuditEventConverter auditEventConverter, JHipsterProperties jhipsterProperties) {
-
- this.persistenceAuditEventRepository = persistenceAuditEventRepository;
- this.auditEventConverter = auditEventConverter;
- this.jHipsterProperties = jhipsterProperties;
- }
-
- /**
- * Old audit events should be automatically deleted after 30 days.
- *
- * This is scheduled to get fired at 12:00 (am).
- */
- @Scheduled(cron = "0 0 12 * * ?")
- public void removeOldAuditEvents() {
- persistenceAuditEventRepository
- .findByAuditEventDateBefore(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod(), ChronoUnit.DAYS))
- .forEach(auditEvent -> {
- log.debug("Deleting audit data {}", auditEvent);
- persistenceAuditEventRepository.delete(auditEvent);
- });
- }
-
- public Page findAll(Pageable pageable) {
- return persistenceAuditEventRepository.findAll(pageable)
- .map(auditEventConverter::convertToAuditEvent);
- }
-
- public Page findByDates(Instant fromDate, Instant toDate, Pageable pageable) {
- return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable)
- .map(auditEventConverter::convertToAuditEvent);
- }
-
- public Optional find(Long id) {
- return persistenceAuditEventRepository.findById(id)
- .map(auditEventConverter::convertToAuditEvent);
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/RequirementManagementAPIService.java b/src/main/java/org/securityrat/casemanagement/service/RequirementManagementAPIService.java
deleted file mode 100644
index 2fa46d4..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/RequirementManagementAPIService.java
+++ /dev/null
@@ -1,427 +0,0 @@
-package org.securityrat.casemanagement.service;
-
-import org.securityrat.casemanagement.client.RequirementManagementServiceClient;
-import org.securityrat.casemanagement.domain.enumeration.AttributeType;
-import org.securityrat.casemanagement.domain.enumeration.ExtensionSection;
-import org.securityrat.casemanagement.service.dto.*;
-import org.securityrat.casemanagement.service.exceptions.IDNotFoundException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.*;
-import java.util.stream.Collectors;
-
-@Service
-public class RequirementManagementAPIService {
-
- private RequirementManagementServiceClient requirementManagementServiceClient;
-
- private final Logger log = LoggerFactory.getLogger(RequirementManagementAPIService.class);
-
- @Autowired
- public RequirementManagementAPIService(RequirementManagementServiceClient requirementManagementServiceClient) {
- this.requirementManagementServiceClient = requirementManagementServiceClient;
- }
-
- public List getActiveRequirementSets() {
- return this.requirementManagementServiceClient.getRequirementSetsFromRequirementManagement(true);
- }
-
- public List getActiveAttributes(Long requirementSetId) {
- return getActiveAttributes(requirementSetId, null);
- }
-
- public List getActiveAttributeKeys(String type) {
- return this.requirementManagementServiceClient.getAttributeKeysFromRequirementManagement(true, type);
- }
-
- /**
- * Get active attributes in a given requirement set and with attributes key type
- * present in a given list of types
- *
- * @param requirementSetId the requirement set id
- * @param types the list of attribute key types
- * @return a list of active attributes
- */
- public List getActiveAttributes(Long requirementSetId, List types) {
- List result = this.requirementManagementServiceClient
- .getAttributesFromRequirementManagement(true);
-
- if (result != null) {
- result.removeIf(attributeDTO -> attributeDTO.getAttributeKey() != null
- && !attributeDTO.getAttributeKey().getRequirementSet().getId().equals(requirementSetId));
- result.removeIf(attributeDTO -> attributeDTO.getAttributeKey() != null
- && !attributeDTO.getAttributeKey().isActive()); // include only attributes with active attributeKey
- // or no attributeKey
- if (types != null && !types.isEmpty())
- result.removeIf(attributeDTO -> attributeDTO.getAttributeKey() != null
- && !types.contains(attributeDTO.getAttributeKey().getType()));
- }
-
- return unflattenAttributeHierarchy(result);
- }
-
- public List getAttributesByIds(List ids) {
- List result = this.requirementManagementServiceClient.getAllAttributesFromRequirementManagement();
-
- if (result != null)
- result.removeIf(attributeDTO -> !ids.contains(attributeDTO.getId()));
-
- if (result != null && result.size() < ids.size())
- throw new IDNotFoundException(); // 404 if user requested non-existent ids
-
- if (result != null) {
- result.removeIf(attributeDTO -> !attributeDTO.isActive());
- result.removeIf(attributeDTO -> attributeDTO.getAttributeKey() != null
- && !attributeDTO.getAttributeKey().isActive()); // include only attributes with active attributeKey
- // or no attributeKey
- }
-
- return unflattenAttributeHierarchy(result);
- }
-
- private List unflattenAttributeHierarchy(List attributeDTOList) {
- List result = new LinkedList<>(attributeDTOList);
-
- // generate a HashMap to map parent relation in result
- HashMap> toTreeHelper = new HashMap<>(); // key: parentId, value: list of children
- for (AttributeDTO attributeDTO : result) {
- if (attributeDTO.getParent() != null) {
- Long parentId = attributeDTO.getParent().getId();
- if (parentId != null) {
- toTreeHelper.putIfAbsent(parentId, new LinkedList<>());
- toTreeHelper.get(parentId).add(attributeDTO);
- }
- }
- }
-
- // move children to their parent's list of children (but only if result contains
- // both child and parent)
- List toRemove = new LinkedList<>();
- for (AttributeDTO possibleParent : result) {
- List childAttributes = toTreeHelper.get(possibleParent.getId());
- if (childAttributes != null) {
- for (AttributeDTO childAttribute : childAttributes) {
- if (result.contains(childAttribute)) {
-
- if (possibleParent.getChildren() == null) {
- possibleParent.setChildren(new LinkedList<>());
- }
- possibleParent.getChildren().add(childAttribute);
- toRemove.add(childAttribute);
- }
- }
- }
- }
-
- // in case there are cyclic relations this will remove too many elements
- result.removeAll(toRemove);
-
- return result;
- }
-
- /**
- * Restructure the given list of attributes to be conform with the
- * {@link GenericAttributeGatewayDTO}
- *
- * @param attributes list of attributes
- * @return the generated restructured list
- */
- public List generateGatewayAttributeDTO(List attributes) {
- List genericGatewayAttributes = new ArrayList<>();
- for (AttributeDTO attrDto : attributes) {
- // Checks whether the attribute key is already in array
- List foundAttributeKeys = genericGatewayAttributes.stream()
- .filter(x -> x.getId().equals(attrDto.getAttributeKey().getId())).collect(Collectors.toList());
- GenericAttributeGatewayDTO genericAttribute;
-
- if (foundAttributeKeys.isEmpty()) {
- // add a new entry to result array
- if (attrDto.getAttributeKey() != null) {
- genericAttribute = new GenericAttributeGatewayDTO(attrDto.getAttributeKey().getId(),
- attrDto.getAttributeKey().getName(), attrDto.getAttributeKey().getType(),
- attrDto.getAttributeKey().getDescription(), attrDto.getAttributeKey().getShowOrder());
- List values = new ArrayList<>();
- values.add(attrDto);
- genericAttribute.setValues(values);
- genericGatewayAttributes.add(genericAttribute);
- }
- } else {
- // update the values array (attributes list for particular attribute key)
- genericAttribute = foundAttributeKeys.get(0);
- genericAttribute.getValues().add(attrDto);
- }
- }
- return genericGatewayAttributes;
- }
-
- public List getActiveExtensionKeys(Long requirementSetId) {
- List activeExtensionKeys = this.requirementManagementServiceClient
- .getAllExtensionKeysFromRequirementManagement(true);
- activeExtensionKeys.removeIf(ex -> !ex.getRequirementSet().getId().equals(requirementSetId));
-
- if (activeExtensionKeys.isEmpty()) {
- log.error("Empty list of extension key to requirementSetId {}", requirementSetId);
- throw new IDNotFoundException();
- }
-
- return activeExtensionKeys;
- }
-
- public List getActiveExtensionForReqStructure(Long requirementSetId) {
- List result = this.requirementManagementServiceClient
- .getAllExtensionsFromRequirementManagement(true);
-
- result.removeIf(x -> !x.getExtensionKey().getRequirementSet().getId().equals(requirementSetId));
-
- return result;
- }
-
- public RequirementStructureDTO generateRequirementStructureDTO(List extensionKeys,
- List extensions) {
-
- RequirementStructureDTO result = new RequirementStructureDTO(true);
-
- for (ExtensionKeyDTO exKey : extensionKeys) {
- switch (exKey.getSection()) {
- case ENHANCEMENT:
- EnhancementForReqStructureDTO enhacement = new EnhancementForReqStructureDTO(exKey);
- result.getEnhancements().add(enhacement);
- break;
-
- case STATUS:
- StatusForReqStructureDTO status = new StatusForReqStructureDTO(exKey);
- List statusValues = extensions.stream()
- .filter(ex -> ex.getExtensionKey().getId().equals(exKey.getId())).collect(Collectors.toList());
- for (GenericExtensionDTO ex : statusValues) {
- ExtensionReqStructureDTO value = new ExtensionReqStructureDTO(ex);
- status.getValues().add(value);
- }
- result.getStatus().add(status);
- break;
-
- default:
- break;
- }
- }
- return result;
- }
-
- /**
- * Adds a AttributeType to the RequirementDTO depending on a given AttributeDTO
- *
- * @param requirement RequirementDTO we want to add the AttributeType
- * @param attributeKey AttributeKey we use to find out the AttributeType
- */
- private void addAttributeTypesToRequirement(RequirementDTO requirement, AttributeKeyDTO attributeKey) {
-
- switch (attributeKey.getType()) {
- case FE_TAG:
- if (requirement.getFeTags() == null) {
- requirement.setFeTags(new ArrayList<>());
- }
- if (!requirement.getFeTags().contains(attributeKey.getId())) {
- requirement.getFeTags().add(attributeKey.getId());
- }
- break;
-
- case PARAMETER:
- if (requirement.getParameters() == null) {
- requirement.setParameters(new ArrayList<>());
- }
- if (!requirement.getParameters().contains(attributeKey.getId())) {
-
- requirement.getParameters().add(attributeKey.getId());
- }
-
- break;
-
- case CATEGORY:
- requirement.setCatergoryId(attributeKey.getId());
- break;
- }
- }
-
- /**
- * Adds Extensions to the RequirementDTO depending on a given ExtensionDTO
- */
-
- private void addExtensionsToRequirement(RequirementDTO requirement, ExtensionReqDTO extension) {
- ExtensionSection extensionType = extension.getExtensionKey().getSection();
- if (extensionType == ExtensionSection.STATUS) {
- boolean extensionKeyFound = false;
- boolean extensionFound = false;
-
- if (requirement.getStatus() == null) {
- requirement.setStatus(new ArrayList<>());
- }
-
- // search if we have already have the extension Key in Our list
- for (StatusForReqDTO status : requirement.getStatus()) {
- if (status.getKeyId().equals(extension.getExtensionKey().getId())) {
- extensionKeyFound = true;
- break;
- }
- }
-
- // if we didn't find it yet we add the Extension and the extensionKey
- if (!extensionKeyFound) {
- StatusForReqDTO tempStatus = new StatusForReqDTO();
- tempStatus.setKeyId(extension.getExtensionKey().getId());
- tempStatus.setValues(new ArrayList<>());
- tempStatus.getValues().add(extension.getId());
- requirement.getStatus().add(tempStatus);
- } else {
-
- // if we already have the extensionKey in our list, we need to check if we
- // have all extension with the extensiionKey
- for (StatusForReqDTO status : requirement.getStatus()) {
- if (status.getKeyId().equals(extension.getExtensionKey().getId())) {
- for (Long value : status.getValues()) {
- if (extension.getId().equals(value)) {
- extensionFound = true;
- break;
- }
- }
- if (!extensionFound) {
- // if the extension isn't in the list we add it
- status.getValues().add(extension.getId());
- }
- }
- }
- }
-
- } else if (extensionType == ExtensionSection.ENHANCEMENT) {
- boolean enhancementExtensionKeyFound = false;
- boolean enhancementExtensionFound = false;
-
- if (requirement.getEnhancements() == null) {
- requirement.setEnhancements(new ArrayList<>());
- }
-
- // search if we have already have the extension Key in Our list
- for (EnhancementForReqDTO enhancement : requirement.getEnhancements()) {
- if (enhancement.getKeyId().equals(extension.getExtensionKey().getId())) {
- enhancementExtensionKeyFound = true;
- break;
- }
- }
- // if we didn't find it yet we add the Extension and the extensionKey.
- // before adding we build up the content
- if (!enhancementExtensionKeyFound) {
- EnhancementForReqDTO tempEnhancement = new EnhancementForReqDTO();
- GenericExtensionDTO tempExtension = new GenericExtensionDTO();
-
- tempEnhancement.setKeyId(extension.getExtensionKey().getId());
- tempEnhancement.setContents(new ArrayList<>());
-
- tempExtension.setId(extension.getId());
- tempExtension.setShowOrder(extension.getShowOrder());
- tempExtension.setContent(extension.getContent());
-
- tempEnhancement.getContents().add(tempExtension);
-
- requirement.getEnhancements().add(tempEnhancement);
-
- } else {
- // if we already have the extensionKey in our list, we need to check if we
- // have all extension with the extensiionKey
- for (EnhancementForReqDTO enhancement : requirement.getEnhancements()) {
-
- if (enhancement.getKeyId().equals(extension.getExtensionKey().getId())) {
- for (GenericExtensionDTO extensionWithoutDescDTO : enhancement.getContents()) {
- if (extension.getId().equals(extensionWithoutDescDTO.getId())) {
- enhancementExtensionFound = true;
- break;
- }
- }
- if (!enhancementExtensionFound) {
- // if the extension isn't in the list we add it
- // before adding we build up the extension
- EnhancementForReqDTO tempEnhancement = new EnhancementForReqDTO();
- GenericExtensionDTO tempExtension = new GenericExtensionDTO();
-
- tempEnhancement.setKeyId(extension.getExtensionKey().getId());
- tempExtension.setId(extension.getId());
- tempExtension.setContent(extension.getContent());
- tempExtension.setShowOrder(extension.getShowOrder());
-
- enhancement.getContents().add(tempExtension);
- }
- }
- }
- }
- }
- }
-
- /**
- * Return a List of Requirements which have requested conditions.
- *
- * @param requirementSetId Id of RequirementSet we want to search for the Requirement
- * @param parameters Id of Parameters the Requirement
- * @return RequirementsDTO which has all the requested conditions
- */
- public List getActiveRequirements(Long requirementSetId, List parameters) {
- // TODO: currently we only build up the requirements without paying attention to the parameters
-
- HashSet skeletonHashSet = new HashSet<>();
- HashSet attributeHashSet = new HashSet<>();
- HashSet extensionHashSet = new HashSet<>();
- HashSet attributeKeyHashSet = new HashSet<>();
- HashSet extensionKeyHashSet = new HashSet<>();
- List result = new ArrayList<>();
-
- List skAtExDTOs = this.requirementManagementServiceClient
- .getAllSkAtExFromRequirementManagement(true);
- skAtExDTOs.removeIf(skAtExDTO -> !skAtExDTO.getSkeleton().getRequirementSet().getId().equals(requirementSetId));
-
- for (SkAtExDTO skAtExDTO : skAtExDTOs) {
- if (skAtExDTO.getSkeleton() != null) {
- skeletonHashSet.add(skAtExDTO.getSkeleton());
- }
-
- if (skAtExDTO.getAttribute() != null) {
- attributeHashSet.add(skAtExDTO.getAttribute());
- }
-
- if (skAtExDTO.getAttribute() != null && skAtExDTO.getAttribute().getAttributeKey() != null) {
- attributeKeyHashSet.add(skAtExDTO.getAttribute().getAttributeKey());
- }
-
- if (skAtExDTO.getExtension() != null && skAtExDTO.getExtension().getExtensionKey() != null) {
- extensionKeyHashSet.add(skAtExDTO.getExtension().getExtensionKey());
- }
-
- if (skAtExDTO.getExtension() != null) {
- extensionHashSet.add(skAtExDTO.getExtension());
- }
- }
-
- for (SkeletonDTO skeletonDTO : skeletonHashSet) {
- RequirementDTO tempRequirement = new RequirementDTO();
- tempRequirement.setId(skeletonDTO.getId());
- tempRequirement.setName(skeletonDTO.getName());
- tempRequirement.setDescription(skeletonDTO.getDescription());
- tempRequirement.setShowOrder(skeletonDTO.getShowOrder());
-
- for (SkAtExDTO skAtExDTO : skAtExDTOs) {
- if (skAtExDTO.getSkeleton().getId().equals(skeletonDTO.getId())) {
- if (skAtExDTO.getAttribute() != null && skAtExDTO.getAttribute().getAttributeKey() != null) {
- addAttributeTypesToRequirement(tempRequirement, skAtExDTO.getAttribute().getAttributeKey());
- }
-
- if (skAtExDTO.getExtension() != null && skAtExDTO.getExtension().getExtensionKey() != null) {
- addExtensionsToRequirement(tempRequirement, skAtExDTO.getExtension());
- }
- }
- }
-
- result.add(tempRequirement);
- }
-
- return result;
- }
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/UserService.java b/src/main/java/org/securityrat/casemanagement/service/UserService.java
index 567bbdf..ed46403 100644
--- a/src/main/java/org/securityrat/casemanagement/service/UserService.java
+++ b/src/main/java/org/securityrat/casemanagement/service/UserService.java
@@ -1,13 +1,16 @@
package org.securityrat.casemanagement.service;
+import java.time.Instant;
+import java.util.*;
+import java.util.stream.Collectors;
import org.securityrat.casemanagement.config.Constants;
import org.securityrat.casemanagement.domain.Authority;
import org.securityrat.casemanagement.domain.User;
import org.securityrat.casemanagement.repository.AuthorityRepository;
import org.securityrat.casemanagement.repository.UserRepository;
import org.securityrat.casemanagement.security.SecurityUtils;
+import org.securityrat.casemanagement.service.dto.AdminUserDTO;
import org.securityrat.casemanagement.service.dto.UserDTO;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
@@ -19,10 +22,6 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
-import java.time.Instant;
-import java.util.*;
-import java.util.stream.Collectors;
-
/**
* Service class for managing users.
*/
@@ -32,113 +31,70 @@ public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
- private final UserRepository appUserRepository;
+ private final UserRepository userRepository;
private final AuthorityRepository authorityRepository;
- public UserService(UserRepository appUserRepository, AuthorityRepository authorityRepository) {
- this.appUserRepository = appUserRepository;
+ public UserService(UserRepository userRepository, AuthorityRepository authorityRepository) {
+ this.userRepository = userRepository;
this.authorityRepository = authorityRepository;
}
/**
- * Update basic information (first name, last name, email, language) for the current appUser.
+ * Update basic information (first name, last name, email, language) for the current user.
*
- * @param firstName first name of appUser.
- * @param lastName last name of appUser.
- * @param email email id of appUser.
+ * @param firstName first name of user.
+ * @param lastName last name of user.
+ * @param email email id of user.
* @param langKey language key.
- * @param imageUrl image URL of appUser.
+ * @param imageUrl image URL of user.
*/
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
- SecurityUtils.getCurrentUserLogin()
- .flatMap(appUserRepository::findOneByLogin)
- .ifPresent(appUser -> {
- appUser.setFirstName(firstName);
- appUser.setLastName(lastName);
- if (email != null) {
- appUser.setEmail(email.toLowerCase());
- }
- appUser.setLangKey(langKey);
- appUser.setImageUrl(imageUrl);
- log.debug("Changed Information for User: {}", appUser);
- });
- }
-
- /**
- * Update all information for a specific appUser, and return the modified appUser.
- *
- * @param userDTO appUser to update.
- * @return updated appUser.
- */
- public Optional updateUser(UserDTO userDTO) {
- return Optional.of(appUserRepository
- .findById(userDTO.getId()))
- .filter(Optional::isPresent)
- .map(Optional::get)
- .map(appUser -> {
- appUser.setLogin(userDTO.getLogin().toLowerCase());
- appUser.setFirstName(userDTO.getFirstName());
- appUser.setLastName(userDTO.getLastName());
- if (userDTO.getEmail() != null) {
- appUser.setEmail(userDTO.getEmail().toLowerCase());
+ SecurityUtils
+ .getCurrentUserLogin()
+ .flatMap(userRepository::findOneByLogin)
+ .ifPresent(
+ user -> {
+ user.setFirstName(firstName);
+ user.setLastName(lastName);
+ if (email != null) {
+ user.setEmail(email.toLowerCase());
+ }
+ user.setLangKey(langKey);
+ user.setImageUrl(imageUrl);
+ log.debug("Changed Information for User: {}", user);
}
- appUser.setImageUrl(userDTO.getImageUrl());
- appUser.setActivated(userDTO.isActivated());
- appUser.setLangKey(userDTO.getLangKey());
- Set managedAuthorities = appUser.getAuthorities();
- managedAuthorities.clear();
- userDTO.getAuthorities().stream()
- .map(authorityRepository::findById)
- .filter(Optional::isPresent)
- .map(Optional::get)
- .forEach(managedAuthorities::add);
- log.debug("Changed Information for User: {}", appUser);
- return appUser;
- })
- .map(UserDTO::new);
- }
-
- public void deleteUser(String login) {
- appUserRepository.findOneByLogin(login).ifPresent(appUser -> {
- appUserRepository.delete(appUser);
- log.debug("Deleted User: {}", appUser);
- });
+ );
}
@Transactional(readOnly = true)
- public Page getAllManagedUsers(Pageable pageable) {
- return appUserRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
+ public Page getAllManagedUsers(Pageable pageable) {
+ return userRepository.findAll(pageable).map(AdminUserDTO::new);
}
@Transactional(readOnly = true)
- public Optional getUserWithAuthoritiesByLogin(String login) {
- return appUserRepository.findOneWithAuthoritiesByLogin(login);
+ public Page getAllPublicUsers(Pageable pageable) {
+ return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new);
}
@Transactional(readOnly = true)
- public Optional getUserWithAuthorities(Long id) {
- return appUserRepository.findOneWithAuthoritiesById(id);
- }
-
- @Transactional(readOnly = true)
- public Optional getUserWithAuthorities() {
- return SecurityUtils.getCurrentUserLogin().flatMap(appUserRepository::findOneWithAuthoritiesByLogin);
+ public Optional getUserWithAuthoritiesByLogin(String login) {
+ return userRepository.findOneWithAuthoritiesByLogin(login);
}
/**
* Gets a list of all the authorities.
* @return a list of all the authorities.
*/
+ @Transactional(readOnly = true)
public List getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
}
- private User syncUserWithIdP(Map details, User appUser) {
- // save authorities in to sync appUser roles/groups between IdP and JHipster's local database
+ private User syncUserWithIdP(Map details, User user) {
+ // save authorities in to sync user roles/groups between IdP and JHipster's local database
Collection dbAuthorities = getAuthorities();
- Collection userAuthorities =
- appUser.getAuthorities().stream().map(Authority::getName).collect(Collectors.toList());
+ Collection userAuthorities = user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toList());
for (String authority : userAuthorities) {
if (!dbAuthorities.contains(authority)) {
log.debug("Saving authority '{}' in local database", authority);
@@ -148,38 +104,37 @@ private User syncUserWithIdP(Map details, User appUser) {
}
}
// save account in to sync users between IdP and JHipster's local database
- Optional existingUser = appUserRepository.findOneByLogin(appUser.getLogin());
+ Optional existingUser = userRepository.findOneByLogin(user.getLogin());
if (existingUser.isPresent()) {
// if IdP sends last updated information, use it to determine if an update should happen
if (details.get("updated_at") != null) {
Instant dbModifiedDate = existingUser.get().getLastModifiedDate();
- Instant idpModifiedDate = new Date(Long.valueOf((Integer) details.get("updated_at"))).toInstant();
+ Instant idpModifiedDate = (Instant) details.get("updated_at");
if (idpModifiedDate.isAfter(dbModifiedDate)) {
- log.debug("Updating appUser '{}' in local database", appUser.getLogin());
- updateUser(appUser.getFirstName(), appUser.getLastName(), appUser.getEmail(),
- appUser.getLangKey(), appUser.getImageUrl());
+ log.debug("Updating user '{}' in local database", user.getLogin());
+ updateUser(user.getFirstName(), user.getLastName(), user.getEmail(), user.getLangKey(), user.getImageUrl());
}
// no last updated info, blindly update
} else {
- log.debug("Updating appUser '{}' in local database", appUser.getLogin());
- updateUser(appUser.getFirstName(), appUser.getLastName(), appUser.getEmail(),
- appUser.getLangKey(), appUser.getImageUrl());
+ log.debug("Updating user '{}' in local database", user.getLogin());
+ updateUser(user.getFirstName(), user.getLastName(), user.getEmail(), user.getLangKey(), user.getImageUrl());
}
} else {
- log.debug("Saving appUser '{}' in local database", appUser.getLogin());
- appUserRepository.save(appUser);
+ log.debug("Saving user '{}' in local database", user.getLogin());
+ userRepository.save(user);
}
- return appUser;
+ return user;
}
/**
- * Returns the appUser from an OAuth 2.0 login or resource server with JWT.
- * Synchronizes the appUser in the local repository.
+ * Returns the user from an OAuth 2.0 login or resource server with JWT.
+ * Synchronizes the user in the local repository.
*
* @param authToken the authentication token.
- * @return the appUser from the authentication.
+ * @return the user from the authentication.
*/
- public UserDTO getUserFromAuthentication(AbstractAuthenticationToken authToken) {
+ @Transactional
+ public AdminUserDTO getUserFromAuthentication(AbstractAuthenticationToken authToken) {
Map attributes;
if (authToken instanceof OAuth2AuthenticationToken) {
attributes = ((OAuth2AuthenticationToken) authToken).getPrincipal().getAttributes();
@@ -188,65 +143,72 @@ public UserDTO getUserFromAuthentication(AbstractAuthenticationToken authToken)
} else {
throw new IllegalArgumentException("AuthenticationToken is not OAuth2 or JWT!");
}
- User appUser = getUser(attributes);
- appUser.setAuthorities(authToken.getAuthorities().stream()
- .map(GrantedAuthority::getAuthority)
- .map(authority -> {
- Authority auth = new Authority();
- auth.setName(authority);
- return auth;
- })
- .collect(Collectors.toSet()));
- return new UserDTO(syncUserWithIdP(attributes, appUser));
+ User user = getUser(attributes);
+ user.setAuthorities(
+ authToken
+ .getAuthorities()
+ .stream()
+ .map(GrantedAuthority::getAuthority)
+ .map(
+ authority -> {
+ Authority auth = new Authority();
+ auth.setName(authority);
+ return auth;
+ }
+ )
+ .collect(Collectors.toSet())
+ );
+ return new AdminUserDTO(syncUserWithIdP(attributes, user));
}
private static User getUser(Map details) {
- User appUser = new User();
+ User user = new User();
+ Boolean activated = Boolean.TRUE;
// handle resource server JWT, where sub claim is email and uid is ID
if (details.get("uid") != null) {
- appUser.setId((String) details.get("uid"));
- appUser.setLogin((String) details.get("sub"));
+ user.setId((String) details.get("uid"));
+ user.setLogin((String) details.get("sub"));
} else {
- appUser.setId((String) details.get("sub"));
+ user.setId((String) details.get("sub"));
}
if (details.get("preferred_username") != null) {
- appUser.setLogin(((String) details.get("preferred_username")).toLowerCase());
- } else if (appUser.getLogin() == null) {
- appUser.setLogin(appUser.getId());
+ user.setLogin(((String) details.get("preferred_username")).toLowerCase());
+ } else if (user.getLogin() == null) {
+ user.setLogin(user.getId());
}
if (details.get("given_name") != null) {
- appUser.setFirstName((String) details.get("given_name"));
+ user.setFirstName((String) details.get("given_name"));
}
if (details.get("family_name") != null) {
- appUser.setLastName((String) details.get("family_name"));
+ user.setLastName((String) details.get("family_name"));
}
if (details.get("email_verified") != null) {
- appUser.setActivated((Boolean) details.get("email_verified"));
+ activated = (Boolean) details.get("email_verified");
}
if (details.get("email") != null) {
- appUser.setEmail(((String) details.get("email")).toLowerCase());
+ user.setEmail(((String) details.get("email")).toLowerCase());
} else {
- appUser.setEmail((String) details.get("sub"));
+ user.setEmail((String) details.get("sub"));
}
if (details.get("langKey") != null) {
- appUser.setLangKey((String) details.get("langKey"));
+ user.setLangKey((String) details.get("langKey"));
} else if (details.get("locale") != null) {
// trim off country code if it exists
String locale = (String) details.get("locale");
if (locale.contains("_")) {
- locale = locale.substring(0, locale.indexOf("_"));
+ locale = locale.substring(0, locale.indexOf('_'));
} else if (locale.contains("-")) {
- locale = locale.substring(0, locale.indexOf("-"));
+ locale = locale.substring(0, locale.indexOf('-'));
}
- appUser.setLangKey(locale.toLowerCase());
+ user.setLangKey(locale.toLowerCase());
} else {
// set langKey to default if not specified by IdP
- appUser.setLangKey(Constants.DEFAULT_LANGUAGE);
+ user.setLangKey(Constants.DEFAULT_LANGUAGE);
}
if (details.get("picture") != null) {
- appUser.setImageUrl((String) details.get("picture"));
+ user.setImageUrl((String) details.get("picture"));
}
- appUser.setActivated(true);
- return appUser;
+ user.setActivated(activated);
+ return user;
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/AdminUserDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/AdminUserDTO.java
new file mode 100644
index 0000000..ad289bd
--- /dev/null
+++ b/src/main/java/org/securityrat/casemanagement/service/dto/AdminUserDTO.java
@@ -0,0 +1,193 @@
+package org.securityrat.casemanagement.service.dto;
+
+import java.time.Instant;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.validation.constraints.*;
+import org.securityrat.casemanagement.config.Constants;
+import org.securityrat.casemanagement.domain.Authority;
+import org.securityrat.casemanagement.domain.User;
+
+/**
+ * A DTO representing a user, with his authorities.
+ */
+public class AdminUserDTO {
+
+ private String id;
+
+ @NotBlank
+ @Pattern(regexp = Constants.LOGIN_REGEX)
+ @Size(min = 1, max = 50)
+ private String login;
+
+ @Size(max = 50)
+ private String firstName;
+
+ @Size(max = 50)
+ private String lastName;
+
+ @Email
+ @Size(min = 5, max = 254)
+ private String email;
+
+ @Size(max = 256)
+ private String imageUrl;
+
+ private boolean activated = false;
+
+ @Size(min = 2, max = 10)
+ private String langKey;
+
+ private String createdBy;
+
+ private Instant createdDate;
+
+ private String lastModifiedBy;
+
+ private Instant lastModifiedDate;
+
+ private Set authorities;
+
+ public AdminUserDTO() {
+ // Empty constructor needed for Jackson.
+ }
+
+ public AdminUserDTO(User user) {
+ this.id = user.getId();
+ this.login = user.getLogin();
+ this.firstName = user.getFirstName();
+ this.lastName = user.getLastName();
+ this.email = user.getEmail();
+ this.activated = user.isActivated();
+ this.imageUrl = user.getImageUrl();
+ this.langKey = user.getLangKey();
+ this.createdBy = user.getCreatedBy();
+ this.createdDate = user.getCreatedDate();
+ this.lastModifiedBy = user.getLastModifiedBy();
+ this.lastModifiedDate = user.getLastModifiedDate();
+ this.authorities = user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toSet());
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getLogin() {
+ return login;
+ }
+
+ public void setLogin(String login) {
+ this.login = login;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getImageUrl() {
+ return imageUrl;
+ }
+
+ public void setImageUrl(String imageUrl) {
+ this.imageUrl = imageUrl;
+ }
+
+ public boolean isActivated() {
+ return activated;
+ }
+
+ public void setActivated(boolean activated) {
+ this.activated = activated;
+ }
+
+ public String getLangKey() {
+ return langKey;
+ }
+
+ public void setLangKey(String langKey) {
+ this.langKey = langKey;
+ }
+
+ public String getCreatedBy() {
+ return createdBy;
+ }
+
+ public void setCreatedBy(String createdBy) {
+ this.createdBy = createdBy;
+ }
+
+ public Instant getCreatedDate() {
+ return createdDate;
+ }
+
+ public void setCreatedDate(Instant createdDate) {
+ this.createdDate = createdDate;
+ }
+
+ public String getLastModifiedBy() {
+ return lastModifiedBy;
+ }
+
+ public void setLastModifiedBy(String lastModifiedBy) {
+ this.lastModifiedBy = lastModifiedBy;
+ }
+
+ public Instant getLastModifiedDate() {
+ return lastModifiedDate;
+ }
+
+ public void setLastModifiedDate(Instant lastModifiedDate) {
+ this.lastModifiedDate = lastModifiedDate;
+ }
+
+ public Set getAuthorities() {
+ return authorities;
+ }
+
+ public void setAuthorities(Set authorities) {
+ this.authorities = authorities;
+ }
+
+ // prettier-ignore
+ @Override
+ public String toString() {
+ return "AdminUserDTO{" +
+ "login='" + login + '\'' +
+ ", firstName='" + firstName + '\'' +
+ ", lastName='" + lastName + '\'' +
+ ", email='" + email + '\'' +
+ ", imageUrl='" + imageUrl + '\'' +
+ ", activated=" + activated +
+ ", langKey='" + langKey + '\'' +
+ ", createdBy=" + createdBy +
+ ", createdDate=" + createdDate +
+ ", lastModifiedBy='" + lastModifiedBy + '\'' +
+ ", lastModifiedDate=" + lastModifiedDate +
+ ", authorities=" + authorities +
+ "}";
+ }
+}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/AttributeDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/AttributeDTO.java
deleted file mode 100644
index 51b7667..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/AttributeDTO.java
+++ /dev/null
@@ -1,148 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import javax.persistence.Lob;
-import javax.validation.constraints.NotNull;
-import java.io.Serializable;
-import java.util.Objects;
-import java.util.List;
-import java.util.ArrayList;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-
-/**
- * A DTO for the Attribute entity.
- */
-public class AttributeDTO implements Serializable {
-
- private Long id;
-
- @NotNull
- private String name;
-
- @Lob
- private String description;
-
- private Integer showOrder;
-
- @NotNull
- @JsonIgnore
- private Boolean active;
-
- @JsonIgnore
- private AttributeDTO parent;
-
- @JsonIgnore
- private AttributeKeyDTO attributeKey;
-
- private List children;
-
- public AttributeDTO() {
- children = new ArrayList<>();
- }
-
- @JsonIgnore
- public AttributeDTO getParent() {
- return parent;
- }
-
- @JsonProperty
- public void setParent(AttributeDTO parent) {
- this.parent = parent;
- }
-
- public List getChildren() {
- return children;
- }
-
- public void setChildren(List children) {
- this.children = children;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Integer getShowOrder() {
- return showOrder;
- }
-
- public void setShowOrder(Integer showOrder) {
- this.showOrder = showOrder;
- }
-
- @JsonIgnore
- public Boolean isActive() {
- return active;
- }
-
- @JsonProperty
- public void setActive(Boolean active) {
- this.active = active;
- }
-
- @JsonIgnore
- public AttributeKeyDTO getAttributeKey() {
- return attributeKey;
- }
-
- @JsonProperty
- public void setAttributeKey(AttributeKeyDTO attributeKey) {
- this.attributeKey = attributeKey;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- AttributeDTO attributeDTO = (AttributeDTO) o;
- if(attributeDTO.getId() == null || getId() == null) {
- return false;
- }
- return Objects.equals(getId(), attributeDTO.getId());
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(getId());
- }
-
- @Override
- public String toString() {
- return "AttributeDTO{" +
- "id=" + getId() +
- ", name='" + getName() + "'" +
- ", description='" + getDescription() + "'" +
- ", showOrder=" + getShowOrder() +
- ", active='" + isActive() + "'" +
- "}";
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/AttributeKeyDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/AttributeKeyDTO.java
deleted file mode 100644
index b891487..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/AttributeKeyDTO.java
+++ /dev/null
@@ -1,155 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import javax.validation.constraints.*;
-import java.io.Serializable;
-import java.util.Objects;
-import javax.persistence.Lob;
-
-import org.securityrat.casemanagement.domain.enumeration.AttributeType;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-
-/**
- * A DTO for the AttributeKey entity.
- */
-public class AttributeKeyDTO implements Serializable {
-
- public AttributeKeyDTO() {
- }
-
- public AttributeKeyDTO(Long id, String name, AttributeType type) {
- this.id = id;
- this.name = name;
- this.type = type;
- }
- public AttributeKeyDTO(Long id, String name, AttributeType type, String description, Integer showOrder) {
- this.id = id;
- this.name = name;
- this.type = type;
- this.description = description;
- this.showOrder = showOrder;
- }
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- @NotNull
- private Long id;
-
- @NotNull
- private String name;
-
- @Lob
- private String description;
-
- @JsonIgnore
- private AttributeType type;
-
- private Integer showOrder;
-
- @NotNull
- @JsonIgnore
- private Boolean active;
-
- @JsonIgnore
- private RequirementSetDTO requirementSet;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @JsonIgnore
- public AttributeType getType() {
- return type;
- }
-
- @JsonProperty
- public void setType(AttributeType type) {
- this.type = type;
- }
-
-
- public Integer getShowOrder() {
- return showOrder;
- }
-
- public void setShowOrder(Integer showOrder) {
- this.showOrder = showOrder;
- }
-
- @JsonIgnore
- public Boolean isActive() {
- return active;
- }
-
- @JsonProperty
- public void setActive(Boolean active) {
- this.active = active;
- }
-
- @JsonIgnore
- public RequirementSetDTO getRequirementSet() {
- return requirementSet;
- }
-
- @JsonProperty
- public void setRequirementSet(RequirementSetDTO requirementSet) {
- this.requirementSet = requirementSet;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- AttributeKeyDTO attributeKeyDTO = (AttributeKeyDTO) o;
- if(attributeKeyDTO.getId() == null || getId() == null) {
- return false;
- }
- return Objects.equals(getId(), attributeKeyDTO.getId());
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(getId());
- }
-
- @Override
- public String toString() {
- return "AttributeKeyDTO{" +
- "id=" + getId() +
- ", name='" + getName() + "'" +
- ", description='" + getDescription() + "'" +
- ", type='" + getType() + "'" +
- ", showOrder=" + getShowOrder() +
- "}";
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/EnhancementForReqDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/EnhancementForReqDTO.java
deleted file mode 100644
index ef91fbd..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/EnhancementForReqDTO.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import java.util.List;
-
-public class EnhancementForReqDTO {
-
- private Long keyId;
- private List contents;
-
- public Long getKeyId() {
- return keyId;
- }
-
- public void setKeyId(Long keyId) {
- this.keyId = keyId;
- }
-
- public List getContents() {
- return contents;
- }
-
- public void setContents(List contents) {
- this.contents = contents;
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/EnhancementForReqStructureDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/EnhancementForReqStructureDTO.java
deleted file mode 100644
index 27d4c9c..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/EnhancementForReqStructureDTO.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import java.util.ArrayList;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-@JsonIgnoreProperties({"type"})
-public class EnhancementForReqStructureDTO extends ExtensionKeyDTO {
-
- public EnhancementForReqStructureDTO() {}
-
- public EnhancementForReqStructureDTO(ExtensionKeyDTO exKey) {
- this.setId(exKey.getId());
- this.setName(exKey.getName());
- this.setRequirementSet(exKey.getRequirementSet());
- this.setDescription(exKey.getDescription());
- this.setSection(exKey.getSection());
- this.setShowOrder(exKey.getShowOrder());
- this.setType(exKey.getType());
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionKeyDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionKeyDTO.java
deleted file mode 100644
index 12fb2eb..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionKeyDTO.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import org.securityrat.casemanagement.domain.enumeration.ExtensionSection;
-import org.securityrat.casemanagement.domain.enumeration.ExtensionType;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import javax.persistence.Lob;
-import javax.validation.constraints.NotNull;
-
-public class ExtensionKeyDTO {
-
- @NotNull
- private Long id;
-
- @JsonIgnore
- private RequirementSetDTO requirementSet;
-
- @NotNull
- private String name;
-
- @Lob
- private String description;
-
- @NotNull
- @JsonIgnore
- private ExtensionSection section;
-
- private ExtensionType type;
-
- private Integer showOrder;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- @JsonIgnore
- public RequirementSetDTO getRequirementSet() {
- return requirementSet;
- }
-
- @JsonProperty
- public void setRequirementSet(RequirementSetDTO requirementSet) {
- this.requirementSet = requirementSet;
- }
-
- @NotNull
- public String getName() {
- return name;
- }
-
- public void setName(@NotNull String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @JsonIgnore
- public ExtensionSection getSection() {
- return section;
- }
-
- @JsonProperty
- public void setSection(ExtensionSection section) {
- this.section = section;
- }
-
- public ExtensionType getType() {
- return type;
- }
-
- public void setType(ExtensionType type) {
- this.type = type;
- }
-
- public Integer getShowOrder() {
- return showOrder;
- }
-
- public void setShowOrder(Integer showOrder) {
- this.showOrder = showOrder;
- }
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionReqDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionReqDTO.java
deleted file mode 100644
index 424c8dc..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionReqDTO.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-@JsonIgnoreProperties({"description"})
-public class ExtensionReqDTO extends GenericExtensionDTO {
-
- public ExtensionReqDTO() {}
-
- public ExtensionReqDTO(GenericExtensionDTO ex) {
- this.setId(ex.getId());
- this.setContent(ex.getContent());
- this.setDescription(ex.getDescription());
- this.setShowOrder(ex.getShowOrder());
- this.setExtensionKey(ex.getExtensionKey());
- }
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionReqStructureDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionReqStructureDTO.java
deleted file mode 100644
index df3ab20..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/ExtensionReqStructureDTO.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-@JsonIgnoreProperties({"extensionKey"})
-public class ExtensionReqStructureDTO extends GenericExtensionDTO {
-
- public ExtensionReqStructureDTO() {}
-
- public ExtensionReqStructureDTO(GenericExtensionDTO ex) {
- this.setId(ex.getId());
- this.setContent(ex.getContent());
- this.setDescription(ex.getDescription());
- this.setShowOrder(ex.getShowOrder());
- this.setExtensionKey(ex.getExtensionKey());
- }
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/GenericAttributeGatewayDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/GenericAttributeGatewayDTO.java
deleted file mode 100644
index beb4ae9..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/GenericAttributeGatewayDTO.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import java.util.List;
-
-import org.securityrat.casemanagement.domain.enumeration.AttributeType;
-
-public class GenericAttributeGatewayDTO extends AttributeKeyDTO{
-
- private static final long serialVersionUID = 1L;
-
- public GenericAttributeGatewayDTO(Long id, String name, AttributeType type) {
- super(id, name, type);
- }
- public GenericAttributeGatewayDTO(Long id, String name, AttributeType type, String description, Integer showOrder) {
- super(id, name, type, description, showOrder);
- }
-
-
- private List values;
-
- public List getValues() {
- return values;
- }
-
- public void setValues(List values) {
- this.values = values;
- }
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/GenericExtensionDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/GenericExtensionDTO.java
deleted file mode 100644
index 2dc21bf..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/GenericExtensionDTO.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import javax.persistence.Lob;
-import javax.validation.constraints.NotNull;
-
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class GenericExtensionDTO {
-
- @NotNull
- private Long id;
-
- @Lob
- @NotNull
- private String content;
-
- private Integer showOrder;
-
- @Lob
- private String description;
-
- @JsonIgnore
- private ExtensionKeyDTO extensionKey;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- public Integer getShowOrder() {
- return showOrder;
- }
-
- public void setShowOrder(Integer showOrder) {
- this.showOrder = showOrder;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @JsonIgnore
- public ExtensionKeyDTO getExtensionKey() {
- return extensionKey;
- }
-
- @JsonProperty
- public void setExtensionKey(ExtensionKeyDTO extensionKey) {
- this.extensionKey = extensionKey;
- }
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/RequirementDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/RequirementDTO.java
deleted file mode 100644
index 6fc9be5..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/RequirementDTO.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import java.util.List;
-
-public class RequirementDTO {
-
- private Long id;
- private String name;
- private String description;
- private Integer showOrder;
- private List feTags;
- private List parameters;
- private Long catergoryId;
- private List enhancements;
- private List status;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Integer getShowOrder() {
- return showOrder;
- }
-
- public void setShowOrder(Integer showOrder) {
- this.showOrder = showOrder;
- }
-
- public List getFeTags() {
- return feTags;
- }
-
- public void setFeTags(List feTags) {
- this.feTags = feTags;
- }
-
- public List getParameters() {
- return parameters;
- }
-
- public void setParameters(List parameters) {
- this.parameters = parameters;
- }
-
- public Long getCatergoryId() {
- return catergoryId;
- }
-
- public void setCatergoryId(Long catergoryId) {
- this.catergoryId = catergoryId;
- }
-
- public List getEnhancements() {
- return enhancements;
- }
-
- public void setEnhancements(List enhancements) {
- this.enhancements = enhancements;
- }
-
- public List getStatus() {
- return status;
- }
-
- public void setStatus(List status) {
- this.status = status;
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/RequirementSetDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/RequirementSetDTO.java
deleted file mode 100644
index 8fa02cc..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/RequirementSetDTO.java
+++ /dev/null
@@ -1,98 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-
-import javax.persistence.Lob;
-import javax.validation.constraints.NotNull;
-import java.io.Serializable;
-import java.util.Objects;
-
-/**
- * A DTO for the (remote) RequirementSet entity.
- */
-public class RequirementSetDTO implements Serializable {
-
- private Long id;
-
- @NotNull
- private String name;
-
- @Lob
- private String description;
-
- private Integer showOrder;
-
- @NotNull
- private Boolean active;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Integer getShowOrder() {
- return showOrder;
- }
-
- public void setShowOrder(Integer showOrder) {
- this.showOrder = showOrder;
- }
-
- public Boolean isActive() {
- return active;
- }
-
- public void setActive(Boolean active) {
- this.active = active;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- RequirementSetDTO requirementSetDTO = (RequirementSetDTO) o;
- if(requirementSetDTO.getId() == null || getId() == null) {
- return false;
- }
- return Objects.equals(getId(), requirementSetDTO.getId());
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(getId());
- }
-
- @Override
- public String toString() {
- return "RequirementSetDTO{" +
- "id=" + getId() +
- ", name='" + getName() + "'" +
- ", description='" + getDescription() + "'" +
- ", showOrder=" + getShowOrder() +
- ", active='" + isActive() + "'" +
- "}";
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/RequirementStructureDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/RequirementStructureDTO.java
deleted file mode 100644
index 0f3ae41..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/RequirementStructureDTO.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class RequirementStructureDTO {
-
- public RequirementStructureDTO() {
-
- }
-
- public RequirementStructureDTO(boolean init) {
- if (init) {
- this.enhancements = new ArrayList<>();
- this.status = new ArrayList<>();
- }
- }
-
- private List enhancements;
-
- private List status;
-
- public List getEnhancements() {
- return enhancements;
- }
-
- public void setEnhancements(List enhancements) {
- this.enhancements = enhancements;
- }
-
- public List getStatus() {
- return status;
- }
-
- public void setStatus(List status) {
- this.status = status;
- }
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/SkAtExDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/SkAtExDTO.java
deleted file mode 100644
index 0441bc0..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/SkAtExDTO.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-public class SkAtExDTO {
-
- private Long id;
- private SkeletonDTO skeleton;
- private AttributeDTO attribute;
- private ExtensionReqDTO extension;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public SkeletonDTO getSkeleton() {
- return skeleton;
- }
-
- public void setSkeleton(SkeletonDTO skeleton) {
- this.skeleton = skeleton;
- }
-
- public AttributeDTO getAttribute() {
- return attribute;
- }
-
- public void setAttribute(AttributeDTO attribute) {
- this.attribute = attribute;
- }
-
- public ExtensionReqDTO getExtension() {
- return extension;
- }
-
- public void setExtension(ExtensionReqDTO extension) {
- this.extension = extension;
- }
-
-
-
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/SkeletonDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/SkeletonDTO.java
deleted file mode 100644
index d7bd246..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/SkeletonDTO.java
+++ /dev/null
@@ -1,94 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import java.util.Objects;
-
-public class SkeletonDTO {
-
- private boolean active;
- private String description;
- private Long id;
- private String name;
- private RequirementSetDTO requirementSet;
- private Integer showOrder;
-
- public boolean isActive() {
- return active;
- }
-
- public void setActive(boolean active) {
- this.active = active;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public RequirementSetDTO getRequirementSet() {
- return requirementSet;
- }
-
- public void setRequirementSet(RequirementSetDTO requirementSet) {
- this.requirementSet = requirementSet;
- }
-
- public Integer getShowOrder() {
- return showOrder;
- }
-
- public void setShowOrder(Integer showOrder) {
- this.showOrder = showOrder;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- SkeletonDTO skeletonDTO = (SkeletonDTO) o;
- if(skeletonDTO.getId() == null || getId() == null) {
- return false;
- }
- return Objects.equals(getId(), skeletonDTO.getId());
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(getId());
- }
-
- @Override
- public String toString() {
- return "SkeletonDTO{" +
- "id=" + getId() +
- ", name='" + getName() + '\'' +
- ", description='" + getDescription() + '\'' +
- ", requirementSet=" + getRequirementSet() +
- ", showOrder=" + getShowOrder() +
- ", active=" + isActive() +
- '}';
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/StatusForReqDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/StatusForReqDTO.java
deleted file mode 100644
index abab987..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/StatusForReqDTO.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import java.util.List;
-
-public class StatusForReqDTO {
-
- private Long keyId;
- private List values;
-
- public Long getKeyId() {
- return keyId;
- }
-
- public void setKeyId(Long keyId) {
- this.keyId = keyId;
- }
-
- public List getValues() {
- return values;
- }
-
- public void setValues(List values) {
- this.values = values;
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/StatusForReqStructureDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/StatusForReqStructureDTO.java
deleted file mode 100644
index e0d5178..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/dto/StatusForReqStructureDTO.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package org.securityrat.casemanagement.service.dto;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-public class StatusForReqStructureDTO extends ExtensionKeyDTO {
-
- public StatusForReqStructureDTO() {}
-
- public StatusForReqStructureDTO(ExtensionKeyDTO exKey) {
- this.setId(exKey.getId());
- this.setName(exKey.getName());
- this.setRequirementSet(exKey.getRequirementSet());
- this.setDescription(exKey.getDescription());
- this.setSection(exKey.getSection());
- this.setShowOrder(exKey.getShowOrder());
- this.setType(exKey.getType());
- this.values = new ArrayList<>();
- }
-
- private List values;
-
- public List getValues() {
- return values;
- }
-
- public void setValues(List values) {
- this.values = values;
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/dto/UserDTO.java b/src/main/java/org/securityrat/casemanagement/service/dto/UserDTO.java
index 0b21d7b..a337e78 100644
--- a/src/main/java/org/securityrat/casemanagement/service/dto/UserDTO.java
+++ b/src/main/java/org/securityrat/casemanagement/service/dto/UserDTO.java
@@ -1,75 +1,24 @@
package org.securityrat.casemanagement.service.dto;
-import org.securityrat.casemanagement.config.Constants;
-
-import org.securityrat.casemanagement.domain.Authority;
import org.securityrat.casemanagement.domain.User;
-import javax.validation.constraints.*;
-import java.time.Instant;
-import java.util.Set;
-import java.util.stream.Collectors;
-
/**
- * A DTO representing a appUser, with his authorities.
+ * A DTO representing a user, with only the public attributes.
*/
public class UserDTO {
private String id;
- @NotBlank
- @Pattern(regexp = Constants.LOGIN_REGEX)
- @Size(min = 1, max = 50)
private String login;
- @Size(max = 50)
- private String firstName;
-
- @Size(max = 50)
- private String lastName;
-
- @Email
- @Size(min = 5, max = 254)
- private String email;
-
- @Size(max = 256)
- private String imageUrl;
-
- private boolean activated = false;
-
- @Size(min = 2, max = 10)
- private String langKey;
-
- private String createdBy;
-
- private Instant createdDate;
-
- private String lastModifiedBy;
-
- private Instant lastModifiedDate;
-
- private Set authorities;
-
public UserDTO() {
// Empty constructor needed for Jackson.
}
- public UserDTO(User appUser) {
- this.id = appUser.getId();
- this.login = appUser.getLogin();
- this.firstName = appUser.getFirstName();
- this.lastName = appUser.getLastName();
- this.email = appUser.getEmail();
- this.activated = appUser.getActivated();
- this.imageUrl = appUser.getImageUrl();
- this.langKey = appUser.getLangKey();
- this.createdBy = appUser.getCreatedBy();
- this.createdDate = appUser.getCreatedDate();
- this.lastModifiedBy = appUser.getLastModifiedBy();
- this.lastModifiedDate = appUser.getLastModifiedDate();
- this.authorities = appUser.getAuthorities().stream()
- .map(Authority::getName)
- .collect(Collectors.toSet());
+ public UserDTO(User user) {
+ this.id = user.getId();
+ // Customize it here if you need, or not, firstName/lastName/etc
+ this.login = user.getLogin();
}
public String getId() {
@@ -88,109 +37,12 @@ public void setLogin(String login) {
this.login = login;
}
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public String getImageUrl() {
- return imageUrl;
- }
-
- public void setImageUrl(String imageUrl) {
- this.imageUrl = imageUrl;
- }
-
- public boolean isActivated() {
- return activated;
- }
-
- public void setActivated(boolean activated) {
- this.activated = activated;
- }
-
- public String getLangKey() {
- return langKey;
- }
-
- public void setLangKey(String langKey) {
- this.langKey = langKey;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
-
- public Instant getCreatedDate() {
- return createdDate;
- }
-
- public void setCreatedDate(Instant createdDate) {
- this.createdDate = createdDate;
- }
-
- public String getLastModifiedBy() {
- return lastModifiedBy;
- }
-
- public void setLastModifiedBy(String lastModifiedBy) {
- this.lastModifiedBy = lastModifiedBy;
- }
-
- public Instant getLastModifiedDate() {
- return lastModifiedDate;
- }
-
- public void setLastModifiedDate(Instant lastModifiedDate) {
- this.lastModifiedDate = lastModifiedDate;
- }
-
- public Set getAuthorities() {
- return authorities;
- }
-
- public void setAuthorities(Set authorities) {
- this.authorities = authorities;
- }
-
+ // prettier-ignore
@Override
public String toString() {
return "UserDTO{" +
- "login='" + login + '\'' +
- ", firstName='" + firstName + '\'' +
- ", lastName='" + lastName + '\'' +
- ", email='" + email + '\'' +
- ", imageUrl='" + imageUrl + '\'' +
- ", activated=" + activated +
- ", langKey='" + langKey + '\'' +
- ", createdBy=" + createdBy +
- ", createdDate=" + createdDate +
- ", lastModifiedBy='" + lastModifiedBy + '\'' +
- ", lastModifiedDate=" + lastModifiedDate +
- ", authorities=" + authorities +
+ "id='" + id + '\'' +
+ ", login='" + login + '\'' +
"}";
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/service/exceptions/IDNotFoundException.java b/src/main/java/org/securityrat/casemanagement/service/exceptions/IDNotFoundException.java
deleted file mode 100644
index 287867c..0000000
--- a/src/main/java/org/securityrat/casemanagement/service/exceptions/IDNotFoundException.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package org.securityrat.casemanagement.service.exceptions;
-
-import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.ResponseStatus;
-
-@ResponseStatus(value = HttpStatus.NOT_FOUND)
-public class IDNotFoundException extends RuntimeException {
-}
diff --git a/src/main/java/org/securityrat/casemanagement/service/mapper/UserMapper.java b/src/main/java/org/securityrat/casemanagement/service/mapper/UserMapper.java
index 2f71aee..fcb92d4 100644
--- a/src/main/java/org/securityrat/casemanagement/service/mapper/UserMapper.java
+++ b/src/main/java/org/securityrat/casemanagement/service/mapper/UserMapper.java
@@ -1,14 +1,16 @@
package org.securityrat.casemanagement.service.mapper;
+import java.util.*;
+import java.util.stream.Collectors;
+import org.mapstruct.BeanMapping;
+import org.mapstruct.Mapping;
+import org.mapstruct.Named;
import org.securityrat.casemanagement.domain.Authority;
import org.securityrat.casemanagement.domain.User;
+import org.securityrat.casemanagement.service.dto.AdminUserDTO;
import org.securityrat.casemanagement.service.dto.UserDTO;
-
import org.springframework.stereotype.Service;
-import java.util.*;
-import java.util.stream.Collectors;
-
/**
* Mapper for the entity {@link User} and its DTO called {@link UserDTO}.
*
@@ -19,52 +21,59 @@
public class UserMapper {
public List usersToUserDTOs(List users) {
- return users.stream()
- .filter(Objects::nonNull)
- .map(this::userToUserDTO)
- .collect(Collectors.toList());
+ return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).collect(Collectors.toList());
+ }
+
+ public UserDTO userToUserDTO(User user) {
+ return new UserDTO(user);
}
- public UserDTO userToUserDTO(User appUser) {
- return new UserDTO(appUser);
+ public List usersToAdminUserDTOs(List users) {
+ return users.stream().filter(Objects::nonNull).map(this::userToAdminUserDTO).collect(Collectors.toList());
}
- public List userDTOsToUsers(List userDTOs) {
- return userDTOs.stream()
- .filter(Objects::nonNull)
- .map(this::userDTOToUser)
- .collect(Collectors.toList());
+ public AdminUserDTO userToAdminUserDTO(User user) {
+ return new AdminUserDTO(user);
}
- public User userDTOToUser(UserDTO userDTO) {
+ public List userDTOsToUsers(List userDTOs) {
+ return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).collect(Collectors.toList());
+ }
+
+ public User userDTOToUser(AdminUserDTO userDTO) {
if (userDTO == null) {
return null;
} else {
- User appUser = new User();
- appUser.setId(userDTO.getId());
- appUser.setLogin(userDTO.getLogin());
- appUser.setFirstName(userDTO.getFirstName());
- appUser.setLastName(userDTO.getLastName());
- appUser.setEmail(userDTO.getEmail());
- appUser.setImageUrl(userDTO.getImageUrl());
- appUser.setActivated(userDTO.isActivated());
- appUser.setLangKey(userDTO.getLangKey());
+ User user = new User();
+ user.setId(userDTO.getId());
+ user.setLogin(userDTO.getLogin());
+ user.setFirstName(userDTO.getFirstName());
+ user.setLastName(userDTO.getLastName());
+ user.setEmail(userDTO.getEmail());
+ user.setImageUrl(userDTO.getImageUrl());
+ user.setActivated(userDTO.isActivated());
+ user.setLangKey(userDTO.getLangKey());
Set authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
- appUser.setAuthorities(authorities);
- return appUser;
+ user.setAuthorities(authorities);
+ return user;
}
}
-
private Set authoritiesFromStrings(Set authoritiesAsString) {
Set authorities = new HashSet<>();
- if(authoritiesAsString != null){
- authorities = authoritiesAsString.stream().map(string -> {
- Authority auth = new Authority();
- auth.setName(string);
- return auth;
- }).collect(Collectors.toSet());
+ if (authoritiesAsString != null) {
+ authorities =
+ authoritiesAsString
+ .stream()
+ .map(
+ string -> {
+ Authority auth = new Authority();
+ auth.setName(string);
+ return auth;
+ }
+ )
+ .collect(Collectors.toSet());
}
return authorities;
@@ -74,8 +83,67 @@ public User userFromId(String id) {
if (id == null) {
return null;
}
- User appUser = new User();
- appUser.setId(id);
- return appUser;
+ User user = new User();
+ user.setId(id);
+ return user;
+ }
+
+ @Named("id")
+ @BeanMapping(ignoreByDefault = true)
+ @Mapping(target = "id", source = "id")
+ public UserDTO toDtoId(User user) {
+ if (user == null) {
+ return null;
+ }
+ UserDTO userDto = new UserDTO();
+ userDto.setId(user.getId());
+ return userDto;
+ }
+
+ @Named("idSet")
+ @BeanMapping(ignoreByDefault = true)
+ @Mapping(target = "id", source = "id")
+ public Set toDtoIdSet(Set users) {
+ if (users == null) {
+ return null;
+ }
+
+ Set userSet = new HashSet<>();
+ for (User userEntity : users) {
+ userSet.add(this.toDtoId(userEntity));
+ }
+
+ return userSet;
+ }
+
+ @Named("login")
+ @BeanMapping(ignoreByDefault = true)
+ @Mapping(target = "id", source = "id")
+ @Mapping(target = "login", source = "login")
+ public UserDTO toDtoLogin(User user) {
+ if (user == null) {
+ return null;
+ }
+ UserDTO userDto = new UserDTO();
+ userDto.setId(user.getId());
+ userDto.setLogin(user.getLogin());
+ return userDto;
+ }
+
+ @Named("loginSet")
+ @BeanMapping(ignoreByDefault = true)
+ @Mapping(target = "id", source = "id")
+ @Mapping(target = "login", source = "login")
+ public Set toDtoLoginSet(Set users) {
+ if (users == null) {
+ return null;
+ }
+
+ Set userSet = new HashSet<>();
+ for (User userEntity : users) {
+ userSet.add(this.toDtoLogin(userEntity));
+ }
+
+ return userSet;
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/web/rest/AccessTokenResource.java b/src/main/java/org/securityrat/casemanagement/web/rest/AccessTokenResource.java
index 7e4633c..5e9a86c 100644
--- a/src/main/java/org/securityrat/casemanagement/web/rest/AccessTokenResource.java
+++ b/src/main/java/org/securityrat/casemanagement/web/rest/AccessTokenResource.java
@@ -1,13 +1,16 @@
package org.securityrat.casemanagement.web.rest;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
import org.securityrat.casemanagement.domain.AccessToken;
import org.securityrat.casemanagement.repository.AccessTokenRepository;
import org.securityrat.casemanagement.repository.UserRepository;
import org.securityrat.casemanagement.web.rest.errors.BadRequestAlertException;
-
-import io.github.jhipster.web.util.HeaderUtil;
-import io.github.jhipster.web.util.PaginationUtil;
-import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
@@ -15,16 +18,12 @@
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
-import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
-
-import javax.validation.Valid;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import java.util.List;
-import java.util.Optional;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+import tech.jhipster.web.util.HeaderUtil;
+import tech.jhipster.web.util.PaginationUtil;
+import tech.jhipster.web.util.ResponseUtil;
/**
* REST controller for managing {@link org.securityrat.casemanagement.domain.AccessToken}.
@@ -42,11 +41,11 @@ public class AccessTokenResource {
private final AccessTokenRepository accessTokenRepository;
- private final UserRepository appUserRepository;
+ private final UserRepository userRepository;
- public AccessTokenResource(AccessTokenRepository accessTokenRepository, UserRepository appUserRepository) {
+ public AccessTokenResource(AccessTokenRepository accessTokenRepository, UserRepository userRepository) {
this.accessTokenRepository = accessTokenRepository;
- this.appUserRepository = appUserRepository;
+ this.userRepository = userRepository;
}
/**
@@ -62,49 +61,120 @@ public ResponseEntity createAccessToken(@Valid @RequestBody AccessT
if (accessToken.getId() != null) {
throw new BadRequestAlertException("A new accessToken cannot already have an ID", ENTITY_NAME, "idexists");
}
-
if (accessToken.getUser() != null) {
- // Save appUser in case it's new and only exists in gateway
- appUserRepository.save(accessToken.getUser());
+ // Save user in case it's new and only exists in gateway
+ userRepository.save(accessToken.getUser());
}
AccessToken result = accessTokenRepository.save(accessToken);
- return ResponseEntity.created(new URI("/api/access-tokens/" + result.getId()))
+ return ResponseEntity
+ .created(new URI("/api/access-tokens/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
- * {@code PUT /access-tokens} : Updates an existing accessToken.
+ * {@code PUT /access-tokens/:id} : Updates an existing accessToken.
*
+ * @param id the id of the accessToken to save.
* @param accessToken the accessToken to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated accessToken,
* or with status {@code 400 (Bad Request)} if the accessToken is not valid,
* or with status {@code 500 (Internal Server Error)} if the accessToken couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
- @PutMapping("/access-tokens")
- public ResponseEntity updateAccessToken(@Valid @RequestBody AccessToken accessToken) throws URISyntaxException {
- log.debug("REST request to update AccessToken : {}", accessToken);
+ @PutMapping("/access-tokens/{id}")
+ public ResponseEntity updateAccessToken(
+ @PathVariable(value = "id", required = false) final Long id,
+ @Valid @RequestBody AccessToken accessToken
+ ) throws URISyntaxException {
+ log.debug("REST request to update AccessToken : {}, {}", id, accessToken);
if (accessToken.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
+ if (!Objects.equals(id, accessToken.getId())) {
+ throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
+ }
+
+ if (!accessTokenRepository.existsById(id)) {
+ throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
+ }
if (accessToken.getUser() != null) {
- // Save appUser in case it's new and only exists in gateway
- appUserRepository.save(accessToken.getUser());
+ // Save user in case it's new and only exists in gateway
+ userRepository.save(accessToken.getUser());
}
AccessToken result = accessTokenRepository.save(accessToken);
- return ResponseEntity.ok()
+ return ResponseEntity
+ .ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, accessToken.getId().toString()))
.body(result);
}
/**
- * {@code GET /access-tokens} : get all the accessTokens.
+ * {@code PATCH /access-tokens/:id} : Partial updates given fields of an existing accessToken, field will ignore if it is null
*
+ * @param id the id of the accessToken to save.
+ * @param accessToken the accessToken to update.
+ * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated accessToken,
+ * or with status {@code 400 (Bad Request)} if the accessToken is not valid,
+ * or with status {@code 404 (Not Found)} if the accessToken is not found,
+ * or with status {@code 500 (Internal Server Error)} if the accessToken couldn't be updated.
+ * @throws URISyntaxException if the Location URI syntax is incorrect.
+ */
+ @PatchMapping(value = "/access-tokens/{id}", consumes = "application/merge-patch+json")
+ public ResponseEntity partialUpdateAccessToken(
+ @PathVariable(value = "id", required = false) final Long id,
+ @NotNull @RequestBody AccessToken accessToken
+ ) throws URISyntaxException {
+ log.debug("REST request to partial update AccessToken partially : {}, {}", id, accessToken);
+ if (accessToken.getId() == null) {
+ throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
+ }
+ if (!Objects.equals(id, accessToken.getId())) {
+ throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
+ }
- * @param pageable the pagination information.
+ if (!accessTokenRepository.existsById(id)) {
+ throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
+ }
+
+ if (accessToken.getUser() != null) {
+ // Save user in case it's new and only exists in gateway
+ userRepository.save(accessToken.getUser());
+ }
+
+ Optional result = accessTokenRepository
+ .findById(accessToken.getId())
+ .map(
+ existingAccessToken -> {
+ if (accessToken.getToken() != null) {
+ existingAccessToken.setToken(accessToken.getToken());
+ }
+ if (accessToken.getExpirationDate() != null) {
+ existingAccessToken.setExpirationDate(accessToken.getExpirationDate());
+ }
+ if (accessToken.getSalt() != null) {
+ existingAccessToken.setSalt(accessToken.getSalt());
+ }
+ if (accessToken.getRefreshToken() != null) {
+ existingAccessToken.setRefreshToken(accessToken.getRefreshToken());
+ }
+
+ return existingAccessToken;
+ }
+ )
+ .map(accessTokenRepository::save);
+
+ return ResponseUtil.wrapOrNotFound(
+ result,
+ HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, accessToken.getId().toString())
+ );
+ }
+ /**
+ * {@code GET /access-tokens} : get all the accessTokens.
+ *
+ * @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of accessTokens in body.
*/
@GetMapping("/access-tokens")
@@ -138,6 +208,9 @@ public ResponseEntity getAccessToken(@PathVariable Long id) {
public ResponseEntity deleteAccessToken(@PathVariable Long id) {
log.debug("REST request to delete AccessToken : {}", id);
accessTokenRepository.deleteById(id);
- return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build();
+ return ResponseEntity
+ .noContent()
+ .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
+ .build();
}
}
diff --git a/src/main/java/org/securityrat/casemanagement/web/rest/AuditResource.java b/src/main/java/org/securityrat/casemanagement/web/rest/AuditResource.java
deleted file mode 100644
index 277e3e4..0000000
--- a/src/main/java/org/securityrat/casemanagement/web/rest/AuditResource.java
+++ /dev/null
@@ -1,79 +0,0 @@
-package org.securityrat.casemanagement.web.rest;
-
-import org.securityrat.casemanagement.service.AuditEventService;
-
-import io.github.jhipster.web.util.PaginationUtil;
-import io.github.jhipster.web.util.ResponseUtil;
-import org.springframework.boot.actuate.audit.AuditEvent;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.Pageable;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.*;
-import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
-
-import java.time.Instant;
-import java.time.LocalDate;
-import java.time.ZoneId;
-import java.util.List;
-
-/**
- * REST controller for getting the {@link AuditEvent}s.
- */
-@RestController
-@RequestMapping("/management/audits")
-public class AuditResource {
-
- private final AuditEventService auditEventService;
-
- public AuditResource(AuditEventService auditEventService) {
- this.auditEventService = auditEventService;
- }
-
- /**
- * {@code GET /audits} : get a page of {@link AuditEvent}s.
- *
- * @param pageable the pagination information.
- * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent}s in body.
- */
- @GetMapping
- public ResponseEntity> getAll(Pageable pageable) {
- Page page = auditEventService.findAll(pageable);
- HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
- return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
- }
-
- /**
- * {@code GET /audits} : get a page of {@link AuditEvent} between the {@code fromDate} and {@code toDate}.
- *
- * @param fromDate the start of the time period of {@link AuditEvent} to get.
- * @param toDate the end of the time period of {@link AuditEvent} to get.
- * @param pageable the pagination information.
- * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent} in body.
- */
- @GetMapping(params = {"fromDate", "toDate"})
- public ResponseEntity> getByDates(
- @RequestParam(value = "fromDate") LocalDate fromDate,
- @RequestParam(value = "toDate") LocalDate toDate,
- Pageable pageable) {
-
- Instant from = fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
- Instant to = toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant();
-
- Page page = auditEventService.findByDates(from, to, pageable);
- HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
- return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
- }
-
- /**
- * {@code GET /audits/:id} : get an {@link AuditEvent} by id.
- *
- * @param id the id of the entity to get.
- * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the {@link AuditEvent} in body, or status {@code 404 (Not Found)}.
- */
- @GetMapping("/{id:.+}")
- public ResponseEntity get(@PathVariable Long id) {
- return ResponseUtil.wrapOrNotFound(auditEventService.find(id));
- }
-}
diff --git a/src/main/java/org/securityrat/casemanagement/web/rest/GatewayAPI.java b/src/main/java/org/securityrat/casemanagement/web/rest/GatewayAPI.java
deleted file mode 100644
index e431868..0000000
--- a/src/main/java/org/securityrat/casemanagement/web/rest/GatewayAPI.java
+++ /dev/null
@@ -1,191 +0,0 @@
-package org.securityrat.casemanagement.web.rest;
-
-
-import io.micrometer.core.annotation.Timed;
-import org.securityrat.casemanagement.domain.enumeration.AttributeType;
-import org.securityrat.casemanagement.service.RequirementManagementAPIService;
-import org.securityrat.casemanagement.service.dto.AttributeDTO;
-import org.securityrat.casemanagement.service.dto.ExtensionKeyDTO;
-import org.securityrat.casemanagement.service.dto.GenericAttributeGatewayDTO;
-import org.securityrat.casemanagement.service.dto.GenericExtensionDTO;
-import org.securityrat.casemanagement.service.dto.RequirementDTO;
-import org.securityrat.casemanagement.service.dto.RequirementSetDTO;
-import org.securityrat.casemanagement.service.dto.RequirementStructureDTO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@RestController
-@RequestMapping("/api")
-public class GatewayAPI {
- private final Logger log = LoggerFactory.getLogger(GatewayAPI.class);
-
- @Autowired
- private RequirementManagementAPIService requirementManagementAPIService;
-
- /**
- * GET /requirementSets : Get active requirementSets.
- *
- * @return the ResponseEntity with status 200 (OK) and the list of
- * requirementSets in body
- */
- @GetMapping("/requirementSets")
- @Timed
- public ResponseEntity> getActiveRequirementSets() {
- log.debug("REST request to get active RequirementSets");
-
- List result = requirementManagementAPIService.getActiveRequirementSets();
- return new ResponseEntity<>(result, HttpStatus.OK);
- }
-
- /**
- * GET /parameters?requirementSet : Get parameters for a given requirementSet.
- *
- * @param requirementSetId
- * The requirementSet ID.
- *
- * @return the ResponseEntity with status 200 (OK) and the list of parameters in
- * body
- */
- @GetMapping(value="/parameters", params="requirementSet")
- @Timed
- public ResponseEntity> getParameters(
- @RequestParam(value = "requirementSet") Long requirementSetId) {
- log.info("REST request to get all active parameter for RequirementSet with ID {}", requirementSetId);
-
- return new ResponseEntity<>(this.getAttributes(requirementSetId, AttributeType.PARAMETER), HttpStatus.OK);
- }
-
- /**
- * GET /parameters?ids : Get parameters of the given parameter ids.
- *
- * @param paramterValueIds
- * List of parameter ids.
- *
- * @return the ResponseEntity with status 200 (OK) and the list of parameters in
- * body
- */
- @GetMapping(value="/parameters", params="ids")
- @Timed
- public ResponseEntity> getParametersByIds(
- @RequestParam(value = "ids") String paramterValueIds) {
- log.info("REST request to get all active parameters in a given list of ids");
- List ids = this.parseStringToList(paramterValueIds);
- List attributes = requirementManagementAPIService.getAttributesByIds(ids);
-
- List result = requirementManagementAPIService
- .generateGatewayAttributeDTO(attributes);
- return new ResponseEntity<>(result, HttpStatus.OK);
- }
-
- /**
- * GET /parameters?requirementSet : Get all tags for a given requirementSet.
- *
- * @param requirementSetId
- * The requirementSet ID.
- *
- * @return the ResponseEntity with status 200 (OK) and the list of tags in
- * body
- */
- @GetMapping("/tags")
- @Timed
- public ResponseEntity> getTags(
- @RequestParam(value = "requirementSet") Long requirementSetId) {
- log.info("REST request to get all active tags for RequirementSet with ID {}", requirementSetId);
- return new ResponseEntity<>(this.getAttributes(requirementSetId, AttributeType.FE_TAG), HttpStatus.OK);
- }
-
- /**
- * GET /parameters?requirementSet : Get all categories for a given requirementSet.
- *
- * @param requirementSetId
- * The requirementSet ID.
- *
- * @return the ResponseEntity with status 200 (OK) and the list of categories in
- * body
- */
- @GetMapping("/categories")
- @Timed
- public ResponseEntity> getCategories(
- @RequestParam(value = "requirementSet") Long requirementSetId) {
- log.info("REST request to get all active parameter for RequirementSet with ID {}", requirementSetId);
-
- return new ResponseEntity<>(this.getAttributes(requirementSetId, AttributeType.CATEGORY), HttpStatus.OK);
- }
-
- /**
- * GET /requirementStructure?requirementSet : Retrieves the requirement table structure of a given requirement set.
- * @param requirementSetId the requirementSet ID
- * @return
- */
- @GetMapping("/requirementStructure")
- public ResponseEntity getRequirementStructure(
- @RequestParam(value = "requirementSet") Long requirementSetId
- ) {
- List extensionKeys = requirementManagementAPIService.getActiveExtensionKeys(requirementSetId);
- List extensions = requirementManagementAPIService.getActiveExtensionForReqStructure(requirementSetId);
-
-
- return new ResponseEntity<>(this.requirementManagementAPIService.generateRequirementStructureDTO(extensionKeys, extensions), HttpStatus.OK);
- }
-
- /**
- * GET /requirements : Get active attributes with given ids.
- *
- * @param requirementSetId
- * Id of requirementSet
- * @param List
- * of parameter ids (comma seperated string)
- * @return the ResponseEntity with status 200 (OK) and the list of requirements
- * in body or 404 (Not found) if one of the specified IDs does not exist
- */
- @GetMapping("/requirements")
- @Timed
- public ResponseEntity> getRequirements(
- @RequestParam(value = "requirementSet") Long requirementSetId,
- @RequestParam(value = "parameters") String parameters) {
- List params = new ArrayList<>();
- if (parameters != null) {
- for (String idAsString : parameters.split(",")) {
- params.add(Long.parseLong(idAsString));
- }
- }
- List result;
- result = requirementManagementAPIService.getActiveRequirements(requirementSetId, params);
-
- return new ResponseEntity<>(result, HttpStatus.OK);
- }
-
-
- /**
- * Parse a comma separated string to long values.
- * @param values comma separated string
- * @return
- */
- private List parseStringToList(String values) {
- List result = new ArrayList<>();
- for (String value: values.split(",")) {
- result.add(Long.parseLong(value));
- }
-
- return result;
- }
-
- private List getAttributes(Long requirementSetId, AttributeType type) {
- List types = new ArrayList<>();
- types.add(type);
- List