Browse Source

first commit

first_push
Nora 3 years ago
commit
9b7e85f6f2
  1. 23
      .editorconfig
  2. 150
      .gitattributes
  3. 147
      .gitignore
  4. 5
      .huskyrc
  5. 53
      .jhipster/Formation.json
  6. 34
      .jhipster/PersonnelFormation.json
  7. 35
      .jhipster/Skill.json
  8. 3
      .lintstagedrc.js
  9. 8
      .prettierignore
  10. 12
      .prettierrc
  11. 40
      .yo-rc.json
  12. 26
      FormationContinue.jdl
  13. 126
      README.md
  14. 309
      build.gradle
  15. 19
      checkstyle.xml
  16. 65
      gradle.properties
  17. 22
      gradle/docker.gradle
  18. 47
      gradle/profile_dev.gradle
  19. 37
      gradle/profile_prod.gradle
  20. 26
      gradle/sonar.gradle
  21. 13
      gradle/war.gradle
  22. BIN
      gradle/wrapper/gradle-wrapper.jar
  23. 5
      gradle/wrapper/gradle-wrapper.properties
  24. 3
      gradle/zipkin.gradle
  25. 188
      gradlew
  26. 100
      gradlew.bat
  27. 16206
      package-lock.json
  28. 23
      package.json
  29. 16
      settings.gradle
  30. 28
      sonar-project.properties
  31. 23
      src/main/docker/app.yml
  32. 8
      src/main/docker/central-server-config/README.md
  33. 15
      src/main/docker/central-server-config/docker-config/application.yml
  34. 15
      src/main/docker/central-server-config/localhost-config/application.yml
  35. 3778
      src/main/docker/grafana/provisioning/dashboards/JVM.json
  36. 11
      src/main/docker/grafana/provisioning/dashboards/dashboard.yml
  37. 50
      src/main/docker/grafana/provisioning/datasources/datasource.yml
  38. 22
      src/main/docker/jhipster-registry.yml
  39. 26
      src/main/docker/monitoring.yml
  40. 16
      src/main/docker/mssql.yml
  41. 31
      src/main/docker/prometheus/prometheus.yml
  42. 7
      src/main/docker/sonar.yml
  43. 20
      src/main/java/com/cm/formationcontinue/ApplicationWebXml.java
  44. 105
      src/main/java/com/cm/formationcontinue/FormationContinueApp.java
  45. 113
      src/main/java/com/cm/formationcontinue/aop/logging/LoggingAspect.java
  46. 18
      src/main/java/com/cm/formationcontinue/client/UserFeignClientInterceptor.java
  47. 13
      src/main/java/com/cm/formationcontinue/config/ApplicationProperties.java
  48. 47
      src/main/java/com/cm/formationcontinue/config/AsyncConfiguration.java
  49. 28
      src/main/java/com/cm/formationcontinue/config/CloudDatabaseConfiguration.java
  50. 12
      src/main/java/com/cm/formationcontinue/config/Constants.java
  51. 21
      src/main/java/com/cm/formationcontinue/config/DatabaseConfiguration.java
  52. 20
      src/main/java/com/cm/formationcontinue/config/DateTimeFormatConfiguration.java
  53. 22
      src/main/java/com/cm/formationcontinue/config/FeignConfiguration.java
  54. 52
      src/main/java/com/cm/formationcontinue/config/JacksonConfiguration.java
  55. 60
      src/main/java/com/cm/formationcontinue/config/LiquibaseConfiguration.java
  56. 27
      src/main/java/com/cm/formationcontinue/config/LocaleConfiguration.java
  57. 19
      src/main/java/com/cm/formationcontinue/config/LoggingAspectConfiguration.java
  58. 56
      src/main/java/com/cm/formationcontinue/config/LoggingConfiguration.java
  59. 69
      src/main/java/com/cm/formationcontinue/config/SecurityConfiguration.java
  60. 58
      src/main/java/com/cm/formationcontinue/config/WebConfigurer.java
  61. 86
      src/main/java/com/cm/formationcontinue/config/audit/AuditEventConverter.java
  62. 4
      src/main/java/com/cm/formationcontinue/config/audit/package-info.java
  63. 4
      src/main/java/com/cm/formationcontinue/config/package-info.java
  64. 77
      src/main/java/com/cm/formationcontinue/domain/AbstractAuditingEntity.java
  65. 202
      src/main/java/com/cm/formationcontinue/domain/Formation.java
  66. 108
      src/main/java/com/cm/formationcontinue/domain/PersistentAuditEvent.java
  67. 107
      src/main/java/com/cm/formationcontinue/domain/PersonnelFormation.java
  68. 121
      src/main/java/com/cm/formationcontinue/domain/Skill.java
  69. 4
      src/main/java/com/cm/formationcontinue/domain/package-info.java
  70. 29
      src/main/java/com/cm/formationcontinue/repository/FormationRepository.java
  71. 14
      src/main/java/com/cm/formationcontinue/repository/PersonnelFormationRepository.java
  72. 14
      src/main/java/com/cm/formationcontinue/repository/SkillRepository.java
  73. 4
      src/main/java/com/cm/formationcontinue/repository/package-info.java
  74. 16
      src/main/java/com/cm/formationcontinue/security/AuthoritiesConstants.java
  75. 85
      src/main/java/com/cm/formationcontinue/security/SecurityUtils.java
  76. 20
      src/main/java/com/cm/formationcontinue/security/SpringSecurityAuditorAware.java
  77. 21
      src/main/java/com/cm/formationcontinue/security/jwt/JWTConfigurer.java
  78. 48
      src/main/java/com/cm/formationcontinue/security/jwt/JWTFilter.java
  79. 111
      src/main/java/com/cm/formationcontinue/security/jwt/TokenProvider.java
  80. 4
      src/main/java/com/cm/formationcontinue/security/package-info.java
  81. 93
      src/main/java/com/cm/formationcontinue/service/FormationService.java
  82. 84
      src/main/java/com/cm/formationcontinue/service/PersonnelFormationService.java
  83. 84
      src/main/java/com/cm/formationcontinue/service/SkillService.java
  84. 113
      src/main/java/com/cm/formationcontinue/service/dto/FormationDTO.java
  85. 78
      src/main/java/com/cm/formationcontinue/service/dto/PersonnelFormationDTO.java
  86. 67
      src/main/java/com/cm/formationcontinue/service/dto/SkillDTO.java
  87. 21
      src/main/java/com/cm/formationcontinue/service/mapper/EntityMapper.java
  88. 29
      src/main/java/com/cm/formationcontinue/service/mapper/FormationMapper.java
  89. 29
      src/main/java/com/cm/formationcontinue/service/mapper/PersonnelFormationMapper.java
  90. 28
      src/main/java/com/cm/formationcontinue/service/mapper/SkillMapper.java
  91. 4
      src/main/java/com/cm/formationcontinue/service/package-info.java
  92. 131
      src/main/java/com/cm/formationcontinue/web/rest/FormationResource.java
  93. 125
      src/main/java/com/cm/formationcontinue/web/rest/PersonnelFormationResource.java
  94. 125
      src/main/java/com/cm/formationcontinue/web/rest/SkillResource.java
  95. 42
      src/main/java/com/cm/formationcontinue/web/rest/errors/BadRequestAlertException.java
  96. 15
      src/main/java/com/cm/formationcontinue/web/rest/errors/ErrorConstants.java
  97. 181
      src/main/java/com/cm/formationcontinue/web/rest/errors/ExceptionTranslator.java
  98. 33
      src/main/java/com/cm/formationcontinue/web/rest/errors/FieldErrorVM.java
  99. 6
      src/main/java/com/cm/formationcontinue/web/rest/errors/package-info.java
  100. 4
      src/main/java/com/cm/formationcontinue/web/rest/package-info.java

23
.editorconfig

@ -0,0 +1,23 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
# Change these settings to your own preference
indent_style = space
indent_size = 4
[*.{ts,tsx,js,jsx,json,css,scss,yml}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false

150
.gitattributes

@ -0,0 +1,150 @@
# This file is inspired by https://github.com/alexkaratarakis/gitattributes
#
# Auto detect text files and perform LF normalization
# http://davidlaing.com/2012/09/19/customise-your-gitattributes-to-become-a-git-ninja/
* text=auto
# The above will handle all files NOT found below
# These files are text and should be normalized (Convert crlf => lf)
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
*.coffee text
*.css text
*.cql text
*.df text
*.ejs text
*.html text
*.java text
*.js text
*.json text
*.less text
*.properties text
*.sass text
*.scss text
*.sh text eol=lf
*.sql text
*.txt text
*.ts text
*.xml text
*.yaml text
*.yml text
# Documents
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
*.markdown text
*.md text
*.adoc text
*.textile text
*.mustache text
*.csv text
*.tab text
*.tsv text
*.txt text
AUTHORS text
CHANGELOG text
CHANGES text
CONTRIBUTING text
COPYING text
copyright text
*COPYRIGHT* text
INSTALL text
license text
LICENSE text
NEWS text
readme text
*README* text
TODO text
# Graphics
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.tif binary
*.tiff binary
*.ico binary
# SVG treated as an asset (binary) by default. If you want to treat it as text,
# comment-out the following line and uncomment the line after.
*.svg binary
#*.svg text
*.eps binary
# These files are binary and should be left untouched
# (binary is a macro for -text -diff)
*.class binary
*.jar binary
*.war binary
## LINTERS
.csslintrc text
.eslintrc text
.jscsrc text
.jshintrc text
.jshintignore text
.stylelintrc text
## CONFIGS
*.conf text
*.config text
.editorconfig text
.gitattributes text
.gitconfig text
.gitignore text
.htaccess text
*.npmignore text
## HEROKU
Procfile text
.slugignore text
## AUDIO
*.kar binary
*.m4a binary
*.mid binary
*.midi binary
*.mp3 binary
*.ogg binary
*.ra binary
## VIDEO
*.3gpp binary
*.3gp binary
*.as binary
*.asf binary
*.asx binary
*.fla binary
*.flv binary
*.m4v binary
*.mng binary
*.mov binary
*.mp4 binary
*.mpeg binary
*.mpg binary
*.swc binary
*.swf binary
*.webm binary
## ARCHIVES
*.7z binary
*.gz binary
*.rar binary
*.tar binary
*.zip binary
## FONTS
*.ttf binary
*.eot binary
*.otf binary
*.woff binary
*.woff2 binary

147
.gitignore

@ -0,0 +1,147 @@
######################
# Project Specific
######################
/build/resources/main/static/**
/src/test/javascript/coverage/
######################
# Node
######################
/node/
node_tmp/
node_modules/
npm-debug.log.*
/.awcache/*
/.cache-loader/*
######################
# SASS
######################
.sass-cache/
######################
# Eclipse
######################
*.pydevproject
.project
.metadata
tmp/
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
.factorypath
/src/main/resources/rebel.xml
# External tool builders
.externalToolBuilders/**
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
# STS-specific
/.sts4-cache/*
######################
# IntelliJ
######################
.idea/
*.iml
*.iws
*.ipr
*.ids
*.orig
classes/
out/
######################
# Visual Studio Code
######################
.vscode/
######################
# Maven
######################
/log/
/target/
######################
# Gradle
######################
.gradle/
/build/
######################
# Package Files
######################
*.jar
*.war
*.ear
*.db
######################
# Windows
######################
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
######################
# Mac OSX
######################
.DS_Store
.svn
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
######################
# Directories
######################
/bin/
/deploy/
######################
# Logs
######################
*.log*
######################
# Others
######################
*.class
*.*~
*~
.merge_file*
######################
# Gradle Wrapper
######################
!gradle/wrapper/gradle-wrapper.jar
######################
# Maven Wrapper
######################
!.mvn/wrapper/maven-wrapper.jar
######################
# ESLint
######################
.eslintcache

5
.huskyrc

@ -0,0 +1,5 @@
{
"hooks": {
"pre-commit": "lint-staged"
}
}

53
.jhipster/Formation.json

@ -0,0 +1,53 @@
{
"name": "Formation",
"fields": [
{
"fieldName": "nomFormation",
"fieldType": "String"
},
{
"fieldName": "description",
"fieldType": "String"
},
{
"fieldName": "dateDebut",
"fieldType": "LocalDate"
},
{
"fieldName": "dateFin",
"fieldType": "LocalDate"
},
{
"fieldName": "idOrganismeFormation",
"fieldType": "Long"
}
],
"relationships": [
{
"relationshipType": "one-to-many",
"otherEntityName": "personnelFormation",
"otherEntityRelationshipName": "formation",
"relationshipName": "idPersonnel"
},
{
"relationshipType": "many-to-many",
"otherEntityName": "skill",
"otherEntityRelationshipName": "formation",
"relationshipName": "skill",
"otherEntityField": "id",
"ownerSide": true
}
],
"changelogDate": "20210618112355",
"entityTableName": "formation",
"dto": "mapstruct",
"pagination": "pagination",
"service": "serviceClass",
"jpaMetamodelFiltering": false,
"fluentMethods": true,
"readOnly": false,
"embedded": false,
"clientRootFolder": "formationContinue",
"applications": "*",
"microserviceName": "FormationContinue"
}

34
.jhipster/PersonnelFormation.json

@ -0,0 +1,34 @@
{
"name": "PersonnelFormation",
"fields": [
{
"fieldName": "idFormation",
"fieldType": "Long"
},
{
"fieldName": "idPersonnel",
"fieldType": "Long"
}
],
"relationships": [
{
"relationshipType": "many-to-one",
"otherEntityName": "formation",
"otherEntityRelationshipName": "idPersonnel",
"relationshipName": "formation",
"otherEntityField": "id"
}
],
"changelogDate": "20210618112555",
"entityTableName": "personnel_formation",
"dto": "mapstruct",
"pagination": "pagination",
"service": "serviceClass",
"jpaMetamodelFiltering": false,
"fluentMethods": true,
"readOnly": false,
"embedded": false,
"clientRootFolder": "formationContinue",
"applications": "*",
"microserviceName": "FormationContinue"
}

35
.jhipster/Skill.json

@ -0,0 +1,35 @@
{
"name": "Skill",
"fields": [
{
"fieldName": "idFormation",
"fieldType": "Long"
},
{
"fieldName": "nom",
"fieldType": "String"
}
],
"relationships": [
{
"relationshipType": "many-to-many",
"otherEntityName": "formation",
"otherEntityRelationshipName": "skill",
"relationshipName": "formation",
"otherEntityField": "id",
"ownerSide": false
}
],
"changelogDate": "20210618112455",
"entityTableName": "skill",
"dto": "mapstruct",
"pagination": "pagination",
"service": "serviceClass",
"jpaMetamodelFiltering": false,
"fluentMethods": true,
"readOnly": false,
"embedded": false,
"clientRootFolder": "formationContinue",
"applications": "*",
"microserviceName": "FormationContinue"
}

3
.lintstagedrc.js

@ -0,0 +1,3 @@
module.exports = {
'{,src/**/}*.{json,md,yml}': ['prettier --write', 'git add']
};

8
.prettierignore

@ -0,0 +1,8 @@
node_modules
target
build
package-lock.json
.git
.mvn
gradle
.gradle

12
.prettierrc

@ -0,0 +1,12 @@
# Prettier configuration
printWidth: 140
singleQuote: true
tabWidth: 2
useTabs: false
# js and ts rules:
arrowParens: avoid
# jsx and tsx rules:
jsxBracketSameLine: false

40
.yo-rc.json

@ -0,0 +1,40 @@
{
"generator-jhipster": {
"promptValues": {
"packageName": "com.cm.formationcontinue",
"nativeLanguage": "fr"
},
"jhipsterVersion": "6.10.5",
"applicationType": "microservice",
"baseName": "formationContinue",
"packageName": "com.cm.formationcontinue",
"packageFolder": "com/cm/formationcontinue",
"serverPort": "3005",
"authenticationType": "jwt",
"cacheProvider": "no",
"websocket": false,
"databaseType": "sql",
"devDatabaseType": "mssql",
"prodDatabaseType": "mssql",
"searchEngine": false,
"messageBroker": false,
"serviceDiscoveryType": "eureka",
"buildTool": "gradle",
"enableSwaggerCodegen": false,
"jwtSecretKey": "ZjQ2YzlmYmI0MTAzMGZjNTAzZjRlNmYyMjliNDg5NTc0MzQwZWYxOWE2NTZjNjQyYzgwYjAzYjI1NDE4YTQ5OTc1NjAzNjVkNGEzODVmYzJkN2Q1N2FiOWUxNWM0NWQzOTdiMzZkMzJiMWUwMGQ5Y2IwMTIyOWJjMmIwNWM4NGY=",
"embeddableLaunchScript": false,
"creationTimestamp": 1624011087437,
"testFrameworks": [],
"jhiPrefix": "jhi",
"entitySuffix": "",
"dtoSuffix": "DTO",
"otherModules": [],
"enableTranslation": true,
"clientPackageManager": "npm",
"nativeLanguage": "fr",
"languages": ["fr", "ar-ly"],
"blueprints": [],
"skipClient": true,
"skipUserManagement": true
}
}

26
FormationContinue.jdl

@ -0,0 +1,26 @@
entity Formation {
nomFormation String,
description String,
dateDebut LocalDate,
dateFin LocalDate,
idOrganismeFormation Long
}
entity Skill {
idFormation Long,
nom String
}
entity PersonnelFormation {
idFormation Long,
idPersonnel Long
}
relationship ManyToMany {
Formation to Skill
}
relationship OneToMany {
Formation{idPersonnel} to PersonnelFormation
}
service all with serviceClass
microservice * with FormationContinue
paginate * with pagination
dto * with mapstruct

126
README.md

@ -0,0 +1,126 @@
# formationContinue
This application was generated using JHipster 6.10.5, you can find documentation and help at [https://www.jhipster.tech/documentation-archive/v6.10.5](https://www.jhipster.tech/documentation-archive/v6.10.5).
This is a "microservice" application intended to be part of a microservice architecture, please refer to the [Doing microservices with JHipster][] page of the documentation for more information.
This application is configured for Service Discovery and Configuration with the JHipster-Registry. On launch, it will refuse to start if it is not able to connect to the JHipster-Registry at [http://localhost:8761](http://localhost:8761). For more information, read our documentation on [Service Discovery and Configuration with the JHipster-Registry][].
## Development
To start your application in the dev profile, run:
```
./gradlew
```
For further instructions on how to develop with JHipster, have a look at [Using JHipster in development][].
## Building for production
### Packaging as jar
To build the final jar and optimize the formationContinue application for production, run:
```
./gradlew -Pprod clean bootJar
```
To ensure everything worked, run:
```
java -jar build/libs/*.jar
```
Refer to [Using JHipster in production][] for more details.
### Packaging as war
To package your application as a war in order to deploy it to an application server, run:
```
./gradlew -Pprod -Pwar clean bootWar
```
## Testing
To launch your application's tests, run:
```
./gradlew test integrationTest jacocoTestReport
```
For more information, refer to the [Running tests page][].
### Code quality
Sonar is used to analyse code quality. You can start a local Sonar server (accessible on http://localhost:9001) with:
```
docker-compose -f src/main/docker/sonar.yml up -d
```
You can run a Sonar analysis with using the [sonar-scanner](https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner) or by using the gradle plugin.
Then, run a Sonar analysis:
```
./gradlew -Pprod clean check jacocoTestReport sonarqube
```
For more information, refer to the [Code quality page][].
## Using Docker to simplify development (optional)
You can use Docker to improve your JHipster development experience. A number of docker-compose configuration are available in the [src/main/docker](src/main/docker) folder to launch required third party services.
For example, to start a mssql database in a docker container, run:
```
docker-compose -f src/main/docker/mssql.yml up -d
```
To stop it and remove the container, run:
```
docker-compose -f src/main/docker/mssql.yml down
```
You can also fully dockerize your application and all the services that it depends on.
To achieve this, first build a docker image of your app by running:
```
./gradlew bootJar -Pprod jibDockerBuild
```
Then run:
```
docker-compose -f src/main/docker/app.yml up -d
```
For more information refer to [Using Docker and Docker-Compose][], this page also contains information on the docker-compose sub-generator (`jhipster docker-compose`), which is able to generate docker configurations for one or several JHipster applications.
## Continuous Integration (optional)
To configure CI for your project, run the ci-cd sub-generator (`jhipster ci-cd`), this will let you generate configuration files for a number of Continuous Integration systems. Consult the [Setting up Continuous Integration][] page for more information.
[jhipster homepage and latest documentation]: https://www.jhipster.tech
[jhipster 6.10.5 archive]: https://www.jhipster.tech/documentation-archive/v6.10.5
[doing microservices with jhipster]: https://www.jhipster.tech/documentation-archive/v6.10.5/microservices-architecture/
[using jhipster in development]: https://www.jhipster.tech/documentation-archive/v6.10.5/development/
[service discovery and configuration with the jhipster-registry]: https://www.jhipster.tech/documentation-archive/v6.10.5/microservices-architecture/#jhipster-registry
[using docker and docker-compose]: https://www.jhipster.tech/documentation-archive/v6.10.5/docker-compose
[using jhipster in production]: https://www.jhipster.tech/documentation-archive/v6.10.5/production/
[running tests page]: https://www.jhipster.tech/documentation-archive/v6.10.5/running-tests/
[code quality page]: https://www.jhipster.tech/documentation-archive/v6.10.5/code-quality/
[setting up continuous integration]: https://www.jhipster.tech/documentation-archive/v6.10.5/setting-up-ci/

309
build.gradle

@ -0,0 +1,309 @@
buildscript {
repositories {
mavenLocal()
mavenCentral()
gradlePluginPortal()
maven { url "https://repo.spring.io/plugins-release" }
}
dependencies {
//jhipster-needle-gradle-buildscript-dependency - JHipster will add additional gradle build script plugins here
}
}
plugins {
id "java"
id "maven-publish"
id "idea"
id "jacoco"
id "org.springframework.boot"
id "com.google.cloud.tools.jib"
id "com.gorylenko.gradle-git-properties"
id "net.ltgt.apt-eclipse"
id "net.ltgt.apt-idea"
id "net.ltgt.apt"
id "org.liquibase.gradle"
id "org.sonarqube"
id "io.spring.nohttp"
//jhipster-needle-gradle-plugins - JHipster will add additional gradle plugins here
}
group = "com.cm.formationcontinue"
version = "0.0.1-SNAPSHOT"
description = ""
sourceCompatibility=1.8
targetCompatibility=1.8
assert System.properties["java.specification.version"] == "1.8" || "11" || "12" || "13" || "14"
apply from: "gradle/docker.gradle"
apply from: "gradle/sonar.gradle"
//jhipster-needle-gradle-apply-from - JHipster will add additional gradle scripts to be applied here
if (project.hasProperty("prod") || project.hasProperty("gae")) {
apply from: "gradle/profile_prod.gradle"
} else {
apply from: "gradle/profile_dev.gradle"
}
if (project.hasProperty("war")) {
apply from: "gradle/war.gradle"
}
if (project.hasProperty("gae")) {
apply plugin: 'maven'
apply plugin: 'org.springframework.boot.experimental.thin-launcher'
apply plugin: 'io.spring.dependency-management'
dependencyManagement {
imports {
mavenBom "io.github.jhipster:jhipster-dependencies:${jhipster_dependencies_version}"
}
}
appengineStage.dependsOn thinResolve
}
if (project.hasProperty("zipkin")) {
apply from: "gradle/zipkin.gradle"
}
idea {
module {
excludeDirs += files("node_modules")
}
}
eclipse {
sourceSets {
main {
java {
srcDirs += ["build/generated/sources/annotationProcessor/java/main"]
}
}
}
}
defaultTasks "bootRun"
springBoot {
mainClassName = "com.cm.formationcontinue.FormationContinueApp"
}
test {
useJUnitPlatform()
exclude "**/*IT*", "**/*IntTest*"
testLogging {
events 'FAILED', 'SKIPPED'
}
// uncomment if the tests reports are not generated
// see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484
// ignoreFailures true
reports.html.enabled = false
}
task integrationTest(type: Test) {
useJUnitPlatform()
description = "Execute integration tests."
group = "verification"
include "**/*IT*", "**/*IntTest*"
testLogging {
events 'FAILED', 'SKIPPED'
}
if (project.hasProperty('testcontainers')) {
environment 'spring.profiles.active', 'testcontainers'
}
// uncomment if the tests reports are not generated
// see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484
// ignoreFailures true
reports.html.enabled = false
}
check.dependsOn integrationTest
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/tests")
reportOn test
}
task integrationTestReport(type: TestReport) {
destinationDir = file("$buildDir/reports/tests")
reportOn integrationTest
}
if (!project.hasProperty("runList")) {
project.ext.runList = "main"
}
project.ext.diffChangelogFile = "src/main/resources/config/liquibase/changelog/" + new Date().format("yyyyMMddHHmmss") + "_changelog.xml"
liquibase {
activities {
main {
driver ""
url "jdbc:sqlserver://localhost:1433;database=formationContinue"
username "SA"
password "yourStrong(!)Password"
changeLogFile "src/main/resources/config/liquibase/master.xml"
defaultSchemaName ""
logLevel "debug"
classpath "src/main/resources/"
}
diffLog {
driver ""
url "jdbc:sqlserver://localhost:1433;database=formationContinue"
username "SA"
password "yourStrong(!)Password"
changeLogFile project.ext.diffChangelogFile
referenceUrl "hibernate:spring:com.cm.formationcontinue.domain?dialect=org.hibernate.dialect.SQLServer2012Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
defaultSchemaName ""
logLevel "debug"
classpath "$buildDir/classes/java/main"
}
}
runList = project.ext.runList
}
gitProperties {
failOnNoGitDirectory = false
keys = ["git.branch", "git.commit.id.abbrev", "git.commit.id.describe"]
}
checkstyle {
toolVersion '${checkstyle_version}'
configFile file("checkstyle.xml")
checkstyleTest.enabled = false
}
nohttp {
source.include "build.gradle", "README.md"
}
configurations {
providedRuntime
implementation.exclude module: "spring-boot-starter-tomcat"
all {
resolutionStrategy {
// Inherited version from Spring Boot can't be used because of regressions:
// To be removed as soon as spring-boot use the same version
force 'org.liquibase:liquibase-core:3.9.0'
}
}
}
repositories {
mavenLocal()
mavenCentral()
jcenter()
//jhipster-needle-gradle-repositories - JHipster will add additional repositories
}
dependencies {
// import JHipster dependencies BOM
if (!project.hasProperty("gae")) {
implementation platform("io.github.jhipster:jhipster-dependencies:${jhipster_dependencies_version}")
}
// Use ", version: jhipster_dependencies_version, changing: true" if you want
// to use a SNAPSHOT release instead of a stable release
implementation group: "io.github.jhipster", name: "jhipster-framework"
implementation "javax.annotation:javax.annotation-api"
implementation "io.dropwizard.metrics:metrics-core"
implementation "io.micrometer:micrometer-registry-prometheus"
implementation "net.logstash.logback:logstash-logback-encoder"
implementation "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
implementation "com.fasterxml.jackson.module:jackson-module-jaxb-annotations"
implementation "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
implementation "com.fasterxml.jackson.core:jackson-annotations"
implementation "com.fasterxml.jackson.core:jackson-databind"
implementation "org.hibernate:hibernate-core"
implementation "com.zaxxer:HikariCP"
implementation "javax.transaction:javax.transaction-api"
implementation "org.hibernate:hibernate-entitymanager"
implementation "org.hibernate.validator:hibernate-validator"
implementation "org.liquibase:liquibase-core"
liquibaseRuntime "org.liquibase:liquibase-core"
liquibaseRuntime "org.liquibase.ext:liquibase-hibernate5:${liquibase_hibernate5_version}"
liquibaseRuntime sourceSets.main.compileClasspath
implementation "org.springframework.boot:spring-boot-loader-tools"
implementation "org.springframework.boot:spring-boot-starter-mail"
implementation "org.springframework.boot:spring-boot-starter-logging"
implementation "org.springframework.boot:spring-boot-starter-actuator"
implementation "org.springframework.boot:spring-boot-starter-aop"
implementation "org.springframework.boot:spring-boot-starter-data-jpa"
testImplementation "org.testcontainers:mssqlserver"
implementation "org.springframework.boot:spring-boot-starter-security"
implementation ("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
implementation "org.springframework.boot:spring-boot-starter-undertow"
implementation "org.springframework.boot:spring-boot-starter-thymeleaf"
implementation "org.zalando:problem-spring-web"
implementation "org.springframework.cloud:spring-cloud-starter"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-ribbon"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-hystrix"
implementation "org.springframework.retry:spring-retry"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-eureka-client"
implementation "org.springframework.cloud:spring-cloud-starter-config"
implementation "org.springframework.cloud:spring-cloud-starter-openfeign"
implementation "org.springframework.boot:spring-boot-starter-cloud-connectors"
implementation "org.springframework.security:spring-security-config"
implementation "org.springframework.security:spring-security-data"
implementation "org.springframework.security:spring-security-web"
implementation "io.jsonwebtoken:jjwt-api"
if (!project.hasProperty("gae")) {
runtimeOnly "io.jsonwebtoken:jjwt-impl"
runtimeOnly "io.jsonwebtoken:jjwt-jackson"
} else {
implementation "io.jsonwebtoken:jjwt-impl"
implementation "io.jsonwebtoken:jjwt-jackson"
}
implementation ("io.springfox:springfox-swagger2") {
exclude module: "mapstruct"
}
implementation "io.springfox:springfox-bean-validators"
implementation "com.microsoft.sqlserver:mssql-jdbc"
implementation "com.github.sabomichal:liquibase-mssql"
liquibaseRuntime "com.microsoft.sqlserver:mssql-jdbc"
liquibaseRuntime "com.github.sabomichal:liquibase-mssql"
implementation "org.mapstruct:mapstruct:${mapstruct_version}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstruct_version}"
annotationProcessor "org.hibernate:hibernate-jpamodelgen:${hibernate_version}"
annotationProcessor "org.glassfish.jaxb:jaxb-runtime:${jaxb_runtime_version}"
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor:${spring_boot_version}"
testImplementation ("org.springframework.boot:spring-boot-starter-test") {
exclude group: "org.junit.vintage", module: "junit-vintage-engine"
}
testImplementation "org.springframework.security:spring-security-test"
testImplementation "org.springframework.boot:spring-boot-test"
testImplementation "com.tngtech.archunit:archunit-junit5-api:${archunit_junit5_version}"
testRuntimeOnly "com.tngtech.archunit:archunit-junit5-engine:${archunit_junit5_version}"
testImplementation "com.h2database:h2"
//jhipster-needle-gradle-dependency - JHipster will add additional dependencies here
}
if (project.hasProperty("gae")) {
task createPom {
def basePath = 'build/resources/main/META-INF/maven'
doLast {
pom {
withXml(dependencyManagement.pomConfigurer)
}.writeTo("${basePath}/${project.group}/${project.name}/pom.xml")
}
}
bootJar.dependsOn = [createPom]
}
task cleanResources(type: Delete) {
delete "build/resources"
}
wrapper {
gradleVersion = "6.5"
}
compileJava.dependsOn processResources
processResources.dependsOn bootBuildInfo

19
checkstyle.xml

@ -0,0 +1,19 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"https://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<!-- Configure checker to use UTF-8 encoding -->
<property name="charset" value="UTF-8"/>
<!-- Configure checker to run on files with these extensions -->
<property name="fileExtensions" value=""/>
<!-- For detailed checkstyle configuration, see https://github.com/spring-io/nohttp/tree/master/nohttp-checkstyle -->
<module name="io.spring.nohttp.checkstyle.check.NoHttpCheck">
</module>
<!-- Allow suppression with comments
// CHECKSTYLE:OFF
... ignored content ...
// CHECKSTYLE:ON
-->
<module name="SuppressWithPlainTextCommentFilter"/>
</module>

65
gradle.properties

@ -0,0 +1,65 @@
rootProject.name=formation-continue
profile=dev
# Build properties
node_version=12.16.1
npm_version=6.14.5
yarn_version=1.22.4
# Dependency versions
jhipster_dependencies_version=3.9.1
# The spring-boot version should match the one managed by
# https://mvnrepository.com/artifact/io.github.jhipster/jhipster-dependencies/${jhipster_dependencies_version}
spring_boot_version=2.2.7.RELEASE
# The hibernate version should match the one managed by
# https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/${spring-boot.version} -->
hibernate_version=5.4.15.Final
mapstruct_version=1.3.1.Final
archunit_junit5_version=0.14.1
liquibase_hibernate5_version=3.8
liquibaseTaskPrefix=liquibase
jaxb_runtime_version=2.3.3
# gradle plugin version
jib_plugin_version=2.4.0
git_properties_plugin_version=2.2.2
apt_plugin_version=0.21
liquibase_plugin_version=2.0.3
sonarqube_plugin_version=2.8
spring_no_http_plugin_version=0.0.4.RELEASE
checkstyle_version=8.32
# jhipster-needle-gradle-property - JHipster will add additional properties here
## below are some of the gradle performance improvement settings that can be used as required, these are not enabled by default
## The Gradle daemon aims to improve the startup and execution time of Gradle.
## The daemon is enabled by default in Gradle 3+ setting this to false will disable this.
## TODO: disable daemon on CI, since builds should be clean and reliable on servers
## https://docs.gradle.org/current/userguide/gradle_daemon.html#sec:ways_to_disable_gradle_daemon
## uncomment the below line to disable the daemon
#org.gradle.daemon=false
## Specifies the JVM arguments used for the daemon process.
## The setting is particularly useful for tweaking memory settings.
## Default value: -Xmx1024m -XX:MaxPermSize=256m
## uncomment the below line to override the daemon defaults
#org.gradle.jvmargs=-Xmx1024m -XX:MaxPermSize=256m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
## When configured, Gradle will run in incubating parallel mode.
## This option should only be used with decoupled projects. More details, visit
## http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
## uncomment the below line to enable parallel mode
#org.gradle.parallel=true
## Enables new incubating mode that makes Gradle selective when configuring projects.
## Only relevant projects are configured which results in faster builds for large multi-projects.
## http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
## uncomment the below line to enable the selective mode
#org.gradle.configureondemand=true

22
gradle/docker.gradle

@ -0,0 +1,22 @@
jib {
from {
image = "adoptopenjdk:11-jre-hotspot"
}
to {
image = "formationcontinue:latest"
}
container {
entrypoint = ["bash", "-c", "/entrypoint.sh"]
ports = ["3005"]
environment = [
SPRING_OUTPUT_ANSI_ENABLED: "ALWAYS",
JHIPSTER_SLEEP: "0"
]
creationTime = "USE_CURRENT_TIMESTAMP"
}
extraDirectories {
paths = file("src/main/jib")
permissions = ["/entrypoint.sh": "755"]
}
}

47
gradle/profile_dev.gradle

@ -0,0 +1,47 @@
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
dependencies {
developmentOnly "org.springframework.boot:spring-boot-devtools"
}
def profiles = "dev"
if (project.hasProperty("no-liquibase")) {
profiles += ",no-liquibase"
}
if (project.hasProperty("tls")) {
profiles += ",tls"
}
springBoot {
buildInfo {
properties {
time = null
}
}
}
bootRun {
args = []
}
processResources {
inputs.property('version', version)
inputs.property('springProfiles', profiles)
filesMatching("**/application.yml") {
filter {
it.replace("#project.version#", version)
}
}
filesMatching("**/bootstrap.yml") {
filter {
it.replace("#spring.profiles.active#", profiles)
}
}
}

37
gradle/profile_prod.gradle

@ -0,0 +1,37 @@
dependencies {
testImplementation "com.h2database:h2"
}
def profiles = "prod"
if (project.hasProperty("no-liquibase")) {
profiles += ",no-liquibase"
}
if (project.hasProperty("swagger")) {
profiles += ",swagger"
}
springBoot {
buildInfo()
}
bootRun {
args = []
}
processResources {
inputs.property('version', version)
inputs.property('springProfiles', profiles)
filesMatching("**/application.yml") {
filter {
it.replace("#project.version#", version)
}
}
filesMatching("**/bootstrap.yml") {
filter {
it.replace("#spring.profiles.active#", profiles)
}
}
}

26
gradle/sonar.gradle

@ -0,0 +1,26 @@
jacoco {
toolVersion = "0.8.5"
}
jacocoTestReport {
executionData tasks.withType(Test)
classDirectories.from = files(sourceSets.main.output.classesDirs)
sourceDirectories.from = files(sourceSets.main.java.srcDirs)
reports {
xml.enabled = true
}
}
file("sonar-project.properties").withReader {
Properties sonarProperties = new Properties()
sonarProperties.load(it)
sonarProperties.each { key, value ->
sonarqube {
properties {
property key, value
}
}
}
}

13
gradle/war.gradle

@ -0,0 +1,13 @@
apply plugin: "war"
bootWar {
mainClassName = "com.cm.formationcontinue.FormationContinueApp"
includes = ["WEB-INF/**", "META-INF/**"]
}
war {
enabled = true
archiveExtension = "war.original"
includes = ["WEB-INF/**", "META-INF/**"]
}

BIN
gradle/wrapper/gradle-wrapper.jar

5
gradle/wrapper/gradle-wrapper.properties

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

3
gradle/zipkin.gradle

@ -0,0 +1,3 @@
dependencies {
implementation "org.springframework.cloud:spring-cloud-starter-zipkin"
}

188
gradlew

@ -0,0 +1,188 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

100
gradlew.bat

@ -0,0 +1,100 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

16206
package-lock.json
File diff suppressed because it is too large
View File

23
package.json

@ -0,0 +1,23 @@
{
"name": "formation-continue",
"version": "0.0.0",
"description": "Description for formationContinue",
"private": true,
"license": "UNLICENSED",
"cacheDirectories": [
"node_modules"
],
"devDependencies": {
"@openapitools/openapi-generator-cli": "1.0.13-4.3.1",
"generator-jhipster": "6.10.5",
"husky": "4.2.5",
"lint-staged": "8.2.1",
"prettier": "2.1.2"
},
"engines": {
"node": ">=12.16.1"
},
"scripts": {
"prettier:format": "prettier --write \"{,src/**/}*.{md,json,yml}\""
}
}

16
settings.gradle

@ -0,0 +1,16 @@
pluginManagement {
plugins {
id 'org.springframework.boot' version "${spring_boot_version}"
id 'com.google.cloud.tools.jib' version "${jib_plugin_version}"
id 'com.gorylenko.gradle-git-properties' version "${git_properties_plugin_version}"
id 'org.liquibase.gradle' version "${liquibase_plugin_version}"
id 'org.sonarqube' version "${sonarqube_plugin_version}"
id 'net.ltgt.apt-eclipse' version "${apt_plugin_version}"
id 'net.ltgt.apt-idea' version "${apt_plugin_version}"
id 'net.ltgt.apt' version "${apt_plugin_version}"
id "io.spring.nohttp" version "${spring_no_http_plugin_version}"
}
}
rootProject.name = "formation-continue"

28
sonar-project.properties

@ -0,0 +1,28 @@
sonar.projectKey=formationContinue
sonar.projectName=formationContinue 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=build/reports/jacoco/test/jacocoTestReport.xml
sonar.java.codeCoveragePlugin=jacoco
sonar.junit.reportPaths=build/test-results/test,build/test-results/integrationTest
sonar.sourceEncoding=UTF-8
sonar.exclusions=src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, build/resources/main/static/**/*.*
sonar.issue.ignore.multicriteria=S3437,S4502,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
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
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%3AS4502&rule_key=squid%3AS4502 is ignored, as for JWT tokens we are not subject to CSRF attack
sonar.issue.ignore.multicriteria.S4502.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.S4502.ruleKey=squid:S4502
# Rule https://sonarcloud.io/coding_rules?open=java%3AS4684&rule_key=java%3AS4684
sonar.issue.ignore.multicriteria.S4684.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.S4684.ruleKey=java:S4684

23
src/main/docker/app.yml

@ -0,0 +1,23 @@
version: '2'
services:
formationcontinue-app:
image: formationcontinue
environment:
- _JAVA_OPTIONS=-Xmx512m -Xms256m
- SPRING_PROFILES_ACTIVE=prod,swagger
- MANAGEMENT_METRICS_EXPORT_PROMETHEUS_ENABLED=true
- EUREKA_CLIENT_SERVICE_URL_DEFAULTZONE=http://admin:$${jhipster.registry.password}@jhipster-registry:8761/eureka
- SPRING_CLOUD_CONFIG_URI=http://admin:$${jhipster.registry.password}@jhipster-registry:8761/config
- SPRING_DATASOURCE_URL=jdbc:sqlserver://formationcontinue-mssql:1433;database=formationContinue
- JHIPSTER_SLEEP=30 # gives time for other services to boot before the application
formationcontinue-mssql:
extends:
file: mssql.yml
service: formationcontinue-mssql
jhipster-registry:
extends:
file: jhipster-registry.yml
service: jhipster-registry
environment:
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_TYPE=native
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_SEARCH_LOCATIONS=file:./central-config/docker-config/

8
src/main/docker/central-server-config/README.md

@ -0,0 +1,8 @@
# Central configuration sources details
The JHipster-Registry will use the following directories as its configuration source :
- localhost-config : when running the registry in docker with the jhipster-registry.yml docker-compose file
- docker-config : when running the registry and the app both in docker with the app.yml docker-compose file
For more info, refer to https://www.jhipster.tech/jhipster-registry/#spring-cloud-config

15
src/main/docker/central-server-config/docker-config/application.yml

@ -0,0 +1,15 @@
# Common configuration shared between all applications
configserver:
name: Docker JHipster Registry
status: Connected to the JHipster Registry running in Docker
jhipster:
security:
authentication:
jwt:
secret: my-secret-key-which-should-be-changed-in-production-and-be-base64-encoded
eureka:
client:
service-url:
defaultZone: http://admin:${jhipster.registry.password}@jhipster-registry:8761/eureka/

15
src/main/docker/central-server-config/localhost-config/application.yml

@ -0,0 +1,15 @@
# Common configuration shared between all applications
configserver:
name: Docker JHipster Registry
status: Connected to the JHipster Registry running in Docker
jhipster:
security:
authentication:
jwt:
secret: my-secret-key-which-should-be-changed-in-production-and-be-base64-encoded
eureka:
client:
service-url:
defaultZone: http://admin:${jhipster.registry.password}@localhost:8761/eureka/

3778
src/main/docker/grafana/provisioning/dashboards/JVM.json
File diff suppressed because it is too large
View File

11
src/main/docker/grafana/provisioning/dashboards/dashboard.yml

@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: 'Prometheus'
orgId: 1
folder: ''
type: file
disableDeletion: false
editable: true
options:
path: /etc/grafana/provisioning/dashboards

50
src/main/docker/grafana/provisioning/datasources/datasource.yml

@ -0,0 +1,50 @@
apiVersion: 1
# list of datasources that should be deleted from the database
deleteDatasources:
- name: Prometheus
orgId: 1
# list of datasources to insert/update depending
# whats available in the database
datasources:
# <string, required> name of the datasource. Required
- name: Prometheus
# <string, required> datasource type. Required
type: prometheus
# <string, required> access mode. direct or proxy. Required
access: proxy
# <int> org id. will default to orgId 1 if not specified
orgId: 1
# <string> url
# On MacOS, replace localhost by host.docker.internal
url: http://localhost:9090
# <string> database password, if used
password:
# <string> database user, if used
user:
# <string> database name, if used
database:
# <bool> enable/disable basic auth
basicAuth: false
# <string> basic auth username
basicAuthUser: admin
# <string> basic auth password
basicAuthPassword: admin
# <bool> enable/disable with credentials headers
withCredentials:
# <bool> mark as default datasource. Max one per org
isDefault: true
# <map> fields that will be converted to json and stored in json_data
jsonData:
graphiteVersion: '1.1'
tlsAuth: false
tlsAuthWithCACert: false
# <string> json object of data that will be encrypted.
secureJsonData:
tlsCACert: '...'
tlsClientCert: '...'
tlsClientKey: '...'
version: 1
# <bool> allow users to edit datasources from the UI.
editable: true

22
src/main/docker/jhipster-registry.yml

@ -0,0 +1,22 @@
version: '2'
services:
jhipster-registry:
image: jhipster/jhipster-registry:v6.3.0
volumes:
- ./central-server-config:/central-config
# When run with the "dev" Spring profile, the JHipster Registry will
# read the config from the local filesystem (central-server-config directory)
# When run with the "prod" Spring profile, it will read the configuration from a Git repository
# See https://www.jhipster.tech/jhipster-registry/#spring-cloud-config
environment:
- _JAVA_OPTIONS=-Xmx512m -Xms256m
- SPRING_PROFILES_ACTIVE=dev,swagger
- SPRING_SECURITY_USER_PASSWORD=admin
- JHIPSTER_REGISTRY_PASSWORD=admin
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_TYPE=native
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_SEARCH_LOCATIONS=file:./central-config/localhost-config/
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_TYPE=git
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_URI=https://github.com/jhipster/jhipster-registry/
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_SEARCH_PATHS=central-config
ports:
- 8761:8761

26
src/main/docker/monitoring.yml

@ -0,0 +1,26 @@
version: '2'
services:
formationcontinue-prometheus:
image: prom/prometheus:v2.18.1
volumes:
- ./prometheus/:/etc/prometheus/
command:
- '--config.file=/etc/prometheus/prometheus.yml'
ports:
- 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
formationcontinue-grafana:
image: grafana/grafana:7.0.1
volumes:
- ./grafana/provisioning/:/etc/grafana/provisioning/
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
- GF_USERS_ALLOW_SIGN_UP=false
- GF_INSTALL_PLUGINS=grafana-piechart-panel
ports:
- 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

16
src/main/docker/mssql.yml

@ -0,0 +1,16 @@
version: '2'
services:
formationcontinue-mssql:
image: mcr.microsoft.com/mssql/server:2017-latest-ubuntu
# volumes are not supported on macOS
# volumes:
# - ~/volumes/jhipster/tempdb/mssql/:/var/opt/mssql/data/
environment:
- ACCEPT_EULA=Y
- MSSQL_PID=Express
- SA_PASSWORD=yourStrong(!)Password
- MSSQL_DATABASE=formationContinue
- MSSQL_SLEEP=60
ports:
- 1433:1433
command: /bin/bash -c '/opt/mssql/bin/sqlservr & echo "wait $$MSSQL_SLEEP sec for DB to start "; sleep $$MSSQL_SLEEP; /opt/mssql-tools/bin/sqlcmd -U sa -P $$SA_PASSWORD -d tempdb -q "EXIT(CREATE DATABASE $$MSSQL_DATABASE)"; wait;'

31
src/main/docker/prometheus/prometheus.yml

@ -0,0 +1,31 @@
# Sample global config for monitoring JHipster applications
global:
scrape_interval: 15s # By default, scrape targets every 15 seconds.
evaluation_interval: 15s # By default, scrape targets every 15 seconds.
# scrape_timeout is set to the global default (10s).
# Attach these labels to any time series or alerts when communicating with
# external systems (federation, remote storage, Alertmanager).
external_labels:
monitor: 'jhipster'
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'prometheus'
# Override the global default and scrape targets from this job every 5 seconds.
scrape_interval: 5s
# scheme defaults to 'http' enable https in case your application is server via https
#scheme: https
# basic auth is not needed by default. See https://www.jhipster.tech/monitoring/#configuring-metrics-forwarding for details
#basic_auth:
# username: admin
# password: admin
metrics_path: /management/prometheus
static_configs:
- targets:
# On MacOS, replace localhost by host.docker.internal
- localhost:3005

7
src/main/docker/sonar.yml

@ -0,0 +1,7 @@
version: '2'
services:
formationcontinue-sonar:
image: sonarqube:8.3.1-community
ports:
- 9001:9000
- 9092:9092

20
src/main/java/com/cm/formationcontinue/ApplicationWebXml.java

@ -0,0 +1,20 @@
package com.cm.formationcontinue;
import io.github.jhipster.config.DefaultProfileUtil;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* This is a helper Java class that provides an alternative to creating a {@code web.xml}.
* This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc.
*/
public class ApplicationWebXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// set a default to use when no profile is configured.
DefaultProfileUtil.addDefaultProfile(application.application());
return application.sources(FormationContinueApp.class);
}
}

105
src/main/java/com/cm/formationcontinue/FormationContinueApp.java

@ -0,0 +1,105 @@
package com.cm.formationcontinue;
import com.cm.formationcontinue.config.ApplicationProperties;
import io.github.jhipster.config.DefaultProfileUtil;
import io.github.jhipster.config.JHipsterConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.core.env.Environment;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
public class FormationContinueApp {
private static final Logger log = LoggerFactory.getLogger(FormationContinueApp.class);
private final Environment env;
public FormationContinueApp(Environment env) {
this.env = env;
}
/**
* Initializes formationContinue.
* <p>
* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>.
*/
@PostConstruct
public void initApplication() {
Collection<String> 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_CLOUD)) {
log.error("You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
/**
* Main method, used to run the application.
*
* @param args the command line arguments.
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(FormationContinueApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
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----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
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);
}
}

113
src/main/java/com/cm/formationcontinue/aop/logging/LoggingAspect.java

@ -0,0 +1,113 @@
package com.cm.formationcontinue.aop.logging;
import io.github.jhipster.config.JHipsterConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import java.util.Arrays;
/**
* Aspect for logging execution of service and repository Spring components.
*
* By default, it only runs with the "dev" profile.
*/
@Aspect
public class LoggingAspect {
private final Environment env;
public LoggingAspect(Environment env) {
this.env = env;
}
/**
* Pointcut that matches all repositories, services and Web REST endpoints.
*/
@Pointcut("within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || 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.
}
/**
* Pointcut that matches all Spring beans in the application's main packages.
*/
@Pointcut("within(com.cm.formationcontinue.repository..*)"+
" || within(com.cm.formationcontinue.service..*)"+
" || within(com.cm.formationcontinue.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.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
logger(joinPoint)
.error(
"Exception in {}() with cause = \'{}\' and exception = \'{}\'",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL",
e.getMessage(),
e
);
} else {
logger(joinPoint)
.error(
"Exception in {}() with cause = {}",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL"
);
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice.
* @return result.
* @throws Throwable throws {@link IllegalArgumentException}.
*/
@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().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
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().getName());
throw e;
}
}
}

18
src/main/java/com/cm/formationcontinue/client/UserFeignClientInterceptor.java

@ -0,0 +1,18 @@
package com.cm.formationcontinue.client;
import com.cm.formationcontinue.security.SecurityUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
@Component
public class UserFeignClientInterceptor implements RequestInterceptor {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER = "Bearer";
@Override
public void apply(RequestTemplate template) {
SecurityUtils.getCurrentUserJWT()
.ifPresent(s -> template.header(AUTHORIZATION_HEADER,String.format("%s %s", BEARER, s)));
}
}

13
src/main/java/com/cm/formationcontinue/config/ApplicationProperties.java

@ -0,0 +1,13 @@
package com.cm.formationcontinue.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties specific to Formation Continue.
* <p>
* Properties are configured in the {@code application.yml} file.
* See {@link io.github.jhipster.config.JHipsterProperties} for a good example.
*/
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {
}

47
src/main/java/com/cm/formationcontinue/config/AsyncConfiguration.java

@ -0,0 +1,47 @@
package com.cm.formationcontinue.config;
import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final TaskExecutionProperties taskExecutionProperties;
public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) {
this.taskExecutionProperties = taskExecutionProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix());
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}

28
src/main/java/com/cm/formationcontinue/config/CloudDatabaseConfiguration.java

@ -0,0 +1,28 @@
package com.cm.formationcontinue.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();
}
}

12
src/main/java/com/cm/formationcontinue/config/Constants.java

@ -0,0 +1,12 @@
package com.cm.formationcontinue.config;
/**
* Application constants.
*/
public final class Constants {
public static final String SYSTEM_ACCOUNT = "system";
private Constants() {
}
}

21
src/main/java/com/cm/formationcontinue/config/DatabaseConfiguration.java

@ -0,0 +1,21 @@
package com.cm.formationcontinue.config;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories("com.cm.formationcontinue.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
}

20
src/main/java/com/cm/formationcontinue/config/DateTimeFormatConfiguration.java

@ -0,0 +1,20 @@
package com.cm.formationcontinue.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Configure the converters to use the ISO format for dates by default.
*/
@Configuration
public class DateTimeFormatConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
}

22
src/main/java/com/cm/formationcontinue/config/FeignConfiguration.java

@ -0,0 +1,22 @@
package com.cm.formationcontinue.config;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@EnableFeignClients(basePackages = "com.cm.formationcontinue")
@Import(FeignClientsConfiguration.class)
public class FeignConfiguration {
/**
* Set the Feign specific log level to log client REST requests.
*/
@Bean
feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.BASIC;
}
}

52
src/main/java/com/cm/formationcontinue/config/JacksonConfiguration.java

@ -0,0 +1,52 @@
package com.cm.formationcontinue.config;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.ProblemModule;
import org.zalando.problem.violations.ConstraintViolationProblemModule;
@Configuration
public class JacksonConfiguration {
/**
* Support for Java date and time API.
* @return the corresponding Jackson module.
*/
@Bean
public JavaTimeModule javaTimeModule() {
return new JavaTimeModule();
}
@Bean
public Jdk8Module jdk8TimeModule() {
return new Jdk8Module();
}
/*
* Support for Hibernate types in Jackson.
*/
@Bean
public Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
/*
* Module for serialization/deserialization of RFC7807 Problem.
*/
@Bean
public ProblemModule problemModule() {
return new ProblemModule();
}
/*
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
@Bean
public ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
}

60
src/main/java/com/cm/formationcontinue/config/LiquibaseConfiguration.java

@ -0,0 +1,60 @@
package com.cm.formationcontinue.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.liquibase.SpringLiquibaseUtil;
import liquibase.integration.spring.SpringLiquibase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseDataSource;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.context.annotation.Bean;
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;
@Configuration
public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
public LiquibaseConfiguration(Environment env) {
this.env = env;
}
@Bean
public SpringLiquibase liquibase(@Qualifier("taskExecutor") Executor executor,
@LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource, LiquibaseProperties liquibaseProperties,
ObjectProvider<DataSource> 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);
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema());
liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace());
liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable());
liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setLabels(liquibaseProperties.getLabels());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
liquibase.setRollbackFile(liquibaseProperties.getRollbackFile());
liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate());
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
return liquibase;
}
}

27
src/main/java/com/cm/formationcontinue/config/LocaleConfiguration.java

@ -0,0 +1,27 @@
package com.cm.formationcontinue.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;
@Configuration
public class LocaleConfiguration implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver();
cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY");
return cookieLocaleResolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
registry.addInterceptor(localeChangeInterceptor);
}
}

19
src/main/java/com/cm/formationcontinue/config/LoggingAspectConfiguration.java

@ -0,0 +1,19 @@
package com.cm.formationcontinue.config;
import com.cm.formationcontinue.aop.logging.LoggingAspect;
import io.github.jhipster.config.JHipsterConstants;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
@Configuration
@EnableAspectJAutoProxy
public class LoggingAspectConfiguration {
@Bean
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public LoggingAspect loggingAspect(Environment env) {
return new LoggingAspect(env);
}
}

56
src/main/java/com/cm/formationcontinue/config/LoggingConfiguration.java

@ -0,0 +1,56 @@
package com.cm.formationcontinue.config;
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 org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.info.BuildProperties;
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.*;
/*
* Configures the console and Logstash log appenders from the app properties
*/
@Configuration
@RefreshScope
public class LoggingConfiguration {
public LoggingConfiguration(@Value("${spring.application.name}") String appName,
@Value("${server.port}") String serverPort,
JHipsterProperties jHipsterProperties,
ObjectProvider<BuildProperties> buildProperties,
ObjectMapper mapper) throws JsonProcessingException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Map<String, String> map = new HashMap<>();
map.put("app_name", appName);
map.put("app_port", serverPort);
buildProperties.ifAvailable(it -> map.put("version", it.getVersion()));
String customFields = mapper.writeValueAsString(map);
JHipsterProperties.Logging loggingProperties = jHipsterProperties.getLogging();
JHipsterProperties.Logging.Logstash logstashProperties = loggingProperties.getLogstash();
if (loggingProperties.isUseJsonFormat()) {
addJsonConsoleAppender(context, customFields);
}
if (logstashProperties.isEnabled()) {
addLogstashTcpSocketAppender(context, customFields, logstashProperties);
}
if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) {
addContextListener(context, customFields, loggingProperties);
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
setMetricsMarkerLogbackFilter(context, loggingProperties.isUseJsonFormat());
}
}
}

69
src/main/java/com/cm/formationcontinue/config/SecurityConfiguration.java

@ -0,0 +1,69 @@
package com.cm.formationcontinue.config;
import com.cm.formationcontinue.security.*;
import com.cm.formationcontinue.security.jwt.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
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.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenProvider tokenProvider;
private final SecurityProblemSupport problemSupport;
public SecurityConfiguration(TokenProvider tokenProvider, SecurityProblemSupport problemSupport) {
this.tokenProvider = tokenProvider;
this.problemSupport = problemSupport;
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.headers()
.contentSecurityPolicy("default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:")
.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'")
.and()
.frameOptions()
.deny()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.apply(securityConfigurerAdapter());
// @formatter:on
}
private JWTConfigurer securityConfigurerAdapter() {
return new JWTConfigurer(tokenProvider);
}
}

58
src/main/java/com/cm/formationcontinue/config/WebConfigurer.java

@ -0,0 +1,58 @@
package com.cm.formationcontinue.config;
import io.github.jhipster.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.*;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.servlet.*;
/**
* Configuration of web application with Servlet 3.0 APIs.
*/
@Configuration
public class WebConfigurer implements ServletContextInitializer {
private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
private final Environment env;
private final JHipsterProperties jHipsterProperties;
public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) {
this.env = env;
this.jHipsterProperties = jHipsterProperties;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
log.info("Web application fully configured");
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
}
return new CorsFilter(source);
}
}

86
src/main/java/com/cm/formationcontinue/config/audit/AuditEventConverter.java

@ -0,0 +1,86 @@
package com.cm.formationcontinue.config.audit;
import com.cm.formationcontinue.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<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
if (persistentAuditEvents == null) {
return Collections.emptyList();
}
List<AuditEvent> 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<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> 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<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, Object> 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;
}
}

4
src/main/java/com/cm/formationcontinue/config/audit/package-info.java

@ -0,0 +1,4 @@
/**
* Audit specific code.
*/
package com.cm.formationcontinue.config.audit;

4
src/main/java/com/cm/formationcontinue/config/package-info.java

@ -0,0 +1,4 @@
/**
* Spring Framework configuration files.
*/
package com.cm.formationcontinue.config;

77
src/main/java/com/cm/formationcontinue/domain/AbstractAuditingEntity.java

@ -0,0 +1,77 @@
package com.cm.formationcontinue.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;
/**
* Base abstract class for entities which will hold definitions for created, last modified, created by,
* last modified by attributes.
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;
@CreatedDate
@Column(name = "created_date", updatable = false)
@JsonIgnore
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
@JsonIgnore
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
@JsonIgnore
private Instant lastModifiedDate = Instant.now();
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;
}
}

202
src/main/java/com/cm/formationcontinue/domain/Formation.java

@ -0,0 +1,202 @@
package com.cm.formationcontinue.domain;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
/**
* A Formation.
*/
@Entity
@Table(name = "formation")
public class Formation implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "nom_formation")
private String nomFormation;
@Column(name = "description")
private String description;
@Column(name = "date_debut")
private LocalDate dateDebut;
@Column(name = "date_fin")
private LocalDate dateFin;
@Column(name = "id_organisme_formation")
private Long idOrganismeFormation;
@OneToMany(mappedBy = "formation")
private Set<PersonnelFormation> idPersonnels = new HashSet<>();
@ManyToMany
@JoinTable(name = "formation_skill",
joinColumns = @JoinColumn(name = "formation_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "skill_id", referencedColumnName = "id"))
private Set<Skill> skills = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNomFormation() {
return nomFormation;
}
public Formation nomFormation(String nomFormation) {
this.nomFormation = nomFormation;
return this;
}
public void setNomFormation(String nomFormation) {
this.nomFormation = nomFormation;
}
public String getDescription() {
return description;
}
public Formation description(String description) {
this.description = description;
return this;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDateDebut() {
return dateDebut;
}
public Formation dateDebut(LocalDate dateDebut) {
this.dateDebut = dateDebut;
return this;
}
public void setDateDebut(LocalDate dateDebut) {
this.dateDebut = dateDebut;
}
public LocalDate getDateFin() {
return dateFin;
}
public Formation dateFin(LocalDate dateFin) {
this.dateFin = dateFin;
return this;
}
public void setDateFin(LocalDate dateFin) {
this.dateFin = dateFin;
}
public Long getIdOrganismeFormation() {
return idOrganismeFormation;
}
public Formation idOrganismeFormation(Long idOrganismeFormation) {
this.idOrganismeFormation = idOrganismeFormation;
return this;
}
public void setIdOrganismeFormation(Long idOrganismeFormation) {
this.idOrganismeFormation = idOrganismeFormation;
}
public Set<PersonnelFormation> getIdPersonnels() {
return idPersonnels;
}
public Formation idPersonnels(Set<PersonnelFormation> personnelFormations) {
this.idPersonnels = personnelFormations;
return this;
}
public Formation addIdPersonnel(PersonnelFormation personnelFormation) {
this.idPersonnels.add(personnelFormation);
personnelFormation.setFormation(this);
return this;
}
public Formation removeIdPersonnel(PersonnelFormation personnelFormation) {
this.idPersonnels.remove(personnelFormation);
personnelFormation.setFormation(null);
return this;
}
public void setIdPersonnels(Set<PersonnelFormation> personnelFormations) {
this.idPersonnels = personnelFormations;
}
public Set<Skill> getSkills() {
return skills;
}
public Formation skills(Set<Skill> skills) {
this.skills = skills;
return this;
}
public Formation addSkill(Skill skill) {
this.skills.add(skill);
skill.getFormations().add(this);
return this;
}
public Formation removeSkill(Skill skill) {
this.skills.remove(skill);
skill.getFormations().remove(this);
return this;
}
public void setSkills(Set<Skill> skills) {
this.skills = skills;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Formation)) {
return false;
}
return id != null && id.equals(((Formation) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "Formation{" +
"id=" + getId() +
", nomFormation='" + getNomFormation() + "'" +
", description='" + getDescription() + "'" +
", dateDebut='" + getDateDebut() + "'" +
", dateFin='" + getDateFin() + "'" +
", idOrganismeFormation=" + getIdOrganismeFormation() +
"}";
}
}

108
src/main/java/com/cm/formationcontinue/domain/PersistentAuditEvent.java

@ -0,0 +1,108 @@
package com.cm.formationcontinue.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.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@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<String, String> 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<String, String> getData() {
return data;
}
public void setData(Map<String, String> 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;
}
// prettier-ignore
@Override
public String toString() {
return "PersistentAuditEvent{" +
"principal='" + principal + '\'' +
", auditEventDate=" + auditEventDate +
", auditEventType='" + auditEventType + '\'' +
'}';
}
}

107
src/main/java/com/cm/formationcontinue/domain/PersonnelFormation.java

@ -0,0 +1,107 @@
package com.cm.formationcontinue.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.io.Serializable;
/**
* A PersonnelFormation.
*/
@Entity
@Table(name = "personnel_formation")
public class PersonnelFormation implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "id_formation")
private Long idFormation;
@Column(name = "id_personnel")
private Long idPersonnel;
@ManyToOne
@JsonIgnoreProperties(value = "idPersonnels", allowSetters = true)
private Formation formation;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIdFormation() {
return idFormation;
}
public PersonnelFormation idFormation(Long idFormation) {
this.idFormation = idFormation;
return this;
}
public void setIdFormation(Long idFormation) {
this.idFormation = idFormation;
}
public Long getIdPersonnel() {
return idPersonnel;
}
public PersonnelFormation idPersonnel(Long idPersonnel) {
this.idPersonnel = idPersonnel;
return this;
}
public void setIdPersonnel(Long idPersonnel) {
this.idPersonnel = idPersonnel;
}
public Formation getFormation() {
return formation;
}
public PersonnelFormation formation(Formation formation) {
this.formation = formation;
return this;
}
public void setFormation(Formation formation) {
this.formation = formation;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PersonnelFormation)) {
return false;
}
return id != null && id.equals(((PersonnelFormation) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "PersonnelFormation{" +
"id=" + getId() +
", idFormation=" + getIdFormation() +
", idPersonnel=" + getIdPersonnel() +
"}";
}
}

121
src/main/java/com/cm/formationcontinue/domain/Skill.java

@ -0,0 +1,121 @@
package com.cm.formationcontinue.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* A Skill.
*/
@Entity
@Table(name = "skill")
public class Skill implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "id_formation")
private Long idFormation;
@Column(name = "nom")
private String nom;
@ManyToMany(mappedBy = "skills")
@JsonIgnore
private Set<Formation> formations = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIdFormation() {
return idFormation;
}
public Skill idFormation(Long idFormation) {
this.idFormation = idFormation;
return this;
}
public void setIdFormation(Long idFormation) {
this.idFormation = idFormation;
}
public String getNom() {
return nom;
}
public Skill nom(String nom) {
this.nom = nom;
return this;
}
public void setNom(String nom) {
this.nom = nom;
}
public Set<Formation> getFormations() {
return formations;
}
public Skill formations(Set<Formation> formations) {
this.formations = formations;
return this;
}
public Skill addFormation(Formation formation) {
this.formations.add(formation);
formation.getSkills().add(this);
return this;
}
public Skill removeFormation(Formation formation) {
this.formations.remove(formation);
formation.getSkills().remove(this);
return this;
}
public void setFormations(Set<Formation> formations) {
this.formations = formations;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Skill)) {
return false;
}
return id != null && id.equals(((Skill) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "Skill{" +
"id=" + getId() +
", idFormation=" + getIdFormation() +
", nom='" + getNom() + "'" +
"}";
}
}

4
src/main/java/com/cm/formationcontinue/domain/package-info.java

@ -0,0 +1,4 @@
/**
* JPA domain objects.
*/
package com.cm.formationcontinue.domain;

29
src/main/java/com/cm/formationcontinue/repository/FormationRepository.java

@ -0,0 +1,29 @@
package com.cm.formationcontinue.repository;
import com.cm.formationcontinue.domain.Formation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
/**
* Spring Data repository for the Formation entity.
*/
@Repository
public interface FormationRepository extends JpaRepository<Formation, Long> {
@Query(value = "select distinct formation from Formation formation left join fetch formation.skills",
countQuery = "select count(distinct formation) from Formation formation")
Page<Formation> findAllWithEagerRelationships(Pageable pageable);
@Query("select distinct formation from Formation formation left join fetch formation.skills")
List<Formation> findAllWithEagerRelationships();
@Query("select formation from Formation formation left join fetch formation.skills where formation.id =:id")
Optional<Formation> findOneWithEagerRelationships(@Param("id") Long id);
}

14
src/main/java/com/cm/formationcontinue/repository/PersonnelFormationRepository.java

@ -0,0 +1,14 @@
package com.cm.formationcontinue.repository;
import com.cm.formationcontinue.domain.PersonnelFormation;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the PersonnelFormation entity.
*/
@SuppressWarnings("unused")
@Repository
public interface PersonnelFormationRepository extends JpaRepository<PersonnelFormation, Long> {
}

14
src/main/java/com/cm/formationcontinue/repository/SkillRepository.java

@ -0,0 +1,14 @@
package com.cm.formationcontinue.repository;
import com.cm.formationcontinue.domain.Skill;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Skill entity.
*/
@SuppressWarnings("unused")
@Repository
public interface SkillRepository extends JpaRepository<Skill, Long> {
}

4
src/main/java/com/cm/formationcontinue/repository/package-info.java

@ -0,0 +1,4 @@
/**
* Spring Data JPA repositories.
*/
package com.cm.formationcontinue.repository;

16
src/main/java/com/cm/formationcontinue/security/AuthoritiesConstants.java

@ -0,0 +1,16 @@
package com.cm.formationcontinue.security;
/**
* Constants for Spring Security authorities.
*/
public final class AuthoritiesConstants {
public static final String ADMIN = "ROLE_ADMIN";
public static final String USER = "ROLE_USER";
public static final String ANONYMOUS = "ROLE_ANONYMOUS";
private AuthoritiesConstants() {
}
}

85
src/main/java/com/cm/formationcontinue/security/SecurityUtils.java

@ -0,0 +1,85 @@
package com.cm.formationcontinue.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Utility class for Spring Security.
*/
public final class SecurityUtils {
private SecurityUtils() {
}
/**
* Get the login of the current user.
*
* @return the login of the current user.
*/
public static Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
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.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
}
/**
* Get the JWT of the current user.
*
* @return the JWT of the current user.
*/
public static Optional<String> getCurrentUserJWT() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.filter(authentication -> authentication.getCredentials() instanceof String)
.map(authentication -> (String) authentication.getCredentials());
}
/**
* Check if a user is authenticated.
*
* @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);
}
/**
* If the current user has a specific authority (security role).
* <p>
* The name of this method comes from the {@code isUserInRole()} method in the Servlet API.
*
* @param authority the authority to check.
* @return true if the current user has the authority, false otherwise.
*/
public static boolean isCurrentUserInRole(String authority) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null &&
getAuthorities(authentication).anyMatch(authority::equals);
}
private static Stream<String> getAuthorities(Authentication authentication) {
return authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority);
}
}

20
src/main/java/com/cm/formationcontinue/security/SpringSecurityAuditorAware.java

@ -0,0 +1,20 @@
package com.cm.formationcontinue.security;
import com.cm.formationcontinue.config.Constants;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of {@link AuditorAware} based on Spring Security.
*/
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT));
}
}

21
src/main/java/com/cm/formationcontinue/security/jwt/JWTConfigurer.java

@ -0,0 +1,21 @@
package com.cm.formationcontinue.security.jwt;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class JWTConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
private final TokenProvider tokenProvider;
public JWTConfigurer(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Override
public void configure(HttpSecurity http) {
JWTFilter customFilter = new JWTFilter(tokenProvider);
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
}
}

48
src/main/java/com/cm/formationcontinue/security/jwt/JWTFilter.java

@ -0,0 +1,48 @@
package com.cm.formationcontinue.security.jwt;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is
* found.
*/
public class JWTFilter extends GenericFilterBean {
public static final String AUTHORIZATION_HEADER = "Authorization";
private final TokenProvider tokenProvider;
public JWTFilter(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String jwt = resolveToken(httpServletRequest);
if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
Authentication authentication = this.tokenProvider.getAuthentication(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(servletRequest, servletResponse);
}
private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
}

111
src/main/java/com/cm/formationcontinue/security/jwt/TokenProvider.java

@ -0,0 +1,111 @@
package com.cm.formationcontinue.security.jwt;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import io.github.jhipster.config.JHipsterProperties;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
@Component
public class TokenProvider {
private final Logger log = LoggerFactory.getLogger(TokenProvider.class);
private static final String AUTHORITIES_KEY = "auth";
private Key key;
private long tokenValidityInMilliseconds;
private long tokenValidityInMillisecondsForRememberMe;
private final JHipsterProperties jHipsterProperties;
public TokenProvider(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
public String createToken(Authentication authentication, boolean rememberMe) {
String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
long now = (new Date()).getTime();
Date validity;
if (rememberMe) {
validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe);
} else {
validity = new Date(now + this.tokenValidityInMilliseconds);
}
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(key, SignatureAlgorithm.HS512)
.setExpiration(validity)
.compact();
}
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
User principal = new User(claims.getSubject(), "", authorities);
return new UsernamePasswordAuthenticationToken(principal, token, authorities);
}
public boolean validateToken(String authToken) {
try {
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(authToken);
return true;
} catch (JwtException | IllegalArgumentException e) {
log.info("Invalid JWT token.");
log.trace("Invalid JWT token trace.", e);
}
return false;
}
}

4
src/main/java/com/cm/formationcontinue/security/package-info.java

@ -0,0 +1,4 @@
/**
* Spring Security configuration.
*/
package com.cm.formationcontinue.security;

93
src/main/java/com/cm/formationcontinue/service/FormationService.java

@ -0,0 +1,93 @@
package com.cm.formationcontinue.service;
import com.cm.formationcontinue.domain.Formation;
import com.cm.formationcontinue.repository.FormationRepository;
import com.cm.formationcontinue.service.dto.FormationDTO;
import com.cm.formationcontinue.service.mapper.FormationMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing {@link Formation}.
*/
@Service
@Transactional
public class FormationService {
private final Logger log = LoggerFactory.getLogger(FormationService.class);
private final FormationRepository formationRepository;
private final FormationMapper formationMapper;
public FormationService(FormationRepository formationRepository, FormationMapper formationMapper) {
this.formationRepository = formationRepository;
this.formationMapper = formationMapper;
}
/**
* Save a formation.
*
* @param formationDTO the entity to save.
* @return the persisted entity.
*/
public FormationDTO save(FormationDTO formationDTO) {
log.debug("Request to save Formation : {}", formationDTO);
Formation formation = formationMapper.toEntity(formationDTO);
formation = formationRepository.save(formation);
return formationMapper.toDto(formation);
}
/**
* Get all the formations.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Transactional(readOnly = true)
public Page<FormationDTO> findAll(Pageable pageable) {
log.debug("Request to get all Formations");
return formationRepository.findAll(pageable)
.map(formationMapper::toDto);
}
/**
* Get all the formations with eager load of many-to-many relationships.
*
* @return the list of entities.
*/
public Page<FormationDTO> findAllWithEagerRelationships(Pageable pageable) {
return formationRepository.findAllWithEagerRelationships(pageable).map(formationMapper::toDto);
}
/**
* Get one formation by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Transactional(readOnly = true)
public Optional<FormationDTO> findOne(Long id) {
log.debug("Request to get Formation : {}", id);
return formationRepository.findOneWithEagerRelationships(id)
.map(formationMapper::toDto);
}
/**
* Delete the formation by id.
*
* @param id the id of the entity.
*/
public void delete(Long id) {
log.debug("Request to delete Formation : {}", id);
formationRepository.deleteById(id);
}
}

84
src/main/java/com/cm/formationcontinue/service/PersonnelFormationService.java

@ -0,0 +1,84 @@
package com.cm.formationcontinue.service;
import com.cm.formationcontinue.domain.PersonnelFormation;
import com.cm.formationcontinue.repository.PersonnelFormationRepository;
import com.cm.formationcontinue.service.dto.PersonnelFormationDTO;
import com.cm.formationcontinue.service.mapper.PersonnelFormationMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing {@link PersonnelFormation}.
*/
@Service
@Transactional
public class PersonnelFormationService {
private final Logger log = LoggerFactory.getLogger(PersonnelFormationService.class);
private final PersonnelFormationRepository personnelFormationRepository;
private final PersonnelFormationMapper personnelFormationMapper;
public PersonnelFormationService(PersonnelFormationRepository personnelFormationRepository, PersonnelFormationMapper personnelFormationMapper) {
this.personnelFormationRepository = personnelFormationRepository;
this.personnelFormationMapper = personnelFormationMapper;
}
/**
* Save a personnelFormation.
*
* @param personnelFormationDTO the entity to save.
* @return the persisted entity.
*/
public PersonnelFormationDTO save(PersonnelFormationDTO personnelFormationDTO) {
log.debug("Request to save PersonnelFormation : {}", personnelFormationDTO);
PersonnelFormation personnelFormation = personnelFormationMapper.toEntity(personnelFormationDTO);
personnelFormation = personnelFormationRepository.save(personnelFormation);
return personnelFormationMapper.toDto(personnelFormation);
}
/**
* Get all the personnelFormations.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Transactional(readOnly = true)
public Page<PersonnelFormationDTO> findAll(Pageable pageable) {
log.debug("Request to get all PersonnelFormations");
return personnelFormationRepository.findAll(pageable)
.map(personnelFormationMapper::toDto);
}
/**
* Get one personnelFormation by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Transactional(readOnly = true)
public Optional<PersonnelFormationDTO> findOne(Long id) {
log.debug("Request to get PersonnelFormation : {}", id);
return personnelFormationRepository.findById(id)
.map(personnelFormationMapper::toDto);
}
/**
* Delete the personnelFormation by id.
*
* @param id the id of the entity.
*/
public void delete(Long id) {
log.debug("Request to delete PersonnelFormation : {}", id);
personnelFormationRepository.deleteById(id);
}
}

84
src/main/java/com/cm/formationcontinue/service/SkillService.java

@ -0,0 +1,84 @@
package com.cm.formationcontinue.service;
import com.cm.formationcontinue.domain.Skill;
import com.cm.formationcontinue.repository.SkillRepository;
import com.cm.formationcontinue.service.dto.SkillDTO;
import com.cm.formationcontinue.service.mapper.SkillMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing {@link Skill}.
*/
@Service
@Transactional
public class SkillService {
private final Logger log = LoggerFactory.getLogger(SkillService.class);
private final SkillRepository skillRepository;
private final SkillMapper skillMapper;
public SkillService(SkillRepository skillRepository, SkillMapper skillMapper) {
this.skillRepository = skillRepository;
this.skillMapper = skillMapper;
}
/**
* Save a skill.
*
* @param skillDTO the entity to save.
* @return the persisted entity.
*/
public SkillDTO save(SkillDTO skillDTO) {
log.debug("Request to save Skill : {}", skillDTO);
Skill skill = skillMapper.toEntity(skillDTO);
skill = skillRepository.save(skill);
return skillMapper.toDto(skill);
}
/**
* Get all the skills.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Transactional(readOnly = true)
public Page<SkillDTO> findAll(Pageable pageable) {
log.debug("Request to get all Skills");
return skillRepository.findAll(pageable)
.map(skillMapper::toDto);
}
/**
* Get one skill by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Transactional(readOnly = true)
public Optional<SkillDTO> findOne(Long id) {
log.debug("Request to get Skill : {}", id);
return skillRepository.findById(id)
.map(skillMapper::toDto);
}
/**
* Delete the skill by id.
*
* @param id the id of the entity.
*/
public void delete(Long id) {
log.debug("Request to delete Skill : {}", id);
skillRepository.deleteById(id);
}
}

113
src/main/java/com/cm/formationcontinue/service/dto/FormationDTO.java

@ -0,0 +1,113 @@
package com.cm.formationcontinue.service.dto;
import java.time.LocalDate;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* A DTO for the {@link com.cm.formationcontinue.domain.Formation} entity.
*/
public class FormationDTO implements Serializable {
private Long id;
private String nomFormation;
private String description;
private LocalDate dateDebut;
private LocalDate dateFin;
private Long idOrganismeFormation;
private Set<SkillDTO> skills = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNomFormation() {
return nomFormation;
}
public void setNomFormation(String nomFormation) {
this.nomFormation = nomFormation;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDateDebut() {
return dateDebut;
}
public void setDateDebut(LocalDate dateDebut) {
this.dateDebut = dateDebut;
}
public LocalDate getDateFin() {
return dateFin;
}
public void setDateFin(LocalDate dateFin) {
this.dateFin = dateFin;
}
public Long getIdOrganismeFormation() {
return idOrganismeFormation;
}
public void setIdOrganismeFormation(Long idOrganismeFormation) {
this.idOrganismeFormation = idOrganismeFormation;
}
public Set<SkillDTO> getSkills() {
return skills;
}
public void setSkills(Set<SkillDTO> skills) {
this.skills = skills;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof FormationDTO)) {
return false;
}
return id != null && id.equals(((FormationDTO) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "FormationDTO{" +
"id=" + getId() +
", nomFormation='" + getNomFormation() + "'" +
", description='" + getDescription() + "'" +
", dateDebut='" + getDateDebut() + "'" +
", dateFin='" + getDateFin() + "'" +
", idOrganismeFormation=" + getIdOrganismeFormation() +
", skills='" + getSkills() + "'" +
"}";
}
}

78
src/main/java/com/cm/formationcontinue/service/dto/PersonnelFormationDTO.java

@ -0,0 +1,78 @@
package com.cm.formationcontinue.service.dto;
import java.io.Serializable;
/**
* A DTO for the {@link com.cm.formationcontinue.domain.PersonnelFormation} entity.
*/
public class PersonnelFormationDTO implements Serializable {
private Long id;
private Long idFormation;
private Long idPersonnel;
private Long formationId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIdFormation() {
return idFormation;
}
public void setIdFormation(Long idFormation) {
this.idFormation = idFormation;
}
public Long getIdPersonnel() {
return idPersonnel;
}
public void setIdPersonnel(Long idPersonnel) {
this.idPersonnel = idPersonnel;
}
public Long getFormationId() {
return formationId;
}
public void setFormationId(Long formationId) {
this.formationId = formationId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PersonnelFormationDTO)) {
return false;
}
return id != null && id.equals(((PersonnelFormationDTO) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "PersonnelFormationDTO{" +
"id=" + getId() +
", idFormation=" + getIdFormation() +
", idPersonnel=" + getIdPersonnel() +
", formationId=" + getFormationId() +
"}";
}
}

67
src/main/java/com/cm/formationcontinue/service/dto/SkillDTO.java

@ -0,0 +1,67 @@
package com.cm.formationcontinue.service.dto;
import java.io.Serializable;
/**
* A DTO for the {@link com.cm.formationcontinue.domain.Skill} entity.
*/
public class SkillDTO implements Serializable {
private Long id;
private Long idFormation;
private String nom;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIdFormation() {
return idFormation;
}
public void setIdFormation(Long idFormation) {
this.idFormation = idFormation;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SkillDTO)) {
return false;
}
return id != null && id.equals(((SkillDTO) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "SkillDTO{" +
"id=" + getId() +
", idFormation=" + getIdFormation() +
", nom='" + getNom() + "'" +
"}";
}
}

21
src/main/java/com/cm/formationcontinue/service/mapper/EntityMapper.java

@ -0,0 +1,21 @@
package com.cm.formationcontinue.service.mapper;
import java.util.List;
/**
* Contract for a generic dto to entity mapper.
*
* @param <D> - DTO type parameter.
* @param <E> - Entity type parameter.
*/
public interface EntityMapper <D, E> {
E toEntity(D dto);
D toDto(E entity);
List <E> toEntity(List<D> dtoList);
List <D> toDto(List<E> entityList);
}

29
src/main/java/com/cm/formationcontinue/service/mapper/FormationMapper.java

@ -0,0 +1,29 @@
package com.cm.formationcontinue.service.mapper;
import com.cm.formationcontinue.domain.*;
import com.cm.formationcontinue.service.dto.FormationDTO;
import org.mapstruct.*;
/**
* Mapper for the entity {@link Formation} and its DTO {@link FormationDTO}.
*/
@Mapper(componentModel = "spring", uses = {SkillMapper.class})
public interface FormationMapper extends EntityMapper<FormationDTO, Formation> {
@Mapping(target = "idPersonnels", ignore = true)
@Mapping(target = "removeIdPersonnel", ignore = true)
@Mapping(target = "removeSkill", ignore = true)
Formation toEntity(FormationDTO formationDTO);
default Formation fromId(Long id) {
if (id == null) {
return null;
}
Formation formation = new Formation();
formation.setId(id);
return formation;
}
}

29
src/main/java/com/cm/formationcontinue/service/mapper/PersonnelFormationMapper.java

@ -0,0 +1,29 @@
package com.cm.formationcontinue.service.mapper;
import com.cm.formationcontinue.domain.*;
import com.cm.formationcontinue.service.dto.PersonnelFormationDTO;
import org.mapstruct.*;
/**
* Mapper for the entity {@link PersonnelFormation} and its DTO {@link PersonnelFormationDTO}.
*/
@Mapper(componentModel = "spring", uses = {FormationMapper.class})
public interface PersonnelFormationMapper extends EntityMapper<PersonnelFormationDTO, PersonnelFormation> {
@Mapping(source = "formation.id", target = "formationId")
PersonnelFormationDTO toDto(PersonnelFormation personnelFormation);
@Mapping(source = "formationId", target = "formation")
PersonnelFormation toEntity(PersonnelFormationDTO personnelFormationDTO);
default PersonnelFormation fromId(Long id) {
if (id == null) {
return null;
}
PersonnelFormation personnelFormation = new PersonnelFormation();
personnelFormation.setId(id);
return personnelFormation;
}
}

28
src/main/java/com/cm/formationcontinue/service/mapper/SkillMapper.java

@ -0,0 +1,28 @@
package com.cm.formationcontinue.service.mapper;
import com.cm.formationcontinue.domain.*;
import com.cm.formationcontinue.service.dto.SkillDTO;
import org.mapstruct.*;
/**
* Mapper for the entity {@link Skill} and its DTO {@link SkillDTO}.
*/
@Mapper(componentModel = "spring", uses = {})
public interface SkillMapper extends EntityMapper<SkillDTO, Skill> {
@Mapping(target = "formations", ignore = true)
@Mapping(target = "removeFormation", ignore = true)
Skill toEntity(SkillDTO skillDTO);
default Skill fromId(Long id) {
if (id == null) {
return null;
}
Skill skill = new Skill();
skill.setId(id);
return skill;
}
}

4
src/main/java/com/cm/formationcontinue/service/package-info.java

@ -0,0 +1,4 @@
/**
* Service layer beans.
*/
package com.cm.formationcontinue.service;

131
src/main/java/com/cm/formationcontinue/web/rest/FormationResource.java

@ -0,0 +1,131 @@
package com.cm.formationcontinue.web.rest;
import com.cm.formationcontinue.service.FormationService;
import com.cm.formationcontinue.web.rest.errors.BadRequestAlertException;
import com.cm.formationcontinue.service.dto.FormationDTO;
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;
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.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link com.cm.formationcontinue.domain.Formation}.
*/
@RestController
@RequestMapping("/api")
public class FormationResource {
private final Logger log = LoggerFactory.getLogger(FormationResource.class);
private static final String ENTITY_NAME = "formationContinueFormation";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final FormationService formationService;
public FormationResource(FormationService formationService) {
this.formationService = formationService;
}
/**
* {@code POST /formations} : Create a new formation.
*
* @param formationDTO the formationDTO to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new formationDTO, or with status {@code 400 (Bad Request)} if the formation has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/formations")
public ResponseEntity<FormationDTO> createFormation(@RequestBody FormationDTO formationDTO) throws URISyntaxException {
log.debug("REST request to save Formation : {}", formationDTO);
if (formationDTO.getId() != null) {
throw new BadRequestAlertException("A new formation cannot already have an ID", ENTITY_NAME, "idexists");
}
FormationDTO result = formationService.save(formationDTO);
return ResponseEntity.created(new URI("/api/formations/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /formations} : Updates an existing formation.
*
* @param formationDTO the formationDTO to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated formationDTO,
* or with status {@code 400 (Bad Request)} if the formationDTO is not valid,
* or with status {@code 500 (Internal Server Error)} if the formationDTO couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/formations")
public ResponseEntity<FormationDTO> updateFormation(@RequestBody FormationDTO formationDTO) throws URISyntaxException {
log.debug("REST request to update Formation : {}", formationDTO);
if (formationDTO.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
FormationDTO result = formationService.save(formationDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, formationDTO.getId().toString()))
.body(result);
}
/**
* {@code GET /formations} : get all the formations.
*
* @param pageable the pagination information.
* @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of formations in body.
*/
@GetMapping("/formations")
public ResponseEntity<List<FormationDTO>> getAllFormations(Pageable pageable, @RequestParam(required = false, defaultValue = "false") boolean eagerload) {
log.debug("REST request to get a page of Formations");
Page<FormationDTO> page;
if (eagerload) {
page = formationService.findAllWithEagerRelationships(pageable);
} else {
page = formationService.findAll(pageable);
}
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /formations/:id} : get the "id" formation.
*
* @param id the id of the formationDTO to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the formationDTO, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/formations/{id}")
public ResponseEntity<FormationDTO> getFormation(@PathVariable Long id) {
log.debug("REST request to get Formation : {}", id);
Optional<FormationDTO> formationDTO = formationService.findOne(id);
return ResponseUtil.wrapOrNotFound(formationDTO);
}
/**
* {@code DELETE /formations/:id} : delete the "id" formation.
*
* @param id the id of the formationDTO to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/formations/{id}")
public ResponseEntity<Void> deleteFormation(@PathVariable Long id) {
log.debug("REST request to delete Formation : {}", id);
formationService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
}
}

125
src/main/java/com/cm/formationcontinue/web/rest/PersonnelFormationResource.java

@ -0,0 +1,125 @@
package com.cm.formationcontinue.web.rest;
import com.cm.formationcontinue.service.PersonnelFormationService;
import com.cm.formationcontinue.web.rest.errors.BadRequestAlertException;
import com.cm.formationcontinue.service.dto.PersonnelFormationDTO;
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;
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.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link com.cm.formationcontinue.domain.PersonnelFormation}.
*/
@RestController
@RequestMapping("/api")
public class PersonnelFormationResource {
private final Logger log = LoggerFactory.getLogger(PersonnelFormationResource.class);
private static final String ENTITY_NAME = "formationContinuePersonnelFormation";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final PersonnelFormationService personnelFormationService;
public PersonnelFormationResource(PersonnelFormationService personnelFormationService) {
this.personnelFormationService = personnelFormationService;
}
/**
* {@code POST /personnel-formations} : Create a new personnelFormation.
*
* @param personnelFormationDTO the personnelFormationDTO to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new personnelFormationDTO, or with status {@code 400 (Bad Request)} if the personnelFormation has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/personnel-formations")
public ResponseEntity<PersonnelFormationDTO> createPersonnelFormation(@RequestBody PersonnelFormationDTO personnelFormationDTO) throws URISyntaxException {
log.debug("REST request to save PersonnelFormation : {}", personnelFormationDTO);
if (personnelFormationDTO.getId() != null) {
throw new BadRequestAlertException("A new personnelFormation cannot already have an ID", ENTITY_NAME, "idexists");
}
PersonnelFormationDTO result = personnelFormationService.save(personnelFormationDTO);
return ResponseEntity.created(new URI("/api/personnel-formations/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /personnel-formations} : Updates an existing personnelFormation.
*
* @param personnelFormationDTO the personnelFormationDTO to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated personnelFormationDTO,
* or with status {@code 400 (Bad Request)} if the personnelFormationDTO is not valid,
* or with status {@code 500 (Internal Server Error)} if the personnelFormationDTO couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/personnel-formations")
public ResponseEntity<PersonnelFormationDTO> updatePersonnelFormation(@RequestBody PersonnelFormationDTO personnelFormationDTO) throws URISyntaxException {
log.debug("REST request to update PersonnelFormation : {}", personnelFormationDTO);
if (personnelFormationDTO.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
PersonnelFormationDTO result = personnelFormationService.save(personnelFormationDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, personnelFormationDTO.getId().toString()))
.body(result);
}
/**
* {@code GET /personnel-formations} : get all the personnelFormations.
*
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of personnelFormations in body.
*/
@GetMapping("/personnel-formations")
public ResponseEntity<List<PersonnelFormationDTO>> getAllPersonnelFormations(Pageable pageable) {
log.debug("REST request to get a page of PersonnelFormations");
Page<PersonnelFormationDTO> page = personnelFormationService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /personnel-formations/:id} : get the "id" personnelFormation.
*
* @param id the id of the personnelFormationDTO to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the personnelFormationDTO, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/personnel-formations/{id}")
public ResponseEntity<PersonnelFormationDTO> getPersonnelFormation(@PathVariable Long id) {
log.debug("REST request to get PersonnelFormation : {}", id);
Optional<PersonnelFormationDTO> personnelFormationDTO = personnelFormationService.findOne(id);
return ResponseUtil.wrapOrNotFound(personnelFormationDTO);
}
/**
* {@code DELETE /personnel-formations/:id} : delete the "id" personnelFormation.
*
* @param id the id of the personnelFormationDTO to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/personnel-formations/{id}")
public ResponseEntity<Void> deletePersonnelFormation(@PathVariable Long id) {
log.debug("REST request to delete PersonnelFormation : {}", id);
personnelFormationService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
}
}

125
src/main/java/com/cm/formationcontinue/web/rest/SkillResource.java

@ -0,0 +1,125 @@
package com.cm.formationcontinue.web.rest;
import com.cm.formationcontinue.service.SkillService;
import com.cm.formationcontinue.web.rest.errors.BadRequestAlertException;
import com.cm.formationcontinue.service.dto.SkillDTO;
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;
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.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link com.cm.formationcontinue.domain.Skill}.
*/
@RestController
@RequestMapping("/api")
public class SkillResource {
private final Logger log = LoggerFactory.getLogger(SkillResource.class);
private static final String ENTITY_NAME = "formationContinueSkill";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final SkillService skillService;
public SkillResource(SkillService skillService) {
this.skillService = skillService;
}
/**
* {@code POST /skills} : Create a new skill.
*
* @param skillDTO the skillDTO to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new skillDTO, or with status {@code 400 (Bad Request)} if the skill has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/skills")
public ResponseEntity<SkillDTO> createSkill(@RequestBody SkillDTO skillDTO) throws URISyntaxException {
log.debug("REST request to save Skill : {}", skillDTO);
if (skillDTO.getId() != null) {
throw new BadRequestAlertException("A new skill cannot already have an ID", ENTITY_NAME, "idexists");
}
SkillDTO result = skillService.save(skillDTO);
return ResponseEntity.created(new URI("/api/skills/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /skills} : Updates an existing skill.
*
* @param skillDTO the skillDTO to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated skillDTO,
* or with status {@code 400 (Bad Request)} if the skillDTO is not valid,
* or with status {@code 500 (Internal Server Error)} if the skillDTO couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/skills")
public ResponseEntity<SkillDTO> updateSkill(@RequestBody SkillDTO skillDTO) throws URISyntaxException {
log.debug("REST request to update Skill : {}", skillDTO);
if (skillDTO.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
SkillDTO result = skillService.save(skillDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, skillDTO.getId().toString()))
.body(result);
}
/**
* {@code GET /skills} : get all the skills.
*
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of skills in body.
*/
@GetMapping("/skills")
public ResponseEntity<List<SkillDTO>> getAllSkills(Pageable pageable) {
log.debug("REST request to get a page of Skills");
Page<SkillDTO> page = skillService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /skills/:id} : get the "id" skill.
*
* @param id the id of the skillDTO to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the skillDTO, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/skills/{id}")
public ResponseEntity<SkillDTO> getSkill(@PathVariable Long id) {
log.debug("REST request to get Skill : {}", id);
Optional<SkillDTO> skillDTO = skillService.findOne(id);
return ResponseUtil.wrapOrNotFound(skillDTO);
}
/**
* {@code DELETE /skills/:id} : delete the "id" skill.
*
* @param id the id of the skillDTO to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/skills/{id}")
public ResponseEntity<Void> deleteSkill(@PathVariable Long id) {
log.debug("REST request to delete Skill : {}", id);
skillService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
}
}

42
src/main/java/com/cm/formationcontinue/web/rest/errors/BadRequestAlertException.java

@ -0,0 +1,42 @@
package com.cm.formationcontinue.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class BadRequestAlertException extends AbstractThrowableProblem {
private static final long serialVersionUID = 1L;
private final String entityName;
private final String errorKey;
public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) {
this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey);
}
public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey));
this.entityName = entityName;
this.errorKey = errorKey;
}
public String getEntityName() {
return entityName;
}
public String getErrorKey() {
return errorKey;
}
private static Map<String, Object> getAlertParameters(String entityName, String errorKey) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("message", "error." + errorKey);
parameters.put("params", entityName);
return parameters;
}
}

15
src/main/java/com/cm/formationcontinue/web/rest/errors/ErrorConstants.java

@ -0,0 +1,15 @@
package com.cm.formationcontinue.web.rest.errors;
import java.net.URI;
public final class ErrorConstants {
public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure";
public static final String ERR_VALIDATION = "error.validation";
public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem";
public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message");
public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation");
private ErrorConstants() {
}
}

181
src/main/java/com/cm/formationcontinue/web/rest/errors/ExceptionTranslator.java

@ -0,0 +1,181 @@
package com.cm.formationcontinue.web.rest.errors;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.web.util.HeaderUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DataAccessException;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.core.env.Environment;
import org.zalando.problem.DefaultProblem;
import org.zalando.problem.Problem;
import org.zalando.problem.ProblemBuilder;
import org.zalando.problem.Status;
import org.zalando.problem.StatusType;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
import org.zalando.problem.violations.ConstraintViolationProblem;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Controller advice to translate the server side exceptions to client-friendly json structures.
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807).
*/
@ControllerAdvice
public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait {
private static final String FIELD_ERRORS_KEY = "fieldErrors";
private static final String MESSAGE_KEY = "message";
private static final String PATH_KEY = "path";
private static final String VIOLATIONS_KEY = "violations";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final Environment env;
public ExceptionTranslator(Environment env) {
this.env = env;
}
/**
* Post-process the Problem payload to add the message key for the front-end if needed.
*/
@Override
public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) {
if (entity == null) {
return entity;
}
Problem problem = entity.getBody();
if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) {
return entity;
}
ProblemBuilder builder = Problem.builder()
.withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType())
.withStatus(problem.getStatus())
.withTitle(problem.getTitle())
.with(PATH_KEY, request.getNativeRequest(HttpServletRequest.class).getRequestURI());
if (problem instanceof ConstraintViolationProblem) {
builder
.with(VIOLATIONS_KEY, ((ConstraintViolationProblem) problem).getViolations())
.with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION);
} else {
builder
.withCause(((DefaultProblem) problem).getCause())
.withDetail(problem.getDetail())
.withInstance(problem.getInstance());
problem.getParameters().forEach(builder::with);
if (!problem.getParameters().containsKey(MESSAGE_KEY) && problem.getStatus() != null) {
builder.with(MESSAGE_KEY, "error.http." + problem.getStatus().getStatusCode());
}
}
return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName().replaceFirst("DTO$", ""), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
.with(FIELD_ERRORS_KEY, fieldErrors)
.build();
return create(ex, problem, request);
}
@ExceptionHandler
public ResponseEntity<Problem> handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) {
return create(ex, request, HeaderUtil.createFailureAlert(applicationName, true, ex.getEntityName(), ex.getErrorKey(), ex.getMessage()));
}
@ExceptionHandler
public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) {
Problem problem = Problem.builder()
.withStatus(Status.CONFLICT)
.with(MESSAGE_KEY, ErrorConstants.ERR_CONCURRENCY_FAILURE)
.build();
return create(ex, problem, request);
}
@Override
public ProblemBuilder prepare(final Throwable throwable, final StatusType status, final URI type) {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
if (throwable instanceof HttpMessageConversionException) {
return Problem.builder()
.withType(type)
.withTitle(status.getReasonPhrase())
.withStatus(status)
.withDetail("Unable to convert http message")
.withCause(Optional.ofNullable(throwable.getCause())
.filter(cause -> isCausalChainsEnabled())
.map(this::toProblem)
.orElse(null));
}
if (throwable instanceof DataAccessException) {
return Problem.builder()
.withType(type)
.withTitle(status.getReasonPhrase())
.withStatus(status)
.withDetail("Failure during data access")
.withCause(Optional.ofNullable(throwable.getCause())
.filter(cause -> isCausalChainsEnabled())
.map(this::toProblem)
.orElse(null));
}
if (containsPackageName(throwable.getMessage())) {
return Problem.builder()
.withType(type)
.withTitle(status.getReasonPhrase())
.withStatus(status)
.withDetail("Unexpected runtime exception")
.withCause(Optional.ofNullable(throwable.getCause())
.filter(cause -> isCausalChainsEnabled())
.map(this::toProblem)
.orElse(null));
}
}
return Problem.builder()
.withType(type)
.withTitle(status.getReasonPhrase())
.withStatus(status)
.withDetail(throwable.getMessage())
.withCause(Optional.ofNullable(throwable.getCause())
.filter(cause -> isCausalChainsEnabled())
.map(this::toProblem)
.orElse(null));
}
private boolean containsPackageName(String message) {
// This list is for sure not complete
return StringUtils.containsAny(message, "org.", "java.", "net.", "javax.", "com.", "io.", "de.", "com.cm.formationcontinue");
}
}

33
src/main/java/com/cm/formationcontinue/web/rest/errors/FieldErrorVM.java

@ -0,0 +1,33 @@
package com.cm.formationcontinue.web.rest.errors;
import java.io.Serializable;
public class FieldErrorVM implements Serializable {
private static final long serialVersionUID = 1L;
private final String objectName;
private final String field;
private final String message;
public FieldErrorVM(String dto, String field, String message) {
this.objectName = dto;
this.field = field;
this.message = message;
}
public String getObjectName() {
return objectName;
}
public String getField() {
return field;
}
public String getMessage() {
return message;
}
}

6
src/main/java/com/cm/formationcontinue/web/rest/errors/package-info.java

@ -0,0 +1,6 @@
/**
* Specific errors used with Zalando's "problem-spring-web" library.
*
* More information on https://github.com/zalando/problem-spring-web
*/
package com.cm.formationcontinue.web.rest.errors;

4
src/main/java/com/cm/formationcontinue/web/rest/package-info.java

@ -0,0 +1,4 @@
/**
* Spring MVC REST controllers.
*/
package com.cm.formationcontinue.web.rest;

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save