First Import

This commit is contained in:
Giancarlo Panichi 2021-11-30 16:47:42 +01:00
commit fe3949d77d
442 changed files with 57106 additions and 0 deletions

23
.editorconfig Normal file
View File

@ -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

9
.eslintignore Normal file
View File

@ -0,0 +1,9 @@
node_modules/
src/main/docker/
src/test/javascript/protractor.conf.js
src/test/javascript/jest.conf.js
webpack/
target/
build/
node/
postcss.config.js

24
.eslintrc.json Normal file
View File

@ -0,0 +1,24 @@
{
"plugins": ["@typescript-eslint/tslint"],
"extends": ["jhipster"],
"parserOptions": {
"project": "./tsconfig.base.json"
},
"rules": {
"@typescript-eslint/tslint/config": [
"error",
{
"lintFile": "./tslint.json"
}
],
"@typescript-eslint/no-unused-vars": [
"warn",
{
"vars": "all",
"args": "after-used",
"ignoreRestSiblings": false
}
],
"@typescript-eslint/no-non-null-assertion": "off"
}
}

150
.gitattributes vendored Normal file
View File

@ -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

155
.gitignore vendored Normal file
View File

@ -0,0 +1,155 @@
######################
# Project Specific
######################
/src/main/webapp/content/css/main.css
/target/classes/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
/.attach_pid1184
/.attach_pid14281
/.attach_pid27581
/.attach_pid28007
/.attach_pid29719
/.attach_pid31807
/.attach_pid4789

5
.huskyrc Normal file
View File

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

3
.lintstagedrc.js Normal file
View File

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

117
.mvn/wrapper/MavenWrapperDownloader.java vendored Normal file
View File

@ -0,0 +1,117 @@
/*
* Copyright 2007-present 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
*
* http://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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

2
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

8
.prettierignore Normal file
View File

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

12
.prettierrc Normal file
View File

@ -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

39
.yo-rc.json Normal file
View File

@ -0,0 +1,39 @@
{
"generator-jhipster": {
"promptValues": {
"packageName": "it.cnr.isti.epasmed"
},
"jhipsterVersion": "6.10.4",
"applicationType": "monolith",
"baseName": "epasmed",
"packageName": "it.cnr.isti.epasmed",
"packageFolder": "it/cnr/isti/epasmed",
"serverPort": "8080",
"authenticationType": "session",
"cacheProvider": "no",
"websocket": false,
"databaseType": "sql",
"devDatabaseType": "h2Disk",
"prodDatabaseType": "postgresql",
"searchEngine": false,
"messageBroker": false,
"serviceDiscoveryType": false,
"buildTool": "maven",
"enableSwaggerCodegen": true,
"rememberMeKey": "4130cb9045e4ce9479bec67eb3d78c04384bd6a04ccfb79510ff9aa8e1dd9233930cb396a534b842ab4537d3d21744127bc7",
"embeddableLaunchScript": false,
"useSass": true,
"clientPackageManager": "npm",
"clientFramework": "angularX",
"clientTheme": "none",
"clientThemeVariant": "",
"creationTimestamp": 1606233754700,
"testFrameworks": [],
"jhiPrefix": "jhi",
"entitySuffix": "",
"dtoSuffix": "DTO",
"otherModules": [],
"enableTranslation": false,
"blueprints": []
}
}

254
README-Orig.md Normal file
View File

@ -0,0 +1,254 @@
# epasmed
This application was generated using JHipster 6.10.4, you can find documentation and help at [https://www.jhipster.tech/documentation-archive/v6.10.4](https://www.jhipster.tech/documentation-archive/v6.10.4).
## Development
Before you can build this project, you must install and configure the following dependencies on your machine:
1. [Node.js][]: We use Node to run a development web server and build the project.
Depending on your system, you can install Node either from source or as a pre-packaged bundle.
After installing Node, you should be able to run the following command to install development tools.
You will only need to run this command when dependencies change in [package.json](package.json).
```
npm install
```
We use npm scripts and [Webpack][] as our build system.
Run the following commands in two separate terminals to create a blissful development experience where your browser
auto-refreshes when files change on your hard drive.
```
./mvnw
npm start
```
Npm is also used to manage CSS and JavaScript dependencies used in this application. You can upgrade dependencies by
specifying a newer version in [package.json](package.json). You can also run `npm update` and `npm install` to manage dependencies.
Add the `help` flag on any command to see how you can use it. For example, `npm help update`.
The `npm run` command will list all of the scripts available to run for this project.
### PWA Support
JHipster ships with PWA (Progressive Web App) support, and it's turned off by default. One of the main components of a PWA is a service worker.
The service worker initialization code is commented out by default. To enable it, uncomment the following code in `src/main/webapp/index.html`:
```html
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js').then(function () {
console.log('Service Worker Registered');
});
}
</script>
```
Note: [Workbox](https://developers.google.com/web/tools/workbox/) powers JHipster's service worker. It dynamically generates the `service-worker.js` file.
### Managing dependencies
For example, to add [Leaflet][] library as a runtime dependency of your application, you would run following command:
```
npm install --save --save-exact leaflet
```
To benefit from TypeScript type definitions from [DefinitelyTyped][] repository in development, you would run following command:
```
npm install --save-dev --save-exact @types/leaflet
```
Then you would import the JS and CSS files specified in library's installation instructions so that [Webpack][] knows about them:
Edit [src/main/webapp/app/vendor.ts](src/main/webapp/app/vendor.ts) file:
```
import 'leaflet/dist/leaflet.js';
```
Edit [src/main/webapp/content/scss/vendor.scss](src/main/webapp/content/scss/vendor.scss) file:
```
@import '~leaflet/dist/leaflet.css';
```
Note: There are still a few other things remaining to do for Leaflet that we won't detail here.
For further instructions on how to develop with JHipster, have a look at [Using JHipster in development][].
### Using Angular CLI
You can also use [Angular CLI][] to generate some custom client code.
For example, the following command:
```
ng generate component my-component
```
will generate few files:
```
create src/main/webapp/app/my-component/my-component.component.html
create src/main/webapp/app/my-component/my-component.component.ts
update src/main/webapp/app/app.module.ts
```
### Doing API-First development using openapi-generator
[OpenAPI-Generator]() is configured for this application. You can generate API code from the `src/main/resources/swagger/api.yml` definition file by running:
```bash
./mvnw generate-sources
```
Then implements the generated delegate classes with `@Service` classes.
To edit the `api.yml` definition file, you can use a tool such as [Swagger-Editor](). Start a local instance of the swagger-editor using docker by running: `docker-compose -f src/main/docker/swagger-editor.yml up -d`. The editor will then be reachable at [http://localhost:7742](http://localhost:7742).
Refer to [Doing API-First development][] for more details.
## Building for production
### Packaging as jar
To build the final jar and optimize the epasmed application for production, run:
```
./mvnw -Pprod clean verify
```
This will concatenate and minify the client CSS and JavaScript files. It will also modify `index.html` so it references these new files.
To ensure everything worked, run:
```
java -jar target/*.jar
```
Then navigate to [http://localhost:8080](http://localhost:8080) in your browser.
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:
```
./mvnw -Pprod,war clean verify
```
## Testing
To launch your application's tests, run:
```
./mvnw verify
```
### Client tests
Unit tests are run by [Jest][] and written with [Jasmine][]. They're located in [src/test/javascript/](src/test/javascript/) and can be run with:
```
npm test
```
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 maven plugin.
Then, run a Sonar analysis:
```
./mvnw -Pprod clean verify sonar:sonar
```
If you need to re-run the Sonar phase, please be sure to specify at least the `initialize` phase since Sonar properties are loaded from the sonar-project.properties file.
```
./mvnw initialize sonar:sonar
```
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 postgresql database in a docker container, run:
```
docker-compose -f src/main/docker/postgresql.yml up -d
```
To stop it and remove the container, run:
```
docker-compose -f src/main/docker/postgresql.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:
```
./mvnw -Pprod verify jib:dockerBuild
```
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.4 archive]: https://www.jhipster.tech/documentation-archive/v6.10.4
[using jhipster in development]: https://www.jhipster.tech/documentation-archive/v6.10.4/development/
[using docker and docker-compose]: https://www.jhipster.tech/documentation-archive/v6.10.4/docker-compose
[using jhipster in production]: https://www.jhipster.tech/documentation-archive/v6.10.4/production/
[running tests page]: https://www.jhipster.tech/documentation-archive/v6.10.4/running-tests/
[code quality page]: https://www.jhipster.tech/documentation-archive/v6.10.4/code-quality/
[setting up continuous integration]: https://www.jhipster.tech/documentation-archive/v6.10.4/setting-up-ci/
[node.js]: https://nodejs.org/
[yarn]: https://yarnpkg.org/
[webpack]: https://webpack.github.io/
[angular cli]: https://cli.angular.io/
[browsersync]: https://www.browsersync.io/
[jest]: https://facebook.github.io/jest/
[jasmine]: https://jasmine.github.io/2.0/introduction.html
[protractor]: https://angular.github.io/protractor/
[leaflet]: https://leafletjs.com/
[definitelytyped]: https://definitelytyped.org/
[openapi-generator]: https://openapi-generator.tech
[swagger-editor]: https://editor.swagger.io
[doing api-first development]: https://www.jhipster.tech/documentation-archive/v6.10.4/doing-api-first-development/

20
README.md Normal file
View File

@ -0,0 +1,20 @@
# ePASMed
ePASMed è il servizio di mediazione tra ePAS il software di rilevazione delle presenze e il Sistema Informativo ISTI
## Structure of the project
- The source code is present in the src folder.
## Built With
- [OpenJDK](https://openjdk.java.net/) - The JDK used
- [Maven](https://maven.apache.org/) - Dependency Management
## Authors
- **Giancarlo Panichi** ([ORCID](http://orcid.org/0000-0001-8375-6644)) - [ISTI-CNR Infrascience Group](http://nemis.isti.cnr.it/groups/infrascience)
## License
This project is licensed under the EUPL V.1.1 License - see the [LICENSE.md](LICENSE.md) file for details.

36
angular.json Normal file
View File

@ -0,0 +1,36 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"epasmed": {
"root": "",
"sourceRoot": "src/main/webapp",
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"skipTests": true,
"style": "scss"
},
"@schematics/angular:directive": {
"skipTests": true
},
"@schematics/angular:guard": {
"skipTests": true
},
"@schematics/angular:pipe": {
"skipTests": true
},
"@schematics/angular:service": {
"skipTests": true
}
},
"prefix": "jhi",
"architect": {}
}
},
"defaultProject": "epasmed",
"cli": {
"packageManager": "npm"
}
}

21
checkstyle.xml Normal file
View File

@ -0,0 +1,21 @@
<?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">
<property name="whitelist" value="http://maven.apache.org/POM/4.0.0&#10;
http://www.w3.org/2001/XMLSchema-instance&#10;http://maven.apache.org/maven-v4_0_0.xsd"/>
</module>
<!-- Allow suppression with comments
// CHECKSTYLE:OFF
... ignored content ...
// CHECKSTYLE:ON
-->
<module name="SuppressWithPlainTextCommentFilter"/>
</module>

310
mvnw vendored Executable file
View File

@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
#
# http://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
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
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
mvnw.cmd vendored Normal file
View File

@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

24027
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

123
package.json Normal file
View File

@ -0,0 +1,123 @@
{
"name": "epasmed",
"version": "0.0.1-SNAPSHOT",
"description": "Description for epasmed",
"private": true,
"license": "UNLICENSED",
"cacheDirectories": [
"node_modules"
],
"dependencies": {
"@angular/common": "10.0.0",
"@angular/compiler": "10.0.0",
"@angular/core": "10.0.0",
"@angular/forms": "10.0.0",
"@angular/localize": "10.0.0",
"@angular/platform-browser": "10.0.0",
"@angular/platform-browser-dynamic": "10.0.0",
"@angular/router": "10.0.0",
"@fortawesome/angular-fontawesome": "0.6.1",
"@fortawesome/fontawesome-svg-core": "1.2.29",
"@fortawesome/free-solid-svg-icons": "5.13.1",
"@ng-bootstrap/ng-bootstrap": "6.1.0",
"@ngx-translate/core": "12.1.2",
"@ngx-translate/http-loader": "5.0.0",
"bootstrap": "4.5.0",
"moment": "2.27.0",
"ng-jhipster": "0.15.0",
"ngx-cookie-service": "3.0.4",
"ngx-infinite-scroll": "9.0.0",
"ngx-webstorage": "5.0.0",
"rxjs": "6.5.5",
"swagger-ui-dist": "3.25.1",
"tslib": "2.0.0",
"zone.js": "0.10.3"
},
"devDependencies": {
"@angular/cli": "10.0.0",
"@angular/compiler-cli": "10.0.0",
"@ngtools/webpack": "10.0.0",
"@openapitools/openapi-generator-cli": "1.0.13-4.3.1",
"@types/jest": "26.0.3",
"@types/node": "13.13.4",
"@typescript-eslint/eslint-plugin": "2.30.0",
"@typescript-eslint/eslint-plugin-tslint": "2.30.0",
"@typescript-eslint/parser": "2.30.0",
"autoprefixer": "9.8.4",
"browser-sync": "2.26.7",
"browser-sync-webpack-plugin": "2.2.2",
"codelyzer": "5.2.2",
"copy-webpack-plugin": "6.0.2",
"css-loader": "3.6.0",
"eslint": "6.8.0",
"eslint-config-jhipster": "0.0.1",
"eslint-config-prettier": "6.11.0",
"eslint-loader": "4.0.2",
"file-loader": "6.0.0",
"friendly-errors-webpack-plugin": "1.7.0",
"generator-jhipster": "6.10.4",
"html-loader": "1.1.0",
"html-webpack-plugin": "4.3.0",
"husky": "4.2.5",
"jest": "26.1.0",
"jest-date-mock": "1.0.8",
"jest-junit": "11.0.1",
"jest-preset-angular": "8.2.1",
"jest-sonar-reporter": "2.0.0",
"lint-staged": "8.2.1",
"mini-css-extract-plugin": "0.9.0",
"moment-locales-webpack-plugin": "1.2.0",
"optimize-css-assets-webpack-plugin": "5.0.3",
"postcss-loader": "3.0.0",
"prettier": "2.1.2",
"rimraf": "3.0.2",
"sass": "1.26.9",
"sass-loader": "8.0.2",
"simple-progress-webpack-plugin": "1.1.2",
"style-loader": "1.2.1",
"terser-webpack-plugin": "3.0.6",
"thread-loader": "2.1.3",
"to-string-loader": "1.1.6",
"ts-loader": "7.0.5",
"tslint": "6.1.2",
"typescript": "3.9.5",
"webpack": "4.43.0",
"webpack-bundle-analyzer": "3.8.0",
"webpack-cli": "3.3.12",
"webpack-dev-server": "3.11.0",
"webpack-merge": "4.2.2",
"webpack-notifier": "1.8.0",
"workbox-webpack-plugin": "5.1.3",
"write-file-webpack-plugin": "4.5.1"
},
"engines": {
"node": ">=12.16.1"
},
"scripts": {
"prettier:format": "prettier --write \"{,src/**/}*.{md,json,ts,css,scss,yml}\"",
"lint": "eslint . --ext .js,.ts",
"lint:fix": "npm run lint -- --fix",
"ngc": "ngc -p tsconfig.app.json",
"cleanup": "rimraf target/classes/static/",
"clean-www": "rimraf target/classes/static/app/{src,target/}",
"start": "npm run webpack:dev",
"start-tls": "npm run webpack:dev -- --env.tls",
"serve": "npm run start",
"build": "npm run webpack:prod",
"test": "npm run lint && jest --coverage --logHeapUsage -w=2 --config src/test/javascript/jest.conf.js",
"test:watch": "npm run test -- --watch",
"webpack:dev": "npm run webpack-dev-server -- --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --env.stats=minimal",
"webpack:dev-verbose": "npm run webpack-dev-server -- --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --profile --progress --env.stats=normal",
"webpack:build:main": "npm run webpack -- --config webpack/webpack.dev.js --env.stats=minimal",
"webpack:build": "npm run cleanup && npm run webpack:build:main",
"webpack:prod:main": "npm run webpack -- --config webpack/webpack.prod.js --profile",
"webpack:prod": "npm run cleanup && npm run webpack:prod:main && npm run clean-www",
"webpack:test": "npm run test",
"webpack-dev-server": "node --max_old_space_size=4096 node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js"
},
"jestSonar": {
"reportPath": "target/test-results/jest",
"reportFile": "TESTS-results-sonar.xml"
}
}

1202
pom.xml Normal file

File diff suppressed because it is too large Load Diff

5
postcss.config.js Normal file
View File

@ -0,0 +1,5 @@
module.exports = {
plugins: [
require('autoprefixer')
]
}

7
proxy.conf.json Normal file
View File

@ -0,0 +1,7 @@
{
"*": {
"target": "http://localhost:8080",
"secure": false,
"loglevel": "debug"
}
}

30
sonar-project.properties Normal file
View File

@ -0,0 +1,30 @@
sonar.projectKey=epasmed
sonar.projectName=epasmed generated by jhipster
sonar.projectVersion=1.0
sonar.sources=src/main/
sonar.host.url=http://localhost:9001
sonar.tests=src/test/
sonar.coverage.jacoco.xmlReportPaths=target/jacoco/test/jacoco.xml,target/jacoco/integrationTest/jacoco.xml
sonar.java.codeCoveragePlugin=jacoco
sonar.junit.reportPaths=target/test-results/test,target/test-results/integrationTest
sonar.testExecutionReportPaths=target/test-results/jest/TESTS-results-sonar.xml
sonar.typescript.lcov.reportPaths=target/test-results/lcov.info
sonar.sourceEncoding=UTF-8
sonar.exclusions=src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/classes/static/**/*.*
sonar.issue.ignore.multicriteria=S3437,S4684,UndocumentedApi,BoldAndItalicTagsCheck
# 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=java%3AS4684&rule_key=java%3AS4684
sonar.issue.ignore.multicriteria.S4684.resourceKey=src/main/java/**/*
sonar.issue.ignore.multicriteria.S4684.ruleKey=java:S4684
# Rule https://sonarcloud.io/coding_rules?open=Web%3ABoldAndItalicTagsCheck&rule_key=Web%3ABoldAndItalicTagsCheck is ignored. Even if we agree that using the "i" tag is an awful practice, this is what is recommended by http://fontawesome.io/examples/
sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.resourceKey=src/main/webapp/app/**/*.*
sonar.issue.ignore.multicriteria.BoldAndItalicTagsCheck.ruleKey=Web:BoldAndItalicTagsCheck

17
src/main/docker/app.yml Normal file
View File

@ -0,0 +1,17 @@
version: '2'
services:
epasmed-app:
image: epasmed
environment:
- _JAVA_OPTIONS=-Xmx512m -Xms256m
- SPRING_PROFILES_ACTIVE=prod,swagger
- MANAGEMENT_METRICS_EXPORT_PROMETHEUS_ENABLED=true
- APPLICATION_DATASOURCEEPASMED_DATASOURCE_URL=jdbc:postgresql://epasmed-postgresql:5432/epasmed
#- SPRING_DATASOURCE_URL=jdbc:postgresql://epasmed-postgresql:5432/epasmed
- JHIPSTER_SLEEP=30 # gives time for other services to boot before the application
ports:
- 8080:8080
epasmed-postgresql:
extends:
file: postgresql.yml
service: epasmed-postgresql

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -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

View File

@ -0,0 +1,26 @@
version: '2'
services:
epasmed-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
epasmed-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

View File

@ -0,0 +1,12 @@
version: '2'
services:
epasmed-postgresql:
image: postgres:12.3
# volumes:
# - ~/volumes/jhipster/epasmed/postgresql/:/var/lib/postgresql/data/
environment:
- POSTGRES_USER=epasmed
- POSTGRES_PASSWORD=
- POSTGRES_HOST_AUTH_METHOD=trust
ports:
- 5432:5432

View File

@ -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: 'epasmed'
# 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:8080

View File

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

View File

@ -0,0 +1,6 @@
version: '2'
services:
swagger-editor:
image: swaggerapi/swagger-editor:latest
ports:
- 7742:8080

View File

@ -0,0 +1,20 @@
package it.cnr.isti.epasmed;
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(EpasmedApp.class);
}
}

View File

@ -0,0 +1,108 @@
package it.cnr.isti.epasmed;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import io.github.jhipster.config.DefaultProfileUtil;
import io.github.jhipster.config.JHipsterConstants;
import it.cnr.isti.epasmed.config.ApplicationProperties;
@SpringBootApplication
//@ComponentScan
//@Configuration
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
//@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,
// DataSourceTransactionManagerAutoConfiguration.class,
// HibernateJpaAutoConfiguration.class})
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class})
public class EpasmedApp {
private static final Logger log = LoggerFactory.getLogger(EpasmedApp.class);
private final Environment env;
public EpasmedApp(Environment env) {
this.env = env;
}
/**
* Initializes epasmed.
* <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(EpasmedApp.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());
}
}

View File

@ -0,0 +1,113 @@
package it.cnr.isti.epasmed.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(it.cnr.isti.epasmed.repository..*)"+
" || within(it.cnr.isti.epasmed.service..*)"+
" || within(it.cnr.isti.epasmed.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;
}
}
}

View File

@ -0,0 +1,942 @@
package it.cnr.isti.epasmed.config;
import java.io.File;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.sql.DataSource;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.jdbc.DataSourceInitializationMode;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Properties specific to Epasmed.
* <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 {
private final DatasourceEpasmed datasourceEpasmed = new DatasourceEpasmed();
private final DatasourceSistemainformativo datasourceSistemainformativo = new DatasourceSistemainformativo();
private final DatasourceEpasRest datasourceEpasRest = new DatasourceEpasRest();
public static class DatasourceEpasmed {
private final DataSourceProperties datasource = new DataSourceProperties();
private final LiquibaseProperties liquibase = new LiquibaseProperties();
private final HikariProperties hikari = new HikariProperties();
public DataSourceProperties getDatasource() {
return datasource;
}
public LiquibaseProperties getLiquibase() {
return liquibase;
}
public HikariProperties getHikari() {
return hikari;
}
}
public static class DatasourceSistemainformativo {
private final DataSourceProperties datasource = new DataSourceProperties();
private final HikariProperties hikari = new HikariProperties();
public DataSourceProperties getDatasource() {
return datasource;
}
public HikariProperties getHikari() {
return hikari;
}
}
public static class DatasourceEpasRest {
private String restUrl;
private String restUsername1;
private String restPassword1;
private String restUsername2;
private String restPassword2;
public String getRestUrl() {
return restUrl;
}
public void setRestUrl(String restUrl) {
this.restUrl = restUrl;
}
public String getRestUsername1() {
return restUsername1;
}
public void setRestUsername1(String restUsername1) {
this.restUsername1 = restUsername1;
}
public String getRestPassword1() {
return restPassword1;
}
public void setRestPassword1(String restPassword1) {
this.restPassword1 = restPassword1;
}
public String getRestUsername2() {
return restUsername2;
}
public void setRestUsername2(String restUsername2) {
this.restUsername2 = restUsername2;
}
public String getRestPassword2() {
return restPassword2;
}
public void setRestPassword2(String restPassword2) {
this.restPassword2 = restPassword2;
}
@Override
public String toString() {
return "DatasourceEpasRest [restUrl=" + restUrl + ", restUsername1=" + restUsername1 + ", restPassword1="
+ restPassword1 + ", restUsername2=" + restUsername2 + ", restPassword2=" + restPassword2 + "]";
}
}
public static class HikariProperties {
private String jdbc_url;
private String database_username;
private String database_password;
private boolean cachePrepStmts = true;
private int prepStmtCacheSize = 250;
private int prepStmtCacheSqlLimit = 2048;
private String poolName = "Hikari1";
private boolean autoCommit = false;
private int maximumPoolSize = 10;
public String getPoolName() {
return poolName;
}
public void setPoolName(String poolName) {
this.poolName = poolName;
}
public boolean isAutoCommit() {
return autoCommit;
}
public void setAutoCommit(boolean autoCommit) {
this.autoCommit = autoCommit;
}
public int getMaximumPoolSize() {
return maximumPoolSize;
}
public void setMaximumPoolSize(int maximumPoolSize) {
this.maximumPoolSize = maximumPoolSize;
}
public String getJdbc_url() {
return jdbc_url;
}
public String getDatabase_username() {
return database_username;
}
public void setDatabase_username(String database_username) {
this.database_username = database_username;
}
public String getDatabase_password() {
return database_password;
}
public void setDatabase_password(String database_password) {
this.database_password = database_password;
}
public boolean isCachePrepStmts() {
return cachePrepStmts;
}
public void setCachePrepStmts(boolean cachePrepStmts) {
this.cachePrepStmts = cachePrepStmts;
}
public int getPrepStmtCacheSize() {
return prepStmtCacheSize;
}
public void setPrepStmtCacheSize(int prepStmtCacheSize) {
this.prepStmtCacheSize = prepStmtCacheSize;
}
public int getPrepStmtCacheSqlLimit() {
return prepStmtCacheSqlLimit;
}
public void setPrepStmtCacheSqlLimit(int prepStmtCacheSqlLimit) {
this.prepStmtCacheSqlLimit = prepStmtCacheSqlLimit;
}
public void setJdbc_url(String jdbc_url) {
this.jdbc_url = jdbc_url;
}
@Override
public String toString() {
return "HikariProperties [jdbc_url=" + jdbc_url + ", database_username=" + database_username
+ ", database_password=" + database_password + ", cachePrepStmts=" + cachePrepStmts
+ ", prepStmtCacheSize=" + prepStmtCacheSize + ", prepStmtCacheSqlLimit=" + prepStmtCacheSqlLimit
+ ", poolName=" + poolName + ", autoCommit=" + autoCommit + ", maximumPoolSize=" + maximumPoolSize
+ "]";
}
}
public static class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
private ClassLoader classLoader;
/**
* Name of the datasource. Default to "testdb" when using an embedded database.
*/
private String name;
/**
* Whether to generate a random datasource name.
*/
private boolean generateUniqueName;
/**
* Fully qualified name of the connection pool implementation to use. By
* default, it is auto-detected from the classpath.
*/
private Class<? extends DataSource> type;
/**
* Fully qualified name of the JDBC driver. Auto-detected based on the URL by
* default.
*/
private String driverClassName;
/**
* JDBC URL of the database.
*/
private String url;
/**
* Login username of the database.
*/
private String username;
/**
* Login password of the database.
*/
private String password;
/**
* JNDI location of the datasource. Class, url, username & password are ignored
* when set.
*/
private String jndiName;
/**
* Initialize the datasource with available DDL and DML scripts.
*/
private DataSourceInitializationMode initializationMode = DataSourceInitializationMode.EMBEDDED;
/**
* Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or
* data-${platform}.sql).
*/
private String platform = "all";
/**
* Schema (DDL) script resource references.
*/
private List<String> schema;
/**
* Username of the database to execute DDL scripts (if different).
*/
private String schemaUsername;
/**
* Password of the database to execute DDL scripts (if different).
*/
private String schemaPassword;
/**
* Data (DML) script resource references.
*/
private List<String> data;
/**
* Username of the database to execute DML scripts (if different).
*/
private String dataUsername;
/**
* Password of the database to execute DML scripts (if different).
*/
private String dataPassword;
/**
* Whether to stop if an error occurs while initializing the database.
*/
private boolean continueOnError = false;
/**
* Statement separator in SQL initialization scripts.
*/
private String separator = ";";
/**
* SQL scripts encoding.
*/
private Charset sqlScriptEncoding;
private EmbeddedDatabaseConnection embeddedDatabaseConnection = EmbeddedDatabaseConnection.NONE;
private Xa xa = new Xa();
private String uniqueName;
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void afterPropertiesSet() throws Exception {
this.embeddedDatabaseConnection = EmbeddedDatabaseConnection.get(this.classLoader);
}
/**
* Initialize a {@link DataSourceBuilder} with the state of this instance.
*
* @return a {@link DataSourceBuilder} initialized with the customizations
* defined on this instance
*/
public DataSourceBuilder<?> initializeDataSourceBuilder() {
return DataSourceBuilder.create(getClassLoader()).type(getType())
.driverClassName(determineDriverClassName()).url(determineUrl()).username(determineUsername())
.password(determinePassword());
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGenerateUniqueName() {
return this.generateUniqueName;
}
public void setGenerateUniqueName(boolean generateUniqueName) {
this.generateUniqueName = generateUniqueName;
}
public Class<? extends DataSource> getType() {
return this.type;
}
public void setType(Class<? extends DataSource> type) {
this.type = type;
}
/**
* Return the configured driver or {@code null} if none was configured.
*
* @return the configured driver
* @see #determineDriverClassName()
*/
public String getDriverClassName() {
return this.driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
/**
* Determine the driver to use based on this configuration and the environment.
*
* @return the driver to use
* @since 1.4.0
*/
public String determineDriverClassName() {
if (StringUtils.hasText(this.driverClassName)) {
Assert.state(driverClassIsLoadable(), () -> "Cannot load driver class: " + this.driverClassName);
return this.driverClassName;
}
String driverClassName = null;
if (StringUtils.hasText(this.url)) {
driverClassName = DatabaseDriver.fromJdbcUrl(this.url).getDriverClassName();
}
if (!StringUtils.hasText(driverClassName)) {
driverClassName = this.embeddedDatabaseConnection.getDriverClassName();
}
if (!StringUtils.hasText(driverClassName)) {
throw new DataSourceBeanCreationException("Failed to determine a suitable driver class", this,
this.embeddedDatabaseConnection);
}
return driverClassName;
}
private boolean driverClassIsLoadable() {
try {
ClassUtils.forName(this.driverClassName, null);
return true;
} catch (UnsupportedClassVersionError ex) {
// Driver library has been compiled with a later JDK, propagate error
throw ex;
} catch (Throwable ex) {
return false;
}
}
/**
* Return the configured url or {@code null} if none was configured.
*
* @return the configured url
* @see #determineUrl()
*/
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
/**
* Determine the url to use based on this configuration and the environment.
*
* @return the url to use
* @since 1.4.0
*/
public String determineUrl() {
if (StringUtils.hasText(this.url)) {
return this.url;
}
String databaseName = determineDatabaseName();
String url = (databaseName != null) ? this.embeddedDatabaseConnection.getUrl(databaseName) : null;
if (!StringUtils.hasText(url)) {
throw new DataSourceBeanCreationException("Failed to determine suitable jdbc url", this,
this.embeddedDatabaseConnection);
}
return url;
}
/**
* Determine the name to used based on this configuration.
*
* @return the database name to use or {@code null}
* @since 2.0.0
*/
public String determineDatabaseName() {
if (this.generateUniqueName) {
if (this.uniqueName == null) {
this.uniqueName = UUID.randomUUID().toString();
}
return this.uniqueName;
}
if (StringUtils.hasLength(this.name)) {
return this.name;
}
if (this.embeddedDatabaseConnection != EmbeddedDatabaseConnection.NONE) {
return "testdb";
}
return null;
}
/**
* Return the configured username or {@code null} if none was configured.
*
* @return the configured username
* @see #determineUsername()
*/
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
/**
* Determine the username to use based on this configuration and the
* environment.
*
* @return the username to use
* @since 1.4.0
*/
public String determineUsername() {
if (StringUtils.hasText(this.username)) {
return this.username;
}
if (EmbeddedDatabaseConnection.isEmbedded(determineDriverClassName())) {
return "sa";
}
return null;
}
/**
* Return the configured password or {@code null} if none was configured.
*
* @return the configured password
* @see #determinePassword()
*/
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* Determine the password to use based on this configuration and the
* environment.
*
* @return the password to use
* @since 1.4.0
*/
public String determinePassword() {
if (StringUtils.hasText(this.password)) {
return this.password;
}
if (EmbeddedDatabaseConnection.isEmbedded(determineDriverClassName())) {
return "";
}
return null;
}
public String getJndiName() {
return this.jndiName;
}
/**
* Allows the DataSource to be managed by the container and obtained via JNDI.
* The {@code URL}, {@code driverClassName}, {@code username} and
* {@code password} fields will be ignored when using JNDI lookups.
*
* @param jndiName the JNDI name
*/
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
public DataSourceInitializationMode getInitializationMode() {
return this.initializationMode;
}
public void setInitializationMode(DataSourceInitializationMode initializationMode) {
this.initializationMode = initializationMode;
}
public String getPlatform() {
return this.platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public List<String> getSchema() {
return this.schema;
}
public void setSchema(List<String> schema) {
this.schema = schema;
}
public String getSchemaUsername() {
return this.schemaUsername;
}
public void setSchemaUsername(String schemaUsername) {
this.schemaUsername = schemaUsername;
}
public String getSchemaPassword() {
return this.schemaPassword;
}
public void setSchemaPassword(String schemaPassword) {
this.schemaPassword = schemaPassword;
}
public List<String> getData() {
return this.data;
}
public void setData(List<String> data) {
this.data = data;
}
public String getDataUsername() {
return this.dataUsername;
}
public void setDataUsername(String dataUsername) {
this.dataUsername = dataUsername;
}
public String getDataPassword() {
return this.dataPassword;
}
public void setDataPassword(String dataPassword) {
this.dataPassword = dataPassword;
}
public boolean isContinueOnError() {
return this.continueOnError;
}
public void setContinueOnError(boolean continueOnError) {
this.continueOnError = continueOnError;
}
public String getSeparator() {
return this.separator;
}
public void setSeparator(String separator) {
this.separator = separator;
}
public Charset getSqlScriptEncoding() {
return this.sqlScriptEncoding;
}
public void setSqlScriptEncoding(Charset sqlScriptEncoding) {
this.sqlScriptEncoding = sqlScriptEncoding;
}
public ClassLoader getClassLoader() {
return this.classLoader;
}
public Xa getXa() {
return this.xa;
}
public void setXa(Xa xa) {
this.xa = xa;
}
/**
* XA Specific datasource settings.
*/
public class Xa {
/**
* XA datasource fully qualified name.
*/
private String dataSourceClassName;
/**
* Properties to pass to the XA data source.
*/
private Map<String, String> properties = new LinkedHashMap<>();
public String getDataSourceClassName() {
return this.dataSourceClassName;
}
public void setDataSourceClassName(String dataSourceClassName) {
this.dataSourceClassName = dataSourceClassName;
}
public Map<String, String> getProperties() {
return this.properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
}
public class DataSourceBeanCreationException extends BeanCreationException {
private static final long serialVersionUID = 1L;
private final DataSourceProperties properties;
private final EmbeddedDatabaseConnection connection;
DataSourceBeanCreationException(String message, DataSourceProperties properties,
EmbeddedDatabaseConnection connection) {
super(message);
this.properties = properties;
this.connection = connection;
}
DataSourceProperties getProperties() {
return this.properties;
}
EmbeddedDatabaseConnection getConnection() {
return this.connection;
}
}
}
public static class LiquibaseProperties {
/**
* Change log configuration path.
*/
private String changeLog = "classpath:/db/changelog/db.changelog-master.yaml";
/**
* Comma-separated list of runtime contexts to use.
*/
private String contexts;
/**
* Default database schema.
*/
private String defaultSchema;
/**
* Schema to use for Liquibase objects.
*/
private String liquibaseSchema;
/**
* Tablespace to use for Liquibase objects.
*/
private String liquibaseTablespace;
/**
* Name of table to use for tracking change history.
*/
private String databaseChangeLogTable = "DATABASECHANGELOG";
/**
* Name of table to use for tracking concurrent Liquibase usage.
*/
private String databaseChangeLogLockTable = "DATABASECHANGELOGLOCK";
/**
* Whether to first drop the database schema.
*/
private boolean dropFirst;
/**
* Whether to enable Liquibase support.
*/
private boolean enabled = true;
/**
* Login user of the database to migrate.
*/
private String user;
/**
* Login password of the database to migrate.
*/
private String password;
/**
* JDBC URL of the database to migrate. If not set, the primary configured data
* source is used.
*/
private String url;
/**
* Comma-separated list of runtime labels to use.
*/
private String labels;
/**
* Change log parameters.
*/
private Map<String, String> parameters;
/**
* File to which rollback SQL is written when an update is performed.
*/
private File rollbackFile;
/**
* Whether rollback should be tested before update is performed.
*/
private boolean testRollbackOnUpdate;
public String getChangeLog() {
return this.changeLog;
}
public void setChangeLog(String changeLog) {
Assert.notNull(changeLog, "ChangeLog must not be null");
this.changeLog = changeLog;
}
public String getContexts() {
return this.contexts;
}
public void setContexts(String contexts) {
this.contexts = contexts;
}
public String getDefaultSchema() {
return this.defaultSchema;
}
public void setDefaultSchema(String defaultSchema) {
this.defaultSchema = defaultSchema;
}
public String getLiquibaseSchema() {
return this.liquibaseSchema;
}
public void setLiquibaseSchema(String liquibaseSchema) {
this.liquibaseSchema = liquibaseSchema;
}
public String getLiquibaseTablespace() {
return this.liquibaseTablespace;
}
public void setLiquibaseTablespace(String liquibaseTablespace) {
this.liquibaseTablespace = liquibaseTablespace;
}
public String getDatabaseChangeLogTable() {
return this.databaseChangeLogTable;
}
public void setDatabaseChangeLogTable(String databaseChangeLogTable) {
this.databaseChangeLogTable = databaseChangeLogTable;
}
public String getDatabaseChangeLogLockTable() {
return this.databaseChangeLogLockTable;
}
public void setDatabaseChangeLogLockTable(String databaseChangeLogLockTable) {
this.databaseChangeLogLockTable = databaseChangeLogLockTable;
}
public boolean isDropFirst() {
return this.dropFirst;
}
public void setDropFirst(boolean dropFirst) {
this.dropFirst = dropFirst;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getUser() {
return this.user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getLabels() {
return this.labels;
}
public void setLabels(String labels) {
this.labels = labels;
}
public Map<String, String> getParameters() {
return this.parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public File getRollbackFile() {
return this.rollbackFile;
}
public void setRollbackFile(File rollbackFile) {
this.rollbackFile = rollbackFile;
}
public boolean isTestRollbackOnUpdate() {
return this.testRollbackOnUpdate;
}
public void setTestRollbackOnUpdate(boolean testRollbackOnUpdate) {
this.testRollbackOnUpdate = testRollbackOnUpdate;
}
}
public DatasourceEpasmed getDatasourceEpasmed() {
return datasourceEpasmed;
}
public DatasourceSistemainformativo getDatasourceSistemainformativo() {
return datasourceSistemainformativo;
}
public DatasourceEpasRest getDatasourceEpasRest() {
return datasourceEpasRest;
}
}

View File

@ -0,0 +1,47 @@
package it.cnr.isti.epasmed.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();
}
}

View File

@ -0,0 +1,28 @@
package it.cnr.isti.epasmed.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();
}
}

View File

@ -0,0 +1,17 @@
package it.cnr.isti.epasmed.config;
/**
* Application constants.
*/
public final class Constants {
// Regex for acceptable logins
public static final String LOGIN_REGEX = "^(?>[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*)|(?>[_.@A-Za-z0-9-]+)$";
public static final String SYSTEM_ACCOUNT = "system";
public static final String DEFAULT_LANGUAGE = "en";
public static final String ANONYMOUS_USER = "anonymoususer";
private Constants() {
}
}

View File

@ -0,0 +1,22 @@
package it.cnr.isti.epasmed.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);
}
}

View File

@ -0,0 +1,202 @@
package it.cnr.isti.epasmed.config;
import java.sql.SQLException;
import java.util.HashMap;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
import it.cnr.isti.epasmed.config.ApplicationProperties.DataSourceProperties;
import it.cnr.isti.epasmed.config.ApplicationProperties.DatasourceEpasmed;
import it.cnr.isti.epasmed.config.ApplicationProperties.HikariProperties;
import it.cnr.isti.epasmed.config.ApplicationProperties.LiquibaseProperties;
import liquibase.integration.spring.SpringLiquibase;
@Configuration
@EnableJpaRepositories(basePackages = "it.cnr.isti.epasmed.repository", entityManagerFactoryRef = "epasMedEntityManagerFactory", transactionManagerRef = "epasMedTransactionManager")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class EpasMedDataSourceConfiguration {
private final Logger log = LoggerFactory.getLogger(EpasMedDataSourceConfiguration.class);
private final Environment env;
private final ApplicationProperties applicationProperties;
public EpasMedDataSourceConfiguration(Environment env, ApplicationProperties applicationProperties) {
this.env = env;
this.applicationProperties = applicationProperties;
}
/**
* Open the TCP port for the H2 database, so it is available remotely.
*
* @return the H2 database TCP server.
* @throws SQLException if the server failed to start.
*/
@Bean(initMethod = "start", destroyMethod = "stop")
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public Object h2TCPServer() throws SQLException {
String port = getValidPortForH2();
log.debug("H2 database is available on port {}", port);
return H2ConfigurationHelper.createServer(port);
}
private String getValidPortForH2() {
int port = Integer.parseInt(env.getProperty("server.port"));
if (port < 10000) {
port = 10000 + port;
} else {
if (port < 63536) {
port = port + 2000;
} else {
port = port - 2000;
}
}
return String.valueOf(port);
}
@Bean
@Primary
public DatasourceEpasmed epasMedDataSourceProperties() {
return applicationProperties.getDatasourceEpasmed();
}
@Bean
@Primary
public DataSource epasMedDataSource() {
log.info("Setup ePASMedDataSource");
DataSourceProperties dsp = epasMedDataSourceProperties().getDatasource();
log.info("Properties: {}",dsp);
HikariProperties hikariProperties = epasMedDataSourceProperties().getHikari();
log.info("Hikari: {}",hikariProperties);
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dsp.getUrl());
config.setUsername(dsp.getUsername());
config.setPassword(dsp.getPassword());
config.addDataSourceProperty("cachePrepStmts", hikariProperties.isCachePrepStmts());
config.addDataSourceProperty("prepStmtCacheSize", hikariProperties.getPrepStmtCacheSize());
config.addDataSourceProperty("prepStmtCacheSqlLimit", hikariProperties.getPrepStmtCacheSqlLimit());
config.setAutoCommit(hikariProperties.isAutoCommit());
config.setPoolName(hikariProperties.getPoolName());
config.setMaximumPoolSize(hikariProperties.getMaximumPoolSize());
log.info("HikariConfig epasmed: {}", dsp.getUrl());
HikariDataSource ds = new HikariDataSource(config);
return ds;
}
@Bean(name = "epasMedEntityManagerFactory")
@Primary
public LocalContainerEntityManagerFactoryBean epasMedEntityManagerFactory(EntityManagerFactoryBuilder builder) {
LocalContainerEntityManagerFactoryBean em = builder.dataSource(epasMedDataSource()).persistenceUnit("epasMedPU")
.packages("it.cnr.isti.epasmed.domain").build();
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
// vendorAdapter.setDatabase(Database.DB2);
vendorAdapter.setShowSql(true);
vendorAdapter.setDatabasePlatform(epasMedDataSourceProperties().getDatasource().getPlatform());
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.jdbc.time_zone", "UTC");
properties.put("hibernate.id.new_generator_mappings", true);
properties.put("hibernate.connection.provider_disables_autocommit", true);
properties.put("hibernate.cache.use_second_level_cache", false);
properties.put("hibernate.cache.use_query_cache", false);
properties.put("hibernate.generate_statistics", false);
// modify batch size as necessary
properties.put("hibernate.jdbc.batch_size", 25);
properties.put("hibernate.order_inserts", true);
properties.put("hibernate.order_updates", true);
properties.put("hibernate.jdbc.lob.non_contextual_creation", true);
properties.put("hibernate.query.fail_on_pagination_over_collection_fetch", true);
properties.put("hibernate.query.in_clause_parameter_padding", true);
// Naming props
properties.put("hibernate.ddl-auto", "none");
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
//org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
properties.put("hibernate.hbm2ddl.auto","none");
// properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
@Primary
public PlatformTransactionManager epasMedTransactionManager(
final @Qualifier("epasMedEntityManagerFactory") LocalContainerEntityManagerFactoryBean epasMedEntityManagerFactory) {
return new JpaTransactionManager(epasMedEntityManagerFactory.getObject());
}
@Bean
public LiquibaseProperties epasMedLiquibaseProperties() {
return applicationProperties.getDatasourceEpasmed().getLiquibase();
}
@Bean
public SpringLiquibase epasMedLiquibase() {
return liquibase(epasMedLiquibaseProperties(), epasMedDataSource());
}
private SpringLiquibase liquibase(LiquibaseProperties epasMedLiquibaseProperties, DataSource epasMedDataSource) {
log.debug("Create EpasMed Liquibase DataSource");
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDataSource(epasMedDataSource);
// SpringLiquibaseUtil.createAsyncSpringLiquibase(env,
// asyncConfiguration.getAsyncExecutor(), liquibaseDataSource,
// epasMedLiquibaseProperties,
// epasMedDataSource, epasMedDataSourceProperties);
log.debug("Set params");
liquibase.setContexts(epasMedLiquibaseProperties.getContexts());
liquibase.setChangeLog(epasMedLiquibaseProperties.getChangeLog());
liquibase.setDefaultSchema(epasMedLiquibaseProperties.getDefaultSchema());
liquibase.setLiquibaseSchema(epasMedLiquibaseProperties.getLiquibaseSchema());
liquibase.setLiquibaseTablespace(epasMedLiquibaseProperties.getLiquibaseTablespace());
liquibase.setDatabaseChangeLogLockTable(epasMedLiquibaseProperties.getDatabaseChangeLogLockTable());
liquibase.setDatabaseChangeLogTable(epasMedLiquibaseProperties.getDatabaseChangeLogTable());
liquibase.setDropFirst(epasMedLiquibaseProperties.isDropFirst());
liquibase.setLabels(epasMedLiquibaseProperties.getLabels());
liquibase.setChangeLogParameters(epasMedLiquibaseProperties.getParameters());
liquibase.setRollbackFile(epasMedLiquibaseProperties.getRollbackFile());
liquibase.setTestRollbackOnUpdate(epasMedLiquibaseProperties.isTestRollbackOnUpdate());
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(epasMedLiquibaseProperties.isEnabled());
log.debug("Configuring epasMed Liquibase");
}
log.debug("Created epasMed Libquibase");
return liquibase;
}
}

View File

@ -0,0 +1,36 @@
package it.cnr.isti.epasmed.config;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
@Configuration
public class EpasRestTemplateConfig {
private final ApplicationProperties applicationProperties;
public EpasRestTemplateConfig(ApplicationProperties applicationProperties) {
super();
this.applicationProperties = applicationProperties;
}
@Bean(name = "RestTemplateForFirstUser")
@Primary
public RestTemplate restTemplateFirst(RestTemplateBuilder builder) {
return builder.defaultHeader("Accept", MediaType.APPLICATION_JSON.toString())
.basicAuthentication(applicationProperties.getDatasourceEpasRest().getRestUsername1(),
applicationProperties.getDatasourceEpasRest().getRestPassword1())
.build();
}
@Bean(name = "RestTemplateForSecondUser")
public RestTemplate restTemplateSecond(RestTemplateBuilder builder) {
return builder.defaultHeader("Accept", MediaType.APPLICATION_JSON.toString())
.basicAuthentication(applicationProperties.getDatasourceEpasRest().getRestUsername2(),
applicationProperties.getDatasourceEpasRest().getRestPassword2())
.build();
}
}

View File

@ -0,0 +1,52 @@
package it.cnr.isti.epasmed.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();
}
}

View File

@ -0,0 +1,27 @@
package it.cnr.isti.epasmed.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);
}
}

View File

@ -0,0 +1,19 @@
package it.cnr.isti.epasmed.config;
import it.cnr.isti.epasmed.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);
}
}

View File

@ -0,0 +1,50 @@
package it.cnr.isti.epasmed.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.annotation.Value;
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
public class LoggingConfiguration {
public LoggingConfiguration(@Value("${spring.application.name}") String appName,
@Value("${server.port}") String serverPort,
JHipsterProperties jHipsterProperties,
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);
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());
}
}
}

View File

@ -0,0 +1,72 @@
package it.cnr.isti.epasmed.config;
import com.google.common.base.Predicates;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.config.apidoc.customizer.SwaggerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import static springfox.documentation.builders.PathSelectors.regex;
@Configuration
@Profile(JHipsterConstants.SPRING_PROFILE_SWAGGER)
public class OpenApiConfiguration {
@Bean
public SwaggerCustomizer noApiFirstCustomizer() {
return docket -> docket.select()
.apis(Predicates.not(RequestHandlerSelectors.basePackage("it.cnr.isti.epasmed.web.api")));
}
@Bean
public Docket apiFirstDocket(JHipsterProperties jHipsterProperties) {
JHipsterProperties.Swagger properties = jHipsterProperties.getSwagger();
Contact contact = new Contact(
properties.getContactName(),
properties.getContactUrl(),
properties.getContactEmail()
);
ApiInfo apiInfo = new ApiInfo(
"API First " + properties.getTitle(),
properties.getDescription(),
properties.getVersion(),
properties.getTermsOfServiceUrl(),
contact,
properties.getLicense(),
properties.getLicenseUrl(),
new ArrayList<>()
);
return new Docket(DocumentationType.SWAGGER_2)
.groupName("openapi")
.host(properties.getHost())
.protocols(new HashSet<>(Arrays.asList(properties.getProtocols())))
.apiInfo(apiInfo)
.useDefaultResponseMessages(properties.isUseDefaultResponseMessages())
.forCodeGeneration(true)
.directModelSubstitute(ByteBuffer.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.ignoredParameterTypes(Pageable.class)
.select()
.apis(RequestHandlerSelectors.basePackage("it.cnr.isti.epasmed.web.api"))
.paths(regex(properties.getDefaultIncludePattern()))
.build();
}
}

View File

@ -0,0 +1,98 @@
package it.cnr.isti.epasmed.config;
import it.cnr.isti.epasmed.security.*;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.security.*;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.web.filter.CorsFilter;
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 JHipsterProperties jHipsterProperties;
private final RememberMeServices rememberMeServices;
private final CorsFilter corsFilter;
private final SecurityProblemSupport problemSupport;
public SecurityConfiguration(JHipsterProperties jHipsterProperties, RememberMeServices rememberMeServices,
CorsFilter corsFilter, SecurityProblemSupport problemSupport) {
this.jHipsterProperties = jHipsterProperties;
this.rememberMeServices = rememberMeServices;
this.corsFilter = corsFilter;
this.problemSupport = problemSupport;
}
@Bean
public AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() {
return new AjaxAuthenticationSuccessHandler();
}
@Bean
public AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler() {
return new AjaxAuthenticationFailureHandler();
}
@Bean
public AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler() {
return new AjaxLogoutSuccessHandler();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**").antMatchers("/app/**/*.{js,html}").antMatchers("/i18n/**")
.antMatchers("/content/**").antMatchers("/h2-console/**").antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.addFilterBefore(corsFilter, CsrfFilter.class).exceptionHandling()
.authenticationEntryPoint(problemSupport).accessDeniedHandler(problemSupport).and().rememberMe()
.rememberMeServices(rememberMeServices).rememberMeParameter("remember-me")
.key(jHipsterProperties.getSecurity().getRememberMe().getKey()).and().formLogin()
.loginProcessingUrl("/api/authentication").successHandler(ajaxAuthenticationSuccessHandler())
.failureHandler(ajaxAuthenticationFailureHandler()).permitAll().and().logout().logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler()).permitAll().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().authorizeRequests().antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/register").hasAnyAuthority(AuthoritiesConstants.ADMIN).antMatchers("/api/activate")
.permitAll().antMatchers("/api/account/reset-password/init").permitAll()
.antMatchers("/api/account/reset-password/finish").permitAll().antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll().antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus")
.hasAnyAuthority(AuthoritiesConstants.ADMIN, AuthoritiesConstants.PROMETHEUS)
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
// @formatter:on
}
}

View File

@ -0,0 +1,88 @@
package it.cnr.isti.epasmed.config;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import it.cnr.isti.epasmed.config.ApplicationProperties.DataSourceProperties;
import it.cnr.isti.epasmed.config.ApplicationProperties.DatasourceSistemainformativo;
import it.cnr.isti.epasmed.config.ApplicationProperties.HikariProperties;
@Configuration
@EnableJdbcRepositories(basePackages = "it.cnr.isti.epasmed.sistemainformativo.repository")
//@EnableJpaRepositories(basePackages = "it.cnr.isti.epasmed.sistemainformativo.repository", entityManagerFactoryRef = "sistemaInformativoEntityManagerFactory", transactionManagerRef = "sistemaInformativoTransactionManager")
//@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class SistemaInformativoDataSourceConfiguration extends AbstractJdbcConfiguration {
private final Logger log = LoggerFactory.getLogger(SistemaInformativoDataSourceConfiguration.class);
private final ApplicationProperties applicationProperties;
public SistemaInformativoDataSourceConfiguration(ApplicationProperties applicationProperties) {
this.applicationProperties = applicationProperties;
}
@Bean
public DatasourceSistemainformativo sistemaInformativoDataSourceProperties() {
return applicationProperties.getDatasourceSistemainformativo();
}
@Bean(name = "sistemaInformativoDataSource")
public DataSource sistemaInformativoDataSource() {
DataSourceProperties dsp = sistemaInformativoDataSourceProperties().getDatasource();
HikariProperties hikariProperties = sistemaInformativoDataSourceProperties().getHikari();
//DriverManagerDataSource dataSource = new DriverManagerDataSource();
//dataSource.setDriverClassName(dsp.getDriverClassName());
//dataSource.setUrl(dsp.getUrl());
//dataSource.setUsername(dsp.getUsername());
//dataSource.setPassword(dsp.getPassword());
//log.info("SistemaInformativoDataSource created");
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dsp.getUrl());
config.setDriverClassName(dsp.getDriverClassName());
config.setUsername(dsp.getUsername());
config.setPassword(dsp.getPassword());
config.addDataSourceProperty("cachePrepStmts", hikariProperties.isCachePrepStmts());
config.addDataSourceProperty("prepStmtCacheSize", hikariProperties.getPrepStmtCacheSize());
config.addDataSourceProperty("prepStmtCacheSqlLimit", hikariProperties.getPrepStmtCacheSqlLimit());
config.setAutoCommit(hikariProperties.isAutoCommit());
config.setPoolName(hikariProperties.getPoolName());
config.setMaximumPoolSize(hikariProperties.getMaximumPoolSize());
log.debug("HikariConfig sistemainformativo: " + dsp.getUrl());
HikariDataSource dataSource = new HikariDataSource(config);
return dataSource;
}
@Bean
NamedParameterJdbcOperations namedParameterJdbcOperations(
final @Qualifier("sistemaInformativoDataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
@Bean
TransactionManager sistemaInformativoTransactionManager(
final @Qualifier("sistemaInformativoDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}

View File

@ -0,0 +1,49 @@
package it.cnr.isti.epasmed.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.concurrent.TimeUnit;
@Configuration
@Profile({JHipsterConstants.SPRING_PROFILE_PRODUCTION})
public class StaticResourcesWebConfiguration implements WebMvcConfigurer {
protected static final String[] RESOURCE_LOCATIONS = new String[]{"classpath:/static/app/", "classpath:/static/content/", "classpath:/static/i18n/"};
protected static final String[] RESOURCE_PATHS = new String[]{"/app/*", "/content/*", "/i18n/*"};
private final JHipsterProperties jhipsterProperties;
public StaticResourcesWebConfiguration(JHipsterProperties jHipsterProperties) {
this.jhipsterProperties = jHipsterProperties;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ResourceHandlerRegistration resourceHandlerRegistration = appendResourceHandler(registry);
initializeResourceHandler(resourceHandlerRegistration);
}
protected ResourceHandlerRegistration appendResourceHandler(ResourceHandlerRegistry registry) {
return registry.addResourceHandler(RESOURCE_PATHS);
}
protected void initializeResourceHandler(ResourceHandlerRegistration resourceHandlerRegistration) {
resourceHandlerRegistration.addResourceLocations(RESOURCE_LOCATIONS).setCacheControl(getCacheControl());
}
protected CacheControl getCacheControl() {
return CacheControl.maxAge(getJHipsterHttpCacheProperty(), TimeUnit.DAYS).cachePublic();
}
private int getJHipsterHttpCacheProperty() {
return jhipsterProperties.getHttp().getCache().getTimeToLiveInDays();
}
}

View File

@ -0,0 +1,138 @@
package it.cnr.isti.epasmed.config;
import static java.net.URLDecoder.decode;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.MimeMappings;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
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.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
/**
* Configuration of web application with Servlet 3.0 APIs.
*/
@Configuration
public class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> {
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());
}
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}
/**
* Customize the Servlet engine: Mime types, the document root, the cache.
*/
@Override
public void customize(WebServerFactory server) {
setMimeMappings(server);
// When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
setLocationForStaticAssets(server);
}
private void setMimeMappings(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase());
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase());
ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server;
servletWebServer.setMimeMappings(mappings);
}
}
private void setLocationForStaticAssets(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory) {
ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server;
File root;
String prefixPath = resolvePathPrefix();
root = new File(prefixPath + "target/classes/static/");
if (root.exists() && root.isDirectory()) {
servletWebServer.setDocumentRoot(root);
}
}
}
/**
* Resolve path prefix to static resources.
*/
private String resolvePathPrefix() {
String fullExecutablePath;
try {
fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
/* try without decoding if this ever happens */
fullExecutablePath = this.getClass().getResource("").getPath();
}
String rootPath = Paths.get(".").toUri().normalize().getPath();
String extractedPath = fullExecutablePath.replace(rootPath, "");
int extractionEndIndex = extractedPath.indexOf("target/");
if (extractionEndIndex <= 0) {
return "";
}
return extractedPath.substring(0, extractionEndIndex);
}
@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);
}
/**
* Initializes H2 console.
*/
private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
H2ConfigurationHelper.initH2Console(servletContext);
}
}

View File

@ -0,0 +1,86 @@
package it.cnr.isti.epasmed.config.audit;
import it.cnr.isti.epasmed.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;
}
}

View File

@ -0,0 +1,4 @@
/**
* Audit specific code.
*/
package it.cnr.isti.epasmed.config.audit;

View File

@ -0,0 +1,4 @@
/**
* Spring Framework configuration files.
*/
package it.cnr.isti.epasmed.config;

View File

@ -0,0 +1,77 @@
package it.cnr.isti.epasmed.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;
}
}

View File

@ -0,0 +1,58 @@
package it.cnr.isti.epasmed.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Objects;
/**
* An authority (a security role) used by Spring Security.
*/
@Entity
@Table(name = "jhi_authority")
public class Authority implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Size(max = 50)
@Id
@Column(length = 50)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Authority)) {
return false;
}
return Objects.equals(name, ((Authority) o).name);
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
// prettier-ignore
@Override
public String toString() {
return "Authority{" +
"name='" + name + '\'' +
"}";
}
}

View File

@ -0,0 +1,108 @@
package it.cnr.isti.epasmed.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 = "persistentAuditEventSequenceGenerator")
@SequenceGenerator(name = "persistentAuditEventSequenceGenerator", allocationSize = 1)
@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 + '\'' +
'}';
}
}

View File

@ -0,0 +1,128 @@
package it.cnr.isti.epasmed.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Objects;
import java.time.LocalDate;
/**
* Persistent tokens are used by Spring Security to automatically log in users.
*
* @see it.cnr.isti.epasmed.security.PersistentTokenRememberMeServices
*/
@Entity
@Table(name = "jhi_persistent_token")
public class PersistentToken implements Serializable {
private static final long serialVersionUID = 1L;
private static final int MAX_USER_AGENT_LEN = 255;
@Id
private String series;
@JsonIgnore
@NotNull
@Column(name = "token_value", nullable = false)
private String tokenValue;
@Column(name = "token_date")
private LocalDate tokenDate;
//an IPV6 address max length is 39 characters
@Size(min = 0, max = 39)
@Column(name = "ip_address", length = 39)
private String ipAddress;
@Column(name = "user_agent")
private String userAgent;
@JsonIgnore
@ManyToOne
private User user;
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public String getTokenValue() {
return tokenValue;
}
public void setTokenValue(String tokenValue) {
this.tokenValue = tokenValue;
}
public LocalDate getTokenDate() {
return tokenDate;
}
public void setTokenDate(LocalDate tokenDate) {
this.tokenDate = tokenDate;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
if (userAgent.length() >= MAX_USER_AGENT_LEN) {
this.userAgent = userAgent.substring(0, MAX_USER_AGENT_LEN - 1);
} else {
this.userAgent = userAgent;
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PersistentToken)) {
return false;
}
return Objects.equals(series, ((PersistentToken) o).series);
}
@Override
public int hashCode() {
return Objects.hashCode(series);
}
// prettier-ignore
@Override
public String toString() {
return "PersistentToken{" +
"series='" + series + '\'' +
", tokenValue='" + tokenValue + '\'' +
", tokenDate=" + tokenDate +
", ipAddress='" + ipAddress + '\'' +
", userAgent='" + userAgent + '\'' +
"}";
}
}

View File

@ -0,0 +1,106 @@
package it.cnr.isti.epasmed.domain;
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
/**
* A user.
*/
@Entity
@Table(name = "tabssi")
public class TabsSI implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "tabssiSequenceGenerator")
@SequenceGenerator(name = "tabssiSequenceGenerator", allocationSize = 1)
private Long id;
@NotNull
@Column(unique = true, nullable = false)
public String nome;
@NotNull
public String operazioni;
@NotNull
public Long idFlusso;
@NotNull
@Column(columnDefinition = "TIMESTAMP" )
private LocalDateTime lastUpdate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getOperazioni() {
return operazioni;
}
public void setOperazioni(String operazioni) {
this.operazioni = operazioni;
}
public Long getIdFlusso() {
return idFlusso;
}
public void setIdFlusso(Long idFlusso) {
this.idFlusso = idFlusso;
}
public LocalDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(LocalDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TabsSI)) {
return false;
}
return id != null && id.equals(((TabsSI) o).id);
}
@Override
public String toString() {
return "TabsSI [id=" + id + ", nome=" + nome + ", operazioni=" + operazioni + ", idFlusso=" + idFlusso
+ ", lastUpdate=" + lastUpdate + "]";
}
}

View File

@ -0,0 +1,240 @@
package it.cnr.isti.epasmed.domain;
import it.cnr.isti.epasmed.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.BatchSize;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* A user.
*/
@Entity
@Table(name = "jhi_user")
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "userSequenceGenerator")
@SequenceGenerator(name = "userSequenceGenerator", allocationSize = 1)
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash", length = 60, nullable = false)
private String password;
@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;
@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
@Column(length = 254, unique = true)
private String email;
@NotNull
@Column(nullable = false)
private boolean activated = false;
@Size(min = 2, max = 10)
@Column(name = "lang_key", length = 10)
private String langKey;
@Size(max = 256)
@Column(name = "image_url", length = 256)
private String imageUrl;
@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
private String activationKey;
@Size(max = 20)
@Column(name = "reset_key", length = 20)
@JsonIgnore
private String resetKey;
@Column(name = "reset_date")
private Instant resetDate = null;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
@JsonIgnore
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
private Set<PersistentToken> persistentTokens = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
public Set<PersistentToken> getPersistentTokens() {
return persistentTokens;
}
public void setPersistentTokens(Set<PersistentToken> persistentTokens) {
this.persistentTokens = persistentTokens;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}

View File

@ -0,0 +1,4 @@
/**
* JPA domain objects.
*/
package it.cnr.isti.epasmed.domain;

View File

@ -0,0 +1,108 @@
package it.cnr.isti.epasmed.epas.client;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import it.cnr.isti.epasmed.config.ApplicationProperties;
import it.cnr.isti.epasmed.epas.dto.EPASAffiliationsDTO;
import it.cnr.isti.epasmed.epas.model.EPASAffiliations;
@Component
public class EPASAffiliationsCient {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("RestTemplateForFirstUser")
RestTemplate rt;
@Autowired
ApplicationProperties appProps;
public EPASAffiliations getById(String id) {
EPASAffiliations epasAffiliations = rt.getForObject(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/affiliations/show?id={id}", EPASAffiliations.class,
id);
log.info("Retrieved Affiliations: {}", epasAffiliations);
return epasAffiliations;
}
public List<EPASAffiliations> getByGroup(String groupId, boolean includeInactive) {
ResponseEntity<List<EPASAffiliations>> responseEntity = rt.exchange(
appProps.getDatasourceEpasRest().getRestUrl()
+ "/v2/affiliations/byGroup?id={groupId}&includeInactive={includeInactive}",
HttpMethod.GET, null, new ParameterizedTypeReference<List<EPASAffiliations>>() {
}, groupId,includeInactive);
List<EPASAffiliations> listEPASAffiliations = responseEntity.getBody();
log.info("Retrieved Affiliations byGroup: {}", listEPASAffiliations);
return listEPASAffiliations;
}
public List<EPASAffiliations> getByPersonId(String personId) {
ResponseEntity<List<EPASAffiliations>> responseEntity = rt.exchange(
appProps.getDatasourceEpasRest().getRestUrl()
+ "/v2/affiliations/byPerson?id={personId}",
HttpMethod.GET, null, new ParameterizedTypeReference<List<EPASAffiliations>>() {
}, personId);
List<EPASAffiliations> listEPASAffiliations = responseEntity.getBody();
log.info("Retrieved Affiliations by Person id: {}", listEPASAffiliations);
return listEPASAffiliations;
}
public List<EPASAffiliations> getByPersonFiscalcode(String fc) {
ResponseEntity<List<EPASAffiliations>> responseEntity = rt.exchange(
appProps.getDatasourceEpasRest().getRestUrl()
+ "/v2/affiliations/byPerson?fiscalCode={fc}",
HttpMethod.GET, null, new ParameterizedTypeReference<List<EPASAffiliations>>() {
}, fc);
List<EPASAffiliations> listEPASAffiliations = responseEntity.getBody();
log.info("Retrieved Affiliations by Person fiscalcode: {}", listEPASAffiliations);
return listEPASAffiliations;
}
public EPASAffiliations create(EPASAffiliationsDTO epasAffiliationsDTO) {
ResponseEntity<EPASAffiliations> response = rt.postForEntity(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/affiliations/create", epasAffiliationsDTO,
EPASAffiliations.class);
EPASAffiliations createdEPASAffiliations = response.getBody();
log.info("Created Affiliations: {}", createdEPASAffiliations);
return createdEPASAffiliations;
}
public void updateById(String id, @Valid EPASAffiliationsDTO epasAffiliationsDTO) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("id", id);
rt.put(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/affiliations/update?id={id}", epasAffiliationsDTO,
uriVariables);
log.info("Updated Affiliations id: {}", id);
return;
}
public void deleteById(String id) {
rt.delete(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/affiliations/delete?id={id}", id);
log.info("Deleted Group id: {}", id);
return;
}
}

View File

@ -0,0 +1,117 @@
package it.cnr.isti.epasmed.epas.client;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import it.cnr.isti.epasmed.config.ApplicationProperties;
import it.cnr.isti.epasmed.epas.dto.EPASContractsDTO;
import it.cnr.isti.epasmed.epas.model.EPASContracts;
@Component
public class EPASContractsCient {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("RestTemplateForFirstUser")
RestTemplate rt;
@Autowired
ApplicationProperties appProps;
public EPASContracts getById(String id) {
EPASContracts epasContracts = rt.getForObject(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/contracts/show/{id}", EPASContracts.class, id);
log.info("Retrieved Contracts: {}", epasContracts);
return epasContracts;
}
public List<EPASContracts> getByPersonId(String id) {
ResponseEntity<List<EPASContracts>> responseEntity = rt.exchange(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/contracts/byPerson?id={id}", HttpMethod.GET, null,
new ParameterizedTypeReference<List<EPASContracts>>() {
}, id);
List<EPASContracts> listEPASContracts = responseEntity.getBody();
log.info("Retrieved Contracts: {}", listEPASContracts);
return listEPASContracts;
}
public List<EPASContracts> getByPersonFiscalcode(String fc) {
ResponseEntity<List<EPASContracts>> responseEntity = rt.exchange(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/contracts/byPerson?fiscalCode={fc}", HttpMethod.GET,
null, new ParameterizedTypeReference<List<EPASContracts>>() {
}, fc);
List<EPASContracts> listEPASContracts = responseEntity.getBody();
log.info("Retrieved Contracts: {}", listEPASContracts);
return listEPASContracts;
}
public EPASContracts create(EPASContractsDTO epasContractsDTO) {
ResponseEntity<EPASContracts> response = rt.postForEntity(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/contracts/create", epasContractsDTO,
EPASContracts.class);
EPASContracts createdEPASContracts = response.getBody();
log.info("Created Contracts: {}", createdEPASContracts);
return createdEPASContracts;
}
public void updateById(String id, @Valid EPASContractsDTO epasContractsDTO) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("id", id);
rt.put(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/contracts/update?id={id}", epasContractsDTO,
uriVariables);
log.info("Updated Contracts id: {}", id);
return;
}
// Continuazione di due contratti consecutivi
// E' possibile impostare che un contratto è continuativo rispetto al precedente
// e ne eredità le ferie non godute precedenti. Questa funzionalità è utilizzare
// per esempio per alcune stabilizzazioni dove il dipendente si porta dietro dal
// precedente contratto la situazione delle ferie non godute. Per impostare e
// rimuovere che un contratto è continuativo rispetto al precedente è possibile
// utilizzare i metodi
/// rest/v2/contract/setPreviousContract
/// rest/v2/contract/unsetPreviousContract
// $ http -a isti_registry_manager DELETE
// https://epas-demo.devel.iit.cnr.it/rest/v2/contract/setPreviousContract?id=4678
// $ http -a isti_registry_manager DELETE
// https://epas-demo.devel.iit.cnr.it/rest/v2/contract/unsetPreviousContract?id=4678
public void setPreviousContract(String id) {
rt.delete(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/contracts/setPreviousContract?id={id}", id);
log.info("Set Previous Contract for Contract id: {}", id);
return;
}
public void setUnsetPreviousContract(String id) {
rt.delete(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/contracts/unsetPreviousContract?id={id}", id);
log.info("Set Unset Previous Contract for Contract id: {}", id);
return;
}
public void deleteById(String id) {
rt.delete(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/contracts/delete?id={id}", id);
log.info("Deleted Contract id: {}", id);
return;
}
}

View File

@ -0,0 +1,83 @@
package it.cnr.isti.epasmed.epas.client;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import it.cnr.isti.epasmed.config.ApplicationProperties;
import it.cnr.isti.epasmed.epas.dto.EPASGroupsDTO;
import it.cnr.isti.epasmed.epas.model.EPASGroups;
@Component
public class EPASGroupsCient {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("RestTemplateForFirstUser")
RestTemplate rt;
@Autowired
ApplicationProperties appProps;
public EPASGroups getById(String id) {
EPASGroups epasGroups = rt.getForObject(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/groups/show?id={id}", EPASGroups.class, id);
log.info("Retrieved Groups: {}", epasGroups);
return epasGroups;
}
public List<EPASGroups> getList(String officeId) {
ResponseEntity<List<EPASGroups>> responseEntity = rt.exchange(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/groups/list?id={officeId}", HttpMethod.GET, null,
new ParameterizedTypeReference<List<EPASGroups>>() {
}, officeId);
List<EPASGroups> listEPASGroups = responseEntity.getBody();
log.info("Retrieved Groups: {}", listEPASGroups);
return listEPASGroups;
}
public EPASGroups create(EPASGroupsDTO epasGroupsDTO) {
ResponseEntity<EPASGroups> response = rt.postForEntity(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/groups/create", epasGroupsDTO, EPASGroups.class);
EPASGroups createdEPASGroups = response.getBody();
log.info("Created Groups: {}", createdEPASGroups);
return createdEPASGroups;
}
public void updateById(String id, @Valid EPASGroupsDTO epasGroupsDTO) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("id", id);
rt.put(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/groups/update?id={id}", epasGroupsDTO, uriVariables);
log.info("Updated Groups id: {}", id);
return;
}
public void deleteById(String id) {
rt.delete(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/groups/delete?id={id}", id);
log.info("Deleted Group id: {}", id);
return;
}
// $ http -a isti_registry_manager POST
// https://epas-demo.devel.iit.cnr.it/rest/v2/groups/create
// name="Gruppo Test" description="Gruppo ISTI di test"
// officeId=201 managerId=4222 externalId="pimpaExternalId"
}

View File

@ -0,0 +1,127 @@
package it.cnr.isti.epasmed.epas.client;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import it.cnr.isti.epasmed.config.ApplicationProperties;
import it.cnr.isti.epasmed.epas.dto.EPASPersonsDTO;
import it.cnr.isti.epasmed.epas.model.EPASPersons;
@Component
public class EPASPersonsCient {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("RestTemplateForFirstUser")
RestTemplate rt;
@Autowired
ApplicationProperties appProps;
public EPASPersons getById(String id) {
EPASPersons epasPersons = rt.getForObject(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/persons/show/{id}", EPASPersons.class, id);
log.info("Retrieved Persons: {}", epasPersons);
return epasPersons;
}
public EPASPersons getByFiscalCode(String fc) {
EPASPersons epasPersons = rt.getForObject(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/persons/show?fiscalCode={fc}", EPASPersons.class, fc);
log.info("Retrieved Persons: {}", epasPersons);
return epasPersons;
}
public List<EPASPersons> getList(String officeId) {
ResponseEntity<List<EPASPersons>> responseEntity = rt.exchange(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/persons/list?id={officeId}", HttpMethod.GET, null,
new ParameterizedTypeReference<List<EPASPersons>>() {
}, officeId);
List<EPASPersons> listEPASPersons = responseEntity.getBody();
log.info("Retrieved Persons: {}", listEPASPersons);
return listEPASPersons;
}
public EPASPersons create(EPASPersonsDTO epasPersonsDTO) {
ResponseEntity<EPASPersons> response = rt.postForEntity(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/persons/create", epasPersonsDTO, EPASPersons.class);
EPASPersons createdEPASPersons = response.getBody();
log.info("Created Persons: {}", createdEPASPersons);
return createdEPASPersons;
}
public void updateById(String id, @Valid EPASPersonsDTO epasPersonsDTO) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("id", id);
rt.put(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/persons/update?id={id}", epasPersonsDTO, uriVariables);
log.info("Updated Persons: {}", id);
return;
}
public void updateByFiscalCode(String fc, EPASPersonsDTO epasPersonsDTO) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("fiscalCode", fc);
rt.put(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/persons/update?fiscalCode={fiscalCode}",
epasPersonsDTO, uriVariables);
log.info("Updated Person: {}", fc);
return;
}
public void deleteById(String id) {
rt.delete(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/persons/delete?id={id}", id);
log.info("Deleted Person with id: {}", id);
return;
}
public void deleteByFiscalCode(String fc) {
rt.delete(appProps.getDatasourceEpasRest().getRestUrl() + "/v2/persons/delete?fiscalCode={fc}", fc);
log.info("Delete Persons with fiscalcode: {}", fc);
return;
}
/*
* HttpHeaders headers = new HttpHeaders();
* headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
*
* MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
* map.add("name", epasPersons.getName()); map.add("surname",
* epasPersons.getSurname()); map.add("fiscalCode",
* epasPersons.getFiscalCode()); map.add("email", epasPersons.getEmail());
* map.add("qualification", epasPersons.getQualifcation()); map.add("officeId",
* epasPersons.getOffice().getId());
*
* HttpEntity<MultiValueMap<String, String>> request = new
* HttpEntity<MultiValueMap<String, String>>(map, headers);
*
* ResponseEntity<EPASPersons> response = rt.postForEntity(
* appProps.getDatasourceEpasRest().getRestUrl() + "/persons/create", request ,
* EPASPersons.class );
*/
// ResponseEntity<EPASPersons> response = rt.postForEntity(
// appProps.getDatasourceEpasRest().getRestUrl()
// + "/persons/create?name={name}&surname={surname}&email={email}"
// +
// "&qualification={qualification}&officeId={officeId}&fiscalCode={fiscalCode}",
// null, EPASPersons.class, uriVariables);
}

View File

@ -0,0 +1,48 @@
package it.cnr.isti.epasmed.epas.client;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import it.cnr.isti.epasmed.config.ApplicationProperties;
import it.cnr.isti.epasmed.epas.model.EPASWorkingTimeTypes;
@Component
public class EPASWorkinTipeTypesCient {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("RestTemplateForFirstUser")
RestTemplate rt;
@Autowired
ApplicationProperties appProps;
public EPASWorkingTimeTypes getById(String id) {
EPASWorkingTimeTypes epasWorkingTimeTypes = rt.getForObject(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/workingtimetypes/show?id={id}",
EPASWorkingTimeTypes.class, id);
log.info("Retrieved Working Time Types : {}", epasWorkingTimeTypes);
return epasWorkingTimeTypes;
}
public List<EPASWorkingTimeTypes> getList(String officeId) {
ResponseEntity<List<EPASWorkingTimeTypes>> responseEntity = rt.exchange(
appProps.getDatasourceEpasRest().getRestUrl() + "/v2/workingtimetypes/list?id={officeId}", HttpMethod.GET,
null, new ParameterizedTypeReference<List<EPASWorkingTimeTypes>>() {
}, officeId);
List<EPASWorkingTimeTypes> listEPASWorkingTimeTypes = responseEntity.getBody();
log.info("Retrieved Retrieved Working Time Types: {}", listEPASWorkingTimeTypes);
return listEPASWorkingTimeTypes;
}
}

View File

@ -0,0 +1,25 @@
package it.cnr.isti.epasmed.epas.dto;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASAffiliationsDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String beginDate;
private String endDate;
private String groupId;
private String id;
private String percentage;
private String personId;
private String externalId;
}

View File

@ -0,0 +1,26 @@
package it.cnr.isti.epasmed.epas.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASContractsDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String beginDate;
private String endContract;
private String endDate;
private String externalId;
private String id;
private boolean onCertificate;
private String personId;
private String previousContract;
}

View File

@ -0,0 +1,24 @@
package it.cnr.isti.epasmed.epas.dto;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASGroupsDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String description;
private String endDate;
private String externalId;
private String id;
private String managerId;
private String name;
private String officeId;
}

View File

@ -0,0 +1,31 @@
package it.cnr.isti.epasmed.epas.dto;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASPersonsDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String surname;
private String othersSurnames;
private String telephone;
private String fax;
private String mobile;
private String qualification;
private String[] badges;
private String officeId;
private String fullname;
private String fiscalCode;
private String email;
private String number;
private String eppn;
}

View File

@ -0,0 +1,47 @@
package it.cnr.isti.epasmed.epas.mapper;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.dto.EPASAffiliationsDTO;
import it.cnr.isti.epasmed.epas.model.EPASAffiliations;
/**
* Mapper for the entity {@link EPASAffiliations} and its DTO called
* {@link EPASAffiliationsDTO}.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as
* MapStruct support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class EPASAffiliationsMapper {
public List<EPASAffiliationsDTO> epasAffiliationsToEPASAffiliationsDTOs(
List<EPASAffiliations> epasAffiliationsList) {
return epasAffiliationsList.stream().filter(Objects::nonNull).map(this::epasAffiliationsToEPASAffiliationsDTO)
.collect(Collectors.toList());
}
public EPASAffiliationsDTO epasAffiliationsToEPASAffiliationsDTO(EPASAffiliations epasAffiliations) {
if (epasAffiliations == null) {
return null;
} else {
EPASAffiliationsDTO epasAffiliationsDTO = new EPASAffiliationsDTO();
epasAffiliationsDTO.setId(epasAffiliations.getId());
epasAffiliationsDTO.setExternalId(epasAffiliations.getExternalId());
epasAffiliationsDTO.setBeginDate(epasAffiliations.getBeginDate());
epasAffiliationsDTO.setEndDate(epasAffiliations.getEndDate());
if (epasAffiliations.getGroup() != null) {
epasAffiliationsDTO.setGroupId(epasAffiliations.getGroup().getId());
}
if (epasAffiliations.getPerson() != null) {
epasAffiliationsDTO.setPersonId(epasAffiliations.getPerson().getId());
}
epasAffiliationsDTO.setPercentage(epasAffiliations.getPercentage());
return epasAffiliationsDTO;
}
}
}

View File

@ -0,0 +1,45 @@
package it.cnr.isti.epasmed.epas.mapper;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.dto.EPASContractsDTO;
import it.cnr.isti.epasmed.epas.model.EPASContracts;
/**
* Mapper for the entity {@link EPASContracts} and its DTO called
* {@link EPASContractsDTO}.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as
* MapStruct support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class EPASContractsMapper {
public List<EPASContractsDTO> epasContractsToEPASContractsDTOs(List<EPASContracts> epasContractsList) {
return epasContractsList.stream().filter(Objects::nonNull).map(this::epasContractsToEPASContractsDTO)
.collect(Collectors.toList());
}
public EPASContractsDTO epasContractsToEPASContractsDTO(EPASContracts epasContracts) {
if (epasContracts == null) {
return null;
} else {
EPASContractsDTO epasContractsDTO = new EPASContractsDTO();
epasContractsDTO.setId(epasContracts.getId());
epasContractsDTO.setExternalId(epasContracts.getExternalId());
epasContractsDTO.setBeginDate(epasContracts.getBeginDate());
epasContractsDTO.setEndDate(epasContracts.getEndDate());
epasContractsDTO.setEndContract(epasContracts.getEndContract());
epasContractsDTO.setOnCertificate(epasContracts.isOnCertificate());
if (epasContracts.getPerson() != null) {
epasContractsDTO.setPersonId(epasContracts.getPerson().getId());
}
epasContractsDTO.setPreviousContract(epasContracts.getPreviousContract());
return epasContractsDTO;
}
}
}

View File

@ -0,0 +1,47 @@
package it.cnr.isti.epasmed.epas.mapper;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.dto.EPASGroupsDTO;
import it.cnr.isti.epasmed.epas.model.EPASGroups;
/**
* Mapper for the entity {@link EPASGroups} and its DTO called
* {@link EPASGroupsDTO}.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as
* MapStruct support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class EPASGroupsMapper {
public List<EPASGroupsDTO> epasGroupsToEPASGroupsDTOs(List<EPASGroups> epasGroupsList) {
return epasGroupsList.stream().filter(Objects::nonNull).map(this::epasGroupsToEPASGroupsDTO)
.collect(Collectors.toList());
}
public EPASGroupsDTO epasGroupsToEPASGroupsDTO(EPASGroups epasGroups) {
if (epasGroups == null) {
return null;
} else {
EPASGroupsDTO epasGroupsDTO = new EPASGroupsDTO();
epasGroupsDTO.setId(epasGroups.getId());
epasGroupsDTO.setName(epasGroups.getName());
epasGroupsDTO.setDescription(epasGroups.getDescription());
epasGroupsDTO.setEndDate(epasGroups.getEndDate());
epasGroupsDTO.setExternalId(epasGroups.getExternalId());
if (epasGroups.getManager() != null) {
epasGroupsDTO.setManagerId(epasGroups.getManager().getId());
}
if (epasGroups.getOffice() != null) {
epasGroupsDTO.setOfficeId(epasGroups.getOffice().getId());
}
return epasGroupsDTO;
}
}
}

View File

@ -0,0 +1,51 @@
package it.cnr.isti.epasmed.epas.mapper;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.dto.EPASPersonsDTO;
import it.cnr.isti.epasmed.epas.model.EPASPersons;
/**
* Mapper for the entity {@link EPASPersons} and its DTO called
* {@link EPASPersonsDTO}.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as
* MapStruct support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class EPASPersonsMapper {
public List<EPASPersonsDTO> epasPersonsToEPASPersonsDTOs(List<EPASPersons> epasPersonsList) {
return epasPersonsList.stream().filter(Objects::nonNull).map(this::epasPersonsToEPASPersonsDTO)
.collect(Collectors.toList());
}
public EPASPersonsDTO epasPersonsToEPASPersonsDTO(EPASPersons epasPersons) {
if (epasPersons == null) {
return null;
} else {
EPASPersonsDTO epasPersonsDTO = new EPASPersonsDTO();
epasPersonsDTO.setId(epasPersons.getId());
epasPersonsDTO.setName(epasPersons.getName());
epasPersonsDTO.setSurname(epasPersons.getSurname());
epasPersonsDTO.setOthersSurnames(epasPersons.getOthersSurnames());
epasPersonsDTO.setTelephone(epasPersons.getTelephone());
epasPersonsDTO.setFax(epasPersons.getFax());
epasPersonsDTO.setQualification(epasPersons.getQualification());
epasPersonsDTO.setBadges(epasPersons.getBadges());
if (epasPersons.getOffice() != null) {
epasPersonsDTO.setOfficeId(epasPersons.getOffice().getId());
}
epasPersonsDTO.setFullname(epasPersons.getFullname());
epasPersonsDTO.setFiscalCode(epasPersons.getFiscalCode());
epasPersonsDTO.setEmail(epasPersons.getEmail());
epasPersonsDTO.setNumber(epasPersons.getNumber());
epasPersonsDTO.setEppn(epasPersons.getEppn());
return epasPersonsDTO;
}
}
}

View File

@ -0,0 +1,26 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASAffiliations implements Serializable {
private static final long serialVersionUID = 1L;
private String beginDate;
private String endDate;
private EPASGroups group;
private String id;
private String percentage;
private EPASPersons person;
private String externalId;
private String updatedAt;
}

View File

@ -0,0 +1,28 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASContracts implements Serializable {
private static final long serialVersionUID = 1L;
private String beginDate;
private String endContract;
private String endDate;
private String externalId;
private String id;
private boolean onCertificate;
private EPASPersons person;
private String previousContract;
private EPASWorkingTimeForPerson[] workingTimeTypes;
private String updatedAt;
}

View File

@ -0,0 +1,25 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASGroups implements Serializable {
private static final long serialVersionUID = 1L;
private String description;
private String endDate;
private String externalId;
private String id;
private EPASGroupsManager manager;
private String name;
private EPASOffice office;
private EPASPersons[] people;
private String updatedAt;
}

View File

@ -0,0 +1,24 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASGroupsManager implements Serializable {
private static final long serialVersionUID = 1L;
private String email;
private String eppn;
private String fiscalCode;
private String fullname;
private String id;
private String number;
}

View File

@ -0,0 +1,22 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASOffice implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String code;
private String codeId;
}

View File

@ -0,0 +1,31 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASPersons implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String surname;
private String othersSurnames;
private String telephone;
private String fax;
private String mobile;
private String qualification;
private String[] badges;
private EPASOffice office;
private String fullname;
private String fiscalCode;
private String email;
private String number;
private String eppn;
}

View File

@ -0,0 +1,20 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASWorkingTimeForPerson implements Serializable {
private static final long serialVersionUID = 1L;
private String beginDate;
private String endDate;
private EPASWorkingTimeTypes workingTimeType;
}

View File

@ -0,0 +1,27 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASWorkingTimeTypeDays implements Serializable {
private static final long serialVersionUID = 1L;
private String breakTicketTime;
private String dayOfWeek;
private String holiday;
private String id;
private String ticketAfternoonThreshold;
private String ticketAfternoonWorkingTime;
private String timeMealFrom;
private String timeMealTo;
private String updatedAt;
private String workingTime;
}

View File

@ -0,0 +1,25 @@
package it.cnr.isti.epasmed.epas.model;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EPASWorkingTimeTypes implements Serializable {
private static final long serialVersionUID = 1L;
private String description;
private String disabled;
private String externalId;
private String horizontal;
private String id;
private String office;
private String updatedAt;
private EPASWorkingTimeTypeDays[] workingTimeTypeDays;
}

View File

@ -0,0 +1,48 @@
package it.cnr.isti.epasmed.epas.service;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.client.EPASAffiliationsCient;
import it.cnr.isti.epasmed.epas.dto.EPASAffiliationsDTO;
import it.cnr.isti.epasmed.epas.model.EPASAffiliations;
@Service
public class EPASAffiliationsService {
@Autowired
EPASAffiliationsCient epasAffiliationsClient;
public EPASAffiliations getById(String id) {
return epasAffiliationsClient.getById(id);
}
public List<EPASAffiliations> getByGroup(String groupId, boolean includeInactive ) {
return epasAffiliationsClient.getByGroup(groupId,includeInactive);
}
public List<EPASAffiliations> getByPersonId(String personId) {
return epasAffiliationsClient.getByPersonId(personId);
}
public List<EPASAffiliations> getByPersonFiscalcode(String fc) {
return epasAffiliationsClient.getByPersonFiscalcode(fc);
}
public EPASAffiliations create(EPASAffiliationsDTO epasAffiliationsDTO) {
return epasAffiliationsClient.create(epasAffiliationsDTO);
}
public void updateById(String id, @Valid EPASAffiliationsDTO epasAffiliationsDTO) {
epasAffiliationsClient.updateById(id,epasAffiliationsDTO);
}
public void deleteById(String id) {
epasAffiliationsClient.deleteById(id);
}
}

View File

@ -0,0 +1,52 @@
package it.cnr.isti.epasmed.epas.service;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.client.EPASContractsCient;
import it.cnr.isti.epasmed.epas.dto.EPASContractsDTO;
import it.cnr.isti.epasmed.epas.model.EPASContracts;
@Service
public class EPASContractsService {
@Autowired
EPASContractsCient epasContractsClient;
public EPASContracts getById(String id) {
return epasContractsClient.getById(id);
}
public List<EPASContracts> getByPersonId(String id) {
return epasContractsClient.getByPersonId(id);
}
public List<EPASContracts> getByPersonFiscalcode(String fc) {
return epasContractsClient.getByPersonFiscalcode(fc);
}
public EPASContracts create(EPASContractsDTO epasContractsDTO) {
return epasContractsClient.create(epasContractsDTO);
}
public void updateById(String id, @Valid EPASContractsDTO epasContractsDTO) {
epasContractsClient.updateById(id, epasContractsDTO);
}
public void setPreviousContract(String id) {
epasContractsClient.setPreviousContract(id);
}
public void setUnsetPreviousContract(String id) {
epasContractsClient.setUnsetPreviousContract(id);
}
public void deleteById(String id) {
epasContractsClient.deleteById(id);
}
}

View File

@ -0,0 +1,40 @@
package it.cnr.isti.epasmed.epas.service;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.client.EPASGroupsCient;
import it.cnr.isti.epasmed.epas.dto.EPASGroupsDTO;
import it.cnr.isti.epasmed.epas.model.EPASGroups;
@Service
public class EPASGroupsService {
@Autowired
EPASGroupsCient epasGroupsClient;
public EPASGroups getById(String id) {
return epasGroupsClient.getById(id);
}
public List<EPASGroups> getList(String officeId) {
return epasGroupsClient.getList(officeId);
}
public EPASGroups create(EPASGroupsDTO epasGroupsDTO) {
return epasGroupsClient.create(epasGroupsDTO);
}
public void updateById(String id, @Valid EPASGroupsDTO epasGroupsDTO) {
epasGroupsClient.updateById(id,epasGroupsDTO);
}
public void deleteById(String id) {
epasGroupsClient.deleteById(id);
}
}

View File

@ -0,0 +1,54 @@
package it.cnr.isti.epasmed.epas.service;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.client.EPASPersonsCient;
import it.cnr.isti.epasmed.epas.dto.EPASPersonsDTO;
import it.cnr.isti.epasmed.epas.model.EPASPersons;
@Service
public class EPASPersonsService {
@Autowired
EPASPersonsCient epasPersonsClient;
public EPASPersons getById(String id) {
return epasPersonsClient.getById(id);
}
public EPASPersons getByFiscalCode(String fc) {
return epasPersonsClient.getByFiscalCode(fc);
}
public List<EPASPersons> getList(String officeId) {
return epasPersonsClient.getList(officeId);
}
public EPASPersons create(EPASPersonsDTO epasPersonsDTO) {
return epasPersonsClient.create(epasPersonsDTO);
}
public void updateById(String id, @Valid EPASPersonsDTO epasPersonsDTO) {
epasPersonsClient.updateById(id,epasPersonsDTO);
}
public void updateByFiscalCode(String fc, EPASPersonsDTO epasPersonsDTO) {
epasPersonsClient.updateByFiscalCode(fc,epasPersonsDTO);
}
public void deleteById(String id) {
epasPersonsClient.deleteById(id);
}
public void deleteByFiscalCode(String fc) {
epasPersonsClient.deleteByFiscalCode(fc);
}
}

View File

@ -0,0 +1,26 @@
package it.cnr.isti.epasmed.epas.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.cnr.isti.epasmed.epas.client.EPASWorkinTipeTypesCient;
import it.cnr.isti.epasmed.epas.model.EPASWorkingTimeTypes;
@Service
public class EPASWorkingTimeTypesService {
@Autowired
EPASWorkinTipeTypesCient epasWorkingTimeTypesClient;
public EPASWorkingTimeTypes getById(String id) {
return epasWorkingTimeTypesClient.getById(id);
}
public List<EPASWorkingTimeTypes> getList(String officeId) {
return epasWorkingTimeTypesClient.getList(officeId);
}
}

View File

@ -0,0 +1,11 @@
package it.cnr.isti.epasmed.repository;
import it.cnr.isti.epasmed.domain.Authority;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Spring Data JPA repository for the {@link Authority} entity.
*/
public interface AuthorityRepository extends JpaRepository<Authority, String> {
}

View File

@ -0,0 +1,89 @@
package it.cnr.isti.epasmed.repository;
import it.cnr.isti.epasmed.config.Constants;
import it.cnr.isti.epasmed.config.audit.AuditEventConverter;
import it.cnr.isti.epasmed.domain.PersistentAuditEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
/**
* An implementation of Spring Boot's {@link AuditEventRepository}.
*/
@Repository
public class CustomAuditEventRepository implements AuditEventRepository {
private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";
/**
* Should be the same as in Liquibase migration.
*/
protected static final int EVENT_DATA_COLUMN_MAX_LENGTH = 255;
private final PersistenceAuditEventRepository persistenceAuditEventRepository;
private final AuditEventConverter auditEventConverter;
private final Logger log = LoggerFactory.getLogger(getClass());
public CustomAuditEventRepository(PersistenceAuditEventRepository persistenceAuditEventRepository,
AuditEventConverter auditEventConverter) {
this.persistenceAuditEventRepository = persistenceAuditEventRepository;
this.auditEventConverter = auditEventConverter;
}
@Override
public List<AuditEvent> find(String principal, Instant after, String type) {
Iterable<PersistentAuditEvent> persistentAuditEvents =
persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type);
return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}
@Override
@Transactional(value="epasMedTransactionManager",propagation = Propagation.REQUIRES_NEW)
public void add(AuditEvent event) {
if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
!Constants.ANONYMOUS_USER.equals(event.getPrincipal())) {
PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
persistentAuditEvent.setPrincipal(event.getPrincipal());
persistentAuditEvent.setAuditEventType(event.getType());
persistentAuditEvent.setAuditEventDate(event.getTimestamp());
Map<String, String> eventData = auditEventConverter.convertDataToStrings(event.getData());
persistentAuditEvent.setData(truncate(eventData));
persistenceAuditEventRepository.save(persistentAuditEvent);
}
}
/**
* Truncate event data that might exceed column length.
*/
private Map<String, String> truncate(Map<String, String> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
String value = entry.getValue();
if (value != null) {
int length = value.length();
if (length > EVENT_DATA_COLUMN_MAX_LENGTH) {
value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH);
log.warn("Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.",
entry.getKey(), length, EVENT_DATA_COLUMN_MAX_LENGTH);
}
}
results.put(entry.getKey(), value);
}
}
return results;
}
}

View File

@ -0,0 +1,23 @@
package it.cnr.isti.epasmed.repository;
import it.cnr.isti.epasmed.domain.PersistentAuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.Instant;
import java.util.List;
/**
* Spring Data JPA repository for the {@link PersistentAuditEvent} entity.
*/
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> {
List<PersistentAuditEvent> findByPrincipal(String principal);
List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principal, Instant after, String type);
Page<PersistentAuditEvent> findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable);
List<PersistentAuditEvent> findByAuditEventDateBefore(Instant before);
}

View File

@ -0,0 +1,19 @@
package it.cnr.isti.epasmed.repository;
import it.cnr.isti.epasmed.domain.PersistentToken;
import it.cnr.isti.epasmed.domain.User;
import java.time.LocalDate;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* Spring Data JPA repository for the {@link PersistentToken} entity.
*/
public interface PersistentTokenRepository extends JpaRepository<PersistentToken, String> {
List<PersistentToken> findByUser(User user);
List<PersistentToken> findByTokenDateBefore(LocalDate localDate);
}

View File

@ -0,0 +1,19 @@
package it.cnr.isti.epasmed.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import it.cnr.isti.epasmed.domain.TabsSI;
import it.cnr.isti.epasmed.domain.User;
/**
* Spring Data JPA repository for the {@link User} entity.
*/
@Repository
public interface TabsSIRepository extends JpaRepository<TabsSI, Long> {
Optional<TabsSI> findOneByNome(String nome);
}

View File

@ -0,0 +1,38 @@
package it.cnr.isti.epasmed.repository;
import it.cnr.isti.epasmed.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.time.Instant;
/**
* Spring Data JPA repository for the {@link User} entity.
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime);
Optional<User> findOneByResetKey(String resetKey);
Optional<User> findOneByEmailIgnoreCase(String email);
Optional<User> findOneByLogin(String login);
@EntityGraph(attributePaths = "authorities")
Optional<User> findOneWithAuthoritiesByLogin(String login);
@EntityGraph(attributePaths = "authorities")
Optional<User> findOneWithAuthoritiesByEmailIgnoreCase(String email);
Page<User> findAllByLoginNot(Pageable pageable, String login);
}

View File

@ -0,0 +1,4 @@
/**
* Spring Data JPA repositories.
*/
package it.cnr.isti.epasmed.repository;

View File

@ -0,0 +1,18 @@
package it.cnr.isti.epasmed.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 PROMETHEUS = "ROLE_PROMETHEUS";
public static final String ANONYMOUS = "ROLE_ANONYMOUS";
private AuthoritiesConstants() {
}
}

View File

@ -0,0 +1,62 @@
package it.cnr.isti.epasmed.security;
import it.cnr.isti.epasmed.domain.User;
import it.cnr.isti.epasmed.repository.UserRepository;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* Authenticate a user from the database.
*/
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional("epasMedTransactionManager")
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
if (new EmailValidator().isValid(login, null)) {
return userRepository.findOneWithAuthoritiesByEmailIgnoreCase(login)
.map(user -> createSpringSecurityUser(login, user))
.orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
}
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin)
.map(user -> createSpringSecurityUser(lowercaseLogin, user))
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));
}
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
grantedAuthorities);
}
}

View File

@ -0,0 +1,228 @@
package it.cnr.isti.epasmed.security;
import it.cnr.isti.epasmed.domain.PersistentToken;
import it.cnr.isti.epasmed.repository.PersistentTokenRepository;
import it.cnr.isti.epasmed.repository.UserRepository;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.security.PersistentTokenCache;
import io.github.jhipster.security.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.rememberme.*;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.*;
/**
* Custom implementation of Spring Security's RememberMeServices.
* <p>
* Persistent tokens are used by Spring Security to automatically log in users.
* <p>
* This is a specific implementation of Spring Security's remember-me authentication, but it is much
* more powerful than the standard implementations:
* <ul>
* <li>It allows a user to see the list of his currently opened sessions, and invalidate them</li>
* <li>It stores more information, such as the IP address and the user agent, for audit purposes<li>
* <li>When a user logs out, only his current session is invalidated, and not all of his sessions</li>
* </ul>
* <p>
* Please note that it allows the use of the same token for 5 seconds, and this value stored in a specific
* cache during that period. This is to allow concurrent requests from the same user: otherwise, two
* requests being sent at the same time could invalidate each other's token.
* <p>
* This is inspired by:
* <ul>
* <li><a href="http://jaspan.com/improved_persistent_login_cookie_best_practice">Improved Persistent Login Cookie
* Best Practice</a></li>
* <li><a href="https://github.com/blog/1661-modeling-your-app-s-user-session">GitHub's "Modeling your App's User Session"</a></li>
* </ul>
* <p>
* The main algorithm comes from Spring Security's {@code PersistentTokenBasedRememberMeServices}, but this class
* couldn't be cleanly extended.
*/
@Service
public class PersistentTokenRememberMeServices extends
AbstractRememberMeServices {
private final Logger log = LoggerFactory.getLogger(PersistentTokenRememberMeServices.class);
// Token is valid for one month
private static final int TOKEN_VALIDITY_DAYS = 31;
private static final int TOKEN_VALIDITY_SECONDS = 60 * 60 * 24 * TOKEN_VALIDITY_DAYS;
private static final long UPGRADED_TOKEN_VALIDITY_MILLIS = 5000l;
private final PersistentTokenCache<UpgradedRememberMeToken> upgradedTokenCache;
private final PersistentTokenRepository persistentTokenRepository;
private final UserRepository userRepository;
public PersistentTokenRememberMeServices(JHipsterProperties jHipsterProperties,
org.springframework.security.core.userdetails.UserDetailsService userDetailsService,
PersistentTokenRepository persistentTokenRepository, UserRepository userRepository) {
super(jHipsterProperties.getSecurity().getRememberMe().getKey(), userDetailsService);
this.persistentTokenRepository = persistentTokenRepository;
this.userRepository = userRepository;
upgradedTokenCache = new PersistentTokenCache<>(UPGRADED_TOKEN_VALIDITY_MILLIS);
}
@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) {
synchronized (this) { // prevent 2 authentication requests from the same user in parallel
String login = null;
UpgradedRememberMeToken upgradedToken = upgradedTokenCache.get(cookieTokens[0]);
if (upgradedToken != null) {
login = upgradedToken.getUserLoginIfValid(cookieTokens);
log.debug("Detected previously upgraded login token for user '{}'", login);
}
if (login == null) {
PersistentToken token = getPersistentToken(cookieTokens);
login = token.getUser().getLogin();
// Token also matches, so login is valid. Update the token value, keeping the *same* series number.
log.debug("Refreshing persistent login token for user '{}', series '{}'", login, token.getSeries());
token.setTokenDate(LocalDate.now());
token.setTokenValue(RandomUtil.generateRandomAlphanumericString());
token.setIpAddress(request.getRemoteAddr());
token.setUserAgent(request.getHeader("User-Agent"));
try {
persistentTokenRepository.saveAndFlush(token);
} catch (DataAccessException e) {
log.error("Failed to update token: ", e);
throw new RememberMeAuthenticationException("Autologin failed due to data access problem", e);
}
addCookie(token, request, response);
upgradedTokenCache.put(cookieTokens[0], new UpgradedRememberMeToken(cookieTokens, login));
}
return getUserDetailsService().loadUserByUsername(login);
}
}
@Override
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication
successfulAuthentication) {
String login = successfulAuthentication.getName();
log.debug("Creating new persistent login for user {}", login);
PersistentToken token = userRepository.findOneByLogin(login).map(u -> {
PersistentToken t = new PersistentToken();
t.setSeries(RandomUtil.generateRandomAlphanumericString());
t.setUser(u);
t.setTokenValue(RandomUtil.generateRandomAlphanumericString());
t.setTokenDate(LocalDate.now());
t.setIpAddress(request.getRemoteAddr());
t.setUserAgent(request.getHeader("User-Agent"));
return t;
}).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the database"));
try {
persistentTokenRepository.saveAndFlush(token);
addCookie(token, request, response);
} catch (DataAccessException e) {
log.error("Failed to save persistent token ", e);
}
}
/**
* When logout occurs, only invalidate the current token, and not all user sessions.
* <p>
* The standard Spring Security implementations are too basic: they invalidate all tokens for the
* current user, so when he logs out from one browser, all his other sessions are destroyed.
*
* @param request the request.
* @param response the response.
* @param authentication the authentication.
*/
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
String rememberMeCookie = extractRememberMeCookie(request);
if (rememberMeCookie != null && rememberMeCookie.length() != 0) {
try {
String[] cookieTokens = decodeCookie(rememberMeCookie);
PersistentToken token = getPersistentToken(cookieTokens);
persistentTokenRepository.deleteById(token.getSeries());
} catch (InvalidCookieException ice) {
log.info("Invalid cookie, no persistent token could be deleted", ice);
} catch (RememberMeAuthenticationException rmae) {
log.debug("No persistent token found, so no token could be deleted", rmae);
}
}
super.logout(request, response, authentication);
}
/**
* Validate the token and return it.
*/
private PersistentToken getPersistentToken(String[] cookieTokens) {
if (cookieTokens.length != 2) {
throw new InvalidCookieException("Cookie token did not contain " + 2 +
" tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
}
String presentedSeries = cookieTokens[0];
String presentedToken = cookieTokens[1];
Optional<PersistentToken> optionalToken = persistentTokenRepository.findById(presentedSeries);
if (!optionalToken.isPresent()) {
// No series match, so we can't authenticate using this cookie
throw new RememberMeAuthenticationException("No persistent token found for series id: " + presentedSeries);
}
PersistentToken token = optionalToken.get();
// We have a match for this user/series combination
log.info("presentedToken={} / tokenValue={}", presentedToken, token.getTokenValue());
if (!presentedToken.equals(token.getTokenValue())) {
// Token doesn't match series value. Delete this session and throw an exception.
persistentTokenRepository.deleteById(token.getSeries());
throw new CookieTheftException("Invalid remember-me token (Series/token) mismatch. Implies previous " +
"cookie theft attack.");
}
if (token.getTokenDate().plusDays(TOKEN_VALIDITY_DAYS).isBefore(LocalDate.now())) {
persistentTokenRepository.deleteById(token.getSeries());
throw new RememberMeAuthenticationException("Remember-me login has expired");
}
return token;
}
private void addCookie(PersistentToken token, HttpServletRequest request, HttpServletResponse response) {
setCookie(
new String[]{token.getSeries(), token.getTokenValue()},
TOKEN_VALIDITY_SECONDS, request, response);
}
private static class UpgradedRememberMeToken implements Serializable {
private static final long serialVersionUID = 1L;
private final String[] upgradedToken;
private final String userLogin;
UpgradedRememberMeToken(String[] upgradedToken, String userLogin) {
this.upgradedToken = upgradedToken;
this.userLogin = userLogin;
}
String getUserLoginIfValid(String[] currentToken) {
if (currentToken[0].equals(this.upgradedToken[0]) &&
currentToken[1].equals(this.upgradedToken[1])) {
return this.userLogin;
}
return null;
}
}
}

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