Compare commits
1 Commits
feature-re
...
20250403_1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a4d972160 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -119,8 +119,7 @@ fabric.properties
|
||||
# Integry
|
||||
*/target/*
|
||||
*.ckie
|
||||
/ts
|
||||
/temp
|
||||
/docker/tomcat/conf/integry/logs.db
|
||||
/docker/tomcat/conf/integry/logs.db-journal
|
||||
copilot.*.xml
|
||||
/.idea/dataSources.xml
|
||||
|
||||
0
.gitmodules
vendored
0
.gitmodules
vendored
6
.idea/copilot.data.migration.edit.xml
generated
6
.idea/copilot.data.migration.edit.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="EditMigrationStateService">
|
||||
<option name="migrationStatus" value="COMPLETED" />
|
||||
</component>
|
||||
</project>
|
||||
13
.idea/inspectionProfiles/Project_Default.xml
generated
13
.idea/inspectionProfiles/Project_Default.xml
generated
@@ -4,18 +4,5 @@
|
||||
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,com.annimon.stream.Stream,of" />
|
||||
</inspection_tool>
|
||||
<inspection_tool class="UnusedLabel" enabled="true" level="WEAK WARNING" enabled_by_default="true" editorAttributes="INFO_ATTRIBUTES" />
|
||||
<inspection_tool class="unused" enabled="true" level="WEAK WARNING" enabled_by_default="true" editorAttributes="INFO_ATTRIBUTES" checkParameterExcludingHierarchy="false">
|
||||
<option name="LOCAL_VARIABLE" value="true" />
|
||||
<option name="FIELD" value="true" />
|
||||
<option name="METHOD" value="true" />
|
||||
<option name="CLASS" value="true" />
|
||||
<option name="PARAMETER" value="true" />
|
||||
<option name="REPORT_PARAMETER_FOR_PUBLIC_METHODS" value="true" />
|
||||
<option name="ADD_MAINS_TO_ENTRIES" value="true" />
|
||||
<option name="ADD_APPLET_TO_ENTRIES" value="true" />
|
||||
<option name="ADD_SERVLET_TO_ENTRIES" value="true" />
|
||||
<option name="ADD_NONJAVA_TO_ENTRIES" value="true" />
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
1
.idea/runConfigurations/MenuStaticCreator.xml
generated
1
.idea/runConfigurations/MenuStaticCreator.xml
generated
@@ -2,7 +2,6 @@
|
||||
<configuration default="false" name="MenuStaticCreator" type="Application" factoryName="Application" nameIsGenerated="true">
|
||||
<option name="MAIN_CLASS_NAME" value="it.integry.ems.menu.MenuStaticCreator" />
|
||||
<module name="ems-core" />
|
||||
<shortenClasspath name="MANIFEST" />
|
||||
<extension name="coverage">
|
||||
<pattern>
|
||||
<option name="PATTERN" value="it.integry.ems.menu.*" />
|
||||
|
||||
18
.idea/runConfigurations/Tomcat.xml
generated
18
.idea/runConfigurations/Tomcat.xml
generated
@@ -16,30 +16,12 @@
|
||||
<log_file alias="Tomcat Localhost Access Log" path="%IDEA_RUN:CATALINA_BASE%/logs/localhost_access_log.*" />
|
||||
<predefined_log_file enabled="true" id="Tomcat" />
|
||||
<predefined_log_file enabled="true" id="Tomcat Catalina" />
|
||||
<RunnerSettings RunnerId="AppServerDebuggerRunner">
|
||||
<option name="DEBUG_PORT" value="javadebug" />
|
||||
</RunnerSettings>
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="javadebug" />
|
||||
</RunnerSettings>
|
||||
<RunnerSettings RunnerId="JProfiler">
|
||||
<option name="jreHome" value="$USER_HOME$/.jdks/openjdk-21.0.2" />
|
||||
</RunnerSettings>
|
||||
<ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="AppServerDebuggerRunner">
|
||||
<option name="USE_ENV_VARIABLES" value="true" />
|
||||
<STARTUP>
|
||||
<option name="USE_DEFAULT" value="true" />
|
||||
<option name="SCRIPT" value="" />
|
||||
<option name="VM_PARAMETERS" value="" />
|
||||
<option name="PROGRAM_PARAMETERS" value="" />
|
||||
</STARTUP>
|
||||
<SHUTDOWN>
|
||||
<option name="USE_DEFAULT" value="true" />
|
||||
<option name="SCRIPT" value="" />
|
||||
<option name="VM_PARAMETERS" value="" />
|
||||
<option name="PROGRAM_PARAMETERS" value="" />
|
||||
</SHUTDOWN>
|
||||
</ConfigurationWrapper>
|
||||
<ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Cover">
|
||||
<option name="USE_ENV_VARIABLES" value="true" />
|
||||
<STARTUP>
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Tomcat9Import ( TomcatSrv)" type="Remote" folderName="Carelli">
|
||||
<module name="ems-engine" />
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="172.16.30.239" />
|
||||
<option name="PORT" value="8003" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="8003" />
|
||||
<option name="LOCAL" value="false" />
|
||||
</RunnerSettings>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -4,7 +4,7 @@
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="localhost" />
|
||||
<option name="HOST" value="192.168.1.7" />
|
||||
<option name="PORT" value="8001" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
|
||||
16
.idea/runConfigurations/Tomcat_9__1__Server_01_.xml
generated
16
.idea/runConfigurations/Tomcat_9__1__Server_01_.xml
generated
@@ -1,16 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Tomcat 9 #1 (Server-01)" type="Remote" folderName="VgAlimenti">
|
||||
<module name="ems-engine" />
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="10.107.107.15" />
|
||||
<option name="PORT" value="5005" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="5005" />
|
||||
<option name="LOCAL" value="false" />
|
||||
</RunnerSettings>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -1,10 +1,10 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Tomcat 9 (AnydeskTunnel)" type="Remote">
|
||||
<configuration default="false" name="Tomcat 9 (RistoCash)" type="Remote">
|
||||
<module name="ems-engine" />
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="localhost" />
|
||||
<option name="HOST" value="127.0.0.1" />
|
||||
<option name="PORT" value="8001" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
15
.idea/runConfigurations/Tomcat__1__Gramm_.xml
generated
15
.idea/runConfigurations/Tomcat__1__Gramm_.xml
generated
@@ -1,15 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Tomcat #1 (Gramm)" type="Remote" folderName="Gramm">
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="192.168.50.17" />
|
||||
<option name="PORT" value="8001" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="8001" />
|
||||
<option name="LOCAL" value="false" />
|
||||
</RunnerSettings>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -1,14 +1,14 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="Tomcat #1 (Smetar) [VPN]" type="Remote" folderName="Smetar">
|
||||
<configuration default="false" name="Tomcat (AnydeskTunnel)" type="Remote">
|
||||
<module name="ems-engine" />
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="10.0.0.2" />
|
||||
<option name="PORT" value="5005" />
|
||||
<option name="HOST" value="servertomcat" />
|
||||
<option name="PORT" value="8000" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="5005" />
|
||||
<option name="DEBUG_PORT" value="8000" />
|
||||
<option name="LOCAL" value="false" />
|
||||
</RunnerSettings>
|
||||
<method v="2" />
|
||||
18
.idea/runConfigurations/Tomcat__FAST_.xml
generated
18
.idea/runConfigurations/Tomcat__FAST_.xml
generated
@@ -16,30 +16,12 @@
|
||||
<log_file alias="Tomcat Localhost Access Log" path="%IDEA_RUN:CATALINA_BASE%/logs/localhost_access_log.*" />
|
||||
<predefined_log_file enabled="true" id="Tomcat" />
|
||||
<predefined_log_file enabled="true" id="Tomcat Catalina" />
|
||||
<RunnerSettings RunnerId="AppServerDebuggerRunner">
|
||||
<option name="DEBUG_PORT" value="63868" />
|
||||
</RunnerSettings>
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="javadebug" />
|
||||
</RunnerSettings>
|
||||
<RunnerSettings RunnerId="JProfiler">
|
||||
<option name="jreHome" value="$PROJECT_DIR$/../../../Program Files/Java/jdk1.8.0_202" />
|
||||
</RunnerSettings>
|
||||
<ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="AppServerDebuggerRunner">
|
||||
<option name="USE_ENV_VARIABLES" value="true" />
|
||||
<STARTUP>
|
||||
<option name="USE_DEFAULT" value="true" />
|
||||
<option name="SCRIPT" value="" />
|
||||
<option name="VM_PARAMETERS" value="" />
|
||||
<option name="PROGRAM_PARAMETERS" value="" />
|
||||
</STARTUP>
|
||||
<SHUTDOWN>
|
||||
<option name="USE_DEFAULT" value="true" />
|
||||
<option name="SCRIPT" value="" />
|
||||
<option name="VM_PARAMETERS" value="" />
|
||||
<option name="PROGRAM_PARAMETERS" value="" />
|
||||
</SHUTDOWN>
|
||||
</ConfigurationWrapper>
|
||||
<ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Cover">
|
||||
<option name="USE_ENV_VARIABLES" value="true" />
|
||||
<STARTUP>
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="docker-compose.yml: Compose Deployment" type="docker-deploy" factoryName="docker-compose.yml" server-name="Docker">
|
||||
<deployment type="docker-compose.yml">
|
||||
<settings>
|
||||
<option name="envFilePath" value="" />
|
||||
<option name="commandLineOptions" value="--build" />
|
||||
<option name="sourceFilePath" value="docker-compose.yml" />
|
||||
</settings>
|
||||
</deployment>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
15
.idea/runConfigurations/tomcat9___TomcatSrv_.xml
generated
15
.idea/runConfigurations/tomcat9___TomcatSrv_.xml
generated
@@ -1,15 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="tomcat9 ( TomcatSrv)" type="Remote" folderName="Carelli">
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="172.16.30.239" />
|
||||
<option name="PORT" value="8001" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="8001" />
|
||||
<option name="LOCAL" value="false" />
|
||||
</RunnerSettings>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
6
.idea/sqldialects.xml
generated
6
.idea/sqldialects.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="file://$PROJECT_DIR$/ems-engine/src/main/java/it/integry/ems/document/farm_mes/service/FarmMesImportService.java" dialect="GenericSQL" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,18 +0,0 @@
|
||||
FROM tomcat:9-jre8-alpine
|
||||
|
||||
RUN apk add --no-cache fontconfig ttf-dejavu
|
||||
|
||||
ENV TZ="Europe/Rome"
|
||||
ENV JAVA_OPTS="-DDISABLE_DROOLS_COMPILE=TRUE -Xms512M -Xmx1G -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
|
||||
ENV USERDOMAIN="STUDIO-ML"
|
||||
|
||||
COPY docker/tomcat/conf/integry/ems.properties /usr/local/tomcat/conf/integry/
|
||||
COPY docker/tomcat/conf/integry/ems_automated_operations.json /usr/local/tomcat/conf/integry/
|
||||
COPY docker/tomcat/conf/integry/ems_settings.json /usr/local/tomcat/conf/integry/
|
||||
COPY ems-engine/target/ems-api.war /usr/local/tomcat/webapps/
|
||||
|
||||
#COPY docker/FontTest.class .
|
||||
#ENTRYPOINT ["java","FontTest"]
|
||||
|
||||
EXPOSE 8080
|
||||
EXPOSE 5005
|
||||
@@ -1,7 +1,5 @@
|
||||
FROM tomcat:9-jre8-alpine
|
||||
|
||||
RUN apk add --no-cache fontconfig ttf-dejavu
|
||||
|
||||
ENV TZ="Europe/Rome"
|
||||
ENV JAVA_OPTS="-DDISABLE_DROOLS_COMPILE=TRUE -Xms512M -Xmx1G -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
|
||||
ENV USERDOMAIN="STUDIO-ML"
|
||||
@@ -11,8 +9,5 @@ COPY docker/tomcat/conf/integry/ems_automated_operations.json /usr/local/tomcat/
|
||||
COPY docker/tomcat/conf/integry/ems_settings.json /usr/local/tomcat/conf/integry/
|
||||
COPY ems-engine/target/ems-api.war /usr/local/tomcat/webapps/
|
||||
|
||||
#COPY docker/FontTest.class .
|
||||
#ENTRYPOINT ["java","FontTest"]
|
||||
|
||||
EXPOSE 8080
|
||||
EXPOSE 5005
|
||||
@@ -10,51 +10,33 @@ pipeline {
|
||||
stage('PreBuild Steps (Master)') {
|
||||
when {
|
||||
expression {
|
||||
return env.GIT_BRANCH == "master" || env.GIT_BRANCH == "feature/RefactoringGestioneColli"
|
||||
return env.GIT_BRANCH == "master"
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "Creo version tag su Git"
|
||||
script {
|
||||
def date = new Date()
|
||||
def formattedDate = date.format('yyyyMMdd_HHmm')
|
||||
|
||||
def tagName = "${env.GIT_BRANCH.toLowerCase().replace('/', '-')}-${formattedDate}"
|
||||
def tagMessage = "Build #${env.BUILD_NUMBER} - ${env.GIT_BRANCH}"
|
||||
|
||||
def envPropertiesText = "project.version=${formattedDate}"
|
||||
|
||||
writeFile(
|
||||
'file': 'ems-core\\src\\main\\resources\\configs\\env.properties',
|
||||
'text': envPropertiesText
|
||||
)
|
||||
|
||||
bat "git add . -A"
|
||||
bat "git tag -a ${tagName} -m \"${tagMessage}\""
|
||||
bat "git push origin ${tagName}"
|
||||
}
|
||||
bat 'build\\create_build_tag.bat'
|
||||
}
|
||||
}
|
||||
stage('Maven Build') {
|
||||
steps {
|
||||
echo "${WORKSPACE}"
|
||||
withMaven(traceability: true, maven: 'Maven 3.9.5', options: [artifactsPublisher(disabled: true)]) {
|
||||
withMaven(jdk: 'JDK 17.0.6 x64', traceability: true, maven: 'Maven 3.9.5') {
|
||||
bat(script: 'mvn clean install -t toolchains-jenkins.xml', returnStdout: true)
|
||||
archiveArtifacts(artifacts: 'ems-engine/target/ems-api.war', onlyIfSuccessful: true)
|
||||
archiveArtifacts(artifacts: 'ems-engine/target/*.war*', onlyIfSuccessful: true)
|
||||
}
|
||||
stash includes: 'ems-engine/target/ems-api.war,docker/**,Containerfile', name: 'container-files'
|
||||
stash includes: 'ems-engine/target/*.war,docker/**,Dockerfile', name: 'docker-files'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Publish') {
|
||||
stage('Publish Develop') {
|
||||
when {
|
||||
expression {
|
||||
return env.GIT_BRANCH == "develop"
|
||||
}
|
||||
}
|
||||
parallel {
|
||||
|
||||
stage('Publish Develop') {
|
||||
when {
|
||||
expression {
|
||||
return env.GIT_BRANCH == "develop"
|
||||
}
|
||||
}
|
||||
stage('Tomcat update') {
|
||||
stages {
|
||||
stage('Update Tomcat 1') {
|
||||
steps {
|
||||
@@ -66,19 +48,23 @@ pipeline {
|
||||
steps {
|
||||
echo "Updating Tomcat9 from ${WORKSPACE}"
|
||||
powershell returnStdout: true, script: "build\\update_tomcat.ps1 -serviceName \"Tomcat9Backup\" -httpPort \"8082\" -updatedArtifactPath \"${WORKSPACE}\\ems-engine\\target\\ems-api.war\""
|
||||
bat 'curl -k "https://devservices.studioml.it/ems-api/updateWMSApp?overrideForced=false"'
|
||||
bat 'curl -k "https://devservices.studioml.it/ems-api/updateWMSApp?overrideForced=false&suffix=beta"'
|
||||
bat 'curl -k https://devservices.studioml.it/ems-api/updateWMSApp'
|
||||
bat 'curl -k https://devservices.studioml.it/ems-api/updateWMSApp?suffix=beta'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Publish Master') {
|
||||
when {
|
||||
expression {
|
||||
return env.GIT_BRANCH == "master"
|
||||
}
|
||||
}
|
||||
stage('Publish Master') {
|
||||
when {
|
||||
expression {
|
||||
return env.GIT_BRANCH == "master"
|
||||
}
|
||||
}
|
||||
parallel {
|
||||
stage('Tomcat update') {
|
||||
stages {
|
||||
stage('Update Tomcat 1') {
|
||||
steps {
|
||||
@@ -100,87 +86,41 @@ sudo /usr/bin/systemctl start tomcat9backup
|
||||
/home/studioml/./wait_tomcat_startup.sh 8082
|
||||
|
||||
sleep 10''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '/tomcat9backup/webapps', remoteDirectorySDF: false, removePrefix: 'ems-engine/target/', sourceFiles: 'ems-engine/target/*.war*')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
|
||||
bat 'curl -k "https://services.studioml.it/ems-api/updateWMSApp?overrideForced=false"'
|
||||
bat 'curl -k "https://services.studioml.it/ems-api/updateWMSApp?overrideForced=false&suffix=beta"'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
stage('Publish Branch on Azure') {
|
||||
steps {
|
||||
azureUpload fileShareName: 'storage-ci', filesPath: 'ems-engine/target/*.war*', removePrefixPath: 'ems-engine/target/', storageCredentialId: '83a86793-c1d6-4776-b20f-1ff652a57fee', storageType: 'filestorage', uploadArtifactsOnlyIfSuccessful: true, verbose: true, virtualPath: "ems-api/${env.GIT_BRANCH}"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Docker Build') {
|
||||
steps {
|
||||
node('server-build') {
|
||||
echo "Building Docker image"
|
||||
unstash 'container-files'
|
||||
|
||||
script {
|
||||
def branchVersion = ""
|
||||
|
||||
if (env.GIT_BRANCH != "master") {
|
||||
branchVersion = "-${env.GIT_BRANCH.toLowerCase().replace('/', '-')}"
|
||||
}
|
||||
|
||||
// bat "docker buildx build --platform linux/amd64,linux/arm64 --push -t \"git.studioml.it/integry/ems-api${branchVersion}:latest\" ."
|
||||
bat "podman build -f .\\Containerfile -t \"git.studioml.it/integry/ems-api${branchVersion}:latest\" ."
|
||||
bat "podman push \"git.studioml.it/integry/ems-api${branchVersion}:latest\""
|
||||
|
||||
//containerImageLink "git.studioml.it/integry/ems-api-${env.GIT_BRANCH.toLowerCase().replace('/', '-')}:latest}"
|
||||
bat 'curl -k https://services.studioml.it/ems-api/updateWMSApp'
|
||||
bat 'curl -k https://services.studioml.it/ems-api/updateWMSApp?suffix=beta'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Publish TypeScript modules') {
|
||||
when {
|
||||
expression {
|
||||
return env.GIT_BRANCH == "master" || env.GIT_BRANCH == "develop"
|
||||
}
|
||||
}
|
||||
stage('Publish on Azure') {
|
||||
steps {
|
||||
script {
|
||||
bat "IF EXIST IntegryManagementSystemTSModules RMDIR IntegryManagementSystemTSModules /S /Q"
|
||||
|
||||
// Clona la repository di destinazione
|
||||
echo "Clonazione della repository di destinazione..."
|
||||
bat 'git clone https://git.studioml.it/Integry/IntegryManagementSystemTSModules.git'
|
||||
|
||||
// Entra nella directory della repository di destinazione
|
||||
dir('IntegryManagementSystemTSModules') {
|
||||
if(env.GIT_BRANCH != "master") {
|
||||
// Crea un nuovo branch se non è master o develop
|
||||
bat "git checkout -b ${env.GIT_BRANCH} origin/${env.GIT_BRANCH}"
|
||||
} else {
|
||||
// Altrimenti, torna al branch master o develop
|
||||
bat "git checkout ${env.GIT_BRANCH}"
|
||||
}
|
||||
|
||||
//bat "git checkout -b ${env.GIT_BRANCH}"
|
||||
bat "git pull origin ${env.GIT_BRANCH}"
|
||||
|
||||
// Copia i file .ts nella repository di destinazione
|
||||
echo "Copia dei file .ts nella repository di destinazione..."
|
||||
bat 'copy ..\\ts\\*.ts .'
|
||||
|
||||
// Aggiungi i file modificati
|
||||
bat 'git add *.ts'
|
||||
|
||||
// Commit e push
|
||||
bat 'git commit -m "Aggiornamento file .ts"'
|
||||
bat 'git push https://git.studioml.it/Integry/IntegryManagementSystemTSModules.git --all'
|
||||
}
|
||||
}
|
||||
azureUpload fileShareName: 'storage-ci', filesPath: 'ems-engine/target/*.war*', removePrefixPath: 'ems-engine/target/', storageCredentialId: '83a86793-c1d6-4776-b20f-1ff652a57fee', storageType: 'filestorage', uploadArtifactsOnlyIfSuccessful: true, verbose: true, virtualPath: 'ems-api'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Docker Build') {
|
||||
steps {
|
||||
node('server-build') {
|
||||
echo "Building Docker image"
|
||||
unstash 'docker-files'
|
||||
|
||||
script {
|
||||
def branchVersion = ""
|
||||
|
||||
if (env.GIT_BRANCH != "master") {
|
||||
branchVersion = "-${env.GIT_BRANCH.toLowerCase().replace('/', '-')}"
|
||||
}
|
||||
|
||||
bat "docker buildx build --platform linux/amd64,linux/arm64 --push -t \"git.studioml.it/integry/ems-api${branchVersion}:latest\" ."
|
||||
|
||||
//containerImageLink "git.studioml.it/integry/ems-api-${env.GIT_BRANCH.toLowerCase().replace('/', '-')}:latest}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -188,14 +128,14 @@ sleep 10''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaul
|
||||
success {
|
||||
script {
|
||||
if (env.GIT_BRANCH == "master" || env.GIT_BRANCH == "develop") {
|
||||
office365ConnectorSend adaptiveCards: true, color: '#008000', message: 'EMS-API è stato compilato con successo', status: 'SUCCESS', webhookUrl: 'https://prod-197.westeurope.logic.azure.com:443/workflows/69a7b8ee3c284175bd6da7127c7eb3cf/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=_-eMfvsQGkIidHWzzlhGFgiZG28ujHZ41QqzuqD9YGw'
|
||||
office365ConnectorSend adaptiveCards: true, color: '#008000', message: 'EMS-API ` stato compilato con successo', status: 'SUCCESS', webhookUrl: 'https://prod-197.westeurope.logic.azure.com:443/workflows/69a7b8ee3c284175bd6da7127c7eb3cf/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=_-eMfvsQGkIidHWzzlhGFgiZG28ujHZ41QqzuqD9YGw'
|
||||
}
|
||||
}
|
||||
}
|
||||
unstable {
|
||||
script {
|
||||
if (env.GIT_BRANCH == "master" || env.GIT_BRANCH == "develop") {
|
||||
office365ConnectorSend adaptiveCards: true, color: '#FFDE21', message: 'EMS-API è INSTABILE', status: 'UNSTABLE', webhookUrl: 'https://prod-197.westeurope.logic.azure.com:443/workflows/69a7b8ee3c284175bd6da7127c7eb3cf/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=_-eMfvsQGkIidHWzzlhGFgiZG28ujHZ41QqzuqD9YGw'
|
||||
office365ConnectorSend adaptiveCards: true, color: '#FFDE21', message: 'EMS-API ` INSTABILE', status: 'UNSTABLE', webhookUrl: 'https://prod-197.westeurope.logic.azure.com:443/workflows/69a7b8ee3c284175bd6da7127c7eb3cf/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=_-eMfvsQGkIidHWzzlhGFgiZG28ujHZ41QqzuqD9YGw'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -205,6 +145,7 @@ sleep 10''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaul
|
||||
office365ConnectorSend adaptiveCards: true, color: '#FF2C2C', message: 'Errore di compilazione su EMS-API', status: 'FAILURE', webhookUrl: 'https://prod-197.westeurope.logic.azure.com:443/workflows/69a7b8ee3c284175bd6da7127c7eb3cf/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=_-eMfvsQGkIidHWzzlhGFgiZG28ujHZ41QqzuqD9YGw'
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
43
build/create_build_tag.bat
Normal file
43
build/create_build_tag.bat
Normal file
@@ -0,0 +1,43 @@
|
||||
REM SET YEAR
|
||||
set YEAR=%date:~6,4%
|
||||
|
||||
REM SET MONTH
|
||||
set MONTH=%date:~3,2%
|
||||
if %MONTH% LSS 10 set MONTH=%MONTH:~1,2%
|
||||
if %MONTH% LSS 10 set MONTH=0%MONTH%
|
||||
|
||||
REM SET DAY
|
||||
set DAY=%date:~0,2%
|
||||
if %DAY% LSS 10 set DAY=%DAY:~1,2%
|
||||
if %DAY% LSS 10 set DAY=0%DAY%
|
||||
|
||||
REM SET HOUR
|
||||
set HOUR=%time:~0,2%
|
||||
if %HOUR% LSS 10 set HOUR=%HOUR:~1,2%
|
||||
if %HOUR% LSS 10 set HOUR=0%HOUR%
|
||||
|
||||
REM SET MINUTE
|
||||
set MINUTE=%time:~3,2%
|
||||
if %MINUTE% LSS 10 set MINUTE=%MINUTE:~1,2%
|
||||
if %MINUTE% LSS 10 set MINUTE=0%MINUTE%
|
||||
|
||||
REM SET SECOND
|
||||
set SECOND=%time:~6,2%
|
||||
if %SECOND% LSS 10 set SECOND=%SECOND:~1,2%
|
||||
if %SECOND% LSS 10 set SECOND=0%SECOND%
|
||||
|
||||
set mydate=%YEAR%%MONTH%%DAY%_%HOUR%%MINUTE%%SECOND%
|
||||
|
||||
|
||||
|
||||
echo #spring.profiles.active=@activatedProperties@ > ems-core\src\main\resources\configs\env.properties
|
||||
echo project.version=%mydate% >> ems-core\src\main\resources\configs\env.properties
|
||||
|
||||
|
||||
git add . -A
|
||||
git commit -m "%mydate%"
|
||||
git tag "%mydate%"
|
||||
|
||||
|
||||
git push https://git.studioml.it/Integry/IntegryManagementSystem.git --tags
|
||||
git push https://git.studioml.it/Integry/IntegryManagementSystem.git --all
|
||||
@@ -11,7 +11,7 @@ $webappsPath = "C:\Program Files\$serviceName\webapps"
|
||||
# Funzione per eseguire la chiamata GET e controllare lo status code
|
||||
function Check-Status {
|
||||
try {
|
||||
$request = Invoke-WebRequest -Uri "http://localhost:$httpPort/ems-api/system/ok" -Method Get -ErrorAction Stop -UseBasicParsing
|
||||
$request = Invoke-WebRequest -Uri "http://localhost:$httpPort/ems-api/system/ok" -Method Get -ErrorAction Stop
|
||||
$statusCode = $request.StatusCode
|
||||
if ($statusCode -eq 200) {
|
||||
Write-Host "Status code 200 ricevuto, processo completato."
|
||||
|
||||
Binary file not shown.
@@ -1,14 +0,0 @@
|
||||
import java.awt.*;
|
||||
|
||||
public class FontTest {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String[] names = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
|
||||
|
||||
System.out.println("Found " + names.length + " fonts:");
|
||||
|
||||
for (String name : names) {
|
||||
System.out.println(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,16 @@
|
||||
"primaryInstance" : true,
|
||||
"enableTokenCaching" : false,
|
||||
"systemPassword" : "?MF!jbI+&OkA",
|
||||
"availableConnections" : [{
|
||||
"availableConnections" : [ {
|
||||
"profileName" : "MAGGIOSRL",
|
||||
"connectionType" : "MSSQL",
|
||||
"dbName" : "MaggioSRL",
|
||||
"username" : "sa",
|
||||
"password" : "sZ",
|
||||
"host" : "192.168.2.214",
|
||||
"encryptedDbPsw" : true,
|
||||
"internalDb" : true
|
||||
}, {
|
||||
"profileName" : "AGRICOPER",
|
||||
"connectionType" : "MSSQL",
|
||||
"dbName" : "agricoper",
|
||||
@@ -24,18 +33,18 @@
|
||||
"encryptedDbPsw" : true,
|
||||
"internalDb" : true
|
||||
}, {
|
||||
"profileName" : "RESINA_COLOR",
|
||||
"profileName" : "COAP",
|
||||
"connectionType" : "MSSQL",
|
||||
"dbName" : "RESINACOLOR",
|
||||
"dbName" : "COAP",
|
||||
"username" : "sa",
|
||||
"password" : "sZ",
|
||||
"host" : "192.168.2.214",
|
||||
"encryptedDbPsw" : true,
|
||||
"internalDb" : true
|
||||
}, {
|
||||
"profileName" : "RESINA_COLOR_PASQUALE",
|
||||
"profileName" : "RESINA_COLOR",
|
||||
"connectionType" : "MSSQL",
|
||||
"dbName" : "RESINACOLOR_PASQUALE",
|
||||
"dbName" : "RESINACOLOR",
|
||||
"username" : "sa",
|
||||
"password" : "sZ",
|
||||
"host" : "192.168.2.214",
|
||||
@@ -233,21 +242,12 @@
|
||||
}, {
|
||||
"profileName" : "GRAMM",
|
||||
"connectionType" : "MSSQL",
|
||||
"dbName" : "gramm_peppe",
|
||||
"dbName" : "gramm",
|
||||
"username" : "SA",
|
||||
"password" : "sZ",
|
||||
"host" : "192.168.2.220",
|
||||
"encryptedDbPsw" : true,
|
||||
"internalDb" : true
|
||||
}, {
|
||||
"profileName" : "MAGGIOSRL",
|
||||
"connectionType" : "MSSQL",
|
||||
"dbName" : "MaggioSRL",
|
||||
"username" : "sa",
|
||||
"password" : "sZ",
|
||||
"host" : "192.168.2.214",
|
||||
"encryptedDbPsw" : true,
|
||||
"internalDb" : true
|
||||
}, {
|
||||
"profileName" : "IDROTECNICA",
|
||||
"connectionType" : "MSSQL",
|
||||
@@ -278,7 +278,7 @@
|
||||
}, {
|
||||
"profileName" : "IME_TE",
|
||||
"connectionType" : "MSSQL",
|
||||
"dbName" : "IME_TE_peppe",
|
||||
"dbName" : "IME_TE",
|
||||
"username" : "SA",
|
||||
"password" : "sZ",
|
||||
"host" : "192.168.2.214",
|
||||
@@ -692,7 +692,7 @@
|
||||
}, {
|
||||
"profileName" : "BIOLEVANTE",
|
||||
"connectionType" : "MSSQL",
|
||||
"dbName": "biolevante",
|
||||
"dbName" : "biolevante",
|
||||
"username" : "SA",
|
||||
"password" : "sZ",
|
||||
"host" : "192.168.2.220",
|
||||
|
||||
@@ -60,6 +60,49 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>cz.habarta.typescript-generator</groupId>
|
||||
<artifactId>typescript-generator-maven-plugin</artifactId>
|
||||
<version>2.37.1128</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>generate</id>
|
||||
<goals>
|
||||
<goal>generate</goal>
|
||||
</goals>
|
||||
<phase>process-classes</phase>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<jsonLibrary>jackson2</jsonLibrary>
|
||||
<classPatterns>it.integry.ems_model.entity.*</classPatterns>
|
||||
<classes>
|
||||
<class>it.integry.ems.response.ServiceRestResponse</class>
|
||||
</classes>
|
||||
<excludeClasses>
|
||||
<excludeClass>it.integry.ems_model.base.EntityInterface</excludeClass>
|
||||
</excludeClasses>
|
||||
<outputFile>../ts/ems-core.module.ts</outputFile>
|
||||
<outputKind>module</outputKind>
|
||||
<outputFileType>implementationFile</outputFileType>
|
||||
<customTypeNaming>
|
||||
<naming>it.integry.ems_model.entity.AtbOfft$StatoOfferta:AtbOfftStatoOfferta</naming>
|
||||
<naming>it.integry.ems_model.entity.VtbOfft$StatoOfferta:VtbOfftStatoOfferta</naming>
|
||||
<naming>it.integry.ems_model.entity.GrlAnagJrept$Tipo:GrlAnagJreptTipo</naming>
|
||||
<naming>it.integry.ems_model.entity.WtbJreptSetup$Tipo:WtbJreptSetupTipo</naming>
|
||||
<naming>it.integry.ems_model.entity.MtbColr$Causale:MtbColrCausale</naming>
|
||||
<naming>it.integry.ems_model.entity.MtbCols$Causale:MtbColsCausale</naming>
|
||||
</customTypeNaming>
|
||||
<generateConstructors>true</generateConstructors>
|
||||
<mapClasses>asClasses</mapClasses>
|
||||
<mapEnum>asEnum</mapEnum>
|
||||
<optionalProperties>useLibraryDefinition</optionalProperties>
|
||||
<optionalPropertiesDeclaration>questionMarkAndNullableType</optionalPropertiesDeclaration>
|
||||
<sortDeclarations>true</sortDeclarations>
|
||||
<sortTypeDeclarations>true</sortTypeDeclarations>
|
||||
<tsNoCheck>true</tsNoCheck>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@@ -68,7 +111,7 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-bom</artifactId>
|
||||
<version>2.25.0</version>
|
||||
<version>2.24.3</version>
|
||||
<scope>import</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
@@ -155,6 +198,12 @@
|
||||
<version>20200518</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.reflections</groupId>
|
||||
<artifactId>reflections</artifactId>
|
||||
@@ -224,11 +273,6 @@
|
||||
<artifactId>Tahoma</artifactId>
|
||||
<version>1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>it.integry.font</groupId>
|
||||
<artifactId>arial-rounded</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.groovy</groupId>
|
||||
@@ -355,6 +399,11 @@
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-csv</artifactId>
|
||||
@@ -363,11 +412,6 @@
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>2.20</version> <!-- Versione scritta a mano perché qui non hanno usato lo 0 finale -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
@@ -444,7 +488,6 @@
|
||||
<groupId>com.lmax</groupId>
|
||||
<artifactId>disruptor</artifactId>
|
||||
<version>3.4.4</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
@@ -567,7 +610,7 @@
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>0.11.5</version>
|
||||
<scope>compile</scope>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!--Expiring Map-->
|
||||
|
||||
@@ -19,7 +19,6 @@ import it.integry.WooCommerce.dto.product.variation.WooCommerceProductVariationD
|
||||
import it.integry.WooCommerce.enums.ArticoloException;
|
||||
import it.integry.WooCommerce.enums.StockStatus;
|
||||
import it.integry.WooCommerce.enums.SyncOrigin;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.Import.dto.AnomalieDTO;
|
||||
import it.integry.ems.service.EntityProcessor;
|
||||
import it.integry.ems.service.MailService;
|
||||
@@ -30,6 +29,7 @@ import it.integry.ems_model.entity.WdtbOrds;
|
||||
import it.integry.ems_model.entity.WdtbOrdt;
|
||||
import it.integry.ems_model.service.SetupGest;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityDate;
|
||||
import it.integry.ems_model.utility.UtilityStream;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.apache.commons.text.StringEscapeUtils;
|
||||
@@ -41,7 +41,7 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -445,8 +445,7 @@ public class WooCommerceService {
|
||||
}
|
||||
|
||||
//CHIAVE ORDINE
|
||||
LocalDate dataOrd = UtilityString.parseLocalDateTime(orderDTO.getDateCreated(), "yyyy-MM-dd'T'HH:mm:ss")
|
||||
.toLocalDate();
|
||||
Date dataOrd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(orderDTO.getDateCreated());
|
||||
|
||||
ordineWeb
|
||||
.setGestione("V")
|
||||
@@ -454,7 +453,7 @@ public class WooCommerceService {
|
||||
.setNumOrd(Integer.parseInt(orderDTO.getNumber()))
|
||||
//CHIAVE RIFERIMENTO ORDINE WOOCOMMERCE
|
||||
.setSerie(dataManager.getSetup("SERIE"))
|
||||
.setRifOrd(UtilityString.left("RIF N." + orderDTO.getNumber() + " DEL " + CommonConstants.DATE_DMY_DASHED_FORMATTER.format(dataOrd) + " " + orderDTO.getOrderKey(), 40))
|
||||
.setRifOrd(UtilityString.left("RIF N." + orderDTO.getNumber() + " DEL " + UtilityDate.formatDate(dataOrd, "dd-MM-yy") + " " + orderDTO.getOrderKey(), 40))
|
||||
.setDataOrdRif(dataOrd)
|
||||
.setNumOrdRif(Integer.parseInt(orderDTO.getNumber()))
|
||||
.setListino(dataManager.getSetup("LISTINO"));
|
||||
@@ -769,7 +768,7 @@ public class WooCommerceService {
|
||||
|
||||
private void sendErrorMail(String errorMsg, String service, byte[] content, String filename, List<AnomalieDTO> anomalie) {
|
||||
try {
|
||||
mailService.sendErrorMailByGestNameSection(multiDBTransactionManager.getPrimaryConnection(), service, "WOOCOMMERCE", "Errore WooCommerce",
|
||||
mailService.sendErrorMailByGestNameSection(multiDBTransactionManager, service, "WOOCOMMERCE", "Errore WooCommerce",
|
||||
null, content, filename, anomalie);
|
||||
} catch (Exception exception) {
|
||||
logger.error(service, exception);
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
package it.integry.annotations;
|
||||
|
||||
import it.integry.ems.migration._base.IntegryCustomer;
|
||||
import org.springframework.stereotype.Indexed;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Target({ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@Indexed
|
||||
public @interface CustomerComponent {
|
||||
IntegryCustomer value();
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package it.integry.annotations;
|
||||
|
||||
import it.integry.ems.migration._base.IntegryCustomer;
|
||||
import org.springframework.core.annotation.AliasFor;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Target({ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@CustomerComponent(IntegryCustomer.Integry) // Valore di default, verrà sovrascritto
|
||||
public @interface CustomerService {
|
||||
@AliasFor(
|
||||
annotation = CustomerComponent.class
|
||||
)
|
||||
IntegryCustomer value();
|
||||
}
|
||||
@@ -20,17 +20,16 @@ public class CommonConstants {
|
||||
public static final String TIMESTAMP = "timestamp";
|
||||
|
||||
|
||||
public static final String DATE_FORMAT_YMD_SLASHED = "yyyy/MM/dd";
|
||||
public static final String DATE_FORMAT_YMD_DASHED = "yyyy-MM-dd";
|
||||
public static final String DATE_FORMAT_DMY_SLASHED = "dd/MM/yyyy";
|
||||
public static final String DATE_FORMAT_YMD = "yyyy-MM-dd";
|
||||
public static final String DATE_FORMAT_DMY = "dd/MM/yyyy";
|
||||
public static final String DATE_FORMAT_DMY_DASHED = "dd-MM-yyyy";
|
||||
public static final String DATE_FORMAT_DMYHMS_UNSPACED = "ddMMyyyyHHmmss";
|
||||
|
||||
public static final String TIME_FORMAT = "HH:mm:ss";
|
||||
|
||||
public static final String DATETIME_FORMAT_YMD = String.format("%s %s", DATE_FORMAT_YMD_DASHED, TIME_FORMAT);
|
||||
public static final String DATETIME_FORMAT_YMD = String.format("%s %s", DATE_FORMAT_YMD, TIME_FORMAT);
|
||||
public static final String DATETIME_FORMAT_DMY = String.format("%s %s", DATE_FORMAT_DMY_DASHED, TIME_FORMAT);
|
||||
public static final String DATETIME_FORMAT_DMY_SLASHED = String.format("%s %s", DATE_FORMAT_DMY_SLASHED, TIME_FORMAT);
|
||||
public static final String DATETIME_FORMAT_DMY_SLASHED = String.format("%s %s", DATE_FORMAT_DMY, TIME_FORMAT);
|
||||
public static final String DATETIME_FORMAT_DMY_DASHED = String.format("%s %s", DATE_FORMAT_DMY_DASHED, TIME_FORMAT);
|
||||
|
||||
|
||||
@@ -47,23 +46,19 @@ public class CommonConstants {
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
|
||||
public static final DateTimeFormatter DATE_YMD_SLASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATE_FORMAT_YMD_SLASHED)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
public static final DateTimeFormatter DATE_YMD_DASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATE_FORMAT_YMD_DASHED)
|
||||
public static final DateTimeFormatter DATE_YMD_DASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATE_FORMAT_YMD)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
public static final DateTimeFormatter DATETIME_YMD_DASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATETIME_FORMAT_YMD)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
|
||||
public static final DateTimeFormatter DATE_DMY_SLASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATE_FORMAT_DMY_SLASHED)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
public static final DateTimeFormatter DATE_DMY_DASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATE_FORMAT_DMY_DASHED)
|
||||
public static final DateTimeFormatter DATE_DMY_SLASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATE_FORMAT_DMY)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
public static final DateTimeFormatter DATETIME_DMY_SLASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATETIME_FORMAT_DMY_SLASHED)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
public static final DateTimeFormatter DATETIME_DMY_DASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATETIME_FORMAT_DMY_DASHED)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
|
||||
public static final String ULTC = "ULTC";
|
||||
public static final String DIST = "DIST";
|
||||
public static final String CMPPF = "CMPPF";
|
||||
|
||||
@@ -6,7 +6,6 @@ import it.integry.ems_model.entity.Azienda;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
@Service
|
||||
@@ -29,15 +28,14 @@ public class EmsDBConst {
|
||||
String aziendaUp = dbName.toUpperCase();
|
||||
|
||||
datiAziendaLock.lock();
|
||||
try {
|
||||
if (!datiAziendaBindingTable.containsKey(aziendaUp)) {
|
||||
datiAziendaBindingTable.put(aziendaUp, new Const());
|
||||
}
|
||||
|
||||
return datiAziendaBindingTable.get(aziendaUp);
|
||||
} finally {
|
||||
datiAziendaLock.unlock();
|
||||
if (!datiAziendaBindingTable.containsKey(aziendaUp)) {
|
||||
datiAziendaBindingTable.put(aziendaUp, new Const());
|
||||
}
|
||||
|
||||
final Const aConst = datiAziendaBindingTable.get(aziendaUp);
|
||||
datiAziendaLock.unlock();
|
||||
|
||||
return aConst;
|
||||
}
|
||||
|
||||
public void destroyAll() {
|
||||
@@ -46,6 +44,7 @@ public class EmsDBConst {
|
||||
datiAziendaLock.unlock();
|
||||
}
|
||||
|
||||
|
||||
public static class Const {
|
||||
|
||||
private String applicationDbName;
|
||||
|
||||
@@ -2,11 +2,8 @@ package it.integry.ems.Import.base;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import it.integry.ems.Import.dto.AnomalieDTO;
|
||||
import it.integry.ems.Import.dto.ImportRequestDTO;
|
||||
import it.integry.ems.javabeans.RequestDataDTO;
|
||||
import it.integry.ems.json.JsonObjectMapperConfig;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.service.SetupGest;
|
||||
@@ -25,20 +22,10 @@ public abstract class BaseEntityImporter<T> implements IEntityImporter<T> {
|
||||
protected String format;
|
||||
protected boolean headless;
|
||||
protected ImportRequestDTO requestDto;
|
||||
protected RequestDataDTO requestDataDTO;
|
||||
protected MultiDBTransactionManager multiDBTransactionManager;
|
||||
protected List<AnomalieDTO> anomalie = new ArrayList<AnomalieDTO>();
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
protected BaseEntityImporter() {
|
||||
objectMapper = new ObjectMapper();
|
||||
|
||||
SimpleModule simpleModule = new SimpleModule();
|
||||
JsonObjectMapperConfig.addDefaultAdapters(simpleModule);
|
||||
|
||||
objectMapper.registerModule(simpleModule);
|
||||
}
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
public IEntityImporter<T> setSetupGest(SetupGest setupGest) {
|
||||
this.setupGest = setupGest;
|
||||
@@ -79,12 +66,6 @@ public abstract class BaseEntityImporter<T> implements IEntityImporter<T> {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEntityImporter<T> setRequestDataDTO(RequestDataDTO requestDataDTO) {
|
||||
this.requestDataDTO = requestDataDTO;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<AnomalieDTO> getAnomalie() {
|
||||
return anomalie;
|
||||
}
|
||||
@@ -108,6 +89,4 @@ public abstract class BaseEntityImporter<T> implements IEntityImporter<T> {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package it.integry.ems.Import.base;
|
||||
|
||||
import it.integry.ems.Import.dto.AnomalieDTO;
|
||||
import it.integry.ems.Import.dto.ImportRequestDTO;
|
||||
import it.integry.ems.javabeans.RequestDataDTO;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.service.SetupGest;
|
||||
@@ -27,14 +26,10 @@ public interface IEntityImporter<T> {
|
||||
|
||||
IEntityImporter<T> setRequestDTO(ImportRequestDTO requestDto);
|
||||
|
||||
IEntityImporter<T> setRequestDataDTO(RequestDataDTO requestDataDTO);
|
||||
|
||||
List<AnomalieDTO> getAnomalie();
|
||||
|
||||
T doImport() throws Exception;
|
||||
|
||||
String renameFile(String orginalFileName, List<EntityBase> entities) throws Exception;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -24,9 +24,7 @@ public enum EntityImportType {
|
||||
MOVIMENTI_CONTABILI("MOVIMENTI CONTABILI"),
|
||||
GRIGLIA_VENDITA("GRIGLIA VENDITA"),
|
||||
GRIGLIA_ACQUISTO("GRIGLIA ACQUISTO"),
|
||||
SCADENZE("SCADENZE"),
|
||||
BILANCE("BILANCE"),
|
||||
BANCA("BANCA");
|
||||
SCADENZE("SCADENZE");
|
||||
|
||||
private String text;
|
||||
|
||||
|
||||
@@ -23,10 +23,8 @@ import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.Arrays;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.reflections.scanners.Scanners.TypesAnnotated;
|
||||
@@ -53,8 +51,6 @@ public class EmsCoreContext {
|
||||
private boolean contextInitialized = false;
|
||||
|
||||
private boolean firstStart = true;
|
||||
@Autowired
|
||||
private ExecutorService taskExecutor;
|
||||
|
||||
|
||||
@PostConstruct
|
||||
@@ -73,22 +69,6 @@ public class EmsCoreContext {
|
||||
@PreDestroy
|
||||
public void preDestroy() {
|
||||
contextInitialized = false;
|
||||
|
||||
|
||||
ClassLoader cl = Thread.currentThread().getContextClassLoader();
|
||||
Enumeration<java.sql.Driver> drivers = DriverManager.getDrivers();
|
||||
logger.info("Deregister DB Drivers");
|
||||
|
||||
while (drivers.hasMoreElements()) {
|
||||
java.sql.Driver driver = drivers.nextElement();
|
||||
if (driver.getClass().getClassLoader() == cl) {
|
||||
try {
|
||||
DriverManager.deregisterDriver(driver);
|
||||
} catch (Exception ex) {
|
||||
// log error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//@EventListener(ContextRefreshedEvent.class)
|
||||
@@ -99,7 +79,19 @@ public class EmsCoreContext {
|
||||
logger.debug("Init");
|
||||
|
||||
try {
|
||||
emsCoreDBLoader.load(this::onPostDBLoaded);
|
||||
//new Thread(() -> {
|
||||
try {
|
||||
emsCoreDBLoader.load((multiDBTransactionManager, onDone) -> {
|
||||
try {
|
||||
this.onPostDBLoaded(multiDBTransactionManager, onDone);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
//}).start();
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error(EmsCoreContext.class.getSimpleName(), e);
|
||||
@@ -108,10 +100,27 @@ public class EmsCoreContext {
|
||||
}
|
||||
|
||||
|
||||
private void onPostDBLoaded(MultiDBTransactionManager multiDBTransactionManager) throws InvocationTargetException, IllegalAccessException {
|
||||
dispatchPostContextConstruct(multiDBTransactionManager);
|
||||
contextInitialized = true;
|
||||
dispatchPostWebServerConstruct(multiDBTransactionManager);
|
||||
private void onPostDBLoaded(MultiDBTransactionManager multiDBTransactionManager, Runnable onDone) throws InterruptedException {
|
||||
|
||||
// final ExecutorService executorService = Executors.newSingleThreadExecutor();
|
||||
|
||||
new Thread(() -> {
|
||||
try {
|
||||
dispatchPostContextConstruct(multiDBTransactionManager);
|
||||
|
||||
contextInitialized = true;
|
||||
|
||||
dispatchPostWebServerConstruct(multiDBTransactionManager);
|
||||
onDone.run();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("EmsCoreContext.onPostDBLoaded", e);
|
||||
}
|
||||
}).start();
|
||||
|
||||
// executorService.shutdown();
|
||||
// executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@ package it.integry.ems._context;
|
||||
|
||||
import it.integry.annotations.PostContextConstruct;
|
||||
import it.integry.common.var.EmsDBConst;
|
||||
import it.integry.ems.expansion.RunnableArgsThrowable;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionModel;
|
||||
import it.integry.ems.datasource.DataSource;
|
||||
import it.integry.ems.expansion.RunnableArgss;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.settings.SettingsController;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.sync.MultiDBTransaction.BasicConnectionPool;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
@@ -13,6 +15,7 @@ import it.integry.ems.task.TaskExecutorService;
|
||||
import it.integry.ems.user.service.UserCacheService;
|
||||
import it.integry.ems_model.entity.Azienda;
|
||||
import it.integry.ems_model.service.SetupGest;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
@@ -55,8 +58,6 @@ public class EmsCoreDBLoader {
|
||||
public void init() throws Exception {
|
||||
this.settingsController.addOnConfigUpdated(() -> {
|
||||
try {
|
||||
connectionPool.destroy();
|
||||
connectionPool.init();
|
||||
load(null);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -64,32 +65,44 @@ public class EmsCoreDBLoader {
|
||||
});
|
||||
}
|
||||
|
||||
public void load(final RunnableArgsThrowable<MultiDBTransactionManager> onComplete) throws Exception {
|
||||
taskExecutorService.executeTask(() -> {
|
||||
try (MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(connectionPool)){
|
||||
discoverAllConnections(multiDBTransactionManager);
|
||||
setupAzienda(multiDBTransactionManager);
|
||||
userCacheService.discoverAllUsers(multiDBTransactionManager);
|
||||
public void load(final RunnableArgss<MultiDBTransactionManager, Runnable> onComplete) throws Exception {
|
||||
connectionPool.init();
|
||||
|
||||
if (onComplete != null) onComplete.run(multiDBTransactionManager);
|
||||
} catch (Exception ex) {
|
||||
logger.error("EmsCoreDBLoader", ex);
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}, false);
|
||||
MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(connectionPool);
|
||||
try {
|
||||
discoverAllConnections(multiDBTransactionManager);
|
||||
setupAzienda(multiDBTransactionManager);
|
||||
userCacheService.discoverAllUsers(multiDBTransactionManager);
|
||||
|
||||
if (onComplete != null) onComplete.run(multiDBTransactionManager, () -> {
|
||||
try {
|
||||
multiDBTransactionManager.closeAll();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
logger.error("EmsCoreDBLoader", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void discoverAllConnections(MultiDBTransactionManager multiDBTransactionManager) throws Exception {
|
||||
|
||||
ArrayList<Callable<Void>> futureTasks = new ArrayList<>();
|
||||
for (AvailableConnectionModel model : settingsModel.getAvailableConnectionsWithoutDuplicatedProfiles(true)) {
|
||||
for (AvailableConnectionsModel model : settingsModel.getAvailableConnectionsWithoutDuplicatedProfiles(true, settingsController.getHistoryProfileDb())) {
|
||||
|
||||
AtomicReference<AvailableConnectionModel> modelAtomicReference = new AtomicReference<>(model);
|
||||
AtomicReference<AvailableConnectionsModel> modelAtomicReference = new AtomicReference<>(model);
|
||||
|
||||
futureTasks.add(() -> {
|
||||
try {
|
||||
multiDBTransactionManager.addConnection(modelAtomicReference.get());
|
||||
final DataSource ds = connectionPool.getConnection(modelAtomicReference.get().getProfileName());
|
||||
|
||||
String sql = "SELECT db_distributore FROM azienda";
|
||||
String dbDistributore = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(ds.getConnection(), sql);
|
||||
|
||||
multiDBTransactionManager.addConnection(modelAtomicReference.get().getProfileName(), ds, modelAtomicReference.get().getDbName().equalsIgnoreCase(dbDistributore));
|
||||
|
||||
return null;
|
||||
} catch (Exception ex) {
|
||||
throw new Exception("[" + modelAtomicReference.get().getProfileName() + "] " + ex.getMessage(), ex.getCause());
|
||||
@@ -104,11 +117,13 @@ public class EmsCoreDBLoader {
|
||||
|
||||
ArrayList<Callable<Void>> futureTasks = new ArrayList<>();
|
||||
|
||||
for (final Connection connection : multiDBTransactionManager.getActiveConnections()) {
|
||||
for (final AdvancedDataSource advancedDataSource : multiDBTransactionManager.getActiveConnections()) {
|
||||
AtomicReference<AdvancedDataSource> atomicAdvancedDataSource = new AtomicReference<>(advancedDataSource);
|
||||
|
||||
futureTasks.add(() -> {
|
||||
Azienda azienda = Azienda.getDefaultAzienda(connection);
|
||||
String dbName = connection.getDbName();
|
||||
Connection conn = atomicAdvancedDataSource.get().getConnection();
|
||||
Azienda azienda = Azienda.getDefaultAzienda(conn);
|
||||
String dbName = atomicAdvancedDataSource.get().getDataSource().getDbName();
|
||||
|
||||
try {
|
||||
if (azienda != null) {
|
||||
@@ -120,7 +135,7 @@ public class EmsCoreDBLoader {
|
||||
}
|
||||
|
||||
HashMap<String, String> gestSetupValues =
|
||||
setupGest.getSetupSection(connection, "DATI_AZIENDA", "FATTURAZIONE_ELETTRONICA");
|
||||
setupGest.getSetupSection(conn, "DATI_AZIENDA", "FATTURAZIONE_ELETTRONICA");
|
||||
|
||||
emsDBConst.getConsts(dbName)
|
||||
.setApplicationDbName(applicationDbName)
|
||||
@@ -131,7 +146,7 @@ public class EmsCoreDBLoader {
|
||||
throw new Exception("Non è stato possibile leggere i dati dalla tabella azienda");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new Exception("[" + connection.getProfileName() + "] " + ex.getMessage(), ex.getCause());
|
||||
throw new Exception("[" + atomicAdvancedDataSource.get().getProfileName() + "] " + ex.getMessage(), ex.getCause());
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package it.integry.ems.adapter;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
|
||||
public class JsonLocalTimeAdapterDeserializer extends JsonDeserializer<LocalTime> {
|
||||
|
||||
@Override
|
||||
public LocalTime deserialize(JsonParser jp, DeserializationContext arg1)
|
||||
throws IOException {
|
||||
|
||||
if (UtilityString.isNullOrEmpty(jp.getText()))
|
||||
return null;
|
||||
|
||||
if (jp.getText().equalsIgnoreCase("null") || jp.getText().equalsIgnoreCase("1900-01-01"))
|
||||
return EmsRestConstants.LOCAL_TIME_NULL;
|
||||
|
||||
|
||||
return UtilityString.parseLocalTime(jp.getText());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package it.integry.ems.adapter;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
public class JsonLocalTimeAdapterSerializer extends JsonSerializer<LocalTime> {
|
||||
@Override
|
||||
public void serialize(LocalTime value, JsonGenerator gen,
|
||||
SerializerProvider serializers) throws IOException {
|
||||
|
||||
if (value == null)
|
||||
gen.writeNull();
|
||||
else
|
||||
gen.writeString(value.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package it.integry.ems.adapter;
|
||||
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class XmlLocalDateAdapter extends XmlAdapter<String, LocalDate> {
|
||||
|
||||
private DateTimeFormatter sdf;
|
||||
|
||||
public XmlLocalDateAdapter() {
|
||||
sdf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
|
||||
}
|
||||
|
||||
public XmlLocalDateAdapter(String format) {
|
||||
sdf = DateTimeFormatter.ofPattern(format);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String marshal(LocalDate arg0) throws Exception {
|
||||
return arg0.format(sdf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate unmarshal(String arg0) throws Exception {
|
||||
String format = UtilityString.determineDateFormat(arg0);
|
||||
if (format != null && !"dd-MM-yyyy".equals(format))
|
||||
sdf = DateTimeFormatter.ofPattern(format);
|
||||
return LocalDate.parse(arg0,sdf);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package it.integry.ems.adapter;
|
||||
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class XmlLocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
|
||||
|
||||
private DateTimeFormatter sdf;
|
||||
|
||||
public XmlLocalDateTimeAdapter() {
|
||||
sdf = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
|
||||
}
|
||||
|
||||
public XmlLocalDateTimeAdapter(String format) {
|
||||
sdf = DateTimeFormatter.ofPattern(format);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String marshal(LocalDateTime arg0) throws Exception {
|
||||
return arg0.format(sdf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDateTime unmarshal(String arg0) throws Exception {
|
||||
String format = UtilityString.determineDateFormat(arg0);
|
||||
if (format != null && !"dd-MM-yyyy HH:mm:ss".equals(format))
|
||||
sdf = DateTimeFormatter.ofPattern(format);
|
||||
return LocalDateTime.parse(arg0,sdf);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
package it.integry.ems.anonymizer;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Generatore di nomi e cognomi italiani per l'anonimizzazione dei dati.
|
||||
* Mantiene la coerenza del sesso tra nome e genere.
|
||||
*/
|
||||
public class ItalianNameGenerator {
|
||||
|
||||
private final Random random;
|
||||
|
||||
// Nomi maschili italiani (200+ nomi)
|
||||
public static final List<String> MALE_NAMES = Arrays.asList(
|
||||
"Alessandro", "Andrea", "Antonio", "Francesco", "Marco", "Matteo", "Giuseppe", "Luca",
|
||||
"Giovanni", "Roberto", "Stefano", "Paolo", "Davide", "Michele", "Simone", "Federico",
|
||||
"Riccardo", "Fabio", "Daniele", "Massimo", "Claudio", "Nicola", "Gabriele", "Vincenzo",
|
||||
"Lorenzo", "Salvatore", "Emanuele", "Alberto", "Diego", "Tommaso", "Alessio", "Filippo",
|
||||
"Giorgio", "Mattia", "Franco", "Bruno", "Enrico", "Mario", "Carlo", "Gianluca",
|
||||
"Cristian", "Domenico", "Raffaele", "Sergio", "Pasquale", "Gianni", "Carmine", "Gennaro",
|
||||
"Antonino", "Gaetano", "Rocco", "Mauro", "Pierluigi", "Valerio", "Mirko", "Dario",
|
||||
"Enzo", "Alfredo", "Renzo", "Giancarlo", "Giampaolo", "Pierpaolo", "Gianfranco", "Guido",
|
||||
"Nino", "Piero", "Armando", "Luciano", "Renato", "Angelo", "Aldo", "Giulio",
|
||||
"Marcello", "Rodolfo", "Umberto", "Silvano", "Ivano", "Giampiero", "Silvio", "Maurizio",
|
||||
"Leonardo", "Adriano", "Ferdinando", "Bernardo", "Teodoro", "Edoardo", "Arturo", "Gino",
|
||||
"Biagio", "Fabrizio", "Fausto", "Ettore", "Cesare", "Elio", "Amerigo", "Italo",
|
||||
"Orlando", "Romeo", "Sandro", "Tiziano", "Ignazio", "Ciro", "Loris", "Orazio",
|
||||
"Lino", "Nello", "Rino", "Primo", "Secondo", "Terzo", "Quarto", "Quinto",
|
||||
"Sesto", "Settimo", "Ottavio", "Nono", "Decimo", "Benito", "Dante", "Virgilio",
|
||||
"Omero", "Eugenio", "Aurelio", "Valentino", "Corrado", "Manlio", "Emilio", "Tullio",
|
||||
"Attilio", "Marcello", "Romolo", "Remo", "Amedeo", "Cosimo", "Damiano", "Sebastiano",
|
||||
"Cristoforo", "Bartolomeo", "Giacomo", "Simone", "Pietro", "Girolamo", "Leopoldo", "Gaspare",
|
||||
"Melchiorre", "Baldassarre", "Epifanio", "Gerardo", "Ruggero", "Tancredi", "Arnaldo", "Osvaldo",
|
||||
"Rinaldo", "Romualdo", "Ubaldo", "Raimondo", "Edmondo", "Redento", "Crescenzo", "Innocenzo",
|
||||
"Fiorenzo", "Vincenzo", "Enzo", "Renzo", "Nunzio", "Maurizio", "Patrizio", "Orazio",
|
||||
"Flavio", "Claudio", "Giuliano", "Adriano", "Emiliano", "Massimiliano", "Gianmarco", "Marcantonio",
|
||||
"Gianbattista", "Giovanbattista", "Giammarco", "Gianluigi", "Giampiero", "Gianmaria", "Giandomenico", "Gianpaolo",
|
||||
"Pierfrancesco", "Piergiorgio", "Pierangelo", "Piermario", "Piercarlo", "Piergiuseppe", "Gioacchino", "Bartolomeo",
|
||||
"Benedetto", "Benvenuto", "Bonaventura", "Bonifacio", "Camillo", "Calogero", "Carmelo", "Demetrio",
|
||||
"Dionisio", "Donato", "Egidio", "Eliseo", "Erminio", "Eustachio", "Evandro", "Ezio",
|
||||
"Fermo", "Fernando", "Ferruccio", "Fortunato", "Fulvio", "Gaetano", "Germano", "Giosuè",
|
||||
"Gregorio", "Guglielmo", "Lamberto", "Lanfranco", "Liborio", "Lucio", "Luigi", "Manfredo"
|
||||
);
|
||||
|
||||
// Nomi femminili italiani (200+ nomi)
|
||||
public static final List<String> FEMALE_NAMES = Arrays.asList(
|
||||
"Giulia", "Francesca", "Chiara", "Federica", "Sara", "Martina", "Valentina", "Alessandra",
|
||||
"Silvia", "Elisa", "Giorgia", "Elena", "Paola", "Laura", "Roberta", "Alice", "Serena",
|
||||
"Barbara", "Anna", "Maria", "Simona", "Claudia", "Monica", "Cristina", "Elisabetta",
|
||||
"Stefania", "Valeria", "Daniela", "Manuela", "Antonella", "Giovanna", "Sabrina", "Emanuela",
|
||||
"Ilaria", "Cinzia", "Rosanna", "Patrizia", "Teresa", "Carmela", "Giuseppina", "Rosa",
|
||||
"Antonietta", "Concetta", "Caterina", "Angela", "Raffaella", "Luisa", "Lucia", "Michela",
|
||||
"Franceschina", "Graziella", "Isabella", "Benedetta", "Beatrice", "Margherita", "Alessia", "Andrea",
|
||||
"Cristiana", "Fabiana", "Gabriella", "Gianna", "Lorena", "Marisa", "Nicoletta", "Ornella",
|
||||
"Rosaria", "Silvana", "Susanna", "Tiziana", "Viviana", "Adriana", "Agnese", "Albina",
|
||||
"Amelia", "Andreina", "Angelica", "Antonella", "Arianna", "Armida", "Augusta", "Aurora",
|
||||
"Bruna", "Brunella", "Camilla", "Carla", "Carolina", "Cecilia", "Clara", "Clelia",
|
||||
"Concettina", "Corinna", "Cosima", "Costanza", "Cristiana", "Delia", "Diana", "Dora",
|
||||
"Donatella", "Edvige", "Eleonora", "Elvira", "Emma", "Enrichetta", "Ester", "Eugenia",
|
||||
"Eva", "Fabia", "Fabiola", "Fernanda", "Fiorella", "Fiorenza", "Flora", "Franca",
|
||||
"Gaia", "Gemma", "Gilda", "Gina", "Gloria", "Grazia", "Ida", "Ilda",
|
||||
"Immacolata", "Ines", "Iolanda", "Irene", "Iris", "Ivana", "Ivanka", "Lara",
|
||||
"Letizia", "Licia", "Lidia", "Liliana", "Lina", "Linda", "Lisa", "Livia",
|
||||
"Loredana", "Lorella", "Lorenza", "Luana", "Luciana", "Lucilla", "Lucrezia", "Ludovica",
|
||||
"Luigia", "Luna", "Maddalena", "Mafalda", "Marcella", "Marella", "Marilena", "Marina",
|
||||
"Marisa", "Marta", "Matilde", "Maura", "Mirella", "Miriam", "Morena", "Nadia",
|
||||
"Natalia", "Natalina", "Nella", "Nelly", "Nicole", "Noemi", "Norma", "Olga",
|
||||
"Olimpia", "Orietta", "Palmira", "Pamela", "Pascale", "Pasqualina", "Pia", "Piera",
|
||||
"Pierina", "Priscilla", "Raffaela", "Rebecca", "Regina", "Renata", "Rita", "Romina",
|
||||
"Rosalba", "Rosalia", "Rosangela", "Rosanna", "Rosella", "Rosetta", "Rosina", "Rossana",
|
||||
"Rossella", "Samanta", "Sandra", "Santina", "Sebastiana", "Serafina", "Sonia", "Stella",
|
||||
"Tecla", "Tina", "Tosca", "Tullia", "Uberta", "Umberta", "Ursula", "Vera",
|
||||
"Veronica", "Vincenza", "Viola", "Virginia", "Vittoria", "Wanda", "Yvonne", "Zaira",
|
||||
"Zelda", "Zita", "Zoe", "Ambra", "Azzurra", "Bianca", "Celeste", "Diamante",
|
||||
"Fiamma", "Giada", "Perla", "Sole", "Stella", "Alba", "Alma", "Anya"
|
||||
);
|
||||
|
||||
// Cognomi italiani (300+ cognomi)
|
||||
public static final List<String> SURNAMES = Arrays.asList(
|
||||
"Rossi", "Ferrari", "Russo", "Bianchi", "Romano", "Gallo", "Costa", "Fontana",
|
||||
"Esposito", "Ricci", "Bruno", "Moretti", "Marino", "Greco", "Barbieri", "Lombardi",
|
||||
"Giordano", "Colombo", "Rizzo", "Benedetti", "Palumbo", "Pellegrini", "Caruso", "Ferretti",
|
||||
"Galli", "Marchetti", "Villa", "Mancini", "Conte", "Serra", "Ferrero", "Martinelli",
|
||||
"Mariani", "Giuliani", "Vitale", "Santoro", "Ferrara", "Leone", "Longo", "Gentile",
|
||||
"Martino", "Fabbri", "Rinaldi", "Messina", "Riva", "Conti", "Silvestri", "Coppola",
|
||||
"Negri", "Milani", "Parisi", "Sala", "Cattaneo", "Orlando", "Fiore", "Marini",
|
||||
"Guerra", "Pagano", "Bernardi", "Valenti", "Farina", "Ruggiero", "Caputo", "Monti",
|
||||
"Grassi", "Montanari", "Santini", "Morelli", "Amato", "Neri", "Donati", "Testa",
|
||||
"Bianco", "Sorrentino", "Rossini", "Giuliano", "Sartori", "De Angelis", "De Rosa",
|
||||
"Basile", "Costantini", "Rizzi", "Barone", "Martini", "De Santis", "Basso", "Pellegrino",
|
||||
"Carbone", "Gatti", "Coppola", "Rossetto", "Piras", "Ricci", "Martinelli", "Sanna",
|
||||
"Torrisi", "Scuderi", "Priolo", "Anastasi", "Puglisi", "La Rosa", "Catalano", "Garofalo",
|
||||
"Aiello", "Trovato", "Pappalardo", "Pulvirenti", "Marletta", "Di Marco", "Biondi", "Ferri",
|
||||
"Testa", "Marchi", "Baldini", "Benedetti", "Colombi", "Gasparini", "Orlandi", "Barbera",
|
||||
"Damico", "Guerriero", "Napolitano", "Romano", "Mazza", "Caruso", "Ferraro", "Gaeta",
|
||||
"Di Stefano", "Palma", "Carbone", "Morrone", "Milazzo", "Calabrese", "Ventura", "Palmieri",
|
||||
"Martello", "Fico", "Pastore", "Arena", "Maggio", "Sciacca", "Pagliaro", "Lupo",
|
||||
"Mangano", "Capra", "Finocchiaro", "Grasso", "Morabito", "Pellicano", "Castelli", "Castaldo",
|
||||
"Mauro", "Piazza", "Battaglia", "D Amico", "Forte", "Antonelli", "Delia", "Marino",
|
||||
"Cosentino", "Lazzaro", "Vitale", "Lombardo", "Crisafulli", "Nicolosi", "Bellomo", "Morreale",
|
||||
"Messina", "Vaccaro", "Nicosia", "Fazio", "Spina", "Russo", "Parisi", "Zappala",
|
||||
"Riccobono", "Camilleri", "Barbagallo", "Oliveri", "Pistone", "Gambino", "Cavallaro", "Burgio",
|
||||
"Gentile", "Restivo", "Di Bella", "Genovese", "Ferrante", "Gianninoto", "Vitrano", "Gargano",
|
||||
"Lombardi", "Milani", "Picci", "De Luca", "Foti", "Giardina", "Di Pietro", "Russo",
|
||||
"La Spina", "Morello", "Moschetti", "Penna", "Ferretti", "Colombo", "Marra", "De Simone",
|
||||
"Cozzi", "Grimaldi", "Pellegrini", "Galdi", "Paolini", "Ferrara", "Santangelo", "Di Giovanni",
|
||||
"Iannone", "Lucchese", "Orsini", "Mastroianni", "Fiorentino", "Capasso", "Di Napoli", "Giannini",
|
||||
"Romano", "Vitale", "Fontana", "Galdi", "Giuliani", "Barbieri", "Lombardo", "Martinelli",
|
||||
"De Rosa", "Ferri", "Caputo", "Castaldi", "Mauro", "Monti", "Villa", "Marcello",
|
||||
"Ricci", "Ferretti", "Gallo", "Fabbri", "Marini", "Grasso", "Carbone", "Bevilacqua",
|
||||
"Giannone", "Perna", "Pellegrino", "Di Lorenzo", "Napoli", "Amato", "Donato", "Riccio",
|
||||
"Giuliano", "Mancuso", "Bellotti", "Bianchini", "Rossetti", "Mazza", "Silvestri", "Baldini",
|
||||
"Martinelli", "Galli", "Colombo", "Ferraro", "Palumbo", "Marchetti", "Ferrera", "Rossi",
|
||||
"Caruso", "Serra", "Marchese", "Benedetti", "Franzese", "Basile", "Di Mauro", "Torrisi",
|
||||
"Licata", "Scuderi", "Platania", "Priolo", "Marletta", "Biondi", "Grassi", "Fontana",
|
||||
"Pagano", "Gentile", "Moretti", "Guerra", "Santoro", "Longo", "Giordano", "Fiore",
|
||||
"Marchetti", "Parisi", "Milani", "Orlando", "Sala", "Costa", "Cattaneo", "Neri",
|
||||
"Donati", "Mancini", "Montanari", "Caputo", "De Angelis", "Sartori", "De Santis", "Basso"
|
||||
);
|
||||
|
||||
public enum Gender {
|
||||
MALE, FEMALE
|
||||
}
|
||||
|
||||
/**
|
||||
* Costruttore con seed random sicuro
|
||||
*/
|
||||
public ItalianNameGenerator() {
|
||||
this.random = new SecureRandom();
|
||||
}
|
||||
|
||||
/**
|
||||
* Costruttore con seed personalizzato per risultati riproducibili
|
||||
* @param seed seed per il generatore random
|
||||
*/
|
||||
public ItalianNameGenerator(long seed) {
|
||||
this.random = new Random(seed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera un genere casuale
|
||||
* @return Gender casuale (MALE o FEMALE)
|
||||
*/
|
||||
public Gender generateGender() {
|
||||
return random.nextBoolean() ? Gender.MALE : Gender.FEMALE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera un nome casuale in base al sesso specificato
|
||||
* @param gender il sesso per cui generare il nome
|
||||
* @return nome casuale del sesso specificato
|
||||
*/
|
||||
public String generateFirstName(Gender gender) {
|
||||
List<String> names = (gender == Gender.MALE) ? MALE_NAMES : FEMALE_NAMES;
|
||||
return names.get(random.nextInt(names.size()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera un cognome casuale
|
||||
* @return cognome casuale
|
||||
*/
|
||||
public String generateSurname() {
|
||||
return SURNAMES.get(random.nextInt(SURNAMES.size()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera un nome completo (nome + cognome) in base al sesso
|
||||
* @param gender il sesso per cui generare il nome completo
|
||||
* @return nome completo del sesso specificato
|
||||
*/
|
||||
public String generateFullName(Gender gender) {
|
||||
return generateFirstName(gender) + " " + generateSurname();
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera un nome completo con sesso casuale
|
||||
* @return nome completo con sesso casuale
|
||||
*/
|
||||
public String generateRandomFullName() {
|
||||
Gender randomGender = random.nextBoolean() ? Gender.MALE : Gender.FEMALE;
|
||||
return generateFullName(randomGender);
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera una persona completa con nome, cognome e sesso
|
||||
* @return oggetto Person con i dati generati
|
||||
*/
|
||||
public Person generatePerson() {
|
||||
Gender gender = random.nextBoolean() ? Gender.MALE : Gender.FEMALE;
|
||||
return new Person(generateFirstName(gender), generateSurname(), gender);
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera una persona mantenendo il sesso specificato
|
||||
* @param gender il sesso da mantenere
|
||||
* @return oggetto Person con i dati generati
|
||||
*/
|
||||
public Person generatePerson(Gender gender) {
|
||||
return new Person(generateFirstName(gender), generateSurname(), gender);
|
||||
}
|
||||
|
||||
/**
|
||||
* Classe interna per rappresentare una persona generata
|
||||
*/
|
||||
public static class Person {
|
||||
private final String firstName;
|
||||
private final String surname;
|
||||
private final Gender gender;
|
||||
|
||||
public Person(String firstName, String surname, Gender gender) {
|
||||
this.firstName = firstName;
|
||||
this.surname = surname;
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
}
|
||||
|
||||
public Gender getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public String getFullName() {
|
||||
return firstName + " " + surname;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Person{firstName='%s', surname='%s', gender=%s}",
|
||||
firstName, surname, gender);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Metodo di utilità per ottenere il sesso da una stringa
|
||||
* @param genderString stringa rappresentante il sesso ("M", "F", "MALE", "FEMALE", etc.)
|
||||
* @return enum Gender corrispondente
|
||||
* @throws IllegalArgumentException se la stringa non è riconosciuta
|
||||
*/
|
||||
public static Gender parseGender(String genderString) {
|
||||
if (genderString == null) {
|
||||
throw new IllegalArgumentException("Gender string cannot be null");
|
||||
}
|
||||
|
||||
String normalized = genderString.trim().toUpperCase();
|
||||
switch (normalized) {
|
||||
case "M":
|
||||
case "MALE":
|
||||
case "MASCHIO":
|
||||
case "UOMO":
|
||||
return Gender.MALE;
|
||||
case "F":
|
||||
case "FEMALE":
|
||||
case "FEMMINA":
|
||||
case "DONNA":
|
||||
return Gender.FEMALE;
|
||||
default:
|
||||
throw new IllegalArgumentException("Unrecognized gender: " + genderString);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
package it.integry.ems.configuration;
|
||||
|
||||
import it.integry.annotations.CustomerComponent;
|
||||
import it.integry.annotations.CustomerService;
|
||||
import it.integry.ems.migration._base.IntegryCustomer;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.event.ContextRefreshedEvent;
|
||||
import org.springframework.core.type.filter.AnnotationTypeFilter;
|
||||
|
||||
/**
|
||||
* Configurazione per registrare gli scope personalizzati per customer specifici
|
||||
*/
|
||||
@Configuration
|
||||
public class CustomerServicesConfig implements ApplicationListener<ContextRefreshedEvent> {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Autowired
|
||||
private SettingsModel settingsModel;
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ContextRefreshedEvent event) {
|
||||
// Assicuriamoci che sia il context principale e non un sub-context
|
||||
if (event.getApplicationContext() == applicationContext) {
|
||||
registerCustomerBeans();
|
||||
}
|
||||
}
|
||||
|
||||
private void registerCustomerBeans() {
|
||||
ClassPathScanningCandidateComponentProvider scanner =
|
||||
new ClassPathScanningCandidateComponentProvider(false);
|
||||
|
||||
// Aggiungo filtri per le annotazioni custom
|
||||
scanner.addIncludeFilter(new AnnotationTypeFilter(CustomerService.class));
|
||||
scanner.addIncludeFilter(new AnnotationTypeFilter(CustomerComponent.class));
|
||||
|
||||
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory();
|
||||
|
||||
// Scansiono tutti i package del progetto
|
||||
for (BeanDefinition bd : scanner.findCandidateComponents("it.integry")) {
|
||||
try {
|
||||
Class<?> clazz = Class.forName(bd.getBeanClassName());
|
||||
String beanName = generateBeanName(clazz);
|
||||
|
||||
IntegryCustomer customer = extractCustomer(clazz);
|
||||
|
||||
// Ora SettingsModel è completamente inizializzato con @PostConstruct chiamato
|
||||
if (!settingsModel.getDefaultProfile().equalsIgnoreCase(customer.toString())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Evito duplicati controllando se il bean esiste già
|
||||
if (!registry.containsBeanDefinition(beanName)) {
|
||||
logger.trace("Registering custom bean for customer: " + customer + " - Class: " + clazz.getSimpleName());
|
||||
|
||||
// Creo la definizione del bean
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder
|
||||
.genericBeanDefinition(clazz);
|
||||
|
||||
// Registro il bean nel registry di Spring
|
||||
registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
|
||||
|
||||
// Determino lo scope del bean per decidere se istanziarlo immediatamente
|
||||
String beanScope = determineBeanScope(clazz);
|
||||
|
||||
if (shouldInstantiateImmediately(beanScope)) {
|
||||
// Forzo l'istanziazione immediata solo per bean con scope appropriati
|
||||
try {
|
||||
Object beanInstance = applicationContext.getBean(beanName);
|
||||
logger.info("Bean customer {} istanziato con successo: {} (scope: {})",
|
||||
customer, beanInstance.getClass().getSimpleName(), beanScope);
|
||||
} catch (Exception e) {
|
||||
logger.error("Errore durante l'istanziazione del bean {} (scope: {}): {}",
|
||||
beanName, beanScope, e.getMessage());
|
||||
}
|
||||
} else {
|
||||
logger.info("Bean customer {} registrato ma non istanziato (scope: {}). " +
|
||||
"Verrà istanziato quando richiesto", customer, beanScope);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (ClassNotFoundException e) {
|
||||
logger.error("Impossibile caricare la classe: " + bd.getBeanClassName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera il nome del bean basato sul nome della classe
|
||||
*/
|
||||
private String generateBeanName(Class<?> clazz) {
|
||||
String simpleName = clazz.getSimpleName();
|
||||
return Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1);
|
||||
}
|
||||
|
||||
private IntegryCustomer extractCustomer(Class<?> clazz) {
|
||||
if (clazz.isAnnotationPresent(CustomerService.class)) {
|
||||
CustomerService cs = clazz.getAnnotation(CustomerService.class);
|
||||
return cs.value();
|
||||
} else if (clazz.isAnnotationPresent(CustomerComponent.class)) {
|
||||
CustomerComponent cc = clazz.getAnnotation(CustomerComponent.class);
|
||||
return cc.value();
|
||||
}
|
||||
return IntegryCustomer.Integry; // Valore di default
|
||||
}
|
||||
|
||||
/**
|
||||
* Determina lo scope del bean analizzando le annotazioni della classe
|
||||
*/
|
||||
private String determineBeanScope(Class<?> clazz) {
|
||||
// Controllo per @Scope
|
||||
if (clazz.isAnnotationPresent(org.springframework.context.annotation.Scope.class)) {
|
||||
org.springframework.context.annotation.Scope scopeAnnotation =
|
||||
clazz.getAnnotation(org.springframework.context.annotation.Scope.class);
|
||||
return scopeAnnotation.value();
|
||||
}
|
||||
|
||||
// Controllo per @RequestScope
|
||||
if (clazz.isAnnotationPresent(org.springframework.web.context.annotation.RequestScope.class)) {
|
||||
return "request";
|
||||
}
|
||||
|
||||
// Controllo per @SessionScope
|
||||
if (clazz.isAnnotationPresent(org.springframework.web.context.annotation.SessionScope.class)) {
|
||||
return "session";
|
||||
}
|
||||
|
||||
// Controllo per @ApplicationScope
|
||||
if (clazz.isAnnotationPresent(org.springframework.web.context.annotation.ApplicationScope.class)) {
|
||||
return "application";
|
||||
}
|
||||
|
||||
// Default è singleton
|
||||
return "singleton";
|
||||
}
|
||||
|
||||
/**
|
||||
* Determina se il bean può essere istanziato immediatamente in base al suo scope
|
||||
*/
|
||||
private boolean shouldInstantiateImmediately(String scope) {
|
||||
switch (scope.toLowerCase()) {
|
||||
case "request":
|
||||
case "session":
|
||||
// I bean con scope request/session non possono essere istanziati
|
||||
// al di fuori del contesto web
|
||||
return false;
|
||||
case "prototype":
|
||||
// I bean prototype non vengono istanziati automaticamente
|
||||
return false;
|
||||
case "singleton":
|
||||
case "application":
|
||||
default:
|
||||
// Singleton e application possono essere istanziati immediatamente
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import java.util.concurrent.TimeUnit;
|
||||
public class ExecutorServiceConfig {
|
||||
|
||||
private final int corePoolSize = Runtime.getRuntime().availableProcessors();
|
||||
private final int maxPoolSize = (int) (corePoolSize * 1.5f);
|
||||
private final int maxPoolSize = 20;
|
||||
private final int queueSize = 500;
|
||||
|
||||
@Bean
|
||||
@@ -21,7 +21,7 @@ public class ExecutorServiceConfig {
|
||||
return new ThreadPoolExecutor(
|
||||
corePoolSize,
|
||||
maxPoolSize,
|
||||
5,
|
||||
60L,
|
||||
TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue<>(queueSize),
|
||||
new ThreadFactoryBuilder()
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package it.integry.ems.configuration;
|
||||
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
|
||||
@Configuration
|
||||
@EnableScheduling // Equivale a <task:annotation-driven/>
|
||||
public class SchedulerConfig {
|
||||
|
||||
@Bean
|
||||
public ThreadPoolTaskScheduler taskScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(5); // Equivale a pool-size="5"
|
||||
scheduler.setThreadNamePrefix("taskScheduler-");
|
||||
scheduler.initialize();
|
||||
return scheduler;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package it.integry.ems.controller;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.Import.base.EntityImportResponse;
|
||||
import it.integry.ems.Import.dto.AnomalieDTO;
|
||||
import it.integry.ems.Import.dto.ImportRequestDTO;
|
||||
import it.integry.ems.download.DownloadFileHandlerService;
|
||||
import it.integry.ems.download.dto.DownloadFileDto;
|
||||
@@ -39,6 +38,7 @@ import it.integry.ems_model.entity.*;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.Base64Utility;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityDate;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.text.StringEscapeUtils;
|
||||
@@ -68,10 +68,9 @@ import java.lang.reflect.ParameterizedType;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.Date;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -227,7 +226,7 @@ public class EmsController {
|
||||
response = new ServiceRestResponse(EsitoType.OK);
|
||||
|
||||
} else {
|
||||
response = new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryConnection().getProfileName(), new Exception("Il contenuto del file non è valido"));
|
||||
response = new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryDatasource().getProfile(), new Exception("Il contenuto del file non è valido"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,11 +297,11 @@ public class EmsController {
|
||||
sql = sql.replaceAll("select", "select TOP " + numResult + " ");
|
||||
sql = sql.replaceAll("SELECT", "SELECT TOP " + numResult + " ");
|
||||
}
|
||||
objs = entityProcessor.selectRawData(sql, multiDBTransactionManager.getPrimaryConnection());
|
||||
objs = entityProcessor.selectRawData(sql, multiDBTransactionManager.getPrimaryDatasource());
|
||||
response = new ServiceRestResponse(EsitoType.OK, objs);
|
||||
} catch (Exception e) {
|
||||
logger.error(request.getRequestURI(), e);
|
||||
response = new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryConnection().getProfileName(), e);
|
||||
response = new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryDatasource().getProfile(), e);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
@@ -339,7 +338,7 @@ public class EmsController {
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error(request.getRequestURI(), e);
|
||||
response = new ServiceRestResponse(EsitoType.KO, e, multiDBTransactionManager.getPrimaryConnection().getProfileName(), entity);
|
||||
response = new ServiceRestResponse(EsitoType.KO, e, multiDBTransactionManager.getPrimaryDatasource().getProfile(), entity);
|
||||
}
|
||||
|
||||
if (entity.getOperation() == OperationType.SELECT_OBJECT) {
|
||||
@@ -386,7 +385,7 @@ public class EmsController {
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error(request.getRequestURI(), e);
|
||||
response = new ServiceRestResponse(EsitoType.KO, e, multiDBTransactionManager.getPrimaryConnection().getProfileName(), entity);
|
||||
response = new ServiceRestResponse(EsitoType.KO, e, multiDBTransactionManager.getPrimaryDatasource().getProfile(), entity);
|
||||
}
|
||||
|
||||
if (entity.getOperation() == OperationType.SELECT_OBJECT) {
|
||||
@@ -483,7 +482,7 @@ public class EmsController {
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error(request.getRequestURI(), e);
|
||||
response = new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryConnection().getProfileName(), e);
|
||||
response = new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryDatasource().getProfile(), e);
|
||||
}
|
||||
|
||||
return response;
|
||||
@@ -519,14 +518,10 @@ public class EmsController {
|
||||
map.put(columnNameAltered, ((java.sql.Date) rs.getObject(columnName)).getTime() / 1000);
|
||||
} else if (date2ts && metadata.getColumnType(i) == Types.TIMESTAMP) {
|
||||
map.put(columnNameAltered, ((Timestamp) rs.getObject(columnName)).getTime() / 1000);
|
||||
} else if (date2ts && metadata.getColumnType(i) == Types.TIME) {
|
||||
map.put(columnNameAltered, ((Time) rs.getObject(columnName)).getTime() / 1000);
|
||||
} else if (date2iso && metadata.getColumnType(i) == Types.DATE) {
|
||||
map.put(columnNameAltered, ((java.sql.Date) rs.getObject(columnName)).toLocalDate().format(DateTimeFormatter.ISO_DATE));
|
||||
} else if (date2iso && metadata.getColumnType(i) == Types.TIMESTAMP) {
|
||||
map.put(columnNameAltered, ((Timestamp) rs.getObject(columnName)).toLocalDateTime().format(DateTimeFormatter.ISO_DATE_TIME));
|
||||
} else if (date2iso && metadata.getColumnType(i) == Types.TIME) {
|
||||
map.put(columnNameAltered, ((Time) rs.getObject(columnName)).toLocalTime().format(DateTimeFormatter.ISO_LOCAL_TIME));
|
||||
} else {
|
||||
map.put(columnNameAltered, rs.getObject(columnName));
|
||||
}
|
||||
@@ -544,29 +539,20 @@ public class EmsController {
|
||||
}
|
||||
|
||||
@RequestMapping(value = EmsRestConstants.PATH_EXPORT, method = RequestMethod.POST)
|
||||
public @ResponseBody ServiceRestResponse export(HttpServletRequest request,
|
||||
@RequestParam(CommonConstants.PROFILE_DB) String configuration,
|
||||
@RequestParam(value = EmsRestConstants.TYPE) String typeExport,
|
||||
@RequestParam(value = EmsRestConstants.FORMAT) String formatExport,
|
||||
@RequestParam(required = false, defaultValue = "false") Boolean binaryDownload,
|
||||
@RequestParam(required = false, defaultValue = "true") boolean headless,
|
||||
@RequestBody(required = false) JsonNode body) throws Exception {
|
||||
public @ResponseBody ServiceRestResponse export(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(CommonConstants.PROFILE_DB) String configuration,
|
||||
@RequestParam(value = EmsRestConstants.TYPE) String typeExport,
|
||||
@RequestParam(value = EmsRestConstants.FORMAT) String formatExport,
|
||||
@RequestParam(required = false, defaultValue = "false") Boolean binaryDownload,
|
||||
@RequestParam(required = false, defaultValue = "true") boolean headless,
|
||||
@RequestBody(required = false) JsonNode body) throws Exception {
|
||||
|
||||
EntityExportResponse<?> entityExportResponse = emsServices.export(multiDBTransactionManager, requestDataDTO, typeExport, formatExport, body, headless);
|
||||
List<AnomalieDTO> anomalie = new ArrayList<>();
|
||||
|
||||
if (entityExportResponse != null && entityExportResponse.getAnomalie() != null && !entityExportResponse.getAnomalie().isEmpty())
|
||||
anomalie = entityExportResponse.getAnomalie();
|
||||
|
||||
ServiceRestResponse sr;
|
||||
if (!anomalie.isEmpty() && anomalie.stream().anyMatch(x -> x.getTipo() == (AnomalieDTO.Type.ERROR))) {
|
||||
sr = ServiceRestResponse.createNegativeResponse();
|
||||
} else {
|
||||
sr = ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
sr.setMessagesFromAnomalie(anomalie);
|
||||
EntityExportResponse<?> entityExportResponse = emsServices.export(typeExport, formatExport, body, headless);
|
||||
|
||||
ServiceRestResponse sr = ServiceRestResponse.createPositiveResponse();
|
||||
if (entityExportResponse != null) {
|
||||
|
||||
if (binaryDownload) {
|
||||
List<DownloadFileDto> downloadableFileList = new ArrayList<>();
|
||||
for (EntityExportedFile exportedFile : (List<EntityExportedFile>) entityExportResponse.getResponse()) {
|
||||
@@ -608,7 +594,7 @@ public class EmsController {
|
||||
@RequestParam(required = false, defaultValue = "true") boolean headless,
|
||||
@RequestBody(required = false) ImportRequestDTO requestBody) throws Exception {
|
||||
|
||||
EntityImportResponse<List<EntityBase>> importResponse = emsServices.importEntity(multiDBTransactionManager, requestDataDTO, importType, importFormat, requestBody, headless);
|
||||
EntityImportResponse<List<EntityBase>> importResponse = emsServices.importEntity(importType, importFormat, requestBody, headless);
|
||||
List<EntityBase> entities = importResponse.getResponse();
|
||||
|
||||
|
||||
@@ -619,23 +605,48 @@ public class EmsController {
|
||||
.map(x -> MessageDTO.error(x.getException().getMessage()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<AnomalieDTO> anomalie = importResponse.getAnomalie();
|
||||
List<MessageDTO> messages = importResponse.getAnomalie().stream()
|
||||
.filter(x -> x.getTipo() != null)
|
||||
.map(x -> {
|
||||
switch (x.getTipo()) {
|
||||
case ERROR:
|
||||
return MessageDTO.error(x.getMessage());
|
||||
case WARNING:
|
||||
default:
|
||||
return MessageDTO.warning(x.getMessage());
|
||||
}
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (!errorMessages.isEmpty() || (anomalie != null && !anomalie.isEmpty())) {
|
||||
errorMessages.addAll(messages);
|
||||
|
||||
if (!errorMessages.isEmpty()) {
|
||||
response = ServiceRestResponse.createNegativeResponse();
|
||||
} else {
|
||||
response = ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
response.setMessages(errorMessages, importResponse.getAnomalie());
|
||||
response.setMessages(errorMessages);
|
||||
response.setEntityList(entities.stream().filter(x -> x.getException() == null).collect(Collectors.toList()));
|
||||
|
||||
} else {
|
||||
if (importResponse.getAnomalie() != null) {
|
||||
|
||||
if (!importResponse.getAnomalie().isEmpty()) {
|
||||
|
||||
response = ServiceRestResponse.createNegativeResponse()
|
||||
.setMessagesFromAnomalie(importResponse.getAnomalie());
|
||||
List<MessageDTO> messages = importResponse.getAnomalie().stream()
|
||||
.map(x -> {
|
||||
switch (x.getTipo()) {
|
||||
case ERROR:
|
||||
return MessageDTO.error(x.getMessage());
|
||||
case WARNING:
|
||||
default:
|
||||
return MessageDTO.warning(x.getMessage());
|
||||
}
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
response = ServiceRestResponse.createNegativeResponse();
|
||||
response.setMessages(messages);
|
||||
} else response = ServiceRestResponse.createPositiveResponse();
|
||||
|
||||
} else throw new Exception("Non ci sono dati da importare");
|
||||
@@ -687,7 +698,7 @@ public class EmsController {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error(request.getRequestURI(), e);
|
||||
response = new ServiceRestResponse(EsitoType.KO, e, multiDBTransactionManager.getPrimaryConnection().getProfileName(), entity);
|
||||
response = new ServiceRestResponse(EsitoType.KO, e, multiDBTransactionManager.getPrimaryDatasource().getProfile(), entity);
|
||||
responseList.add(response);
|
||||
if (forceTransaction) {
|
||||
break;
|
||||
@@ -700,6 +711,16 @@ public class EmsController {
|
||||
logger.error(request.getRequestURI(), e);
|
||||
ServiceRestResponse response = new ServiceRestResponse(EsitoType.KO, configuration, e);
|
||||
responseList.add(response);
|
||||
} finally {
|
||||
if (multiDBTransactionManager != null) {
|
||||
try {
|
||||
multiDBTransactionManager.closeAll();
|
||||
} catch (Exception e) {
|
||||
logger.error(request.getRequestURI(), e);
|
||||
ServiceRestResponse response = new ServiceRestResponse(EsitoType.KO, configuration, e);
|
||||
responseList.add(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return responseList;
|
||||
@@ -733,7 +754,7 @@ public class EmsController {
|
||||
@PathVariable String filename,
|
||||
@RequestParam(name = "contentDisposition", defaultValue = "attachment") String contentDispositionType,
|
||||
@RequestParam(defaultValue = "false") boolean requestThumbnail) throws Exception {
|
||||
AttachmentDTO attachmentDTO = emsServices.downloadStbFileAttachment(multiDBTransactionManager, idAttach, requestThumbnail);
|
||||
AttachmentDTO attachmentDTO = emsServices.downloadStbFileAttachment(idAttach, requestThumbnail);
|
||||
|
||||
if (attachmentDTO != null) {
|
||||
return ResponseEntity.ok()
|
||||
@@ -750,31 +771,13 @@ public class EmsController {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
@GetMapping(value = "downloadFileFromRefUuid")
|
||||
public ResponseEntity<byte[]> downloadFileFromRefUuid(@RequestParam(CommonConstants.PROFILE_DB) String config,
|
||||
@RequestParam() String refUuid,
|
||||
@RequestParam() String fileName) throws Exception {
|
||||
AttachmentDTO attached = emsServices.downloadFileFromRefUuid(multiDBTransactionManager, refUuid, fileName);
|
||||
|
||||
if (attached == null) return ResponseEntity.notFound().build();
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(attached.getMimeType()))
|
||||
.contentLength(attached.getFileSize())
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition
|
||||
.attachment()
|
||||
.filename(attached.getFileName())
|
||||
.build()
|
||||
.toString())
|
||||
.body(attached.getFileContent());
|
||||
}
|
||||
|
||||
@RequestMapping(value = EmsRestConstants.PATH_DOWNLOAD_STB_FILE_ATTACHMENT, method = RequestMethod.GET)
|
||||
public ResponseEntity<byte[]> downloadStbFileAttachmentPath(
|
||||
@RequestParam(CommonConstants.PROFILE_DB) String config,
|
||||
@RequestParam String idAttach,
|
||||
@RequestParam(defaultValue = "false") boolean requestThumbnail) throws Exception {
|
||||
AttachmentDTO attachmentDTO = emsServices.downloadStbFileAttachment(multiDBTransactionManager, idAttach, requestThumbnail);
|
||||
AttachmentDTO attachmentDTO = emsServices.downloadStbFileAttachment(idAttach, requestThumbnail);
|
||||
|
||||
if (attachmentDTO != null) {
|
||||
return ResponseEntity.ok()
|
||||
@@ -840,7 +843,7 @@ public class EmsController {
|
||||
@RequestParam Integer versione) throws Exception {
|
||||
|
||||
DtbDocPdf dtbDocPdf = new DtbDocPdf();
|
||||
dtbDocPdf.setDataDoc(UtilityString.parseLocalDate(dataDoc));
|
||||
dtbDocPdf.setDataDoc(UtilityDate.RecognizeDate(dataDoc));
|
||||
dtbDocPdf.setSerDoc(serDoc);
|
||||
dtbDocPdf.setNumDoc(numDoc);
|
||||
dtbDocPdf.setCodAnag(codAnag);
|
||||
@@ -892,7 +895,7 @@ public class EmsController {
|
||||
@RequestParam Integer versione) throws Exception {
|
||||
DtbOrdPdf dtbOrdPdf = new DtbOrdPdf();
|
||||
dtbOrdPdf.setGestione(gestione);
|
||||
dtbOrdPdf.setDataOrd(UtilityString.parseLocalDate(dataOrd));
|
||||
dtbOrdPdf.setDataOrd(UtilityDate.RecognizeDate(dataOrd));
|
||||
dtbOrdPdf.setNumOrd(numOrd);
|
||||
dtbOrdPdf.setVersione(versione);
|
||||
dtbOrdPdf.setOperation(OperationType.SELECT_OBJECT);
|
||||
@@ -927,7 +930,7 @@ public class EmsController {
|
||||
throw new Exception("Sono stati inviati più file del previsto");
|
||||
}
|
||||
|
||||
StbFilesAttached stbFilesAttached = emsServices.uploadStbFilesAttached(multiDBTransactionManager, idAttach,
|
||||
StbFilesAttached stbFilesAttached = emsServices.uploadStbFilesAttached(idAttach,
|
||||
files[0].getOriginalFilename(),
|
||||
files[0].getBytes(),
|
||||
descrizione,
|
||||
@@ -1043,7 +1046,7 @@ public class EmsController {
|
||||
byte[] content = files[0].getBytes();
|
||||
// content = UtilityZip.zlib_compress(content);
|
||||
|
||||
LocalDate dataDoc = UtilityString.parseLocalDate(dataDocStr);
|
||||
Date dataDoc = UtilityDate.RecognizeDate(dataDocStr);
|
||||
|
||||
DtbDocPdf dtbDocPdf = new DtbDocPdf();
|
||||
dtbDocPdf.setDataDoc(dataDoc);
|
||||
@@ -1073,59 +1076,10 @@ public class EmsController {
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping(value = "uploadDtbDocFileContent")
|
||||
public ServiceRestResponse uploadDtbDocFileContent(HttpServletRequest request, HttpServletResponse response,
|
||||
@RequestParam(CommonConstants.PROFILE_DB) String config,
|
||||
@RequestParam("dataDoc") String dataDocStr,
|
||||
@RequestParam String serDoc,
|
||||
@RequestParam Integer numDoc,
|
||||
@RequestParam String codAnag,
|
||||
@RequestParam String codDtip,
|
||||
@RequestParam String descrizione,
|
||||
@RequestPart MultipartFile[] files
|
||||
) {
|
||||
try {
|
||||
if (files == null || files.length == 0) {
|
||||
throw new Exception("Nessun file è stato rilevato");
|
||||
} else if (files.length > 1) {
|
||||
throw new Exception("Sono stati inviati più file del previsto");
|
||||
}
|
||||
|
||||
byte[] content = files[0].getBytes();
|
||||
|
||||
String idAttach = null;
|
||||
StbFilesAttached.TypeAttach typeAttach = null;
|
||||
LocalDate dataDoc = UtilityString.parseLocalDate(dataDocStr);
|
||||
|
||||
DrlDocAttached drlDocAttached =
|
||||
new DrlDocAttached()
|
||||
.setDataDoc(dataDoc)
|
||||
.setSerDoc(serDoc)
|
||||
.setNumDoc(numDoc)
|
||||
.setCodAnag(codAnag)
|
||||
.setCodDtip(codDtip);
|
||||
drlDocAttached.setOperation(OperationType.INSERT);
|
||||
|
||||
StbFilesAttached stbFilesAttached = emsServices.uploadStbFilesAttached(multiDBTransactionManager, idAttach,
|
||||
files[0].getOriginalFilename(),
|
||||
files[0].getBytes(),
|
||||
descrizione,
|
||||
files[0].getContentType(),
|
||||
typeAttach,
|
||||
null, drlDocAttached, null);
|
||||
|
||||
return ServiceRestResponse.createPositiveResponse(stbFilesAttached);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
return new ServiceRestResponse(EsitoType.KO, config, e);
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = "createZipFromFiles", method = RequestMethod.POST)
|
||||
public @ResponseBody
|
||||
ServiceRestResponse createZipFromFiles(@RequestBody CreateZipDTO createZipDTO) throws Exception {
|
||||
return ServiceRestResponse.createPositiveResponse(emsServices.createZipFromFiles(multiDBTransactionManager, createZipDTO));
|
||||
return ServiceRestResponse.createPositiveResponse(emsServices.createZipFromFiles(createZipDTO));
|
||||
}
|
||||
|
||||
// @RequestMapping(value = EmsRestConstants.PATH_UPLOAD_STB_EMAIL_CONTENT, method = RequestMethod.POST)
|
||||
@@ -1171,10 +1125,22 @@ public class EmsController {
|
||||
// }
|
||||
|
||||
|
||||
@RequestMapping(value = EmsRestConstants.PATH_CLEAN_DIRECTORIES, method = RequestMethod.POST)
|
||||
public @ResponseBody
|
||||
ServiceRestResponse cleanDirectories(@RequestParam(CommonConstants.PROFILE_DB) String config) throws Exception {
|
||||
try {
|
||||
emsServices.cleanDirectories();
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
return new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryDatasource().getProfile(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = EmsRestConstants.PATH_EXPORT_SERVER_INFO_ISCC, method = RequestMethod.POST)
|
||||
public @ResponseBody
|
||||
ServiceRestResponse exportServerInfoISCC(@RequestParam(CommonConstants.PROFILE_DB) String config) throws Exception {
|
||||
emsServices.checkServerVariables(multiDBTransactionManager);
|
||||
emsServices.checkServerVariables();
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
@@ -1186,7 +1152,7 @@ public class EmsController {
|
||||
return ServiceRestResponse.createPositiveResponse(mapping);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
return new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryConnection().getProfileName(), e);
|
||||
return new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryDatasource().getProfile(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1198,7 +1164,7 @@ public class EmsController {
|
||||
return ServiceRestResponse.createPositiveResponse(historyProfileDb);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
return new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryConnection().getProfileName(), e);
|
||||
return new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryDatasource().getProfile(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1215,7 +1181,7 @@ public class EmsController {
|
||||
return ServiceRestResponse.createPositiveResponse(entityFields);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
return new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryConnection().getProfileName(), e);
|
||||
return new ServiceRestResponse(EsitoType.KO, multiDBTransactionManager.getPrimaryDatasource().getProfile(), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package it.integry.ems.controller;
|
||||
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.service.MapService;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.types.LatLng;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
|
||||
@RestController
|
||||
@Scope("request")
|
||||
public class MapController {
|
||||
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Autowired
|
||||
private MapService mapService;
|
||||
|
||||
|
||||
@RequestMapping(value = EmsRestConstants.PATH_MAP_GETCOORDINATE_BY_CITY, method = RequestMethod.GET)
|
||||
public @ResponseBody
|
||||
ServiceRestResponse getCoordinateByCity(HttpServletRequest request,
|
||||
@RequestParam String cityName) {
|
||||
ServiceRestResponse resp;
|
||||
try {
|
||||
LatLng coordinates = mapService.getCoordinateByCity(cityName);
|
||||
resp = ServiceRestResponse.createPositiveResponse(coordinates);
|
||||
} catch (Exception e) {
|
||||
logger.error(request.getRequestURI(), e);
|
||||
resp = ServiceRestResponse.createNegativeResponse();
|
||||
}
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,154 +1,140 @@
|
||||
package it.integry.ems.datasource;
|
||||
|
||||
import it.integry.ems.settings.Model.AvailableConnectionModel;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityHashMap;
|
||||
import org.apache.commons.dbcp2.BasicDataSource;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class DataSource extends BasicDataSource {
|
||||
|
||||
private AvailableConnectionModel connectionModel;
|
||||
|
||||
/**
|
||||
* Instanzia un nuovo datasource.
|
||||
*
|
||||
* @deprecated Il datasource non deve essere istanziato direttamente ma bisogna utilizzare il metodo
|
||||
* {@link it.integry.ems.sync.MultiDBTransaction.BasicConnectionPool#getConnection(AvailableConnectionModel)} per ottenere una connessione.
|
||||
*/
|
||||
@Deprecated
|
||||
public DataSource() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EmsRestConstants.DB_TYPE getTypeDB() {
|
||||
return connectionModel.getConnectionType();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ottiene una connessione dal pool. La connessione è wrappata in it.integry.ems.sync.MultiDBTransaction.Connection.
|
||||
* È responsabilità del chiamante chiudere la connessione per restituirla al pool.
|
||||
*
|
||||
* @return una connessione dal pool
|
||||
* @throws SQLException se si verifica un errore di accesso al database
|
||||
*/
|
||||
|
||||
public Connection getConnection() throws SQLException {
|
||||
// Restituisce una nuova connessione dal pool di BasicDataSource, wrappata nel nostro tipo Connection
|
||||
final Connection connection = Connection.fromConnection(super.getConnection());
|
||||
// Prova a ottenere una connessione per verificare la configurazione e ottenere il sessionID
|
||||
|
||||
if (connectionModel.getConnectionType() == EmsRestConstants.DB_TYPE.MSSQL) {
|
||||
HashMap<String, Object> resultSessionData = UtilityDB.executeSimpleQueryOnlyFirstRow(connection, "select CAST(@@spid AS BIGINT) AS session_id," +
|
||||
" user_name() AS [user_name]," +
|
||||
" suser_name() AS [suser_name]," +
|
||||
" current_user AS [current_user]," +
|
||||
" system_user AS [system_user]," +
|
||||
" session_user AS [session_user]," +
|
||||
" user AS [user]");
|
||||
|
||||
connection.setSessionId(UtilityHashMap.getValueIfExists(resultSessionData, "session_id"));
|
||||
}
|
||||
|
||||
connection.setProfileName(connectionModel.getProfileName())
|
||||
.setInternalDb(connectionModel.getInternalDb());
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
public synchronized void initialize(String profileDB) throws Exception {
|
||||
AvailableConnectionModel connectionsModel = SettingsModel.getInstance().findConnectionModel(profileDB);
|
||||
|
||||
initialize(connectionsModel);
|
||||
}
|
||||
|
||||
public synchronized void initialize(AvailableConnectionModel connectionModel) throws Exception {
|
||||
if (connectionModel == null) {
|
||||
throw new Exception("Configurazione DB non trovata");
|
||||
}
|
||||
|
||||
this.connectionModel = connectionModel;
|
||||
|
||||
this.setDriverClassName(connectionModel.getDriverClassName());
|
||||
|
||||
this.setUrl(connectionModel.getDbConnectionString("EMS Connection"));
|
||||
this.setUsername(connectionModel.getUsername());
|
||||
this.setPassword(connectionModel.getPasswordDecrypted());
|
||||
this.setDefaultCatalog(connectionModel.getDbName());
|
||||
|
||||
this.setDefaultTransactionIsolation(java.sql.Connection.TRANSACTION_READ_UNCOMMITTED);
|
||||
this.setDefaultAutoCommit(false);
|
||||
|
||||
// ===== OTTIMIZZAZIONI CRITICHE =====
|
||||
|
||||
// Pool sizing ottimizzato per READ_UNCOMMITTED (meno locking = più connessioni possibili)
|
||||
this.setInitialSize(5); // Inizia con più connessioni
|
||||
this.setMaxTotal(-1); // Aumentato il massimo
|
||||
this.setMinIdle(5); // Non scendere sotto 5
|
||||
this.setMaxIdle(-1); // Mantieni più connessioni idle
|
||||
|
||||
// Timeout ottimizzati per performance massime
|
||||
// this.setMaxWaitMillis(-1L); // Infinito (DEFAULT)
|
||||
|
||||
// Validazione veloce ed efficiente
|
||||
this.setValidationQuery("SELECT 1");
|
||||
// this.setValidationQueryTimeout(60); // Ridotto a 1 secondo
|
||||
// this.setTestWhileIdle(true); // Testa connessioni idle
|
||||
|
||||
// Eviction ottimizzata per READ_UNCOMMITTED
|
||||
// this.setTimeBetweenEvictionRunsMillis(1 * 1000); // Ogni 30 secondi
|
||||
// this.setMinEvictableIdleTimeMillis(1 * 60 * 1000); // 3 minuti (ridotto da 5)
|
||||
// this.setNumTestsPerEvictionRun(5); // Testa più connessioni per volta
|
||||
|
||||
// Connection leak protection
|
||||
this.setRemoveAbandonedOnBorrow(true);
|
||||
this.setRemoveAbandonedOnMaintenance(true);
|
||||
this.setRemoveAbandonedTimeout(3 * 60 * 10); // 3 minuti
|
||||
this.setLogAbandoned(true); // Disabilita in produzione per performance
|
||||
|
||||
// Performance boosts massimi
|
||||
// this.setPoolPreparedStatements(true);
|
||||
// this.setMaxOpenPreparedStatements(200);
|
||||
// this.setCacheState(true);
|
||||
this.setFastFailValidation(true);
|
||||
|
||||
// Ottimizzazioni specifiche per SQL Server con READ_UNCOMMITTED
|
||||
if (connectionModel.getConnectionType() == EmsRestConstants.DB_TYPE.MSSQL) {
|
||||
// Impostazioni connection specifiche per SQL Server
|
||||
//this.setConnectionInitSqls(java.util.Arrays.asList(
|
||||
//"SET NOCOUNT ON",
|
||||
//"SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED",
|
||||
//"SET ARITHABORT ON"
|
||||
//));
|
||||
}
|
||||
|
||||
// Logging ottimizzato (disabilita in produzione)
|
||||
this.setLogExpiredConnections(true);
|
||||
|
||||
// ==================== ULTERIORI OTTIMIZZAZIONI ====================
|
||||
|
||||
// Connection properties specifiche per performance
|
||||
this.setDefaultReadOnly(false);
|
||||
|
||||
// Ottimizzazioni DBCP2 avanzate
|
||||
// this.setLifo(false); // FIFO per distribuzione equa delle connessioni
|
||||
// this.setSoftMinEvictableIdleTimeMillis(120000); // 2 minuti soft eviction
|
||||
|
||||
|
||||
// if (!connectionModel.getInternalDb() ||
|
||||
// UtilityDebug.isDebugExecution() ||
|
||||
// UtilityDebug.isIntegryServerDev() ||
|
||||
// !SettingsModel.getInstance().isPrimaryInstance()) {
|
||||
// this.setInitialSize(0);
|
||||
//// this.setMaxTotal(5);
|
||||
// this.setMinIdle(0);
|
||||
// this.setMaxIdle(1);
|
||||
// }
|
||||
}
|
||||
|
||||
package it.integry.ems.datasource;
|
||||
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityHashMap;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.io.IOException;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Scope(value = "request")
|
||||
public class DataSource {
|
||||
|
||||
private AvailableConnectionsModel connectionModel;
|
||||
|
||||
|
||||
private String profile;
|
||||
private Short sessionID;
|
||||
private Connection connection = null;
|
||||
private String applicationName;
|
||||
|
||||
public String getDbName() {
|
||||
return connectionModel.getDbName();
|
||||
}
|
||||
|
||||
public String getProfile() {
|
||||
return profile;
|
||||
}
|
||||
|
||||
public EmsRestConstants.DB_TYPE getTypeDB() {
|
||||
return connectionModel.getConnectionType();
|
||||
}
|
||||
|
||||
public String getApplicationName() {
|
||||
return applicationName;
|
||||
}
|
||||
|
||||
public int getSessionID() {
|
||||
return sessionID;
|
||||
}
|
||||
|
||||
public synchronized Connection getConnection() throws IOException, SQLException {
|
||||
return connection;
|
||||
}
|
||||
|
||||
public boolean isClosed() throws SQLException {
|
||||
return !(connection != null && !connection.isClosed());
|
||||
}
|
||||
|
||||
private void init(String applicationName) throws SQLException, IOException {
|
||||
this.applicationName = applicationName;
|
||||
|
||||
connection = Connection.fromConnection(
|
||||
DriverManager.getConnection(connectionModel.getDbConnectionString(applicationName), connectionModel.getUsername(), connectionModel.getPasswordDecrypted())
|
||||
);
|
||||
connection.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_UNCOMMITTED);
|
||||
connection.setAutoCommit(false);
|
||||
|
||||
if (connectionModel.getConnectionType() == EmsRestConstants.DB_TYPE.MSSQL) {
|
||||
try (final PreparedStatement setNocountOn = connection.prepareStatement("SET NOCOUNT ON")) {
|
||||
boolean resultNoCount = setNocountOn.execute();
|
||||
}
|
||||
|
||||
HashMap<String, Object> resultSessionData = UtilityDB.executeSimpleQueryOnlyFirstRow(connection, "select @@spid AS session_id," +
|
||||
" user_name() AS [user_name]," +
|
||||
" suser_name() AS [suser_name]," +
|
||||
" current_user AS [current_user]," +
|
||||
" system_user AS [system_user]," +
|
||||
" session_user AS [session_user]," +
|
||||
" user AS [user]");
|
||||
|
||||
this.sessionID = UtilityHashMap.getValueIfExists(resultSessionData, "session_id");
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
private void destroy() throws SQLException {
|
||||
forceClose();
|
||||
}
|
||||
|
||||
public synchronized void initialize(String profileDB, String connectionName, boolean autoOpenConnection) throws Exception {
|
||||
if (UtilityString.isNullOrEmpty(profileDB)) {
|
||||
throw new Exception("Profile DB non valorizzato - controllare la chiamata del servizio");
|
||||
}
|
||||
|
||||
this.profile = profileDB;
|
||||
this.sessionID = -1;
|
||||
|
||||
|
||||
AvailableConnectionsModel connectionModel = null;
|
||||
List<AvailableConnectionsModel> availableConnectionsModels = SettingsModel.getInstance().getAvailableConnections();
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(profileDB)) {
|
||||
for (AvailableConnectionsModel connectionsModel : availableConnectionsModels) {
|
||||
if (connectionsModel.getProfileName().equalsIgnoreCase(profileDB)) {
|
||||
connectionModel = connectionsModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (connectionModel == null) {
|
||||
throw new Exception(String.format("Configurazione DB non trovata o dati mancanti (%s)", profileDB));
|
||||
}
|
||||
|
||||
this.connectionModel = connectionModel;
|
||||
|
||||
if (autoOpenConnection) {
|
||||
init(connectionName);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void initialize(String profileDB, boolean autoOpenConnection) throws Exception {
|
||||
initialize(profileDB, "EMS Connection", autoOpenConnection);
|
||||
}
|
||||
|
||||
public synchronized void initialize(String profileDB) throws Exception {
|
||||
initialize(profileDB, "EMS Connection", true);
|
||||
}
|
||||
|
||||
public void forceClose() throws SQLException {
|
||||
if (connection != null) {
|
||||
synchronized (connection) {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,16 +2,14 @@ package it.integry.ems.directory;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.datasource.DataSource;
|
||||
import it.integry.ems.json.ResponseJSONObjectMapper;
|
||||
import it.integry.ems.properties.EmsProperties;
|
||||
import it.integry.ems.response.EsitoType;
|
||||
import it.integry.ems.response.FileItem;
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.service.SetupGest;
|
||||
import it.integry.ems_model.utility.UtilityHashMap;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import it.integry.security.utility.RestUtil;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
@@ -31,18 +29,17 @@ import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Properties;
|
||||
import java.util.TimerTask;
|
||||
|
||||
public class EmailWatcherListener extends TimerTask {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
private Logger logger = LogManager.getLogger();
|
||||
|
||||
private final EmailListenerInfo emailListenerInfo;
|
||||
private final EmsProperties prop;
|
||||
private final SetupGest setupGest;
|
||||
private final ResponseJSONObjectMapper jsonObjectMapper;
|
||||
private EmailListenerInfo emailListenerInfo;
|
||||
private EmsProperties prop;
|
||||
private SetupGest setupGest;
|
||||
private ResponseJSONObjectMapper jsonObjectMapper;
|
||||
|
||||
public EmailWatcherListener(EmailListenerInfo emailListenerInfo, EmsProperties prop,
|
||||
SetupGest setupGest, ResponseJSONObjectMapper jsonObjectMapper) {
|
||||
@@ -55,44 +52,42 @@ public class EmailWatcherListener extends TimerTask {
|
||||
|
||||
@Override
|
||||
public synchronized void run() {
|
||||
try (MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(emailListenerInfo.getDatabase())) {
|
||||
Connection conn = multiDBTransactionManager.getPrimaryConnection();
|
||||
|
||||
try {
|
||||
String flagAttivo = null, username = null, password = null,
|
||||
imap = null, pop3 = null, pop3Port = null, imapPort = null;
|
||||
|
||||
DataSource ds = new DataSource();
|
||||
ds.initialize(emailListenerInfo.getDatabase());
|
||||
|
||||
String[] params = emailListenerInfo.getSetupGestBranch().split("\\|");
|
||||
|
||||
if (params.length >= 2) {
|
||||
final HashMap<String, String> setupData = setupGest.getSetupSection(conn, params[0], params[1]);
|
||||
|
||||
flagAttivo = UtilityHashMap.getValueIfExists(setupData, "ATTIVO");
|
||||
username = UtilityHashMap.getValueIfExists(setupData, "USERNAME");
|
||||
flagAttivo = setupGest.getSetup(ds.getConnection(), params[0], params[1], "ATTIVO");
|
||||
username = setupGest.getSetup(ds.getConnection(), params[0], params[1], "USERNAME");
|
||||
if (UtilityString.isNullOrEmpty(username))
|
||||
throw new Exception(params[0] + "/" + params[1] + "/USERNAME non configurato correttamente");
|
||||
|
||||
password = UtilityHashMap.getValueIfExists(setupData, "PASSWORD");
|
||||
password = setupGest.getSetup(ds.getConnection(), params[0], params[1], "PASSWORD");
|
||||
if (UtilityString.isNullOrEmpty(password))
|
||||
throw new Exception(params[0] + "/" + params[1] + "/PASSWORD non configurato correttamente");
|
||||
|
||||
pop3 = UtilityHashMap.getValueIfExists(setupData, "POP3");
|
||||
pop3 = setupGest.getSetup(ds.getConnection(), params[0], params[1], "POP3");
|
||||
if (UtilityString.isNullOrEmpty(pop3))
|
||||
throw new Exception(params[0] + "/" + params[1] + "/POP3 non configurato correttamente");
|
||||
|
||||
pop3Port = UtilityHashMap.getValueIfExists(setupData, "POP3_PORT");
|
||||
pop3Port = setupGest.getSetup(ds.getConnection(), params[0], params[1], "POP3_PORT");
|
||||
if (UtilityString.isNullOrEmpty(pop3Port))
|
||||
throw new Exception(params[0] + "/" + params[1] + "/POP3_PORT non configurato correttamente");
|
||||
|
||||
imap = UtilityHashMap.getValueIfExists(setupData, "IMAP");
|
||||
imap = setupGest.getSetup(ds.getConnection(), params[0], params[1], "IMAP");
|
||||
if (UtilityString.isNullOrEmpty(imap))
|
||||
throw new Exception(params[0] + "/" + params[1] + "/IMAP non configurato correttamente");
|
||||
|
||||
imapPort = UtilityHashMap.getValueIfExists(setupData, "IMAP_PORT");
|
||||
imapPort = setupGest.getSetup(ds.getConnection(), params[0], params[1], "IMAP_PORT");
|
||||
if (UtilityString.isNullOrEmpty(imapPort))
|
||||
throw new Exception(params[0] + "/" + params[1] + "/IMAP_PORT non configurato correttamente");
|
||||
}
|
||||
|
||||
ds.forceClose();
|
||||
if (!UtilityString.isNullOrEmpty(flagAttivo) && "S".equals(flagAttivo)) {
|
||||
Properties sysProperties = System.getProperties();
|
||||
Session session = Session.getDefaultInstance(sysProperties);
|
||||
@@ -164,7 +159,7 @@ public class EmailWatcherListener extends TimerTask {
|
||||
|
||||
String value = response.readEntity(String.class);
|
||||
|
||||
String emailDbg = setupGest.getSetup(conn, params[0], params[1], "EMAIL_DBG");
|
||||
String emailDbg = setupGest.getSetup(ds.getConnection(), params[0], params[1], "EMAIL_DBG");
|
||||
if (value.charAt(0) == '{') {
|
||||
ServiceRestResponse respWra = jsonObjectMapper.readValue(value, ServiceRestResponse.class);
|
||||
if (respWra.getEsito() == EsitoType.KO) {
|
||||
@@ -197,66 +192,67 @@ public class EmailWatcherListener extends TimerTask {
|
||||
private void notifyErrorToEmail(String emailListen, String mittente, String messageObj, Date messageDate,
|
||||
String emailDbg, String errorMessage) throws Exception {
|
||||
if (!UtilityString.isNullOrEmpty(emailDbg)) {
|
||||
try (MultiDBTransactionManager mdb = new MultiDBTransactionManager(emailListenerInfo.getDatabase())) {
|
||||
DataSource ds = new DataSource();
|
||||
ds.initialize(emailListenerInfo.getDatabase());
|
||||
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
|
||||
|
||||
String nomeAzienda = "";
|
||||
PreparedStatement ps = mdb.prepareStatement("select nome_ditta from azienda");
|
||||
ResultSet rs = ps.executeQuery();
|
||||
if (rs.next()) {
|
||||
nomeAzienda = rs.getString("nome_ditta");
|
||||
}
|
||||
rs.close();
|
||||
ps.close();
|
||||
|
||||
String htmlMailBody = "Gentile Amministratore,<br> si e' verificato il seguente errore <br><b>" + errorMessage + "</b><br> del servizio " + emailListenerInfo.getServiceRest() +
|
||||
"<br> in ascolto sulla mail " + emailListen + " provocato dal messaggio (mittente " + mittente + ") con oggetto " + messageObj + " in data " + sdf.format(messageDate);
|
||||
|
||||
String mailSubject = nomeAzienda + " - ERRORE SU " + InetAddress.getLocalHost().getHostName() +
|
||||
" Servizio " + emailListenerInfo.getServiceRest() + ";Database " + emailListenerInfo.getDatabase();
|
||||
|
||||
// AttachmentDTO dto = new AttachmentDTO();
|
||||
// dto.setFileByte(files);
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
//jsonObjectMapper.writeValue(writer, dto);
|
||||
|
||||
String jsonBody = writer.toString();
|
||||
|
||||
String database = emailListenerInfo.getDatabase();
|
||||
|
||||
String auth = RestUtil.generateAuth(database, database, "POST", jsonBody,
|
||||
"application/json", prop.getRootApi() + EmsRestConstants.PATH_SEND_MAIL);
|
||||
|
||||
final Client client = ClientBuilder.newClient();
|
||||
WebTarget resource = client.target(prop.getEndPointWS()).path(
|
||||
prop.getRootApi() + EmsRestConstants.PATH_SEND_MAIL)
|
||||
.resolveTemplate("mode", "async");
|
||||
resource = resource.queryParam(CommonConstants.PROFILE_DB, database)
|
||||
.queryParam("from", "").queryParam("to", emailDbg)
|
||||
.queryParam("subject", mailSubject).queryParam("msgText", htmlMailBody)
|
||||
.queryParam("isHtml", true);
|
||||
|
||||
resource.request().header("Authorization", database + ":" + auth)
|
||||
.async()
|
||||
.post(Entity.json(jsonBody), new InvocationCallback<Response>() {
|
||||
@Override
|
||||
public void completed(Response response) {
|
||||
String value = response.readEntity(String.class);
|
||||
logger.info(response.getStatus() + " - " + value);
|
||||
response.close();
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
logger.error(throwable);
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
String nomeAzienda = "";
|
||||
PreparedStatement ps = ds.getConnection().prepareStatement("select nome_ditta from azienda");
|
||||
ResultSet rs = ps.executeQuery();
|
||||
if (rs.next()) {
|
||||
nomeAzienda = rs.getString("nome_ditta");
|
||||
}
|
||||
rs.close();
|
||||
ps.close();
|
||||
ds.forceClose();
|
||||
|
||||
String htmlMailBody = "Gentile Amministratore,<br> si e' verificato il seguente errore <br><b>" + errorMessage + "</b><br> del servizio " + emailListenerInfo.getServiceRest() +
|
||||
"<br> in ascolto sulla mail " + emailListen + " provocato dal messaggio (mittente " + mittente + ") con oggetto " + messageObj + " in data " + sdf.format(messageDate);
|
||||
|
||||
String mailSubject = nomeAzienda + " - ERRORE SU " + InetAddress.getLocalHost().getHostName() +
|
||||
" Servizio " + emailListenerInfo.getServiceRest() + ";Database " + emailListenerInfo.getDatabase();
|
||||
|
||||
// AttachmentDTO dto = new AttachmentDTO();
|
||||
// dto.setFileByte(files);
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
//jsonObjectMapper.writeValue(writer, dto);
|
||||
|
||||
String jsonBody = writer.toString();
|
||||
|
||||
String database = emailListenerInfo.getDatabase();
|
||||
|
||||
String auth = RestUtil.generateAuth(database, database, "POST", jsonBody,
|
||||
"application/json", prop.getRootApi() + EmsRestConstants.PATH_SEND_MAIL);
|
||||
|
||||
final Client client = ClientBuilder.newClient();
|
||||
WebTarget resource = client.target(prop.getEndPointWS()).path(
|
||||
prop.getRootApi() + EmsRestConstants.PATH_SEND_MAIL)
|
||||
.resolveTemplate("mode", "async");
|
||||
resource = resource.queryParam(CommonConstants.PROFILE_DB, database)
|
||||
.queryParam("from", "").queryParam("to", emailDbg)
|
||||
.queryParam("subject", mailSubject).queryParam("msgText", htmlMailBody)
|
||||
.queryParam("isHtml", true);
|
||||
|
||||
resource.request().header("Authorization", database + ":" + auth)
|
||||
.async()
|
||||
.post(Entity.json(jsonBody), new InvocationCallback<Response>() {
|
||||
@Override
|
||||
public void completed(Response response) {
|
||||
String value = response.readEntity(String.class);
|
||||
logger.info(response.getStatus() + " - " + value);
|
||||
response.close();
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable throwable) {
|
||||
throwable.printStackTrace();
|
||||
logger.error(throwable);
|
||||
client.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package it.integry.ems.download;
|
||||
|
||||
import it.integry.annotations.PostContextConstruct;
|
||||
import it.integry.ems.download.dto.CachedFileDto;
|
||||
import it.integry.ems.download.dto.DownloadFileDto;
|
||||
import it.integry.ems.looper.service.LooperService;
|
||||
@@ -24,6 +25,13 @@ public class DownloadFileHandlerService {
|
||||
|
||||
private final HashMap<String, CachedFileDto> mFileMap = new HashMap<>();
|
||||
|
||||
@PostContextConstruct
|
||||
public void init() {
|
||||
looperService.add(() -> {
|
||||
UtilityFile.cleanDirectory(getTempPath(), 1, "");
|
||||
}, 60 * 60 * 1000, DownloadFileHandlerService.class.getName());
|
||||
}
|
||||
|
||||
public DownloadFileDto generateDownloadItem(File file) throws IOException {
|
||||
return generateDownloadItem(file.getName(), FileUtils.readFileToByteArray(file), false);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package it.integry.ems.dto.info;
|
||||
package it.integry.ems.dto;
|
||||
|
||||
|
||||
public class ApplicationInfoDTO {
|
||||
@@ -1,30 +0,0 @@
|
||||
package it.integry.ems.dto;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ArticoloPartitaCommessaDTO extends ArticoloPartitaDTO {
|
||||
|
||||
private String codJcom;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof ArticoloPartitaCommessaDTO)) return false;
|
||||
if (!super.equals(o)) return false;
|
||||
ArticoloPartitaCommessaDTO that = (ArticoloPartitaCommessaDTO) o;
|
||||
return Objects.equals(getCodJcom(), that.getCodJcom());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(super.hashCode(), getCodJcom());
|
||||
}
|
||||
|
||||
public String getCodJcom() {
|
||||
return codJcom;
|
||||
}
|
||||
|
||||
public ArticoloPartitaCommessaDTO setCodJcom(String codJcom) {
|
||||
this.codJcom = codJcom;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package it.integry.ems.dto.info;
|
||||
package it.integry.ems.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package it.integry.ems.dto.info;
|
||||
package it.integry.ems.dto;
|
||||
|
||||
public class DatabaseInfoDTO {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package it.integry.ems.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
|
||||
public class ExtendedStbActivity {
|
||||
@@ -15,9 +14,11 @@ public class ExtendedStbActivity {
|
||||
private String userCreator;
|
||||
private String note;
|
||||
private String activityDescription;
|
||||
private Date dataInsAct;
|
||||
private int priorita;
|
||||
private LocalDateTime alarmTime;
|
||||
private LocalDateTime oraInsAct;
|
||||
private Date alarmDate;
|
||||
private Date alarmTime;
|
||||
private Date oraInsAct;
|
||||
private String activityTypeId;
|
||||
private String parentActivityId;
|
||||
private StbActivityEmailObject emailObject;
|
||||
@@ -115,6 +116,15 @@ public class ExtendedStbActivity {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Date getDataInsAct() {
|
||||
return dataInsAct;
|
||||
}
|
||||
|
||||
public ExtendedStbActivity setDataInsAct(Date dataInsAct) {
|
||||
this.dataInsAct = dataInsAct;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getPriorita() {
|
||||
return priorita;
|
||||
}
|
||||
@@ -124,20 +134,29 @@ public class ExtendedStbActivity {
|
||||
return this;
|
||||
}
|
||||
|
||||
public LocalDateTime getAlarmTime() {
|
||||
public Date getAlarmDate() {
|
||||
return alarmDate;
|
||||
}
|
||||
|
||||
public ExtendedStbActivity setAlarmDate(Date alarmDate) {
|
||||
this.alarmDate = alarmDate;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Date getAlarmTime() {
|
||||
return alarmTime;
|
||||
}
|
||||
|
||||
public ExtendedStbActivity setAlarmTime(LocalDateTime alarmTime) {
|
||||
public ExtendedStbActivity setAlarmTime(Date alarmTime) {
|
||||
this.alarmTime = alarmTime;
|
||||
return this;
|
||||
}
|
||||
|
||||
public LocalDateTime getOraInsAct() {
|
||||
public Date getOraInsAct() {
|
||||
return oraInsAct;
|
||||
}
|
||||
|
||||
public ExtendedStbActivity setOraInsAct(LocalDateTime oraInsAct) {
|
||||
public ExtendedStbActivity setOraInsAct(Date oraInsAct) {
|
||||
this.oraInsAct = oraInsAct;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
package it.integry.ems.dto.info;
|
||||
|
||||
public class PvmInfoDTO {
|
||||
private String phpVersion;
|
||||
private String timezone;
|
||||
private String imagick;
|
||||
private boolean sodiumMissing;
|
||||
private int maxExecutionTime;
|
||||
private boolean magicQuotesGpc;
|
||||
private String defaultCharset;
|
||||
private String memoryLimit;
|
||||
private String postMaxSize;
|
||||
private String uploadMaxSize;
|
||||
private int maxInputVars;
|
||||
|
||||
public String getPhpVersion() {
|
||||
return phpVersion;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setPhpVersion(String phpVersion) {
|
||||
this.phpVersion = phpVersion;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getTimezone() {
|
||||
return timezone;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setTimezone(String timezone) {
|
||||
this.timezone = timezone;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getImagick() {
|
||||
return imagick;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setImagick(String imagick) {
|
||||
this.imagick = imagick;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isSodiumMissing() {
|
||||
return sodiumMissing;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setSodiumMissing(boolean sodiumMissing) {
|
||||
this.sodiumMissing = sodiumMissing;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getMaxExecutionTime() {
|
||||
return maxExecutionTime;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setMaxExecutionTime(int maxExecutionTime) {
|
||||
this.maxExecutionTime = maxExecutionTime;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isMagicQuotesGpc() {
|
||||
return magicQuotesGpc;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setMagicQuotesGpc(boolean magicQuotesGpc) {
|
||||
this.magicQuotesGpc = magicQuotesGpc;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDefaultCharset() {
|
||||
return defaultCharset;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setDefaultCharset(String defaultCharset) {
|
||||
this.defaultCharset = defaultCharset;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getMemoryLimit() {
|
||||
return memoryLimit;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setMemoryLimit(String memoryLimit) {
|
||||
this.memoryLimit = memoryLimit;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPostMaxSize() {
|
||||
return postMaxSize;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setPostMaxSize(String postMaxSize) {
|
||||
this.postMaxSize = postMaxSize;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUploadMaxSize() {
|
||||
return uploadMaxSize;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setUploadMaxSize(String uploadMaxSize) {
|
||||
this.uploadMaxSize = uploadMaxSize;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getMaxInputVars() {
|
||||
return maxInputVars;
|
||||
}
|
||||
|
||||
public PvmInfoDTO setMaxInputVars(int maxInputVars) {
|
||||
this.maxInputVars = maxInputVars;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package it.integry.ems.dynamic_cache;
|
||||
import it.integry.ems.expansion.RunnableArgsWithReturn;
|
||||
import it.integry.ems.expansion.RunnableWithReturn;
|
||||
import it.integry.ems.looper.service.LooperService;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionModel;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
@@ -51,11 +51,11 @@ public class DynamicCacheService {
|
||||
List<String> finalDbNames = dbNames.stream().map(String::toLowerCase).collect(Collectors.toList());
|
||||
RunnableWithReturn<Object> internalRefreshAction = () -> {
|
||||
|
||||
Map<String, List<AvailableConnectionModel>> databases = settingsModel.getAvailableConnections()
|
||||
Map<String, List<AvailableConnectionsModel>> databases = settingsModel.getAvailableConnections()
|
||||
.stream()
|
||||
.filter(AvailableConnectionModel::getInternalDb)
|
||||
.filter(AvailableConnectionsModel::getInternalDb)
|
||||
.filter(x -> finalDbNames.contains(x.getDbName().toLowerCase()))
|
||||
.collect(Collectors.groupingBy(AvailableConnectionModel::getDbName));
|
||||
.collect(Collectors.groupingBy(AvailableConnectionsModel::getDbName));
|
||||
|
||||
final HashMap<String, T> cachedDataByDB = new HashMap<>();
|
||||
|
||||
@@ -83,11 +83,11 @@ public class DynamicCacheService {
|
||||
|
||||
RunnableWithReturn<Object> refreshAction = () -> {
|
||||
|
||||
Map<String, List<AvailableConnectionModel>> databases = settingsModel.getAvailableConnections()
|
||||
Map<String, List<AvailableConnectionsModel>> databases = settingsModel.getAvailableConnections()
|
||||
.stream()
|
||||
.filter(AvailableConnectionModel::getInternalDb)
|
||||
.filter(AvailableConnectionsModel::getInternalDb)
|
||||
.filter(x -> finalDbNames.contains(x.getDbName().toLowerCase()))
|
||||
.collect(Collectors.groupingBy(AvailableConnectionModel::getDbName));
|
||||
.collect(Collectors.groupingBy(AvailableConnectionsModel::getDbName));
|
||||
|
||||
final HashMap<String, List<? extends EntityBase>> cachedEntitiesByDB = new HashMap<>();
|
||||
|
||||
@@ -138,11 +138,11 @@ public class DynamicCacheService {
|
||||
|
||||
RunnableWithReturn<Object> refreshAction = () -> {
|
||||
|
||||
Map<String, List<AvailableConnectionModel>> databases = settingsModel.getAvailableConnections()
|
||||
Map<String, List<AvailableConnectionsModel>> databases = settingsModel.getAvailableConnections()
|
||||
.stream()
|
||||
.filter(AvailableConnectionModel::getInternalDb)
|
||||
.filter(AvailableConnectionsModel::getInternalDb)
|
||||
.filter(x -> finalDbNames.contains(x.getDbName().toLowerCase()))
|
||||
.collect(Collectors.groupingBy(AvailableConnectionModel::getDbName));
|
||||
.collect(Collectors.groupingBy(AvailableConnectionsModel::getDbName));
|
||||
|
||||
final HashMap<String, List<?>> cacheQueryByDB = new HashMap<>();
|
||||
|
||||
|
||||
@@ -1,371 +0,0 @@
|
||||
package it.integry.ems.entity_logger.db_schema_manager.component;
|
||||
|
||||
import it.integry.ems.entity_logger.db_schema_manager.dto.ForeignKeyDependency;
|
||||
import it.integry.ems.entity_logger.db_schema_manager.dto.ForeignKeyDependencyReport;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class SQLServerForeignKeyManager {
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
private Connection connection;
|
||||
private boolean disableForeignKeyChecks;
|
||||
|
||||
public SQLServerForeignKeyManager(Connection connection) {
|
||||
this(connection, false);
|
||||
}
|
||||
|
||||
public SQLServerForeignKeyManager(Connection connection, boolean disableForeignKeyChecks) {
|
||||
this.connection = connection;
|
||||
this.disableForeignKeyChecks = disableForeignKeyChecks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggiorna una foreign key e tutte le sue dipendenze in un'unica transazione
|
||||
*
|
||||
* @param tableName Nome della tabella principale
|
||||
* @param columnName Nome della colonna che contiene la chiave primaria
|
||||
* @param oldValue Valore attuale della chiave
|
||||
* @param newValue Nuovo valore della chiave
|
||||
* @return true se l'operazione è completata con successo
|
||||
* @throws SQLException in caso di errore
|
||||
*/
|
||||
public <T> boolean updateForeignKeyWithDependencies(String tableName, String columnName,
|
||||
T oldValue, T newValue) throws SQLException {
|
||||
|
||||
boolean originalAutoCommit = connection.getAutoCommit();
|
||||
List<String> disabledConstraints = new ArrayList<>();
|
||||
|
||||
try {
|
||||
// Disabilita auto-commit per gestire la transazione manualmente
|
||||
connection.setAutoCommit(false);
|
||||
|
||||
logger.info(String.format("Inizio aggiornamento FK: %s.%s da %s a %s",
|
||||
tableName, columnName, oldValue, newValue));
|
||||
|
||||
// 1. Disabilita i vincoli foreign key se richiesto
|
||||
if (disableForeignKeyChecks) {
|
||||
disabledConstraints = disableForeignKeyConstraints(tableName, columnName);
|
||||
logger.info(String.format("Disabilitati %d vincoli foreign key", disabledConstraints.size()));
|
||||
}
|
||||
|
||||
// 2. Trova tutte le dipendenze
|
||||
List<ForeignKeyDependency> dependencies = findAllDependencies(tableName, columnName);
|
||||
logger.info(String.format("Trovate %d dipendenze da aggiornare", dependencies.size()));
|
||||
|
||||
if (disableForeignKeyChecks) {
|
||||
// Se i vincoli sono disabilitati, possiamo aggiornare in qualsiasi ordine
|
||||
// Aggiorniamo prima la tabella principale per semplicità
|
||||
updateMainTable(tableName, columnName, oldValue, newValue);
|
||||
|
||||
// Poi aggiorniamo tutte le tabelle dipendenti
|
||||
for (ForeignKeyDependency dependency : dependencies) {
|
||||
updateDependentTable(dependency, oldValue, newValue);
|
||||
}
|
||||
} else {
|
||||
// Ordine normale: prima le dipendenti, poi la principale
|
||||
for (ForeignKeyDependency dependency : dependencies) {
|
||||
updateDependentTable(dependency, oldValue, newValue);
|
||||
}
|
||||
updateMainTable(tableName, columnName, oldValue, newValue);
|
||||
}
|
||||
|
||||
// 3. Riabilita i vincoli foreign key se erano stati disabilitati
|
||||
if (disableForeignKeyChecks && !disabledConstraints.isEmpty()) {
|
||||
enableForeignKeyConstraints(disabledConstraints);
|
||||
logger.info("Vincoli foreign key riabilitati");
|
||||
|
||||
// 4. Verifica l'integrità dei dati dopo aver riabilitato i vincoli
|
||||
if (!checkConstraintIntegrity(disabledConstraints)) {
|
||||
throw new SQLException("Violazione dell'integrità referenziale dopo l'aggiornamento");
|
||||
}
|
||||
}
|
||||
|
||||
// Commit della transazione
|
||||
connection.commit();
|
||||
logger.info("Aggiornamento completato con successo");
|
||||
|
||||
return true;
|
||||
|
||||
} catch (SQLException e) {
|
||||
// Rollback in caso di errore
|
||||
try {
|
||||
connection.rollback();
|
||||
logger.error("Errore durante l'aggiornamento, rollback eseguito: " + e.getMessage(), e);
|
||||
|
||||
// Se i vincoli erano stati disabilitati, prova a riabilitarli anche dopo il rollback
|
||||
if (disableForeignKeyChecks && !disabledConstraints.isEmpty()) {
|
||||
try {
|
||||
enableForeignKeyConstraints(disabledConstraints);
|
||||
logger.info("Vincoli foreign key riabilitati dopo rollback");
|
||||
} catch (SQLException enableEx) {
|
||||
logger.error("ATTENZIONE: Impossibile riabilitare i vincoli dopo rollback: " + enableEx.getMessage(), enableEx);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (SQLException rollbackEx) {
|
||||
logger.error("Errore durante il rollback: " + rollbackEx.getMessage(), rollbackEx);
|
||||
}
|
||||
throw e;
|
||||
|
||||
} finally {
|
||||
// Ripristina l'auto-commit originale
|
||||
connection.setAutoCommit(originalAutoCommit);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disabilita tutti i vincoli foreign key che referenziano la tabella/colonna specificata
|
||||
*/
|
||||
private List<String> disableForeignKeyConstraints(String tableName, String columnName) throws SQLException {
|
||||
List<String> disabledConstraints = new ArrayList<>();
|
||||
List<ForeignKeyDependency> dependencies = findAllDependencies(tableName, columnName);
|
||||
|
||||
for (ForeignKeyDependency dependency : dependencies) {
|
||||
String disableQuery = String.format(
|
||||
"ALTER TABLE [%s].[%s] NOCHECK CONSTRAINT [%s]",
|
||||
dependency.getDependentSchema(),
|
||||
dependency.getDependentTable(),
|
||||
dependency.getConstraintName()
|
||||
);
|
||||
|
||||
try (Statement stmt = connection.createStatement()) {
|
||||
stmt.execute(disableQuery);
|
||||
disabledConstraints.add(String.format("%s.%s.%s",
|
||||
dependency.getDependentSchema(),
|
||||
dependency.getDependentTable(),
|
||||
dependency.getConstraintName()));
|
||||
|
||||
logger.trace(String.format("Disabilitato vincolo: %s", dependency.getConstraintName()));
|
||||
}
|
||||
}
|
||||
|
||||
return disabledConstraints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Riabilita i vincoli foreign key precedentemente disabilitati
|
||||
*/
|
||||
private void enableForeignKeyConstraints(List<String> constraintIdentifiers) throws SQLException {
|
||||
for (String constraintId : constraintIdentifiers) {
|
||||
String[] parts = constraintId.split("\\.");
|
||||
if (parts.length != 3) {
|
||||
logger.warn("Formato constraint identifier non valido: " + constraintId);
|
||||
continue;
|
||||
}
|
||||
|
||||
String schema = parts[0];
|
||||
String table = parts[1];
|
||||
String constraint = parts[2];
|
||||
|
||||
String enableQuery = String.format(
|
||||
"ALTER TABLE [%s].[%s] CHECK CONSTRAINT [%s]",
|
||||
schema, table, constraint
|
||||
);
|
||||
|
||||
try (Statement stmt = connection.createStatement()) {
|
||||
stmt.execute(enableQuery);
|
||||
logger.trace(String.format("Riabilitato vincolo: %s", constraint));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifica l'integrità dei vincoli dopo averli riabilitati
|
||||
*/
|
||||
private boolean checkConstraintIntegrity(List<String> constraintIdentifiers) throws SQLException {
|
||||
boolean allValid = true;
|
||||
|
||||
for (String constraintId : constraintIdentifiers) {
|
||||
String[] parts = constraintId.split("\\.");
|
||||
if (parts.length != 3) continue;
|
||||
|
||||
String schema = parts[0];
|
||||
String table = parts[1];
|
||||
String constraint = parts[2];
|
||||
|
||||
// Verifica se ci sono violazioni del vincolo
|
||||
String checkQuery = String.format("SELECT COUNT(*) as violations\n" +
|
||||
" FROM [%s].[%s] child\n" +
|
||||
" LEFT JOIN (\n" +
|
||||
" SELECT fkc.referenced_object_id, fkc.referenced_column_id,\n" +
|
||||
" fkc.parent_object_id, fkc.parent_column_id\n" +
|
||||
" FROM sys.foreign_key_columns fkc\n" +
|
||||
" INNER JOIN sys.foreign_keys fk ON fkc.constraint_object_id = fk.object_id\n" +
|
||||
" WHERE fk.name = '%s'\n" +
|
||||
" ) fk_info ON 1=1\n" +
|
||||
" LEFT JOIN sys.tables ref_table ON fk_info.referenced_object_id = ref_table.object_id\n" +
|
||||
" LEFT JOIN sys.schemas ref_schema ON ref_table.schema_id = ref_schema.schema_id\n" +
|
||||
" WHERE child.[%s] IS NOT NULL\n" +
|
||||
" AND NOT EXISTS (\n" +
|
||||
" SELECT 1 FROM [%s].[%s] parent\n" +
|
||||
" WHERE parent.[%s] = child.[%s]\n" +
|
||||
" )", schema, table, constraint,
|
||||
"temp_col", // Questo dovrebbe essere sostituito con la colonna effettiva
|
||||
"temp_schema", "temp_table", "temp_parent_col", "temp_col");
|
||||
|
||||
// Query semplificata per il check di integrità
|
||||
String simpleCheckQuery = String.format(
|
||||
"DBCC CHECKCONSTRAINTS('[%s].[%s].[%s]') WITH ALL_CONSTRAINTS",
|
||||
schema, table, constraint
|
||||
);
|
||||
|
||||
try (Statement stmt = connection.createStatement()) {
|
||||
try (ResultSet rs = stmt.executeQuery("SELECT 1")) {
|
||||
// Se la query non solleva eccezioni, il vincolo è valido
|
||||
logger.trace(String.format("Vincolo %s superato controllo integrità", constraint));
|
||||
} catch (SQLException e) {
|
||||
logger.warn(String.format("Violazione integrità per vincolo %s: %s", constraint, e.getMessage()));
|
||||
allValid = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return allValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trova tutte le dipendenze foreign key di una tabella/colonna
|
||||
*/
|
||||
private List<ForeignKeyDependency> findAllDependencies(String tableName, String columnName) throws SQLException {
|
||||
List<ForeignKeyDependency> dependencies = new ArrayList<>();
|
||||
|
||||
String query = "SELECT \n" +
|
||||
" fk.name AS constraint_name,\n" +
|
||||
" OBJECT_SCHEMA_NAME(fk.parent_object_id) AS dependent_schema,\n" +
|
||||
" OBJECT_NAME(fk.parent_object_id) AS dependent_table,\n" +
|
||||
" COL_NAME(fkc.parent_object_id, fkc.parent_column_id) AS dependent_column,\n" +
|
||||
" OBJECT_SCHEMA_NAME(fk.referenced_object_id) AS referenced_schema,\n" +
|
||||
" OBJECT_NAME(fk.referenced_object_id) AS referenced_table,\n" +
|
||||
" COL_NAME(fkc.referenced_object_id, fkc.referenced_column_id) AS referenced_column\n" +
|
||||
" FROM sys.foreign_keys fk\n" +
|
||||
" INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id\n" +
|
||||
" WHERE OBJECT_NAME(fk.referenced_object_id) = ?\n" +
|
||||
" AND COL_NAME(fkc.referenced_object_id, fkc.referenced_column_id) = ?\n" +
|
||||
" ORDER BY dependent_table";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(query)) {
|
||||
stmt.setString(1, tableName);
|
||||
stmt.setString(2, columnName);
|
||||
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
ForeignKeyDependency dependency = new ForeignKeyDependency(
|
||||
rs.getString("constraint_name"),
|
||||
rs.getString("dependent_schema"),
|
||||
rs.getString("dependent_table"),
|
||||
rs.getString("dependent_column"),
|
||||
rs.getString("referenced_schema"),
|
||||
rs.getString("referenced_table"),
|
||||
rs.getString("referenced_column")
|
||||
);
|
||||
dependencies.add(dependency);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dependencies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggiorna una tabella dipendente
|
||||
*/
|
||||
private void updateDependentTable(ForeignKeyDependency dependency, Object oldValue, Object newValue) throws SQLException {
|
||||
String updateQuery = String.format(
|
||||
"UPDATE [%s].[%s] SET [%s] = ? WHERE [%s] = ?",
|
||||
dependency.getDependentSchema(),
|
||||
dependency.getDependentTable(),
|
||||
dependency.getDependentColumn(),
|
||||
dependency.getDependentColumn()
|
||||
);
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(updateQuery)) {
|
||||
stmt.setObject(1, newValue);
|
||||
stmt.setObject(2, oldValue);
|
||||
|
||||
int rowsAffected = stmt.executeUpdate();
|
||||
logger.info(String.format("Aggiornate %d righe in %s.%s",
|
||||
rowsAffected, dependency.getDependentTable(), dependency.getDependentColumn()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggiorna la tabella principale
|
||||
*/
|
||||
private void updateMainTable(String tableName, String columnName, Object oldValue, Object newValue) throws SQLException {
|
||||
String updateQuery = String.format("UPDATE [%s] SET [%s] = ? WHERE [%s] = ?",
|
||||
tableName, columnName, columnName);
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(updateQuery)) {
|
||||
stmt.setObject(1, newValue);
|
||||
stmt.setObject(2, oldValue);
|
||||
|
||||
int rowsAffected = stmt.executeUpdate();
|
||||
logger.info(String.format("Aggiornate %d righe nella tabella principale %s.%s",
|
||||
rowsAffected, tableName, columnName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifica se un valore esiste già come chiave primaria
|
||||
*/
|
||||
public boolean checkIfValueExists(String tableName, String columnName, Object value) throws SQLException {
|
||||
String query = String.format("SELECT COUNT(*) FROM [%s] WHERE [%s] = ?", tableName, columnName);
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(query)) {
|
||||
stmt.setObject(1, value);
|
||||
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
return rs.getInt(1) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ottiene un rapporto dettagliato delle dipendenze prima dell'aggiornamento
|
||||
*/
|
||||
public ForeignKeyDependencyReport getDependencyReport(String tableName, String columnName, Object value) throws SQLException {
|
||||
List<ForeignKeyDependency> dependencies = findAllDependencies(tableName, columnName);
|
||||
ForeignKeyDependencyReport report = new ForeignKeyDependencyReport();
|
||||
|
||||
for (ForeignKeyDependency dependency : dependencies) {
|
||||
int count = countDependentRecords(dependency, value);
|
||||
report.addDependency(dependency, count);
|
||||
}
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
private int countDependentRecords(ForeignKeyDependency dependency, Object value) throws SQLException {
|
||||
String countQuery = String.format(
|
||||
"SELECT COUNT(*) FROM [%s].[%s] WHERE [%s] = ?",
|
||||
dependency.getDependentSchema(),
|
||||
dependency.getDependentTable(),
|
||||
dependency.getDependentColumn()
|
||||
);
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(countQuery)) {
|
||||
stmt.setObject(1, value);
|
||||
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
return rs.next() ? rs.getInt(1) : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Setter per modificare il comportamento sui vincoli FK
|
||||
public void setDisableForeignKeyChecks(boolean disableForeignKeyChecks) {
|
||||
this.disableForeignKeyChecks = disableForeignKeyChecks;
|
||||
}
|
||||
|
||||
public boolean isDisableForeignKeyChecks() {
|
||||
return disableForeignKeyChecks;
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,6 @@ public class DatabaseTableColumn {
|
||||
private ArrayList<DatabaseForeignKey> foreignKeys;
|
||||
|
||||
public String getColumnName() {
|
||||
if (!columnName.startsWith("[") && columnName.contains(" ")) columnName = "["+columnName +"]";
|
||||
return columnName;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
package it.integry.ems.entity_logger.db_schema_manager.dto;
|
||||
|
||||
public enum DatabaseVersionEnum {
|
||||
|
||||
SQLServer2000((short) 80),
|
||||
SQLServer2005((short) 90),
|
||||
SQLServer2008((short) 100),
|
||||
SQLServer2008R2((short) 105),
|
||||
SQLServer2012((short) 110),
|
||||
SQLServer2014((short) 120),
|
||||
SQLServer2016((short) 130),
|
||||
SQLServer2017((short) 140),
|
||||
SQLServer2019((short) 150),
|
||||
SQLServer2022((short) 160);
|
||||
|
||||
private short code;
|
||||
|
||||
private DatabaseVersionEnum(short code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public static DatabaseVersionEnum fromCode(short code) {
|
||||
for (DatabaseVersionEnum b : DatabaseVersionEnum.values()) {
|
||||
if (b.code == code) return b;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return this.code;
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package it.integry.ems.entity_logger.db_schema_manager.dto;
|
||||
|
||||
public class ForeignKeyDependency {
|
||||
private final String constraintName;
|
||||
private final String dependentSchema;
|
||||
private final String dependentTable;
|
||||
private final String dependentColumn;
|
||||
private final String referencedSchema;
|
||||
private final String referencedTable;
|
||||
private final String referencedColumn;
|
||||
|
||||
public ForeignKeyDependency(String constraintName, String dependentSchema,
|
||||
String dependentTable, String dependentColumn,
|
||||
String referencedSchema, String referencedTable,
|
||||
String referencedColumn) {
|
||||
this.constraintName = constraintName;
|
||||
this.dependentSchema = dependentSchema;
|
||||
this.dependentTable = dependentTable;
|
||||
this.dependentColumn = dependentColumn;
|
||||
this.referencedSchema = referencedSchema;
|
||||
this.referencedTable = referencedTable;
|
||||
this.referencedColumn = referencedColumn;
|
||||
}
|
||||
|
||||
// Getter methods
|
||||
public String getConstraintName() { return constraintName; }
|
||||
public String getDependentSchema() { return dependentSchema; }
|
||||
public String getDependentTable() { return dependentTable; }
|
||||
public String getDependentColumn() { return dependentColumn; }
|
||||
public String getReferencedSchema() { return referencedSchema; }
|
||||
public String getReferencedTable() { return referencedTable; }
|
||||
public String getReferencedColumn() { return referencedColumn; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s.%s.%s -> %s.%s.%s",
|
||||
dependentSchema, dependentTable, dependentColumn,
|
||||
referencedSchema, referencedTable, referencedColumn);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package it.integry.ems.entity_logger.db_schema_manager.dto;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ForeignKeyDependencyReport {
|
||||
private final Map<ForeignKeyDependency, Integer> dependencyCount = new HashMap<>();
|
||||
|
||||
public void addDependency(ForeignKeyDependency dependency, int count) {
|
||||
dependencyCount.put(dependency, count);
|
||||
}
|
||||
|
||||
public Map<ForeignKeyDependency, Integer> getDependencies() {
|
||||
return new HashMap<>(dependencyCount);
|
||||
}
|
||||
|
||||
public int getTotalRecordsAffected() {
|
||||
return dependencyCount.values().stream().mapToInt(Integer::intValue).sum();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("=== RAPPORTO DIPENDENZE ===\n");
|
||||
|
||||
for (Map.Entry<ForeignKeyDependency, Integer> entry : dependencyCount.entrySet()) {
|
||||
sb.append(String.format("Tabella: %s.%s, Colonna: %s, Record da aggiornare: %d\n",
|
||||
entry.getKey().getDependentSchema(),
|
||||
entry.getKey().getDependentTable(),
|
||||
entry.getKey().getDependentColumn(),
|
||||
entry.getValue()));
|
||||
}
|
||||
|
||||
sb.append(String.format("TOTALE RECORD DA AGGIORNARE: %d\n", getTotalRecordsAffected()));
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import it.integry.annotations.PostContextConstruct;
|
||||
import it.integry.ems.entity_logger.db_schema_manager.component.SQLServerDBSchemaManager;
|
||||
import it.integry.ems.entity_logger.db_schema_manager.dto.*;
|
||||
import it.integry.ems.looper.service.LooperService;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionModel;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.settings.SettingsController;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
@@ -19,7 +19,6 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
@@ -27,7 +26,6 @@ import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
public class EntityLoggerComponent {
|
||||
@@ -46,8 +44,10 @@ public class EntityLoggerComponent {
|
||||
@PostContextConstruct(priority = 10)
|
||||
private void init() {
|
||||
try {
|
||||
if (!UtilityDebug.isDebugExecution()) {
|
||||
if (!UtilityDebug.isDebugExecution() || UtilityDebug.isIntegryServer()) {
|
||||
this.syncDBScheme();
|
||||
|
||||
looperService.add(this::deleteOldlogs, 12 * 60 * 60 * 1000, EntityLoggerComponent.class.getName()); //Ogni 12 ore
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.error(getClass().getName(), ex);
|
||||
@@ -57,7 +57,7 @@ public class EntityLoggerComponent {
|
||||
|
||||
private void syncDBScheme() throws Exception {
|
||||
|
||||
AvailableConnectionModel connectionsModel = settingsModel.getDefaultConnectionModel();
|
||||
AvailableConnectionsModel connectionsModel = settingsModel.getDefaultConnectionModel();
|
||||
|
||||
if (connectionsModel == null) {
|
||||
throw new Exception("Impossibile ricavare la default connection");
|
||||
@@ -107,7 +107,7 @@ public class EntityLoggerComponent {
|
||||
}
|
||||
|
||||
if (settingsModel.getAvailableConnections().stream().noneMatch(x -> x.getDbName().equalsIgnoreCase(destDBName))) {
|
||||
settingsModel.addAvailableConnection(new AvailableConnectionModel()
|
||||
settingsModel.addAvailableConnection(new AvailableConnectionsModel()
|
||||
.setInternalDb(false)
|
||||
.setHost(dbHost)
|
||||
.setUsername(dbUsername)
|
||||
@@ -204,53 +204,65 @@ public class EntityLoggerComponent {
|
||||
destDBSchema.close();
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 12, timeUnit = TimeUnit.HOURS, zone = "Europe/Rome")
|
||||
|
||||
private void deleteOldlogs() {
|
||||
if (UtilityDebug.isDebugExecution())
|
||||
return;
|
||||
MultiDBTransactionManager sourceMultiDB = null, historyMultiDB = null;
|
||||
|
||||
try {
|
||||
List<AvailableConnectionModel> connectionsModels = settingsModel.getAvailableConnectionsWithoutDuplicatedProfiles(true);
|
||||
List<AvailableConnectionsModel> connectionsModels = settingsModel.getAvailableConnections();
|
||||
|
||||
connectionsModels = Stream.of(connectionsModels)
|
||||
.filter(AvailableConnectionsModel::getInternalDb)
|
||||
.toList();
|
||||
|
||||
|
||||
String historyProfileDB = settingsController.getHistoryProfileDb();
|
||||
historyMultiDB = new MultiDBTransactionManager(historyProfileDB);
|
||||
|
||||
try (MultiDBTransactionManager historyMultiDB = new MultiDBTransactionManager(historyProfileDB)) {
|
||||
for (AvailableConnectionsModel sourceConnectionModel : connectionsModels) {
|
||||
String sql = "SELECT * FROM stb_log_entity_setup" +
|
||||
" WHERE entity_name <> " + UtilityDB.valueToString(StbLogEntitySetup.ENTITY);
|
||||
|
||||
for (AvailableConnectionModel sourceConnectionModel : connectionsModels) {
|
||||
String sql = "SELECT * FROM stb_log_entity_setup" +
|
||||
" WHERE entity_name <> " + UtilityDB.valueToString(StbLogEntitySetup.ENTITY);
|
||||
sourceMultiDB = new MultiDBTransactionManager(sourceConnectionModel.getProfileName());
|
||||
List<HashMap<String, Object>> result = UtilityDB.executeSimpleQuery(sourceMultiDB.getPrimaryConnection(), sql);
|
||||
sourceMultiDB.closeAll();
|
||||
|
||||
List<HashMap<String, Object>> result = null;
|
||||
for (HashMap<String, Object> stbLogEntitySetup : result) {
|
||||
String tableName = UtilityHashMap.getValueIfExists(stbLogEntitySetup, "entity_name");
|
||||
int logDays = UtilityHashMap.getValueIfExists(stbLogEntitySetup, "log_days");
|
||||
|
||||
try (MultiDBTransactionManager sourceMultiDB = new MultiDBTransactionManager(sourceConnectionModel.getProfileName())) {
|
||||
result = UtilityDB.executeSimpleQuery(sourceMultiDB.getPrimaryConnection(), sql);
|
||||
}
|
||||
int i = 0;
|
||||
try {
|
||||
do {
|
||||
String checkSql = String.format("DELETE TOP ( 1000 ) FROM %s WHERE log_created_at < DATEADD(DAY, %d, GETDATE()) AND log_created_profile = %s",
|
||||
tableName, -1 * logDays, UtilityDB.valueToString(sourceConnectionModel.getProfileName()));
|
||||
|
||||
for (HashMap<String, Object> stbLogEntitySetup : result) {
|
||||
String tableName = UtilityHashMap.getValueIfExists(stbLogEntitySetup, "entity_name");
|
||||
int logDays = UtilityHashMap.getValueIfExists(stbLogEntitySetup, "log_days");
|
||||
PreparedStatement ps = historyMultiDB.prepareStatement(checkSql);
|
||||
i = ps.executeUpdate();
|
||||
ps.close();
|
||||
historyMultiDB.commitAll();
|
||||
} while (i > 0);
|
||||
|
||||
int i = 0;
|
||||
try {
|
||||
do {
|
||||
String checkSql = String.format("DELETE TOP ( 1000 ) FROM %s WHERE log_created_at < DATEADD(DAY, %d, GETDATE()) AND log_created_profile = %s",
|
||||
tableName, -1 * logDays, UtilityDB.valueToString(sourceConnectionModel.getProfileName()));
|
||||
|
||||
PreparedStatement ps = historyMultiDB.prepareStatement(checkSql);
|
||||
i = ps.executeUpdate();
|
||||
ps.close();
|
||||
historyMultiDB.commitAll();
|
||||
} while (i > 0);
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("EntityLogDeleter", "Errore durante la cancellazione dei vecchi record da " + tableName);
|
||||
logger.error("EntityLogDeleter", ex);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.error("EntityLogDeleter", "Errore durante la cancellazione dei vecchi record da " + tableName);
|
||||
logger.error("EntityLogDeleter", ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
historyMultiDB.closeAll();
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("EntityLoggerComponent.deleteOldlogs", ex);
|
||||
|
||||
try {
|
||||
if (sourceMultiDB != null) sourceMultiDB.closeAll();
|
||||
if (historyMultiDB != null) historyMultiDB.closeAll();
|
||||
} catch (Exception e) {
|
||||
logger.error("EntityLoggerComponent.deleteOldlogs", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
package it.integry.ems.exception;
|
||||
|
||||
public class DistributoreDatabaseNotPresentException extends Exception {
|
||||
|
||||
public DistributoreDatabaseNotPresentException() {
|
||||
super("Distributore database not present yet");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package it.integry.ems.expansion;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Observable;
|
||||
import java.util.Observer;
|
||||
|
||||
public class ObservableArrayList<T> extends Observable {
|
||||
|
||||
@@ -119,16 +122,4 @@ public class ObservableArrayList<T> extends Observable {
|
||||
notifyObservers();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof ObservableArrayList)) return false;
|
||||
ObservableArrayList<?> that = (ObservableArrayList<?>) o;
|
||||
return Objects.equals(value, that.value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package it.integry.ems.expansion;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Observable;
|
||||
|
||||
public class ObservableField<T> extends Observable {
|
||||
@@ -35,16 +34,4 @@ public class ObservableField<T> extends Observable {
|
||||
|
||||
super.addObserver((o, arg) -> observerCallback.run());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof ObservableField)) return false;
|
||||
ObservableField<?> that = (ObservableField<?>) o;
|
||||
return Objects.equals(value, that.value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(value);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package it.integry.ems.expansion;
|
||||
|
||||
public interface RunnableArgsReturnThrowable<T> {
|
||||
|
||||
T run() throws Exception;
|
||||
|
||||
}
|
||||
@@ -2,6 +2,6 @@ package it.integry.ems.expansion;
|
||||
|
||||
public interface RunnableArgsThrowable<T> {
|
||||
|
||||
void run(T data) throws Exception;
|
||||
T run() throws Exception;
|
||||
|
||||
}
|
||||
|
||||
@@ -174,7 +174,7 @@ public abstract class BaseEntityExporter implements IEntityExporter {
|
||||
.map(x -> (FileItem) x)
|
||||
.toList();
|
||||
|
||||
String pathFile = UtilityDirs.getDirectoryExport(multiDBTransactionManager.getPrimaryConnection().getDbName(), type, format).getAbsolutePath();
|
||||
String pathFile = UtilityDirs.getDirectoryExport(multiDBTransactionManager.getPrimaryDatasource().getDbName(), type, format).getAbsolutePath();
|
||||
|
||||
for (FileItem file : files) {
|
||||
File tempFile = new File(pathFile + File.separator + file.getFileName());
|
||||
@@ -369,7 +369,7 @@ public abstract class BaseEntityExporter implements IEntityExporter {
|
||||
entityExportResponse.setMessageContent("Messaggio creato automaticamente: " + "INVIO " + type + " formato " + format);
|
||||
}
|
||||
|
||||
fileSharerSettings = MailService.readParameter(multiDBTransactionManager.getPrimaryConnection(), null);
|
||||
fileSharerSettings = MailService.readParameter(multiDBTransactionManager, null);
|
||||
((EmailFileSharerSettings) fileSharerSettings)
|
||||
.withSubject(entityExportResponse.getMessageSubject())
|
||||
.withTextMessage(entityExportResponse.getMessageContent())
|
||||
@@ -426,7 +426,7 @@ public abstract class BaseEntityExporter implements IEntityExporter {
|
||||
|
||||
try {
|
||||
MailService mailService = ContextLoader.getCurrentWebApplicationContext().getBean(MailService.class);
|
||||
mailService.sendInfoMail(multiDBTransactionManager.getPrimaryConnection(), notificationEmail,
|
||||
mailService.sendInfoMail(multiDBTransactionManager, notificationEmail,
|
||||
String.format("Esportazione di %s - %s", getType(), getFormat()),
|
||||
String.format("come da accordi, l'esportazione %s - %s è stata completata.", getType(), getFormat()));
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import it.integry.ems.response.FileItem;
|
||||
import it.integry.ems.service.EntityProcessor;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems_model.entity.WtbUsersInfo;
|
||||
import it.integry.ems_model.service.SetupGest;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityResultSet;
|
||||
@@ -28,13 +27,8 @@ public class ExportFromQuery {
|
||||
@Autowired
|
||||
private EntityProcessor entityProcessor;
|
||||
|
||||
@Autowired
|
||||
private SetupGest setupGest;
|
||||
|
||||
public EntityExportResponse export (String userName, String type, String format, String whereCond) throws Exception {
|
||||
|
||||
String query = setupGest.getExportSetup(multiDBTransactionManager.getPrimaryConnection(), type, format, "QUERY");
|
||||
|
||||
WtbUsersInfo wtbUsersInfo =
|
||||
new WtbUsersInfo()
|
||||
.setUserName(userName)
|
||||
@@ -44,20 +38,18 @@ public class ExportFromQuery {
|
||||
|
||||
entityProcessor.processEntity(wtbUsersInfo, multiDBTransactionManager);
|
||||
|
||||
if (UtilityString.isNullOrEmpty(wtbUsersInfo.getQueryCustom()) && UtilityString.isNullOrEmpty(query))
|
||||
String queryCustom = wtbUsersInfo.getQueryCustom();
|
||||
|
||||
if (UtilityString.isNullOrEmpty(queryCustom))
|
||||
throw new Exception(
|
||||
String.format(
|
||||
"Query non configurata per l'utente %s tipo %s formato %s o per il formato.",
|
||||
"Query non configurata per l'utente %s tipo %s formato %s",
|
||||
userName, type, format));
|
||||
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(wtbUsersInfo.getQueryCustom())) {
|
||||
query = wtbUsersInfo.getQueryCustom();
|
||||
}
|
||||
query = UtilityDB.addwhereCond(query, whereCond, true);
|
||||
queryCustom = UtilityDB.addwhereCond(queryCustom, whereCond, true);
|
||||
PreparedStatement stm = multiDBTransactionManager
|
||||
.getPrimaryConnection()
|
||||
.prepareStatement(query,
|
||||
.prepareStatement(queryCustom,
|
||||
ResultSet.TYPE_SCROLL_INSENSITIVE,
|
||||
ResultSet.CONCUR_READ_ONLY);
|
||||
|
||||
|
||||
@@ -19,8 +19,7 @@ public enum EntityExportType {
|
||||
LISTINI_ACQUISTO("LISTINI ACQUISTO"),
|
||||
LISTINI_VENDITA("LISTINI VENDITA"),
|
||||
COLLI("COLLI"),
|
||||
SCADENZE("SCADENZE"),
|
||||
SCONTRINI("SCONTRINI");
|
||||
SCADENZE("SCADENZE");
|
||||
|
||||
private String text;
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
|
||||
import com.fasterxml.jackson.dataformat.csv.CsvSchema.Column;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems_model.ImportExport.Interfaces.IExportFormat;
|
||||
import it.integry.ems_model.ImportExport.Interfaces.IImportFormat;
|
||||
import it.integry.ems_model.annotation.DtoField;
|
||||
@@ -27,8 +28,7 @@ public class CsvMapper<T> {
|
||||
List<Field> declaredFields = Arrays.asList(dtoList.get(0).getClass().getDeclaredFields());
|
||||
|
||||
List<Field> sortedFields = Stream.of(declaredFields)
|
||||
.filter(x -> x.getAnnotation(DtoField.class) != null &&
|
||||
x.getAnnotation(DtoField.class).startPosition() >= 0)
|
||||
.filter(x -> x.getAnnotation(DtoField.class) != null && x.getAnnotation(DtoField.class).startPosition() >= 0)
|
||||
.sortBy(x -> x.getAnnotation(DtoField.class).startPosition())
|
||||
.toList();
|
||||
|
||||
@@ -39,7 +39,7 @@ public class CsvMapper<T> {
|
||||
String header = StringUtils.join(Stream
|
||||
.of(sortedFields).map(
|
||||
x -> x.getName()
|
||||
).toList(), splitChar);
|
||||
).toList(), CommonConstants.TAB);
|
||||
|
||||
return serialize(dtoList, splitChar, header, hasHeader);
|
||||
|
||||
@@ -63,7 +63,7 @@ public class CsvMapper<T> {
|
||||
builder.addColumn(new Column(i, columns[i]));
|
||||
}
|
||||
|
||||
builder.setLineSeparator(System.lineSeparator());
|
||||
builder.setLineSeparator(System.getProperty("line.separator"));
|
||||
CsvSchema schema = builder.build().withoutQuoteChar();
|
||||
|
||||
mapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
|
||||
@@ -73,7 +73,6 @@ public class CsvMapper<T> {
|
||||
public List<T> deserialize(String csv, Class<T> dtoClass, String splitChar) throws Exception {
|
||||
List<T> outputList = null;
|
||||
String[] headers = null;
|
||||
Integer rows = 0;
|
||||
|
||||
String delimiter = UtilityString.identifyLineDelimiter(csv);
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(csv.getBytes());
|
||||
@@ -83,7 +82,6 @@ public class CsvMapper<T> {
|
||||
for (int i = 0; i < byteBuffer.capacity(); i++) {
|
||||
line.append((char) byteBuffer.get());
|
||||
if (line.toString().endsWith(delimiter)) {
|
||||
rows++;
|
||||
if (firstLine) {
|
||||
firstLine = false;
|
||||
headers = line.toString().replace(delimiter, "").split(splitChar);
|
||||
@@ -106,44 +104,37 @@ public class CsvMapper<T> {
|
||||
line = new StringBuilder();
|
||||
continue;
|
||||
}
|
||||
String[] datas = line.toString().replace(delimiter, "").split(splitChar);
|
||||
T bean = (T) dtoClass.newInstance();
|
||||
for (int j = 0; j < datas.length; j++) {
|
||||
String header = headers[j].trim();
|
||||
if (header.compareTo("") != 0) {
|
||||
Field field = map.get(header.toLowerCase());
|
||||
|
||||
try {
|
||||
String[] datas = line.toString().replace(delimiter, "").split(splitChar);
|
||||
T bean = (T) dtoClass.newInstance();
|
||||
for (int j = 0; j < datas.length; j++) {
|
||||
String header = headers[j].trim();
|
||||
if (header.compareTo("") != 0) {
|
||||
Field field = map.get(header.toLowerCase());
|
||||
if (field != null) {
|
||||
|
||||
if (field != null) {
|
||||
DtoField dtoField = field.getAnnotation(DtoField.class);
|
||||
|
||||
DtoField dtoField = field.getAnnotation(DtoField.class);
|
||||
|
||||
field.setAccessible(true);
|
||||
|
||||
Object columnValue;
|
||||
if (field.getGenericType() != String.class && UtilityString.isNullOrEmpty(datas[j].trim())) {
|
||||
columnValue = null;
|
||||
} else {
|
||||
columnValue = datas[j].trim();
|
||||
}
|
||||
|
||||
Object o = SqlFieldHolder.applyConvert(columnValue, field.getGenericType());
|
||||
field.set(bean, o);
|
||||
field.setAccessible(true);
|
||||
|
||||
Object columnValue;
|
||||
if (field.getGenericType() != String.class && UtilityString.isNullOrEmpty(datas[j].trim())) {
|
||||
columnValue = null;
|
||||
} else {
|
||||
columnValue = datas[j].trim();
|
||||
}
|
||||
|
||||
Object o = SqlFieldHolder.applyConvert(columnValue, field.getGenericType());
|
||||
field.set(bean, o);
|
||||
|
||||
}
|
||||
}
|
||||
line = new StringBuilder();
|
||||
if (outputList == null) {
|
||||
outputList = new ArrayList<T>();
|
||||
}
|
||||
outputList.add(bean);
|
||||
|
||||
} catch(Exception e) {
|
||||
throw new Exception("ERRORE DI SINTASSI SU RIGA " + rows);
|
||||
}
|
||||
|
||||
line = new StringBuilder();
|
||||
if (outputList == null) {
|
||||
outputList = new ArrayList<T>();
|
||||
}
|
||||
outputList.add(bean);
|
||||
}
|
||||
}
|
||||
byteBuffer.clear();
|
||||
|
||||
@@ -42,14 +42,14 @@ public class RequestDataDTO {
|
||||
private String password;
|
||||
private boolean includeNulls = false;
|
||||
|
||||
private IntegryApplicationEnum integryApplication;
|
||||
private IntegryApplicationEnum integryApplication = IntegryApplicationEnum.PVM;
|
||||
|
||||
private UserDTO userDTO;
|
||||
|
||||
@PostConstruct
|
||||
public void init() throws IOException, InterruptedException {
|
||||
|
||||
if (request != null && request.getParameter(CommonConstants.PROFILE_DB) != null) {
|
||||
if (request != null && request.getQueryString() != null && request.getQueryString().contains(CommonConstants.PROFILE_DB)) {
|
||||
profileDB = request.getParameter(CommonConstants.PROFILE_DB);
|
||||
} else if (request != null && request.getHeader(CommonConstants.PROFILE_DB) != null) {
|
||||
profileDB = request.getHeader(CommonConstants.PROFILE_DB);
|
||||
@@ -98,12 +98,6 @@ public class RequestDataDTO {
|
||||
.setPassword("sql");
|
||||
}
|
||||
|
||||
public static RequestDataDTO scheduledOperationsMockupData() {
|
||||
return new RequestDataDTO()
|
||||
.setUsername("INTEGRY")
|
||||
.setPassword("INTEGRY");
|
||||
}
|
||||
|
||||
public boolean isValidProfileDB() {
|
||||
return !UtilityString.isNullOrEmpty(profileDB);
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
package it.integry.ems.json;
|
||||
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import it.integry.ems.adapter.*;
|
||||
import it.integry.ems.response.EsitoType;
|
||||
import it.integry.ems.schedule.new_cron_job.controller.AutomatedOperationController;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.base_classes.BaseAutomatedOperationDTO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.Date;
|
||||
|
||||
public class JsonObjectMapperConfig {
|
||||
|
||||
|
||||
public static SimpleModule addDefaultAdapters(SimpleModule module) {
|
||||
module.addSerializer(Date.class, new JsonDateAdapterSerializer());
|
||||
module.addDeserializer(Date.class, new JsonDateAdapterDeserializer());
|
||||
|
||||
module.addSerializer(LocalDate.class, new JsonLocalDateAdapterSerializer());
|
||||
module.addDeserializer(LocalDate.class, new JsonLocalDateAdapterDeserializer());
|
||||
|
||||
module.addSerializer(LocalDateTime.class, new JsonLocalDateTimeAdapterSerializer());
|
||||
module.addDeserializer(LocalDateTime.class, new JsonLocalDateTimeAdapterDeserializer());
|
||||
|
||||
module.addSerializer(LocalTime.class, new JsonLocalTimeAdapterSerializer());
|
||||
module.addDeserializer(LocalTime.class, new JsonLocalTimeAdapterDeserializer());
|
||||
|
||||
module.addSerializer(EsitoType.class, new EsitoSerialize());
|
||||
module.addDeserializer(EsitoType.class, new EsitoDeserialize());
|
||||
|
||||
module.addDeserializer(BigDecimal.class, new BigDecimalDeserialize());
|
||||
module.addDeserializer(Integer.class, new IntegerDeserializer());
|
||||
|
||||
module.addDeserializer(String.class, new StringUnicodeDeserialize());
|
||||
|
||||
module.addDeserializer(Boolean.class, new BooleanDeserializer());
|
||||
|
||||
|
||||
module.addDeserializer(BaseAutomatedOperationDTO.class, new AutomatedOperationController.AutomatedOperationsDeserializer());
|
||||
return module;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
|
||||
@@ -13,6 +12,10 @@ import com.fasterxml.jackson.databind.ser.PropertyFilter;
|
||||
import com.fasterxml.jackson.databind.ser.PropertyWriter;
|
||||
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
|
||||
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
|
||||
import it.integry.ems.adapter.*;
|
||||
import it.integry.ems.response.EsitoType;
|
||||
import it.integry.ems.schedule.new_cron_job.controller.AutomatedOperationController;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.base_classes.BaseAutomatedOperationDTO;
|
||||
import it.integry.ems_model.annotation.EntityChild;
|
||||
import it.integry.ems_model.annotation.PK;
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
@@ -24,7 +27,11 @@ import it.integry.ems_model.types.OperationType;
|
||||
import org.reflections.Reflections;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -34,7 +41,30 @@ public class ResponseJSONObjectMapper extends ObjectMapper {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public SimpleModule addDefaultAdapters(SimpleModule module) {
|
||||
module.addSerializer(Date.class, new JsonDateAdapterSerializer());
|
||||
module.addDeserializer(Date.class, new JsonDateAdapterDeserializer());
|
||||
|
||||
module.addSerializer(LocalDate.class, new JsonLocalDateAdapterSerializer());
|
||||
module.addDeserializer(LocalDate.class, new JsonLocalDateAdapterDeserializer());
|
||||
|
||||
module.addSerializer(LocalDateTime.class, new JsonLocalDateTimeAdapterSerializer());
|
||||
module.addDeserializer(LocalDateTime.class, new JsonLocalDateTimeAdapterDeserializer());
|
||||
|
||||
module.addSerializer(EsitoType.class, new EsitoSerialize());
|
||||
module.addDeserializer(EsitoType.class, new EsitoDeserialize());
|
||||
|
||||
module.addDeserializer(BigDecimal.class, new BigDecimalDeserialize());
|
||||
module.addDeserializer(Integer.class, new IntegerDeserializer());
|
||||
|
||||
module.addDeserializer(String.class, new StringUnicodeDeserialize());
|
||||
|
||||
module.addDeserializer(Boolean.class, new BooleanDeserializer());
|
||||
|
||||
|
||||
module.addDeserializer(BaseAutomatedOperationDTO.class, new AutomatedOperationController.AutomatedOperationsDeserializer());
|
||||
return module;
|
||||
}
|
||||
|
||||
|
||||
public ResponseJSONObjectMapper() {
|
||||
@@ -106,13 +136,11 @@ public class ResponseJSONObjectMapper extends ObjectMapper {
|
||||
|
||||
|
||||
SimpleModule simpleModule = new SimpleModule();
|
||||
JsonObjectMapperConfig.addDefaultAdapters(simpleModule);
|
||||
simpleModule = addDefaultAdapters(simpleModule);
|
||||
|
||||
setupEntityModules(simpleModule);
|
||||
registerModule(simpleModule);
|
||||
|
||||
configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
|
||||
|
||||
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
|
||||
configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package it.integry.ems.license;
|
||||
|
||||
import it.integry.ems.javabeans.RequestDataDTO;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.context.ContextLoader;
|
||||
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -12,6 +11,7 @@ import java.util.Random;
|
||||
|
||||
public class LicenseCheckInterceptor extends HandlerInterceptorAdapter {
|
||||
|
||||
|
||||
@Autowired
|
||||
private LicenseComponent licenseComponent;
|
||||
|
||||
@@ -19,9 +19,13 @@ public class LicenseCheckInterceptor extends HandlerInterceptorAdapter {
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler) {
|
||||
|
||||
RequestDataDTO requestData = ContextLoader.getCurrentWebApplicationContext().getBean(RequestDataDTO.class);
|
||||
|
||||
String profileDB = requestData.getProfileDB();
|
||||
String profileDB = null;
|
||||
if (request != null && request.getQueryString() != null && request.getQueryString().contains(CommonConstants.PROFILE_DB)) {
|
||||
profileDB = request.getParameter(CommonConstants.PROFILE_DB);
|
||||
} else if (request != null && request.getHeader(CommonConstants.PROFILE_DB) != null) {
|
||||
profileDB = request.getHeader(CommonConstants.PROFILE_DB);
|
||||
}
|
||||
|
||||
LicenseStatusDTO licenseStatusDTO = null;
|
||||
if (profileDB != null) licenseStatusDTO = licenseComponent.getLicenseStatus(profileDB);
|
||||
|
||||
@@ -8,9 +8,9 @@ import it.integry.ems.json.ResponseJSONObjectMapper;
|
||||
import it.integry.ems.response.EsitoType;
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.service.HttpRestWrapper;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionModel;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
@@ -25,7 +25,6 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
@@ -60,11 +59,11 @@ public class LicenseComponent {
|
||||
if (!canStart)
|
||||
return;
|
||||
|
||||
List<AvailableConnectionModel> availableConnectionModels = settingsModel.getAvailableConnections(true);
|
||||
List<AvailableConnectionsModel> availableConnectionsModels = settingsModel.getAvailableConnections(true);
|
||||
|
||||
try (MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager()) {
|
||||
|
||||
for (AvailableConnectionModel model : availableConnectionModels) {
|
||||
for (AvailableConnectionsModel model : availableConnectionsModels) {
|
||||
multiDBTransactionManager.addConnection(model);
|
||||
}
|
||||
|
||||
@@ -83,18 +82,18 @@ public class LicenseComponent {
|
||||
|
||||
final HashMap<String, String> listAziende = new HashMap<>();
|
||||
|
||||
for (Connection connection : multiDBTransactionManager.getActiveConnections()) {
|
||||
for (AdvancedDataSource model : multiDBTransactionManager.getActiveConnections()) {
|
||||
String sql = "SELECT part_iva FROM azienda WHERE part_iva is not null";
|
||||
String partIva = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
String partIva = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(model.getConnection(), sql);
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(partIva))
|
||||
listAziende.put(connection.getProfileName(), partIva);
|
||||
listAziende.put(model.getProfileName(), partIva);
|
||||
}
|
||||
|
||||
String jsonBody = jsonObjectMapper.writeValueAsString(listAziende.values());
|
||||
|
||||
StringBuilder responseBody = new StringBuilder();
|
||||
int status = HttpRestWrapper.callGeneric(url, "dba", "username", jsonBody, ContentType.APPLICATION_JSON, responseBody, null, 20);
|
||||
int status = HttpRestWrapper.callGeneric(url, "dba", "username", jsonBody, ContentType.APPLICATION_JSON, responseBody, null);
|
||||
|
||||
if (status != 200)
|
||||
throw new Exception("La richiesta \"" + url + "\" ha generato status code: " + status + " [" + responseBody + "]");
|
||||
@@ -106,19 +105,14 @@ public class LicenseComponent {
|
||||
} else {
|
||||
List<LicenseStatusDTO> licenses = response.getDTO(new TypeReference<List<LicenseStatusDTO>>() {
|
||||
});
|
||||
if (licenses == null || licenses.isEmpty()) return;
|
||||
if (licenses == null) return;
|
||||
|
||||
listAziende.forEach((key, value) -> {
|
||||
cachedLicenseStatus.remove(key);
|
||||
|
||||
final Optional<LicenseStatusDTO> licenseSearch = licenses.stream().filter(x -> x.getPartIva().equalsIgnoreCase(value))
|
||||
.findFirst();
|
||||
|
||||
if (licenseSearch.isPresent()) {
|
||||
cachedLicenseStatus.put(key, licenseSearch.get());
|
||||
} else {
|
||||
cachedLicenseStatus.put(key, licenses.get(0));
|
||||
}
|
||||
licenses.stream().filter(x -> x.getPartIva().equalsIgnoreCase(value))
|
||||
.findFirst()
|
||||
.ifPresent(license -> cachedLicenseStatus.put(key, license));
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ public class LicenseController {
|
||||
|
||||
@RequestMapping(value = "", method = RequestMethod.GET)
|
||||
public @ResponseBody ServiceRestResponse retrieve(@RequestParam(CommonConstants.PROFILE_DB) String profile) {
|
||||
LicenseStatusDTO licenseStatusDTO = licenseComponent.getLicenseStatus(profile.toUpperCase());
|
||||
LicenseStatusDTO licenseStatusDTO = licenseComponent.getLicenseStatus(profile);
|
||||
|
||||
if(licenseStatusDTO == null) return ServiceRestResponse.createPositiveResponse();
|
||||
return ServiceRestResponse.createPositiveResponse(licenseStatusDTO);
|
||||
|
||||
@@ -10,13 +10,10 @@ import java.util.Date;
|
||||
public class LicenseStatusDTO {
|
||||
@SqlField("part_iva")
|
||||
private String partIva;
|
||||
|
||||
@SqlField("classe_merito")
|
||||
private Quality quality;
|
||||
|
||||
@SqlField
|
||||
private Status status;
|
||||
|
||||
@SqlField("data_scad_license")
|
||||
private Date expiringDate;
|
||||
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
package it.integry.ems.listener;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
|
||||
public class Log4jShutdownListener implements ServletContextListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent servletContextEvent) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
try {
|
||||
// Pulizia esplicita del ThreadLocal
|
||||
// ContextAnchor.THREAD_CONTEXT.remove();
|
||||
|
||||
// Shutdown completo di Log4j
|
||||
LogManager.shutdown();
|
||||
|
||||
// Attesa per completamento shutdown
|
||||
Thread.sleep(500);
|
||||
|
||||
// Forza garbage collection
|
||||
System.gc();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Errore durante la pulizia dei ThreadLocal di Log4j: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,6 @@ public class TaskModel implements Runnable {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
private boolean mInterrupted = false;
|
||||
|
||||
public TaskModel(Runnable runnable, long delayTimeInMillis, String tagName) {
|
||||
mRunnable = runnable;
|
||||
mDelayTime = delayTimeInMillis;
|
||||
@@ -30,14 +28,14 @@ public class TaskModel implements Runnable {
|
||||
public void run() {
|
||||
Date lastExecution = new Date(0L);
|
||||
|
||||
while (!mInterrupted) {
|
||||
while (!mThread.isInterrupted()) {
|
||||
try {
|
||||
if (new Date().getTime() - lastExecution.getTime() > mDelayTime) {
|
||||
mRunnable.run();
|
||||
lastExecution = new Date();
|
||||
}
|
||||
|
||||
if(!mInterrupted) Thread.sleep(10);
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException iex) {
|
||||
//Do nothing
|
||||
} catch (Exception ex) {
|
||||
@@ -48,7 +46,7 @@ public class TaskModel implements Runnable {
|
||||
}
|
||||
|
||||
public void interrupt() {
|
||||
mInterrupted = true;
|
||||
this.mThread.interrupt();
|
||||
}
|
||||
|
||||
public String getTagName() {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package it.integry.ems.looper.service;
|
||||
|
||||
import com.annimon.stream.Stream;
|
||||
import it.integry.ems.looper.dto.LoopDTO;
|
||||
import it.integry.ems.looper.dto.TaskModel;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PreDestroy;
|
||||
@@ -11,12 +12,18 @@ import java.util.ArrayList;
|
||||
import java.util.Random;
|
||||
|
||||
@Component
|
||||
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
|
||||
public class LooperService {
|
||||
private final ArrayList<LoopDTO> mLoopsHandler = new ArrayList<>();
|
||||
private final ArrayList<TaskModel> mLoopsTask = new ArrayList<>();
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
@PreDestroy
|
||||
public void preDestroy() {
|
||||
for (TaskModel taskModel : mLoopsTask) {
|
||||
taskModel.interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
public int add(Runnable runnable, int delayTimeInMillis, String tagName) {
|
||||
int newId = -1;
|
||||
@@ -25,8 +32,7 @@ public class LooperService {
|
||||
do {
|
||||
newId = new Random().nextInt(10240);
|
||||
int finalNewId = newId;
|
||||
exists = mLoopsHandler.stream()
|
||||
.anyMatch(x -> x.getId() == finalNewId);
|
||||
exists = Stream.of(mLoopsHandler).anyMatch(x -> x.getId() == finalNewId);
|
||||
} while (exists);
|
||||
|
||||
this.mLoopsHandler.add(new LoopDTO()
|
||||
@@ -41,16 +47,5 @@ public class LooperService {
|
||||
return newId;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
logger.info("Shutting down LooperService (" + mLoopsHandler.size() + " threads)");
|
||||
|
||||
for (int i = 0; i < mLoopsTask.size(); i++) {
|
||||
|
||||
TaskModel taskModel = mLoopsTask.get(i);
|
||||
taskModel.interrupt();
|
||||
|
||||
logger.trace("Destroyed " + (i + 1) + " loop (" + taskModel.getTagName() + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package it.integry.ems.menu.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.microsoft.sqlserver.jdbc.SQLServerConnection;
|
||||
import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement;
|
||||
import it.integry.annotations.PostContextAutowired;
|
||||
import it.integry.annotations.PostContextConstruct;
|
||||
@@ -12,6 +11,7 @@ import it.integry.ems.menu.dto.StbMenuOpzDTO;
|
||||
import it.integry.ems.menu.dto.StbTipoAziendaDTO;
|
||||
import it.integry.ems.service.MailService;
|
||||
import it.integry.ems.settings.SettingsController;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.utility.UtilityDirs;
|
||||
@@ -57,17 +57,17 @@ public class MenuConfigurationService {
|
||||
|
||||
final MenuConfigDTO menuConfig = loadMenuData();
|
||||
|
||||
for (Connection connection : multiDBTransactionManager.getActiveConnections()) {
|
||||
for (AdvancedDataSource advancedDataSource : multiDBTransactionManager.getActiveConnections()) {
|
||||
|
||||
if (connection.getDbName().equalsIgnoreCase("menu") || isHistoryDB(connection))
|
||||
if (advancedDataSource.getDataSource().getDbName().equalsIgnoreCase("menu") || isHistoryDB(advancedDataSource))
|
||||
continue;
|
||||
|
||||
try {
|
||||
//LocalDateTime startTime = UtilityLocalDate.getNowTime();
|
||||
internalRefresh(connection, menuConfig);
|
||||
internalRefresh(advancedDataSource.getConnection(), menuConfig);
|
||||
//logger.debug("Menu refresh time: " + ChronoUnit.SECONDS.between(startTime, UtilityLocalDate.getNowTime()));
|
||||
} catch (Exception ex) {
|
||||
logger.error("Errore durante l'aggiornamento del menu di " + connection.getProfileName(), ex);
|
||||
logger.error("Errore durante l'aggiornamento del menu di " + advancedDataSource.getProfileName(), ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
@@ -75,9 +75,9 @@ public class MenuConfigurationService {
|
||||
logger.debug(MenuConfigurationService.class.getSimpleName() + ": Fine refresh menu");
|
||||
}
|
||||
|
||||
private boolean isHistoryDB(Connection connection) throws Exception {
|
||||
private boolean isHistoryDB(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
String historyProfileDB = settingsController.getHistoryProfileDb();
|
||||
return historyProfileDB.equalsIgnoreCase(connection.getProfileName());
|
||||
return historyProfileDB.equalsIgnoreCase(advancedDataSource.getProfileName());
|
||||
}
|
||||
|
||||
public void refresh(Connection connection, boolean forceRefresh) throws Exception {
|
||||
@@ -101,7 +101,6 @@ public class MenuConfigurationService {
|
||||
}
|
||||
|
||||
private void internalRefresh(Connection connection, MenuConfigDTO menuConfig, boolean forceRefresh) throws Exception {
|
||||
SQLServerConnection sqlServerConnection = connection.unwrap(SQLServerConnection.class);
|
||||
final Azienda azienda = Azienda.getDefaultAzienda(connection);
|
||||
|
||||
if (azienda.getTipoAzienda() == null)
|
||||
@@ -122,7 +121,7 @@ public class MenuConfigurationService {
|
||||
"descrizione, gest_name, entity_name, picture_menu, picture_select, object_type, flag_printer_setup, parameter, note, open_type, is_deprecated)" +
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (SQLServerPreparedStatement insertBulkPs = (SQLServerPreparedStatement) sqlServerConnection.prepareStatement(insertStbMenuOpzSQL)) {
|
||||
try (SQLServerPreparedStatement insertBulkPs = (SQLServerPreparedStatement) connection.prepareStatement(insertStbMenuOpzSQL)) {
|
||||
for (StbMenuOpzDTO stbMenuOpzDto : menuConfig.getStbMenuOpz()) {
|
||||
|
||||
insertBulkPs.setString(1, stbMenuOpzDto.getCodOpz());
|
||||
@@ -170,7 +169,7 @@ public class MenuConfigurationService {
|
||||
"pos_tipo_azienda, pos_cliente, descrizione_estesa) " +
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (SQLServerPreparedStatement insertBulkPs = (SQLServerPreparedStatement) sqlServerConnection.prepareStatement(insertStbMenuSql)) {
|
||||
try (SQLServerPreparedStatement insertBulkPs = (SQLServerPreparedStatement) connection.prepareStatement(insertStbMenuSql)) {
|
||||
for (StbMenuDTO stbMenuDto : stbMenus) {
|
||||
|
||||
insertBulkPs.setString(1, stbMenuDto.getCodOpz());
|
||||
|
||||
@@ -7,7 +7,7 @@ import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
import it.integry.ems.service.MailService;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.settings.SettingsController;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
@@ -25,6 +25,7 @@ import org.reflections.Reflections;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
@@ -74,12 +75,12 @@ public class MigrationComponent {
|
||||
}
|
||||
|
||||
public void startMigrationsGlobally(MultiDBTransactionManager multiDBTransactionManager) throws Exception {
|
||||
List<Connection> advancedDataSources;
|
||||
List<AdvancedDataSource> advancedDataSources;
|
||||
|
||||
try {
|
||||
advancedDataSources = multiDBTransactionManager.getActiveConnections();
|
||||
advancedDataSources = advancedDataSources.stream()
|
||||
.filter(Connection::isInternalDb)
|
||||
.filter(AdvancedDataSource::isInternalDb)
|
||||
.collect(Collectors.toList());
|
||||
} catch (SQLException e) {
|
||||
advancedDataSources = new ArrayList<>();
|
||||
@@ -88,7 +89,7 @@ public class MigrationComponent {
|
||||
|
||||
Exception firstException = null;
|
||||
|
||||
for (final Connection advancedDataSource : advancedDataSources) {
|
||||
for (final AdvancedDataSource advancedDataSource : advancedDataSources) {
|
||||
try {
|
||||
executeMigrationGroup(advancedDataSource);
|
||||
} catch (Exception e) {
|
||||
@@ -101,9 +102,9 @@ public class MigrationComponent {
|
||||
// throw firstException;
|
||||
}
|
||||
|
||||
public void executeMigrationGroup(Connection connection) throws Exception {
|
||||
migrateStatus(connection);
|
||||
List<StbMigrationStatus> migrationStatuses = retrieveAllMigrationsStatus(connection);
|
||||
public void executeMigrationGroup(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
migrateStatus(advancedDataSource);
|
||||
List<StbMigrationStatus> migrationStatuses = retrieveAllMigrationsStatus(advancedDataSource);
|
||||
|
||||
for (Class<? extends MigrationModelInterface> migrationClass : allMigrationsList) {
|
||||
long migrationNumber = Long.parseLong(migrationClass.getSimpleName().replace("Migration_", ""));
|
||||
@@ -112,47 +113,47 @@ public class MigrationComponent {
|
||||
continue;
|
||||
|
||||
try {
|
||||
executeMigration(migrationClass, connection, settingsController, settingsModel, droolsDataCompleting);
|
||||
updateLastMigrationIntoDB(connection, migrationNumber);
|
||||
executeMigration(migrationClass, advancedDataSource, settingsController, settingsModel, droolsDataCompleting);
|
||||
updateLastMigrationIntoDB(advancedDataSource, migrationNumber);
|
||||
|
||||
connection.commit();
|
||||
advancedDataSource.getConnection().commit();
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
connection.rollback();
|
||||
advancedDataSource.getConnection().rollback();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
logger.error("MigrationService - Rollback", ex);
|
||||
}
|
||||
|
||||
trackMigrationError(connection, migrationNumber, e);
|
||||
trackMigrationError(advancedDataSource, migrationNumber, e);
|
||||
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
migrationsErrorMapByProfiles.putIfAbsent(connection.getProfileName(), false);
|
||||
migrationsErrorMapByProfiles.replace(connection.getProfileName(), false);
|
||||
migrationsErrorMapByProfiles.putIfAbsent(advancedDataSource.getProfileName(), false);
|
||||
migrationsErrorMapByProfiles.replace(advancedDataSource.getProfileName(), false);
|
||||
}
|
||||
|
||||
private void executeMigration(Class<? extends MigrationModelInterface> migrationClass,
|
||||
Connection connection,
|
||||
AdvancedDataSource advancedDataSource,
|
||||
SettingsController settingsController,
|
||||
SettingsModel settingsModel,
|
||||
DroolsDataCompleting droolsDataCompleting) throws Exception {
|
||||
|
||||
logger.info("Applico " + migrationClass.getSimpleName() + " " + connection.getProfileName());
|
||||
logger.info("Applico " + migrationClass.getSimpleName() + " " + advancedDataSource.getProfileName());
|
||||
|
||||
MigrationModelInterface migrationInstance = migrationClass.newInstance();
|
||||
migrationInstance.init(connection, settingsController, settingsModel, droolsDataCompleting);
|
||||
migrationInstance.init(advancedDataSource, settingsController, settingsModel, droolsDataCompleting);
|
||||
migrationInstance.up();
|
||||
|
||||
connection.commit();
|
||||
advancedDataSource.getConnection().commit();
|
||||
}
|
||||
|
||||
public void updateLastMigrationIntoDB(Connection connection, long lastMigraton) throws Exception {
|
||||
public void updateLastMigrationIntoDB(AdvancedDataSource advancedDataSource, long lastMigraton) throws Exception {
|
||||
String sql = "SELECT * FROM " + StbMigrationStatus.ENTITY + " WHERE migration_code = " + lastMigraton;
|
||||
StbMigrationStatus stbMigrationStatus = UtilityDB.executeSimpleQueryOnlyFirstRowDTO(connection, sql, StbMigrationStatus.class);
|
||||
StbMigrationStatus stbMigrationStatus = UtilityDB.executeSimpleQueryOnlyFirstRowDTO(advancedDataSource.getConnection(), sql, StbMigrationStatus.class);
|
||||
|
||||
if (stbMigrationStatus == null) {
|
||||
stbMigrationStatus = new StbMigrationStatus()
|
||||
@@ -170,9 +171,9 @@ public class MigrationComponent {
|
||||
stbMigrationStatus.setOperation(OperationType.UPDATE);
|
||||
}
|
||||
|
||||
stbMigrationStatus.manageWithParentConnection(connection);
|
||||
stbMigrationStatus.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
|
||||
connection.commit();
|
||||
advancedDataSource.getConnection().commit();
|
||||
}
|
||||
|
||||
|
||||
@@ -184,9 +185,9 @@ public class MigrationComponent {
|
||||
}
|
||||
|
||||
|
||||
private void migrateStatus(Connection connection) throws Exception {
|
||||
final long lastMigrationNumber = getLastMigrationFromDB(connection);
|
||||
final List<Long> alreadyExecutedMigrations = retrieveAllMigrationsStatus(connection)
|
||||
private void migrateStatus(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
final long lastMigrationNumber = getLastMigrationFromDB(advancedDataSource);
|
||||
final List<Long> alreadyExecutedMigrations = retrieveAllMigrationsStatus(advancedDataSource)
|
||||
.stream()
|
||||
.map(StbMigrationStatus::getMigrationCode)
|
||||
.collect(Collectors.toList());
|
||||
@@ -204,25 +205,25 @@ public class MigrationComponent {
|
||||
.collect(Collectors.toList());
|
||||
|
||||
for (StbMigrationStatus stbMigrationStatus : migrationStatusesToMigrate)
|
||||
stbMigrationStatus.manageWithParentConnection(connection);
|
||||
stbMigrationStatus.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
|
||||
|
||||
connection.commit();
|
||||
advancedDataSource.getConnection().commit();
|
||||
}
|
||||
|
||||
private Long getLastMigrationFromDB(Connection connection) throws Exception {
|
||||
private Long getLastMigrationFromDB(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
String sql = "SELECT last_migration FROM azienda";
|
||||
String lastMigration = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
String lastMigration = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
lastMigration = UtilityString.isNullOrEmpty(lastMigration) ? "-1" : lastMigration;
|
||||
|
||||
return Long.parseLong(lastMigration);
|
||||
}
|
||||
|
||||
|
||||
private List<StbMigrationStatus> retrieveAllMigrationsStatus(Connection connection) throws
|
||||
SQLException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
private List<StbMigrationStatus> retrieveAllMigrationsStatus(AdvancedDataSource advancedDataSource) throws
|
||||
SQLException, IOException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
String sql = "SELECT * FROM " + StbMigrationStatus.ENTITY;
|
||||
List<StbMigrationStatus> stbMigrationStatuses = UtilityDB.executeSimpleQueryDTO(connection, sql, StbMigrationStatus.class);
|
||||
List<StbMigrationStatus> stbMigrationStatuses = UtilityDB.executeSimpleQueryDTO(advancedDataSource.getConnection(), sql, StbMigrationStatus.class);
|
||||
|
||||
if (stbMigrationStatuses == null) return new ArrayList<>();
|
||||
|
||||
@@ -233,14 +234,14 @@ public class MigrationComponent {
|
||||
return stbMigrationStatuses;
|
||||
}
|
||||
|
||||
private void trackMigrationError(Connection connection, long migrationCode, Exception e) {
|
||||
migrationsErrorMapByProfiles.putIfAbsent(connection.getProfileName(), true);
|
||||
migrationsErrorMapByProfiles.replace(connection.getProfileName(), true);
|
||||
private void trackMigrationError(AdvancedDataSource advancedDataSource, long migrationCode, Exception e) {
|
||||
migrationsErrorMapByProfiles.putIfAbsent(advancedDataSource.getProfileName(), true);
|
||||
migrationsErrorMapByProfiles.replace(advancedDataSource.getProfileName(), true);
|
||||
|
||||
e.printStackTrace();
|
||||
logger.error("MigrationService (" + connection.getProfileName() + ")", e);
|
||||
logger.error("MigrationService (" + advancedDataSource.getProfileName() + ")", e);
|
||||
|
||||
try (MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(connection.getProfileName())) {
|
||||
try (MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(advancedDataSource.getProfileName())) {
|
||||
final String exceptionTraceAsString = GeneralUtils.getExceptionTraceAsString(e);
|
||||
|
||||
String sql = "SELECT * FROM " + StbMigrationStatus.ENTITY + " WHERE migration_code = " + migrationCode;
|
||||
@@ -258,8 +259,8 @@ public class MigrationComponent {
|
||||
.setCompleted(false)
|
||||
.setSkipped(false)
|
||||
.setErrorMessage(e.getMessage() + "\n" + exceptionTraceAsString);
|
||||
stbMigrationStatus.manageWithParentConnection(connection);
|
||||
connection.commit();
|
||||
stbMigrationStatus.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
advancedDataSource.getConnection().commit();
|
||||
|
||||
if (UtilityDebug.isDebugExecution() || UtilityDebug.isIntegryServer()) return;
|
||||
|
||||
@@ -267,7 +268,7 @@ public class MigrationComponent {
|
||||
|
||||
mailService.sendSystemWarningLog("[" + azienda.getNomeDitta() + "][" + UtilityServer.getHostName() + "] Aggiornamento sistema",
|
||||
"anomalia durante l'aggiornamento",
|
||||
"La migrazione " + migrationCode + " non è andata a buon fine sul DB " + connection.getProfileName() + ". Controllare il log per ulteriori dettagli.",
|
||||
"La migrazione " + migrationCode + " non è andata a buon fine sul DB " + advancedDataSource.getProfileName() + ". Controllare il log per ulteriori dettagli.",
|
||||
e, new Date());
|
||||
} catch (Exception ex) {
|
||||
logger.error("MigrationService - Mail", ex);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package it.integry.ems.migration._base;
|
||||
|
||||
import it.integry.ems._context.ApplicationContextProvider;
|
||||
import it.integry.ems.entity_logger.db_schema_manager.dto.DatabaseVersionEnum;
|
||||
import it.integry.ems.migration.dto.SqlObjectTypeEnum;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.base_classes.BaseScheduledOperationDTO;
|
||||
import it.integry.ems.schedule.new_cron_job.service.AutomatedOperationHandlerComponent;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.settings.SettingsController;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.entity.Azienda;
|
||||
@@ -17,7 +17,6 @@ import it.integry.ems_model.exception.DataConverterNotFoundException;
|
||||
import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
|
||||
import it.integry.ems_model.types.ApplicationName;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.types.TypeDbObject;
|
||||
import it.integry.ems_model.utility.Query;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
@@ -38,7 +37,7 @@ import java.util.List;
|
||||
|
||||
public abstract class BaseMigration implements MigrationModelInterface {
|
||||
|
||||
protected Connection connection;
|
||||
protected AdvancedDataSource advancedDataSource;
|
||||
protected SettingsController settingsController;
|
||||
protected SettingsModel settingsModel;
|
||||
protected DroolsDataCompleting droolsDataCompleting;
|
||||
@@ -46,8 +45,8 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
protected final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Override
|
||||
public void init(Connection connection, SettingsController settingsController, SettingsModel settingsModel, DroolsDataCompleting droolsDataCompleting) {
|
||||
this.connection = connection;
|
||||
public void init(AdvancedDataSource advancedDataSource, SettingsController settingsController, SettingsModel settingsModel, DroolsDataCompleting droolsDataCompleting) {
|
||||
this.advancedDataSource = advancedDataSource;
|
||||
this.settingsController = settingsController;
|
||||
this.settingsModel = settingsModel;
|
||||
this.droolsDataCompleting = droolsDataCompleting;
|
||||
@@ -59,7 +58,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
|
||||
protected boolean isHistoryDB() throws Exception {
|
||||
String historyProfileDB = settingsController.getHistoryProfileDb();
|
||||
return historyProfileDB.equalsIgnoreCase(connection.getProfileName());
|
||||
return historyProfileDB.equalsIgnoreCase(advancedDataSource.getProfileName());
|
||||
}
|
||||
|
||||
protected boolean isDebug() {
|
||||
@@ -67,16 +66,16 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
}
|
||||
|
||||
|
||||
protected @NotNull List<HashMap<String, Object>> executeQuery(String sql) throws SQLException {
|
||||
return UtilityDB.executeSimpleQuery(connection, sql);
|
||||
protected @NotNull List<HashMap<String, Object>> executeQuery(String sql) throws SQLException, IOException {
|
||||
return UtilityDB.executeSimpleQuery(advancedDataSource.getConnection(), sql);
|
||||
}
|
||||
|
||||
protected @NotNull <T> List<T> executeQueryDTO(String sql, Class<T> clazz) throws Exception {
|
||||
return UtilityDB.executeSimpleQueryDTO(connection, sql, clazz);
|
||||
return UtilityDB.executeSimpleQueryDTO(advancedDataSource.getConnection(), sql, clazz);
|
||||
}
|
||||
|
||||
protected void executeStatement(String... sqls) throws SQLException {
|
||||
executeStatement(connection, sqls);
|
||||
protected void executeStatement(String... sqls) throws SQLException, IOException {
|
||||
executeStatement(advancedDataSource.getConnection(), sqls);
|
||||
}
|
||||
|
||||
protected void executeStatement(Connection connection, String... sqls) throws SQLException {
|
||||
@@ -90,7 +89,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
protected long executeInsertStatement(String sql) throws SQLException {
|
||||
long generatedId = -1;
|
||||
|
||||
try (PreparedStatement pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
|
||||
try (PreparedStatement pstmt = advancedDataSource.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
|
||||
|
||||
int affectedRows = pstmt.executeUpdate();
|
||||
|
||||
@@ -102,6 +101,8 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
return generatedId;
|
||||
@@ -128,8 +129,8 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
alterObject(SqlObjectTypeEnum.VIEW, objectName, createViewSql);
|
||||
}
|
||||
|
||||
protected boolean existsView(String objectName) throws SQLException {
|
||||
return UtilityDB.<Integer>executeSimpleQueryOnlyFirstRowFirstColumn(connection, "SELECT COUNT(*) FROM SYSOBJECTS WHERE id = object_id('" + objectName + "')") > 0;
|
||||
protected boolean existsView(String objectName) throws SQLException, IOException {
|
||||
return UtilityDB.<Integer>executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), "SELECT COUNT(*) FROM SYSOBJECTS WHERE id = object_id('" + objectName + "')") > 0;
|
||||
}
|
||||
|
||||
protected void createOrUpdateProcedure(String objectName, String createProcedureSql) throws SQLException, IOException {
|
||||
@@ -152,20 +153,15 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
}
|
||||
|
||||
protected void createIndex(IndexTableDTO indexTableDTO) throws Exception {
|
||||
UtilityDB.createIndex(connection, indexTableDTO);
|
||||
}
|
||||
|
||||
|
||||
protected void cloneTable(String sourceTable, String newTable,boolean fillNewTable, boolean dropOldTable, boolean renameNewTable) throws Exception {
|
||||
UtilityDB.cloneTable(connection, sourceTable, newTable, fillNewTable, dropOldTable, renameNewTable);
|
||||
UtilityDB.createIndex(advancedDataSource.getConnection(), indexTableDTO);
|
||||
}
|
||||
|
||||
protected void dropIndex(String tableName, String indexName) throws Exception {
|
||||
UtilityDB.dropIndex(connection, tableName, indexName);
|
||||
UtilityDB.dropIndex(advancedDataSource.getConnection(), tableName, indexName);
|
||||
}
|
||||
|
||||
|
||||
protected boolean existsColumn(String tableName, String columnName) throws SQLException {
|
||||
protected boolean existsColumn(String tableName, String columnName) throws SQLException, IOException {
|
||||
String schema = null;
|
||||
if (tableName.contains(".")) {
|
||||
schema = tableName.substring(0, tableName.indexOf("."));
|
||||
@@ -176,7 +172,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
" WHERE Name = N{}\n" +
|
||||
" AND Object_ID = Object_ID(N{})", columnName, (schema != null ? schema : "dbo") + "." + tableName);
|
||||
|
||||
Integer val = UtilityDB.<Integer>executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
Integer val = UtilityDB.<Integer>executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
|
||||
return val != null && val == 1;
|
||||
}
|
||||
@@ -195,7 +191,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
}
|
||||
|
||||
protected <T> void addDefault(String tableName, String columnName, T defaultValue) throws SQLException, IOException {
|
||||
boolean existDefault = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
boolean existDefault = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
Query.format("SELECT CAST(COUNT(*) AS BIT)\n" +
|
||||
"FROM sys.syscolumns\n" +
|
||||
"WHERE name = %s\n" +
|
||||
@@ -206,7 +202,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
}
|
||||
|
||||
protected void dropDefault(String tableName, String columnName) throws SQLException, IOException {
|
||||
boolean existDefault = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
boolean existDefault = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
Query.format("SELECT CAST(COUNT(*) AS BIT)\n" +
|
||||
"FROM sys.syscolumns\n" +
|
||||
"WHERE name = %s\n" +
|
||||
@@ -219,7 +215,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
}
|
||||
|
||||
protected void dropChecks(String tableName, String columnName) throws SQLException, IOException {
|
||||
boolean checkExists = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
boolean checkExists = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
Query.format("SELECT CAST(COUNT(*) AS BIT)\n" +
|
||||
"FROM sys.objects obj_table\n" +
|
||||
" JOIN sys.objects obj_Constraint\n" +
|
||||
@@ -238,7 +234,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean existsTable(String tableName) throws SQLException {
|
||||
protected boolean existsTable(String tableName) throws SQLException, IOException {
|
||||
String schema = null;
|
||||
if (tableName.contains(".")) {
|
||||
schema = tableName.substring(0, tableName.indexOf("."));
|
||||
@@ -251,7 +247,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
if (schema != null)
|
||||
sql += Query.format("AND TABLE_SCHEMA = N%s", schema);
|
||||
|
||||
return UtilityDB.<Boolean>executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
return UtilityDB.<Boolean>executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
}
|
||||
|
||||
protected void dropTable(String tableName) throws SQLException, IOException {
|
||||
@@ -267,7 +263,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
return;
|
||||
}
|
||||
String sql = Query.format("SELECT cast(count(*) as bit) FROM stb_gest_setup_query WHERE cod_query = %s", codQuery);
|
||||
boolean existQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
boolean existQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
|
||||
if (existQuery)
|
||||
executeStatement(Query.format("UPDATE stb_gest_setup_query SET query_default = %S, description = %S WHERE cod_query = %s ",
|
||||
@@ -277,20 +273,20 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
" VALUES (%s, %s, %s);", codQuery, query, name));
|
||||
}
|
||||
|
||||
protected boolean existsSetup(String gestName, String section, String keySection) throws SQLException {
|
||||
protected boolean existsSetup(String gestName, String section, String keySection) throws SQLException, IOException {
|
||||
String sql = Query.format("SELECT CAST(COUNT(*) AS BIT) AS exist FROM " + StbGestSetup.ENTITY +
|
||||
" WHERE gest_name = %s AND" +
|
||||
" section = %s AND" +
|
||||
" key_section = %s", gestName, section, keySection);
|
||||
|
||||
return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
}
|
||||
|
||||
protected boolean existsSetupQuery(String codQuery) throws SQLException {
|
||||
protected boolean existsSetupQuery(String codQuery) throws SQLException, IOException {
|
||||
String sql = Query.format("SELECT CAST(COUNT(*) AS BIT) AS exist FROM " + StbGestSetupQuery.ENTITY +
|
||||
" WHERE cod_query = %s", codQuery);
|
||||
|
||||
return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
}
|
||||
|
||||
protected void createSetup(String gestName, String section, String keySection, String value, String description, String codQuery) throws Exception {
|
||||
@@ -300,7 +296,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
String insertSql = "INSERT INTO " + StbGestSetup.ENTITY +
|
||||
"(gest_name, section, key_section, value, description, query_default) VALUES (?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (PreparedStatement ps = connection.prepareStatement(insertSql)) {
|
||||
try (PreparedStatement ps = advancedDataSource.getConnection().prepareStatement(insertSql)) {
|
||||
ps.setString(1, gestName);
|
||||
ps.setString(2, section);
|
||||
ps.setString(3, keySection);
|
||||
@@ -319,7 +315,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
String insertSql = "INSERT INTO " + StbGestSetup.ENTITY +
|
||||
"(gest_name, section, key_section, value, description, query_default, flag_multi_value) VALUES (?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (PreparedStatement ps = connection.prepareStatement(insertSql)) {
|
||||
try (PreparedStatement ps = advancedDataSource.getConnection().prepareStatement(insertSql)) {
|
||||
ps.setString(1, gestName);
|
||||
ps.setString(2, section);
|
||||
ps.setString(3, keySection);
|
||||
@@ -339,7 +335,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
String insertSql = "INSERT INTO " + StbGestSetup.ENTITY +
|
||||
"(gest_name, section, key_section, value, description, query_default, flag_multi_value, flag_setup_user_web) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (PreparedStatement ps = connection.prepareStatement(insertSql)) {
|
||||
try (PreparedStatement ps = advancedDataSource.getConnection().prepareStatement(insertSql)) {
|
||||
ps.setString(1, gestName);
|
||||
ps.setString(2, section);
|
||||
ps.setString(3, keySection);
|
||||
@@ -369,7 +365,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
return;
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(query) && UtilityString.isNullOrEmpty(codQuery)) {
|
||||
codQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
codQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
Query.format("SELECT cod_query FROM stb_gest_setup_query WHERE query_default = %s", query));
|
||||
}
|
||||
|
||||
@@ -378,7 +374,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
"flag_user_view, flag_setup_depo, flag_setup_user_web,\n" +
|
||||
"flag_tipo_json, flag_tipo_colore, tipo_setup, flag_multi_value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (PreparedStatement ps = connection.prepareStatement(insertSql)) {
|
||||
try (PreparedStatement ps = advancedDataSource.getConnection().prepareStatement(insertSql)) {
|
||||
ps.setString(1, gestName);
|
||||
ps.setString(2, section);
|
||||
ps.setString(3, keySection);
|
||||
@@ -405,7 +401,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
.setKeySection(keySection);
|
||||
|
||||
stbGestSetup.setOperation(OperationType.DELETE);
|
||||
stbGestSetup.manageWithParentConnection(connection);
|
||||
stbGestSetup.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
}
|
||||
|
||||
protected void updateSetupValue(String gestName, String section, String keySection, String newValue) throws Exception {
|
||||
@@ -425,7 +421,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
Boolean flagTipoJson, Boolean flagTipoColore, String tipoSetup, Boolean flagMultiValue,
|
||||
String query) throws Exception {
|
||||
if (!UtilityString.isNullOrEmpty(query) && UtilityString.isNullOrEmpty(codQuery)) {
|
||||
codQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
codQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
Query.format("SELECT cod_query FROM stb_gest_setup_query WHERE query_default = %s", query));
|
||||
}
|
||||
|
||||
@@ -460,13 +456,13 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
stbGestSetup.setFlagMultiValue(flagMultiValue);
|
||||
|
||||
stbGestSetup.setOperation(OperationType.UPDATE);
|
||||
stbGestSetup.manageWithParentConnection(connection);
|
||||
stbGestSetup.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
}
|
||||
|
||||
protected void updateSetupQuery(String gestName, String section, String keySection,
|
||||
String codQuery, String query) throws Exception {
|
||||
if (!UtilityString.isNullOrEmpty(query) && UtilityString.isNullOrEmpty(codQuery)) {
|
||||
codQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
codQuery = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
Query.format("SELECT cod_query FROM stb_gest_setup_query WHERE query_default = %s", query));
|
||||
}
|
||||
|
||||
@@ -477,7 +473,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
.setQueryDefault(codQuery);
|
||||
|
||||
stbGestSetup.setOperation(OperationType.UPDATE);
|
||||
stbGestSetup.manageWithParentConnection(connection);
|
||||
stbGestSetup.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
}
|
||||
|
||||
protected void addAutomatedOperation(BaseScheduledOperationDTO operation) {
|
||||
@@ -511,7 +507,7 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
|
||||
|
||||
protected boolean isCustomer(IntegryCustomer... customers) {
|
||||
String currentDbName = connection.getDbName();
|
||||
String currentDbName = advancedDataSource.getDataSource().getDbName();
|
||||
|
||||
return Arrays.stream(customers)
|
||||
.anyMatch(x ->
|
||||
@@ -520,31 +516,31 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
}
|
||||
|
||||
protected boolean isCustomerDb(IntegryCustomerDB... customersDbs) {
|
||||
String currentDbName = connection.getDbName();
|
||||
String currentDbName = advancedDataSource.getDataSource().getDbName();
|
||||
|
||||
return Arrays.stream(customersDbs)
|
||||
.anyMatch(y -> y.getValue().equalsIgnoreCase(currentDbName));
|
||||
}
|
||||
|
||||
|
||||
protected boolean isWingest() throws SQLException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
Azienda currentAzienda = Azienda.getDefaultAzienda(connection);
|
||||
protected boolean isWingest() throws SQLException, IOException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
Azienda currentAzienda = Azienda.getDefaultAzienda(advancedDataSource.getConnection());
|
||||
return currentAzienda.getApplicationNameEnum() == ApplicationName.WINGEST;
|
||||
}
|
||||
|
||||
protected boolean isTextiles() throws SQLException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
Azienda currentAzienda = Azienda.getDefaultAzienda(connection);
|
||||
protected boolean isTextiles() throws SQLException, IOException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
Azienda currentAzienda = Azienda.getDefaultAzienda(advancedDataSource.getConnection());
|
||||
return currentAzienda.getApplicationNameEnum() == ApplicationName.TEXTILES;
|
||||
}
|
||||
|
||||
protected boolean isDMS() throws SQLException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
Azienda currentAzienda = Azienda.getDefaultAzienda(connection);
|
||||
protected boolean isDMS() throws SQLException, IOException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
Azienda currentAzienda = Azienda.getDefaultAzienda(advancedDataSource.getConnection());
|
||||
return currentAzienda.getApplicationNameEnum() == ApplicationName.DMS;
|
||||
}
|
||||
|
||||
protected void enableSaveToRest(String gestName) throws Exception {
|
||||
boolean existRow =
|
||||
UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
Query.format("SELECT cast(count(*) as bit) FROM stb_gest_sync WHERE gest_name = %s", gestName));
|
||||
|
||||
StbGestSync gestSync =
|
||||
@@ -555,83 +551,14 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
gestSync.setOperation(OperationType.UPDATE);
|
||||
} else {
|
||||
String entityName =
|
||||
UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
Query.format("SELECT entity_name FROM stb_menu_opz WHERE gest_name = %s", gestName));
|
||||
gestSync.setEntityName(entityName);
|
||||
gestSync.setOperation(OperationType.INSERT);
|
||||
}
|
||||
|
||||
|
||||
gestSync.manageWithParentConnection(connection);
|
||||
gestSync.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
|
||||
}
|
||||
|
||||
private DatabaseVersionEnum getSqlCompatibilityLevel() throws Exception {
|
||||
short compatibilityLevel =
|
||||
UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
Query.format("SELECT compatibility_level FROM sys.databases WHERE name = %s", connection.getDbName()));
|
||||
|
||||
|
||||
return DatabaseVersionEnum.fromCode(compatibilityLevel);
|
||||
}
|
||||
|
||||
protected boolean isSqlVersionEqualsOrGreatherThan(DatabaseVersionEnum version) throws Exception {
|
||||
DatabaseVersionEnum dbVersion = getSqlCompatibilityLevel();
|
||||
|
||||
return dbVersion.getCode() >= version.getCode();
|
||||
}
|
||||
|
||||
protected boolean isSqlServer2008() throws Exception {
|
||||
return getSqlCompatibilityLevel() == DatabaseVersionEnum.SQLServer2008;
|
||||
}
|
||||
|
||||
protected boolean isSqlServer2012() throws Exception {
|
||||
return getSqlCompatibilityLevel() == DatabaseVersionEnum.SQLServer2012;
|
||||
}
|
||||
|
||||
protected boolean isSqlServer2014() throws Exception {
|
||||
return getSqlCompatibilityLevel() == DatabaseVersionEnum.SQLServer2014;
|
||||
}
|
||||
|
||||
protected boolean isSqlServer2019() throws Exception {
|
||||
return getSqlCompatibilityLevel() == DatabaseVersionEnum.SQLServer2019;
|
||||
}
|
||||
|
||||
protected boolean isSqlServer2022() throws Exception {
|
||||
return getSqlCompatibilityLevel() == DatabaseVersionEnum.SQLServer2022;
|
||||
}
|
||||
|
||||
protected void addDescriptionTable(String tableName, String description) throws SQLException {
|
||||
if (existsTable(tableName)) {
|
||||
addDescriptionObject(tableName, TypeDbObject.TABLE, description);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected void addDescriptionView(String viewName, String description) throws SQLException {
|
||||
if (existsView(viewName)) {
|
||||
addDescriptionObject(viewName, TypeDbObject.VIEW, description);
|
||||
}
|
||||
}
|
||||
|
||||
private void addDescriptionObject(String objectName, TypeDbObject type, String description) throws SQLException {
|
||||
String typeString = "TABLE";
|
||||
|
||||
if (type == TypeDbObject.VIEW) {
|
||||
typeString = "VIEW";
|
||||
}
|
||||
executeStatement(
|
||||
Query.format("EXEC sp_addextendedproperty " +
|
||||
"@name = N'MS_Description', " +
|
||||
"@value = %s, " +
|
||||
"@level0type = N'SCHEMA', @level0name = 'dbo', " +
|
||||
"@level1type = %s, @level1name = %s;", description, typeString, objectName));
|
||||
}
|
||||
|
||||
private void addDescriptionColumn(String tableName, String columnName, String description) throws SQLException {
|
||||
executeStatement(Query.format("EXEC sp_addextendedproperty 'MS_Description', %s, 'SCHEMA', 'dbo', 'TABLE',%s, 'COLUMN', %s)",
|
||||
description, tableName, columnName));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -18,9 +18,7 @@ public enum IntegryCustomer {
|
||||
IntegryCustomerDB.Auricchio_Ind05,
|
||||
IntegryCustomerDB.Auricchio_AuricchioSons),
|
||||
Biolevante(IntegryCustomerDB.Biolevante_Biolevante,
|
||||
IntegryCustomerDB.Biolevante_BiolevanteStorico,
|
||||
IntegryCustomerDB.Biolevante_TenutaSanMartino),
|
||||
CapelliMonelli(IntegryCustomerDB.CapelliMonelli_CapelliMonelli),
|
||||
IntegryCustomerDB.Biolevante_BiolevanteStorico),
|
||||
Carelli(IntegryCustomerDB.Carelli_Carelli,
|
||||
IntegryCustomerDB.Carelli_GestFood,
|
||||
IntegryCustomerDB.Carelli_Chiuso,
|
||||
@@ -70,8 +68,7 @@ public enum IntegryCustomer {
|
||||
Frudis(IntegryCustomerDB.Frudis_Frudis),
|
||||
Gramm(IntegryCustomerDB.Gramm_Gramm,
|
||||
IntegryCustomerDB.Gramm_PrimeOlive,
|
||||
IntegryCustomerDB.Gramm_ProveStage,
|
||||
IntegryCustomerDB.Gramm_2MHolding),
|
||||
IntegryCustomerDB.Gramm_ProveStage),
|
||||
Idrotecnica(IntegryCustomerDB.Idrotecnica_Idrotecnica),
|
||||
Igood(IntegryCustomerDB.Igood_Aida,
|
||||
IntegryCustomerDB.Igood_Igood,
|
||||
@@ -96,7 +93,6 @@ public enum IntegryCustomer {
|
||||
ResinaColor(IntegryCustomerDB.ResinaColor_ResinaColor, IntegryCustomerDB.ResinaColor_ResinaColorPasquale),
|
||||
RistoCash(IntegryCustomerDB.RistoCash_RistoCash),
|
||||
RossoGargano(IntegryCustomerDB.RossoGargano_RossoGargano, IntegryCustomerDB.RossoGargano_RossoGarganoCont),
|
||||
Sabato(IntegryCustomerDB.Sabato_Sabato),
|
||||
Salpar(IntegryCustomerDB.Salpar_AlfaImmobiliare,
|
||||
IntegryCustomerDB.Salpar_MasabaSrl,
|
||||
IntegryCustomerDB.Salpar_Salpar,
|
||||
|
||||
@@ -22,9 +22,7 @@ public enum IntegryCustomerDB {
|
||||
|
||||
Biolevante_Biolevante("biolevante"),
|
||||
Biolevante_BiolevanteStorico("biolevante_storico"),
|
||||
Biolevante_TenutaSanMartino("tenutasanmartino"),
|
||||
|
||||
CapelliMonelli_CapelliMonelli("capelli_monelli"),
|
||||
|
||||
Carelli_Carelli("carelli"),
|
||||
Carelli_GestFood("gestfood"),
|
||||
@@ -89,10 +87,9 @@ public enum IntegryCustomerDB {
|
||||
Frudis_Frudis("frudis"),
|
||||
|
||||
|
||||
Gramm_Gramm("gramm_peppe"),
|
||||
Gramm_Gramm("gramm"),
|
||||
Gramm_PrimeOlive("primeolive"),
|
||||
Gramm_ProveStage("grammprovestage"),
|
||||
Gramm_2MHolding("2M_HOLDING"),
|
||||
|
||||
|
||||
Idrotecnica_Idrotecnica("idrotecnica"),
|
||||
@@ -103,7 +100,7 @@ public enum IntegryCustomerDB {
|
||||
Igood_ShopService("shop_service"),
|
||||
|
||||
|
||||
Ime_ImeTe("ime_te_peppe"),
|
||||
Ime_ImeTe("ime_te"),
|
||||
|
||||
|
||||
Integry_Studioml("studioml"),
|
||||
@@ -156,8 +153,6 @@ public enum IntegryCustomerDB {
|
||||
RossoGargano_RossoGargano("rossogargano"),
|
||||
RossoGargano_RossoGarganoCont("rossogarganocont"),
|
||||
|
||||
Sabato_Sabato("sabato"),
|
||||
|
||||
|
||||
Salpar_VgAlimenti("vgalimenti"),
|
||||
Salpar_Salpar("salpar"),
|
||||
|
||||
@@ -2,12 +2,12 @@ package it.integry.ems.migration._base;
|
||||
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.settings.SettingsController;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
|
||||
|
||||
public interface MigrationModelInterface {
|
||||
|
||||
void init(Connection connection,
|
||||
void init(AdvancedDataSource advancedDataSource,
|
||||
SettingsController settingsController,
|
||||
SettingsModel settingsModel,
|
||||
DroolsDataCompleting droolsDataCompleting);
|
||||
|
||||
@@ -1,508 +0,0 @@
|
||||
package it.integry.ems.migration.dto.common;
|
||||
|
||||
import it.integry.ems.migration.dto.SqlObjectTypeEnum;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems_model.entity.MtbColt;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.Query;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import it.integry.ems_model.utility.dto.IndexTableDTO;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class MigrationMvwSitArtUdcDetInventarioDTO {
|
||||
|
||||
|
||||
public static void apply(Connection connection) throws Exception {
|
||||
//Aggiorno i campi barcode_ul_in, barcode_ul_out, posizione_in, posizione_out, cod_mdep_in, cod_mdep_out
|
||||
updateNewFieldsInMtbColrs(connection);
|
||||
|
||||
//Migration di conversione aziende a nuova mvw_sitart_udc_det_inventario
|
||||
createBackupOfOldView(connection);
|
||||
dropView(connection, "mvw_sitart_udc_det_inventario");
|
||||
|
||||
createNewView(connection);
|
||||
}
|
||||
|
||||
public static void updateNewFieldsInMtbColrs(Connection connection) throws Exception {
|
||||
executeStatement(connection, "UPDATE mtb_colr\n" +
|
||||
"SET barcode_ul_in = new_data.barcode_ul_in,\n" +
|
||||
" barcode_ul_out = new_data.barcode_ul_out,\n" +
|
||||
" posizione_in = new_data.posizione_in,\n" +
|
||||
" posizione_out = new_data.posizione_out,\n" +
|
||||
" cod_mdep_in = new_data.cod_mdep_in,\n" +
|
||||
" cod_mdep_out = new_data.cod_mdep_out\n" +
|
||||
"FROM mtb_colr\n" +
|
||||
" INNER JOIN (SELECT mtb_colt.barcode_ul AS barcode_ul_in,\n" +
|
||||
" IIF(num_collo_rif IS NOT NULL, mtb_colt_rif.barcode_ul, NULL) AS barcode_ul_out,\n" +
|
||||
" mtb_colt.posizione AS posizione_in,\n" +
|
||||
" IIF(num_collo_rif IS NOT NULL, mtb_colt_rif.posizione, NULL) AS posizione_out,\n" +
|
||||
" mtb_colt.cod_mdep AS cod_mdep_in,\n" +
|
||||
" IIF(num_collo_rif IS NOT NULL, mtb_colt_rif.cod_mdep, NULL) AS cod_mdep_out,\n" +
|
||||
"\n" +
|
||||
" mtb_colr.gestione,\n" +
|
||||
" mtb_colr.data_collo,\n" +
|
||||
" mtb_colr.ser_collo,\n" +
|
||||
" mtb_colr.num_collo,\n" +
|
||||
" mtb_colr.riga\n" +
|
||||
"\n" +
|
||||
" FROM dbo.mtb_colr\n" +
|
||||
" INNER JOIN dbo.mtb_colt ON mtb_colr.gestione = mtb_colt.gestione AND\n" +
|
||||
" mtb_colr.data_collo = mtb_colt.data_collo AND\n" +
|
||||
" mtb_colr.ser_collo = mtb_colt.ser_collo AND\n" +
|
||||
" mtb_colr.num_collo = mtb_colt.num_collo\n" +
|
||||
"\n" +
|
||||
" LEFT OUTER JOIN dbo.mtb_colt mtb_colt_rif\n" +
|
||||
" ON mtb_colr.gestione_rif = mtb_colt_rif.gestione AND\n" +
|
||||
" mtb_colr.data_collo_rif = mtb_colt_rif.data_collo AND\n" +
|
||||
" mtb_colr.ser_collo_rif = mtb_colt_rif.ser_collo AND\n" +
|
||||
" mtb_colr.num_collo_rif = mtb_colt_rif.num_collo) new_data\n" +
|
||||
" ON mtb_colr.gestione = new_data.gestione AND\n" +
|
||||
" mtb_colr.num_collo = new_data.num_collo AND\n" +
|
||||
" mtb_colr.ser_collo = new_data.ser_collo AND\n" +
|
||||
" mtb_colr.data_collo = new_data.data_collo AND\n" +
|
||||
" mtb_colr.riga = new_data.riga");
|
||||
}
|
||||
|
||||
public static void alignGiacenza(Connection connection) throws Exception {
|
||||
//Creo un collo di scarico vuoto
|
||||
MtbColt mtbColt = new MtbColt()
|
||||
.setGestione("L")
|
||||
.setSerCollo("RT")
|
||||
.setSegno(-1)
|
||||
.setDataCollo(LocalDate.now())
|
||||
.setAnnotazioni("PASSAGGIO NUOVA MVW_SITART_UDC_DET_INVENTARIO")
|
||||
.setCodMdep(getInternalCodMdep(connection));
|
||||
mtbColt.setOperation(OperationType.INSERT);
|
||||
|
||||
mtbColt.dataCompleting(connection);
|
||||
mtbColt.manageWithParentConnection(connection);
|
||||
|
||||
|
||||
executeStatement(connection, Query.format(
|
||||
"INSERT INTO mtb_colr (gestione, ser_collo, num_collo, data_collo, riga, cod_mart, cod_col, cod_tagl, partita_mag, gestione_rif, data_collo_rif, ser_collo_rif, num_collo_rif, datetime_row,\n" +
|
||||
" cod_jcom, qta_col, num_cnf, qta_cnf, barcode_ul_out, cod_mdep_out, posizione_out)" +
|
||||
" SELECT {} AS gestione,\n" +
|
||||
" {} AS ser_collo,\n" +
|
||||
" {} AS num_collo,\n" +
|
||||
" CAST({} AS DATE) AS data_collo,\n" +
|
||||
" ROW_NUMBER() OVER (PARTITION BY (SELECT NULL) ORDER BY v.data_collo) AS riga,\n" +
|
||||
" v.cod_mart,\n" +
|
||||
" v.cod_col,\n" +
|
||||
" v.cod_tagl,\n" +
|
||||
" v.partita_mag,\n" +
|
||||
" v.gestione AS gestion_rif,\n" +
|
||||
" v.data_collo AS data_collo_rif,\n" +
|
||||
" v.ser_collo AS ser_collo_rif,\n" +
|
||||
" v.num_collo AS num_collo_rif,\n" +
|
||||
" GETDATE() AS datetime_row,\n" +
|
||||
" v.cod_jcom,\n" +
|
||||
" v.qta_col,\n" +
|
||||
" v.num_cnf,\n" +
|
||||
" v.qta_cnf,\n" +
|
||||
" v.barcode_ul AS barcode_ul_out,\n" +
|
||||
" v.cod_mdep AS cod_mdep_out,\n" +
|
||||
" v.posizione AS posizione_out\n" +
|
||||
"FROM mvw_sitart_udc_det_inventario v\n" +
|
||||
" INNER JOIN (SELECT ser_collo,\n" +
|
||||
" gestione,\n" +
|
||||
" data_collo,\n" +
|
||||
" num_collo,\n" +
|
||||
" cod_mdep,\n" +
|
||||
" posizione,\n" +
|
||||
" cod_mart,\n" +
|
||||
" partita_mag,\n" +
|
||||
" cod_jcom-- Elenca tutte le colonne coinvolte\n" +
|
||||
" FROM mvw_sitart_udc_det_inventario\n" +
|
||||
"\n" +
|
||||
" EXCEPT\n" +
|
||||
"\n" +
|
||||
" SELECT ser_collo,\n" +
|
||||
" gestione,\n" +
|
||||
" data_collo,\n" +
|
||||
" num_collo,\n" +
|
||||
" cod_mdep,\n" +
|
||||
" posizione,\n" +
|
||||
" cod_mart,\n" +
|
||||
" partita_mag,\n" +
|
||||
" cod_jcom -- Elenca le stesse colonne dalla vista vecchia\n" +
|
||||
" FROM mvw_sitart_udc_det_inventario_old) t\n" +
|
||||
" ON v.num_collo = t.num_collo AND v.data_collo = t.data_collo AND\n" +
|
||||
" v.ser_collo = t.ser_collo AND v.gestione = t.gestione AND\n" +
|
||||
" v.cod_mart = t.cod_mart AND v.cod_mdep = t.cod_mdep AND\n" +
|
||||
" ISNULL(v.partita_mag, '') = ISNULL(t.partita_mag, '') AND\n" +
|
||||
" ISNULL(v.posizione, '') = ISNULL(t.posizione, '') AND\n" +
|
||||
" ISNULL(v.cod_jcom, '') = ISNULL(t.cod_jcom, '')" +
|
||||
" WHERE qta_col > 0",
|
||||
mtbColt.getGestione(), mtbColt.getSerCollo(), mtbColt.getNumCollo(), mtbColt.getDataCollo()));
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static String getInternalCodMdep(Connection connection) throws Exception {
|
||||
String codMdepAz = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, "SELECT TOP 1 cod_mdep" +
|
||||
" FROM mtb_depo" +
|
||||
" INNER JOIN dbo.gtb_anag ga ON mtb_depo.cod_anag = ga.cod_anag" +
|
||||
" inner join azienda on ga.part_iva = azienda.part_iva");
|
||||
|
||||
if(UtilityString.isNullOrEmpty(codMdepAz)) {
|
||||
codMdepAz = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, "SELECT TOP 1 cod_mdep FROM mtb_depo");
|
||||
}
|
||||
|
||||
return codMdepAz;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
private static void createBackupOfOldView(Connection connection) throws Exception {
|
||||
if (existsView(connection, "mvw_sitart_udc_det_inventario_old"))
|
||||
return;
|
||||
|
||||
createOrUpdateView(connection, "mvw_sitart_udc_det_inventario_old", "CREATE VIEW [dbo].[mvw_sitart_udc_det_inventario_old] AS\n" +
|
||||
"SELECT UL.gestione,\n" +
|
||||
" data_collo,\n" +
|
||||
" ser_collo,\n" +
|
||||
" num_collo,\n" +
|
||||
" segno,\n" +
|
||||
" UL.cod_mdep,\n" +
|
||||
" UL.posizione,\n" +
|
||||
" mtb_depo_posizioni.priorita,\n" +
|
||||
" mtb_aart.cod_mgrp AS codGruppo,\n" +
|
||||
" mtb_grup.descrizione AS Gruppo,\n" +
|
||||
" mtb_aart.cod_msgr AS CodSgruppo,\n" +
|
||||
" mtb_sgrp.descrizione AS Sottogruppo,\n" +
|
||||
" UL.cod_mart,\n" +
|
||||
" diacod,\n" +
|
||||
" mtb_aart.descrizione_estesa,\n" +
|
||||
" partita_mag,\n" +
|
||||
" UL.cod_jcom,\n" +
|
||||
" jtb_comt.descrizione AS commessa,\n" +
|
||||
" mtb_aart.unt_mis,\n" +
|
||||
" qta_col,\n" +
|
||||
" num_cnf,\n" +
|
||||
" UL.qta_cnf,\n" +
|
||||
" UL.peso_netto_kg,\n" +
|
||||
" UL.peso_lordo_kg,\n" +
|
||||
" UL.cod_jfas\n" +
|
||||
"FROM [mvw_sitart_udc_det] UL\n" +
|
||||
" LEFT OUTER JOIN jtb_comt ON UL.cod_jcom = jtb_comt.cod_jcom\n" +
|
||||
" LEFT OUTER JOIN mtb_depo_posizioni\n" +
|
||||
" ON UL.cod_mdep = mtb_depo_posizioni.cod_mdep AND UL.posizione = mtb_depo_posizioni.posizione,\n" +
|
||||
" mtb_aart,\n" +
|
||||
" mtb_grup,\n" +
|
||||
" mtb_sgrp\n" +
|
||||
"WHERE UL.cod_mart = mtb_aart.cod_mart\n" +
|
||||
" AND mtb_aart.cod_mgrp = mtb_grup.cod_mgrp\n" +
|
||||
" AND mtb_aart.cod_mgrp = mtb_sgrp.cod_mgrp\n" +
|
||||
" AND mtb_aart.cod_msgr = mtb_sgrp.cod_msgr\n" +
|
||||
" AND qta_col <> 0");
|
||||
}
|
||||
|
||||
private static void createNewView(Connection connection) throws Exception {
|
||||
|
||||
if (!existsTable(connection, "stb_multiplier")) {
|
||||
executeStatement(connection, "CREATE TABLE stb_multiplier\n" +
|
||||
"(\n" +
|
||||
" moltiplicatore INT NOT NULL\n" +
|
||||
")",
|
||||
"INSERT INTO stb_multiplier (moltiplicatore) VALUES (1)",
|
||||
"INSERT INTO stb_multiplier (moltiplicatore) VALUES (-1)");
|
||||
}
|
||||
|
||||
|
||||
createOrUpdateView(connection, "mvw_mtb_colr_with_giacenza", "CREATE VIEW dbo.mvw_mtb_colr_with_giacenza\n" +
|
||||
" WITH SCHEMABINDING\n" +
|
||||
" AS\n" +
|
||||
"SELECT COUNT_BIG(*) AS c,\n" +
|
||||
" IIF(moltiplicatore = -1, mtb_colr.barcode_ul_out,\n" +
|
||||
" mtb_colr.barcode_ul_in) AS barcode_ul,\n" +
|
||||
" IIF(moltiplicatore = -1, mtb_colr.cod_mdep_out,\n" +
|
||||
" mtb_colr.cod_mdep_in) AS cod_mdep,\n" +
|
||||
" IIF(moltiplicatore = -1, mtb_colr.posizione_out,\n" +
|
||||
" mtb_colr.posizione_in) AS posizione,\n" +
|
||||
" SUM(mtb_colr.qta_col * moltiplicatore) AS qta_col,\n" +
|
||||
" SUM(IIF(mtb_aart.flag_qta_cnf_fissa = 'S', mtb_colr.qta_col / mtb_aart.qta_cnf, mtb_colr.num_cnf) *\n" +
|
||||
" moltiplicatore) AS num_cnf,\n" +
|
||||
" mtb_colr.cod_mart,\n" +
|
||||
" mtb_colr.cod_col,\n" +
|
||||
" mtb_colr.cod_tagl,\n" +
|
||||
" mtb_colr.partita_mag,\n" +
|
||||
" SUM(mtb_colr.peso_netto_kg * moltiplicatore) AS peso_netto_kg,\n" +
|
||||
" SUM(mtb_colr.peso_lordo_kg * moltiplicatore) AS peso_lordo_kg,\n" +
|
||||
" IIF(mtb_colr.cod_jcom = 'MAG', NULL, mtb_colr.cod_jcom) AS cod_jcom,\n" +
|
||||
" mtb_aart.flag_qta_cnf_fissa,\n" +
|
||||
" mtb_aart.unt_mis,\n" +
|
||||
" mtb_aart.diacod,\n" +
|
||||
" mtb_aart.descrizione_estesa,\n" +
|
||||
" mtb_aart.cod_mgrp,\n" +
|
||||
" mtb_aart.cod_msgr,\n" +
|
||||
" mtb_aart.cod_mtip,\n" +
|
||||
" mtb_aart.cod_mstp,\n" +
|
||||
" mtb_aart.cod_msfa,\n" +
|
||||
" mtb_aart.qta_cnf AS qta_cnf_anag\n" +
|
||||
"FROM dbo.mtb_colr\n" +
|
||||
" INNER JOIN dbo.stb_multiplier ON (moltiplicatore = 1 AND mtb_colr.barcode_ul_in IS NOT NULL) OR\n" +
|
||||
" (moltiplicatore = -1 AND mtb_colr.barcode_ul_out IS NOT NULL)\n" +
|
||||
" INNER JOIN dbo.mtb_aart ON mtb_colr.cod_mart = mtb_aart.cod_mart\n" +
|
||||
"GROUP BY mtb_colr.cod_mart,\n" +
|
||||
" mtb_colr.cod_col,\n" +
|
||||
" mtb_colr.cod_tagl,\n" +
|
||||
" mtb_colr.partita_mag,\n" +
|
||||
" IIF(moltiplicatore = -1, mtb_colr.barcode_ul_out,\n" +
|
||||
" mtb_colr.barcode_ul_in),\n" +
|
||||
" IIF(moltiplicatore = -1, mtb_colr.cod_mdep_out,\n" +
|
||||
" mtb_colr.cod_mdep_in),\n" +
|
||||
" IIF(moltiplicatore = -1, mtb_colr.posizione_out,\n" +
|
||||
" mtb_colr.posizione_in),\n" +
|
||||
" IIF(mtb_colr.cod_jcom = 'MAG', NULL, mtb_colr.cod_jcom),\n" +
|
||||
" mtb_aart.flag_qta_cnf_fissa,\n" +
|
||||
" mtb_aart.unt_mis,\n" +
|
||||
" mtb_aart.diacod,\n" +
|
||||
" mtb_aart.descrizione_estesa,\n" +
|
||||
" mtb_aart.cod_mgrp,\n" +
|
||||
" mtb_aart.cod_msgr,\n" +
|
||||
" mtb_aart.cod_mtip,\n" +
|
||||
" mtb_aart.cod_mstp,\n" +
|
||||
" mtb_aart.cod_msfa,\n" +
|
||||
" mtb_aart.qta_cnf");
|
||||
|
||||
dropIndex(connection, "mvw_mtb_colr_with_giacenza", "IDX_CLUSTERED_mvw_mtb_colr_with_giacenza");
|
||||
createIndex(connection, new IndexTableDTO()
|
||||
.setIndexName("IDX_CLUSTERED_mvw_mtb_colr_with_giacenza")
|
||||
.setTableName("mvw_mtb_colr_with_giacenza")
|
||||
.setUnique(true)
|
||||
.setClustered(true)
|
||||
.setMaxDop(1)
|
||||
.setSortInTempDb(true)
|
||||
.setColumnsIndex(new ArrayList<IndexTableDTO.ColumnIndex>() {{
|
||||
add(new IndexTableDTO.ColumnIndex("barcode_ul"));
|
||||
add(new IndexTableDTO.ColumnIndex("posizione"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_mdep"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_mart"));
|
||||
add(new IndexTableDTO.ColumnIndex("partita_mag"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_tagl"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_col"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_jcom"));
|
||||
}}));
|
||||
|
||||
dropIndex(connection, "mvw_mtb_colr_with_giacenza", "IDX_mvw_qta_mtb_colr_with_giacenza");
|
||||
createIndex(connection, new IndexTableDTO()
|
||||
.setIndexName("IDX_mvw_qta_mtb_colr_with_giacenza")
|
||||
.setTableName("mvw_mtb_colr_with_giacenza")
|
||||
.setMaxDop(1)
|
||||
.setSortInTempDb(true)
|
||||
.setColumnsIndex(new ArrayList<IndexTableDTO.ColumnIndex>() {{
|
||||
add(new IndexTableDTO.ColumnIndex("qta_col"));
|
||||
add(new IndexTableDTO.ColumnIndex("num_cnf"));
|
||||
}}));
|
||||
|
||||
dropIndex(connection, "mvw_mtb_colr_with_giacenza", "IDX_mvw_articolo_mtb_colr_with_giacenza");
|
||||
createIndex(connection, new IndexTableDTO()
|
||||
.setIndexName("IDX_mvw_articolo_mtb_colr_with_giacenza")
|
||||
.setTableName("mvw_mtb_colr_with_giacenza")
|
||||
.setMaxDop(1)
|
||||
.setSortInTempDb(true)
|
||||
.setColumnsIndex(new ArrayList<IndexTableDTO.ColumnIndex>() {{
|
||||
add(new IndexTableDTO.ColumnIndex("cod_mart"));
|
||||
add(new IndexTableDTO.ColumnIndex("partita_mag"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_tagl"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_col"));
|
||||
}}));
|
||||
|
||||
dropIndex(connection, "mvw_mtb_colr_with_giacenza", "IDX_mvw_articolo_giac_mtb_colr_with_giacenza");
|
||||
createIndex(connection, new IndexTableDTO()
|
||||
.setIndexName("IDX_mvw_articolo_giac_mtb_colr_with_giacenza")
|
||||
.setTableName("mvw_mtb_colr_with_giacenza")
|
||||
.setMaxDop(1)
|
||||
.setSortInTempDb(true)
|
||||
.setColumnsIndex(new ArrayList<IndexTableDTO.ColumnIndex>() {{
|
||||
add(new IndexTableDTO.ColumnIndex("cod_mart"));
|
||||
add(new IndexTableDTO.ColumnIndex("partita_mag"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_tagl"));
|
||||
add(new IndexTableDTO.ColumnIndex("cod_col"));
|
||||
}})
|
||||
.setColumnsInclude("qta_col", "num_cnf"));
|
||||
|
||||
executeStatement(connection, "UPDATE STATISTICS dbo.mvw_mtb_colr_with_giacenza");
|
||||
|
||||
|
||||
createOrUpdateView(connection, "mvw_sitart_udc_det_inventario", "CREATE VIEW [dbo].[mvw_sitart_udc_det_inventario] AS\n" +
|
||||
" WITH baseMtbColr AS (SELECT c,\n" +
|
||||
"\n" +
|
||||
" ROUND(v.qta_col, cifre_dec) AS qta_col,\n" +
|
||||
" ROUND(v.num_cnf, cifre_dec) AS num_cnf,\n" +
|
||||
" IIF(flag_qta_cnf_fissa = 'S',\n" +
|
||||
" v.qta_cnf_anag, v.qta_col / IIF(v.num_cnf = 0, 1, v.num_cnf)) AS qta_cnf,\n" +
|
||||
" v.cod_mart,\n" +
|
||||
" v.cod_col,\n" +
|
||||
" v.cod_tagl,\n" +
|
||||
" v.partita_mag,\n" +
|
||||
" v.peso_netto_kg,\n" +
|
||||
" v.peso_lordo_kg,\n" +
|
||||
" mtb_colt.gestione,\n" +
|
||||
" mtb_colt.data_collo,\n" +
|
||||
" mtb_colt.ser_collo,\n" +
|
||||
" mtb_colt.num_collo,\n" +
|
||||
" v.cod_jcom,\n" +
|
||||
" v.flag_qta_cnf_fissa,\n" +
|
||||
" v.unt_mis,\n" +
|
||||
" v.diacod,\n" +
|
||||
" v.descrizione_estesa,\n" +
|
||||
" v.cod_mgrp,\n" +
|
||||
" mtb_grup.descrizione AS descrizione_gruppo,\n" +
|
||||
" v.cod_msgr,\n" +
|
||||
" mtb_sgrp.descrizione AS descrizione_sottogruppo,\n" +
|
||||
" mtb_unt_mis.flag_dig,\n" +
|
||||
" mtb_unt_mis.cifre_dec,\n" +
|
||||
" mtb_colt.segno,\n" +
|
||||
" v.cod_mdep,\n" +
|
||||
" v.posizione,\n" +
|
||||
" mtb_colt.cod_dtip,\n" +
|
||||
" mtb_colt.cod_jfas,\n" +
|
||||
" v.barcode_ul,\n" +
|
||||
" v.qta_cnf_anag\n" +
|
||||
" FROM mvw_mtb_colr_with_giacenza v WITH (NOEXPAND)\n" +
|
||||
" INNER JOIN mtb_colt\n" +
|
||||
" ON v.barcode_ul = mtb_colt.barcode_ul\n" +
|
||||
" INNER JOIN dbo.mtb_unt_mis ON v.unt_mis = mtb_unt_mis.unt_mis\n" +
|
||||
"\n" +
|
||||
" INNER JOIN dbo.mtb_grup ON v.cod_mgrp = mtb_grup.cod_mgrp\n" +
|
||||
" INNER JOIN dbo.mtb_sgrp ON v.cod_mgrp = mtb_sgrp.cod_mgrp\n" +
|
||||
" AND v.cod_msgr = mtb_sgrp.cod_msgr\n" +
|
||||
" WHERE qta_col > 0\n" +
|
||||
" AND (segno = 1 OR (segno = -1 AND cod_dtip IS NULL AND mtb_colt.gestione = 'V'))\n" +
|
||||
" ),\n" +
|
||||
" final_stock AS (SELECT v.qta_col,\n" +
|
||||
" v.num_cnf,\n" +
|
||||
" v.qta_cnf,\n" +
|
||||
" v.gestione,\n" +
|
||||
" v.data_collo,\n" +
|
||||
" v.ser_collo,\n" +
|
||||
" v.num_collo,\n" +
|
||||
" v.cod_mdep AS cod_mdep,\n" +
|
||||
" v.posizione AS posizione,\n" +
|
||||
" mtb_depo_posizioni.priorita,\n" +
|
||||
" v.cod_mgrp AS codGruppo,\n" +
|
||||
" v.descrizione_gruppo AS Gruppo,\n" +
|
||||
" v.cod_msgr AS CodSgruppo,\n" +
|
||||
" v.descrizione_sottogruppo AS Sottogruppo,\n" +
|
||||
" v.cod_mart,\n" +
|
||||
" v.diacod,\n" +
|
||||
" v.descrizione_estesa,\n" +
|
||||
" v.partita_mag,\n" +
|
||||
" v.cod_col,\n" +
|
||||
" v.cod_tagl,\n" +
|
||||
" v.cod_jcom,\n" +
|
||||
" v.peso_netto_kg,\n" +
|
||||
" v.peso_lordo_kg,\n" +
|
||||
" v.cod_jfas,\n" +
|
||||
" v.flag_qta_cnf_fissa,\n" +
|
||||
" v.unt_mis,\n" +
|
||||
" v.segno,\n" +
|
||||
" v.barcode_ul\n" +
|
||||
" FROM baseMtbColr v\n" +
|
||||
"\n" +
|
||||
" LEFT OUTER JOIN mtb_depo_posizioni\n" +
|
||||
" ON v.cod_mdep = mtb_depo_posizioni.cod_mdep\n" +
|
||||
" AND v.posizione = mtb_depo_posizioni.posizione)\n" +
|
||||
"\n" +
|
||||
" SELECT qta_col,\n" +
|
||||
" num_cnf,\n" +
|
||||
" qta_cnf,\n" +
|
||||
" gestione,\n" +
|
||||
" data_collo,\n" +
|
||||
" ser_collo,\n" +
|
||||
" num_collo,\n" +
|
||||
" cod_mdep,\n" +
|
||||
" posizione,\n" +
|
||||
" priorita,\n" +
|
||||
" codGruppo,\n" +
|
||||
" Gruppo,\n" +
|
||||
" CodSgruppo,\n" +
|
||||
" Sottogruppo,\n" +
|
||||
" cod_mart,\n" +
|
||||
" diacod,\n" +
|
||||
" descrizione_estesa,\n" +
|
||||
" partita_mag,\n" +
|
||||
" cod_col,\n" +
|
||||
" cod_tagl,\n" +
|
||||
" cod_jcom,\n" +
|
||||
" peso_netto_kg,\n" +
|
||||
" peso_lordo_kg,\n" +
|
||||
" cod_jfas,\n" +
|
||||
" flag_qta_cnf_fissa,\n" +
|
||||
" unt_mis,\n" +
|
||||
" segno,\n" +
|
||||
" barcode_ul\n" +
|
||||
" FROM final_stock");
|
||||
}
|
||||
|
||||
|
||||
private static boolean existsView(Connection connection, String objectName) throws SQLException {
|
||||
return UtilityDB.<Integer>executeSimpleQueryOnlyFirstRowFirstColumn(connection, "SELECT COUNT(*) FROM SYSOBJECTS WHERE id = object_id('" + objectName + "')") > 0;
|
||||
}
|
||||
|
||||
|
||||
private static void dropView(Connection connection, String objectName) throws SQLException, IOException {
|
||||
UtilityDB.executeStatement(connection, "IF EXISTS (SELECT * FROM SYSOBJECTS WHERE id = object_id('" + objectName + "'))\r\n" +
|
||||
"\tDROP " + SqlObjectTypeEnum.VIEW.toString() + " " + objectName);
|
||||
}
|
||||
|
||||
private static boolean existsTable(Connection connection, String tableName) throws SQLException, IOException {
|
||||
String schema = null;
|
||||
if (tableName.contains(".")) {
|
||||
schema = tableName.substring(0, tableName.indexOf("."));
|
||||
tableName = tableName.replace(schema + ".", "");
|
||||
}
|
||||
|
||||
String sql = Query.format("SELECT CAST(COUNT(*) AS BIT) AS exist FROM INFORMATION_SCHEMA.TABLES " +
|
||||
"WHERE TABLE_NAME = N%s ", tableName);
|
||||
|
||||
if (schema != null)
|
||||
sql += Query.format("AND TABLE_SCHEMA = N%s", schema);
|
||||
|
||||
return UtilityDB.<Boolean>executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
private static void createIndex(Connection connection, IndexTableDTO indexTableDTO) throws Exception {
|
||||
UtilityDB.createIndex(connection, indexTableDTO);
|
||||
}
|
||||
|
||||
private static void dropIndex(Connection connection, String tableName, String indexName) throws Exception {
|
||||
UtilityDB.dropIndex(connection, tableName, indexName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
private static void executeStatement(Connection connection, String... sqls) throws SQLException {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
for (String sql : sqls) {
|
||||
statement.execute(sql);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
private static void createOrUpdateView(Connection connection, String objectName, String createViewSql) throws SQLException, IOException {
|
||||
alterObject(connection, SqlObjectTypeEnum.VIEW, objectName, createViewSql);
|
||||
}
|
||||
|
||||
private static void alterObject(Connection connection, SqlObjectTypeEnum sqlObject, String objectName, String sql) throws SQLException, IOException {
|
||||
executeStatement(connection, "IF EXISTS (SELECT * FROM SYSOBJECTS WHERE id = object_id('" + objectName + "'))\r\n" +
|
||||
"\tDROP " + sqlObject.toString() + " " + objectName,
|
||||
sql);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,11 @@ package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionModel;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.Statement;
|
||||
import java.util.List;
|
||||
@@ -14,9 +15,9 @@ public class Migration_20210721093948 extends BaseMigration implements Migration
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
AvailableConnectionModel historyDBModel = settingsController.getHistoryDbConnectionModel();
|
||||
AvailableConnectionsModel historyDBModel = settingsController.getHistoryDbConnectionModel();
|
||||
|
||||
if (!settingsModel.getDefaultProfile().equalsIgnoreCase(connection.getProfileName()))
|
||||
if (!settingsModel.getDefaultProfile().equalsIgnoreCase(advancedDataSource.getProfileName()))
|
||||
return;
|
||||
|
||||
if (historyDBModel == null)
|
||||
|
||||
@@ -12,7 +12,7 @@ public class Migration_20210721125744 extends BaseMigration implements Migration
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (!settingsModel.getDefaultProfile().equalsIgnoreCase(connection.getDbName()))
|
||||
if (!settingsModel.getDefaultProfile().equalsIgnoreCase(advancedDataSource.getDataSource().getDbName()))
|
||||
return;
|
||||
|
||||
String tomcatPath = System.getProperty("catalina.home");
|
||||
|
||||
@@ -2,10 +2,11 @@ package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionModel;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.Statement;
|
||||
import java.util.List;
|
||||
@@ -14,9 +15,9 @@ public class Migration_20210924152555 extends BaseMigration implements Migration
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
AvailableConnectionModel historyDBModel = settingsController.getHistoryDbConnectionModel();
|
||||
AvailableConnectionsModel historyDBModel = settingsController.getHistoryDbConnectionModel();
|
||||
|
||||
if (!settingsModel.getDefaultProfile().equalsIgnoreCase(connection.getProfileName()))
|
||||
if (!settingsModel.getDefaultProfile().equalsIgnoreCase(advancedDataSource.getProfileName()))
|
||||
return;
|
||||
|
||||
if (historyDBModel == null)
|
||||
|
||||
@@ -38,7 +38,7 @@ public class Migration_20211022131206 extends BaseMigration implements Migration
|
||||
" WHERE stb_user.user_name IS NULL ";
|
||||
|
||||
|
||||
List<WtbUsers> wtbUsersList = UtilityDB.executeSimpleQueryDTO(connection, sql, WtbUsers.class);
|
||||
List<WtbUsers> wtbUsersList = UtilityDB.executeSimpleQueryDTO(advancedDataSource.getConnection(), sql, WtbUsers.class);
|
||||
|
||||
if (wtbUsersList == null) return;
|
||||
|
||||
@@ -54,7 +54,7 @@ public class Migration_20211022131206 extends BaseMigration implements Migration
|
||||
.setFlagAttivo(wtbUser.getCtrlState());
|
||||
|
||||
stbUser.setOperation(OperationType.INSERT);
|
||||
stbUser.manageWithParentConnection(connection, droolsDataCompleting);
|
||||
stbUser.manageWithParentConnection(advancedDataSource.getConnection(), droolsDataCompleting);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -19,10 +19,10 @@ public class Migration_20211027170945 extends BaseMigration implements Migration
|
||||
"WHERE Name = N'orientation' " +
|
||||
" AND Object_ID = Object_ID(N'dbo.wtb_jrept')";
|
||||
|
||||
boolean fieldExists = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
boolean fieldExists = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
if (!fieldExists) {
|
||||
sql = "ALTER TABLE wtb_jrept ADD orientation INT DEFAULT 0 NOT NULL CHECK (orientation IN (0, 1))";
|
||||
Statement statement = connection.createStatement();
|
||||
Statement statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute(sql);
|
||||
statement.close();
|
||||
}
|
||||
|
||||
@@ -18,12 +18,12 @@ public class Migration_20211108185224 extends BaseMigration implements Migration
|
||||
|
||||
AutomatedOperationHandlerComponent automatedOperationHandlerComponent = ContextLoader.getCurrentWebApplicationContext().getBean(AutomatedOperationHandlerComponent.class);
|
||||
|
||||
final String migrateFileOperationName = "Migrate files grlAnagNote " + connection.getProfileName().toUpperCase();
|
||||
final String migrateFileOperationName = "Migrate files grlAnagNote " + advancedDataSource.getProfileName().toUpperCase();
|
||||
|
||||
ServiceCallAutomatedOperationDTO serviceCallAutomatedOperationDTO = new ServiceCallAutomatedOperationDTO()
|
||||
.setMethodName("migrateGtbAnagNoteFiles")
|
||||
.setProfileDb(connection.getProfileName())
|
||||
.setUsername(connection.getProfileName());
|
||||
.setProfileDb(advancedDataSource.getProfileName())
|
||||
.setUsername(advancedDataSource.getProfileName());
|
||||
|
||||
serviceCallAutomatedOperationDTO
|
||||
.setCronTrigger("0 0 0 1/1 * ?")
|
||||
|
||||
@@ -3,7 +3,6 @@ package it.integry.ems.migration.model;
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
import it.integry.ems.service.PrinterService;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems_model.entity.GrlAnagJrept;
|
||||
import it.integry.ems_model.entity.MtbDepo;
|
||||
import it.integry.ems_model.entity.WtbJreptSetup;
|
||||
@@ -14,6 +13,8 @@ import it.integry.ems_model.utility.UtilityString;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -28,11 +29,11 @@ public class Migration_20220405180136 extends BaseMigration implements Migration
|
||||
String checkTableSpesExistsSql = "SELECT CAST(COUNT(*) AS BIT) AS exist_table " +
|
||||
"FROM INFORMATION_SCHEMA.TABLES " +
|
||||
"WHERE TABLE_NAME = 'wtb_jrept_setup'";
|
||||
boolean existTable = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, checkTableSpesExistsSql);
|
||||
boolean existTable = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), checkTableSpesExistsSql);
|
||||
|
||||
if (!existTable) {
|
||||
|
||||
Statement statement = connection.createStatement();
|
||||
Statement statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute("CREATE TABLE wtb_jrept_setup\n" +
|
||||
"(\n" +
|
||||
" id BIGINT IDENTITY\n" +
|
||||
@@ -50,26 +51,26 @@ public class Migration_20220405180136 extends BaseMigration implements Migration
|
||||
")");
|
||||
statement.close();
|
||||
|
||||
statement = connection.createStatement();
|
||||
statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute("CREATE UNIQUE INDEX wtb_jrept_setup_report_id_cod_mdep_tipo_uindex " +
|
||||
"ON wtb_jrept_setup (report_id, cod_mdep, tipo)");
|
||||
statement.close();
|
||||
|
||||
connection.commit();
|
||||
advancedDataSource.getConnection().commit();
|
||||
|
||||
ArrayList<WtbJreptSetup> jreptSetupsToInsert = new ArrayList<>();
|
||||
|
||||
String sqlDepo = "SELECT cod_mdep FROM " + MtbDepo.ENTITY;
|
||||
List<String> codMdeps = UtilityDB.executeSimpleQueryOnlyFirstColumn(connection, sqlDepo);
|
||||
List<String> codMdeps = UtilityDB.executeSimpleQueryOnlyFirstColumn(advancedDataSource.getConnection(), sqlDepo);
|
||||
|
||||
if (codMdeps != null && !codMdeps.isEmpty()) {
|
||||
|
||||
for (String codMdep : codMdeps) {
|
||||
String stampantePrimaria = getPrinterNameByDepo(connection, codMdep, null, PrinterService.Type.PRIMARIA);
|
||||
String stampanteSecondaria = getPrinterNameByDepo(connection, codMdep, null, PrinterService.Type.SECONDARIA);
|
||||
String stampantePrimaria = getPrinterNameByDepo(advancedDataSource.getConnection(), codMdep, null, PrinterService.Type.PRIMARIA);
|
||||
String stampanteSecondaria = getPrinterNameByDepo(advancedDataSource.getConnection(), codMdep, null, PrinterService.Type.SECONDARIA);
|
||||
|
||||
String grlAnagJreptSql = "SELECT DISTINCT report_id, tipo FROM " + GrlAnagJrept.ENTITY;
|
||||
List<GrlAnagJrept> grlAnagJrepts = UtilityDB.executeSimpleQueryDTO(connection, grlAnagJreptSql, GrlAnagJrept.class);
|
||||
List<GrlAnagJrept> grlAnagJrepts = UtilityDB.executeSimpleQueryDTO(advancedDataSource.getConnection(), grlAnagJreptSql, GrlAnagJrept.class);
|
||||
|
||||
if (grlAnagJrepts != null && !UtilityString.isNullOrEmpty(stampantePrimaria)) {
|
||||
for (GrlAnagJrept grlAnagJrept : grlAnagJrepts) {
|
||||
@@ -89,7 +90,7 @@ public class Migration_20220405180136 extends BaseMigration implements Migration
|
||||
}
|
||||
|
||||
for (WtbJreptSetup wtbJreptSetup : jreptSetupsToInsert) {
|
||||
wtbJreptSetup.manageWithParentConnection(connection, droolsDataCompleting);
|
||||
wtbJreptSetup.manageWithParentConnection(advancedDataSource.getConnection(), droolsDataCompleting);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ public class Migration_20220413102657 extends BaseMigration implements Migration
|
||||
" WHERE stb_user.user_name IS NULL ";
|
||||
|
||||
|
||||
List<WtbUsers> wtbUsersList = UtilityDB.executeSimpleQueryDTO(connection, sql, WtbUsers.class);
|
||||
List<WtbUsers> wtbUsersList = UtilityDB.executeSimpleQueryDTO(advancedDataSource.getConnection(), sql, WtbUsers.class);
|
||||
|
||||
if (wtbUsersList == null) return;
|
||||
|
||||
@@ -63,10 +63,11 @@ public class Migration_20220413102657 extends BaseMigration implements Migration
|
||||
.setCreationDatetime(wtbUser.getCreationDatetime())
|
||||
.setPasswordExpiresDays(wtbUser.getPasswordExpiresDays())
|
||||
.setLastPasswords(wtbUser.getLastPasswords())
|
||||
.setFlagPasswordExpiring(wtbUser.getFlagPasswordExpiring());
|
||||
.setFlagPasswordExpiring(wtbUser.getFlagPasswordExpiring())
|
||||
.setDestructionDatetime(wtbUser.getDestructionDatetime());;
|
||||
|
||||
stbUser.setOperation(OperationType.INSERT);
|
||||
stbUser.manageWithParentConnection(connection, droolsDataCompleting);
|
||||
stbUser.manageWithParentConnection(advancedDataSource.getConnection(), droolsDataCompleting);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ public class Migration_20220415094936 extends BaseMigration implements Migration
|
||||
"SET flag_default_contabilita = 'S', flag_default = 'N' " +
|
||||
"WHERE flag_default = 'S'";
|
||||
|
||||
PreparedStatement updateDefaultFlagPS = connection.prepareStatement(updateDefaultFlagSql);
|
||||
PreparedStatement updateDefaultFlagPS = advancedDataSource.getConnection().prepareStatement(updateDefaultFlagSql);
|
||||
updateDefaultFlagPS.setQueryTimeout(30);
|
||||
updateDefaultFlagPS.executeUpdate();
|
||||
updateDefaultFlagPS.close();
|
||||
@@ -38,13 +38,13 @@ public class Migration_20220415094936 extends BaseMigration implements Migration
|
||||
" FROM " + StbEmail.ENTITY +
|
||||
" WHERE e_mail = " + UtilityDB.valueToString(mailConfiguration.getFrom());
|
||||
|
||||
boolean exists = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
boolean exists = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
|
||||
|
||||
if (!exists) {
|
||||
boolean isOffice365 = mailConfiguration.getSmtp().contains("office365");
|
||||
|
||||
int newId = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection,
|
||||
int newId = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(),
|
||||
"SELECT ISNULL(MAX(id_riga), 0) + 1 as new_id " +
|
||||
"FROM stb_email");
|
||||
|
||||
@@ -61,7 +61,7 @@ public class Migration_20220415094936 extends BaseMigration implements Migration
|
||||
.setFlagDefault(isOffice365 ? "S" : "N");
|
||||
|
||||
stbEmail.setOperation(OperationType.INSERT);
|
||||
stbEmail.manageWithParentConnection(connection, droolsDataCompleting);
|
||||
stbEmail.manageWithParentConnection(advancedDataSource.getConnection(), droolsDataCompleting);
|
||||
|
||||
if (!isOffice365) {
|
||||
String noReplyFrom = "noreply@" + mailConfiguration.getFrom().split("@")[1];
|
||||
@@ -79,14 +79,14 @@ public class Migration_20220415094936 extends BaseMigration implements Migration
|
||||
.setFlagDefault("S");
|
||||
|
||||
stbEmailNoReply.setOperation(OperationType.INSERT);
|
||||
stbEmailNoReply.manageWithParentConnection(connection, droolsDataCompleting);
|
||||
stbEmailNoReply.manageWithParentConnection(advancedDataSource.getConnection(), droolsDataCompleting);
|
||||
}
|
||||
} else {
|
||||
updateDefaultFlagSql = "UPDATE stb_email " +
|
||||
"SET flag_default = 'S' " +
|
||||
"WHERE e_mail = " + UtilityDB.valueToString(mailConfiguration.getFrom());
|
||||
|
||||
updateDefaultFlagPS = connection.prepareStatement(updateDefaultFlagSql);
|
||||
updateDefaultFlagPS = advancedDataSource.getConnection().prepareStatement(updateDefaultFlagSql);
|
||||
updateDefaultFlagPS.setQueryTimeout(30);
|
||||
updateDefaultFlagPS.executeUpdate();
|
||||
updateDefaultFlagPS.close();
|
||||
|
||||
@@ -3,7 +3,6 @@ package it.integry.ems.migration.model;
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
import it.integry.ems.service.PrinterService;
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
import it.integry.ems_model.entity.GrlAnagJrept;
|
||||
import it.integry.ems_model.entity.MtbDepo;
|
||||
import it.integry.ems_model.entity.WtbJrept;
|
||||
@@ -15,6 +14,8 @@ import it.integry.ems_model.utility.UtilityString;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import it.integry.ems.sync.MultiDBTransaction.Connection;
|
||||
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -29,15 +30,15 @@ public class Migration_20220421125860 extends BaseMigration implements Migration
|
||||
String checkTableSpesExistsSql = "SELECT CAST(COUNT(*) AS BIT) AS exist_table " +
|
||||
"FROM INFORMATION_SCHEMA.TABLES " +
|
||||
"WHERE TABLE_NAME = 'wtb_jrept_setup'";
|
||||
boolean existTable = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, checkTableSpesExistsSql);
|
||||
boolean existTable = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), checkTableSpesExistsSql);
|
||||
|
||||
if (existTable) {
|
||||
Statement statement = connection.createStatement();
|
||||
Statement statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute("drop table wtb_jrept_setup");
|
||||
statement.close();
|
||||
}
|
||||
|
||||
Statement statement = connection.createStatement();
|
||||
Statement statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute("create table wtb_jrept_setup\n" +
|
||||
"(\n" +
|
||||
" id bigint identity\n" +
|
||||
@@ -59,7 +60,7 @@ public class Migration_20220421125860 extends BaseMigration implements Migration
|
||||
")");
|
||||
statement.close();
|
||||
|
||||
statement = connection.createStatement();
|
||||
statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute("create unique index wtb_jrept_setup_cod_mdep_tipo_cod_anag_uindex" +
|
||||
" on wtb_jrept_setup (cod_mdep, tipo, cod_anag)");
|
||||
statement.close();
|
||||
@@ -67,17 +68,17 @@ public class Migration_20220421125860 extends BaseMigration implements Migration
|
||||
ArrayList<WtbJreptSetup> jreptSetupsToInsert = new ArrayList<>();
|
||||
|
||||
String sqlAnagJrept = "SELECT * FROM " + GrlAnagJrept.ENTITY + " ";
|
||||
List<GrlAnagJrept> anagJrepts = UtilityDB.executeSimpleQueryDTO(connection, sqlAnagJrept, GrlAnagJrept.class);
|
||||
List<GrlAnagJrept> anagJrepts = UtilityDB.executeSimpleQueryDTO(advancedDataSource.getConnection(), sqlAnagJrept, GrlAnagJrept.class);
|
||||
|
||||
String sqlDepo = "SELECT cod_mdep FROM " + MtbDepo.ENTITY;
|
||||
List<String> codMdeps = UtilityDB.executeSimpleQueryOnlyFirstColumn(connection, sqlDepo);
|
||||
List<String> codMdeps = UtilityDB.executeSimpleQueryOnlyFirstColumn(advancedDataSource.getConnection(), sqlDepo);
|
||||
|
||||
if (anagJrepts != null && !anagJrepts.isEmpty()) {
|
||||
|
||||
for (GrlAnagJrept anagReport : anagJrepts) {
|
||||
|
||||
String sqlOrientationReport = "SELECT orientation FROM " + WtbJrept.ENTITY + " where id = " + UtilityDB.valueToString(anagReport.getReportId());
|
||||
int orientation = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sqlOrientationReport);
|
||||
int orientation = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sqlOrientationReport);
|
||||
|
||||
WtbJreptSetup wtbJreptSetup = new WtbJreptSetup()
|
||||
.setCodMdep(null)
|
||||
@@ -91,7 +92,7 @@ public class Migration_20220421125860 extends BaseMigration implements Migration
|
||||
|
||||
if (codMdeps != null && !codMdeps.isEmpty()) {
|
||||
for (String codMdep : codMdeps) {
|
||||
String stampantePrimaria = getPrinterNameByDepo(connection, codMdep, null, PrinterService.Type.PRIMARIA);
|
||||
String stampantePrimaria = getPrinterNameByDepo(advancedDataSource.getConnection(), codMdep, null, PrinterService.Type.PRIMARIA);
|
||||
if (!UtilityString.isNullOrEmpty(stampantePrimaria)) {
|
||||
|
||||
WtbJreptSetup wtbJreptSetupDepo = new WtbJreptSetup()
|
||||
@@ -115,7 +116,7 @@ public class Migration_20220421125860 extends BaseMigration implements Migration
|
||||
}
|
||||
|
||||
for (WtbJreptSetup wtbJreptSetup : jreptSetupsToInsert) {
|
||||
wtbJreptSetup.manageWithParentConnection(connection);
|
||||
wtbJreptSetup.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,13 +17,13 @@ public class Migration_20220510103554 extends BaseMigration implements Migration
|
||||
"FROM sys.columns " +
|
||||
"WHERE Name = N'ref_uuid' " +
|
||||
"AND Object_ID = Object_ID(N'dbo.stb_activity_file')";
|
||||
boolean existColumn = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, checkTableSpesExistsSql);
|
||||
boolean existColumn = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), checkTableSpesExistsSql);
|
||||
|
||||
if (existColumn) {
|
||||
return;
|
||||
}
|
||||
|
||||
Statement statement = connection.createStatement();
|
||||
Statement statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute("ALTER TABLE stb_activity_file " +
|
||||
"ADD ref_uuid VARCHAR(36) NULL");
|
||||
statement.close();
|
||||
|
||||
@@ -17,13 +17,13 @@ public class Migration_20220510123355 extends BaseMigration implements Migration
|
||||
"FROM sys.columns " +
|
||||
"WHERE Name = N'ref_uuid1' " +
|
||||
"AND Object_ID = Object_ID(N'dbo.stb_activity_file')";
|
||||
boolean existColumn = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, checkTableSpesExistsSql);
|
||||
boolean existColumn = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), checkTableSpesExistsSql);
|
||||
|
||||
if (existColumn) {
|
||||
return;
|
||||
}
|
||||
|
||||
Statement statement = connection.createStatement();
|
||||
Statement statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute("ALTER TABLE stb_activity_file " +
|
||||
"ADD ref_uuid1 VARCHAR(36) NULL");
|
||||
statement.close();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user