Versione ristrutturata

This commit is contained in:
Gaetano Savo 2025-06-30 10:32:05 +02:00
parent d6a7b653ec
commit 7afe463354
22 changed files with 684 additions and 686 deletions

34
.gitignore vendored
View File

@ -1,33 +1,3 @@
HELP.md
.vscode/
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
*.log

177
README.md
View File

@ -1,119 +1,102 @@
# Spring Boot Batch Data Processing
# Spring Boot Batch Demo
Questo progetto è un'applicazione Spring Boot Batch per il processing di dati.
Partiti con
creare un progetto con un job "Spring Boot Batch" con database jdbc:sqlserver://;serverName=localhost;databaseName=C6StampeCentralizzate user: F701264 pass: centrsei
aggiungere un secondo database jdbc:sqlserver://;serverName=localhost;databaseName=SEIReport user: F701264 pass: centrsei
Una semplice applicazione Spring Boot Batch che inserisce una riga su LogN.
## Requisiti
- Java 17
- Java 21 o superiore
- Maven
## Struttura del Progetto
- `src/main/java/com/fideuram/batch/BatchApplication.java`: Classe principale dell'applicazione
- `src/main/java/com/fideuram/batch/config/BatchConfig.java`: Configurazione base dei batch job
- `src/main/java/com/fideuram/batch/config/PreTrimestraleJobConfig.java`: Configurazione del job PreTrimestrale
- `src/main/resources/application.properties`: File di configurazione
- `src/main/resources/schema.sql`: Script di creazione delle tabelle batch
## Jobs Disponibili
### PreTrimestrale Job
Job che esegue le operazioni preliminari per l'elaborazione trimestrale:
1. Invio email di notifica inizio processo
2. Truncate della tabella C6MartPeriodico.tab_semaforo
3. Avvio elaborazione trimestrale:
- Esecuzione SP_Valorizza_Stati_semaforo_TRIM
- Rimozione record con id_milestone > 8
4. Congelamento contratti SEI:
- Esecuzione RP_ST_CONTRATTIPRETRIMESTRALE
5. Invio email di notifica fine processo
### RicodificaMassiva Job
Job indipendente che esegue la ricodifica massiva dei codici fiscali su entrambi i database:
1. Ricodifica su SEIReport:
- Esecuzione srv_change_codfiscaleMassiva_CU sul database SEIReport
2. Ricodifica su C6StampeCentralizzate:
- Esecuzione srv_change_codfiscaleMassiva_CU sul database C6StampeCentralizzate
### AppoContratti Job
Job che gestisce la creazione e l'aggiornamento della tabella APPO_CONTRATTI. Include automaticamente l'esecuzione del RicodificaMassiva Job come prerequisito:
1. Esecuzione RicodificaMassiva Job:
- Ricodifica codici fiscali su SEIReport
- Ricodifica codici fiscali su C6StampeCentralizzate
2. Creazione APPO_CONTRATTI:
- Esecuzione RP_ST_APPO_CONTRATTI
## Flusso di Esecuzione
I job possono essere eseguiti in tre modi:
1. **RicodificaMassiva**: Esegue solo la ricodifica dei codici fiscali su entrambi i database
2. **AppoContratti**: Esegue prima RicodificaMassiva e poi crea la tabella APPO_CONTRATTI
3. **PreTrimestrale**: Esegue le operazioni preliminari per l'elaborazione trimestrale
## Come eseguire
1. Compilare il progetto: `mvn clean package`
2. Eseguire un job specifico:
```bash
# Eseguire il job PreTrimestrale
java -jar target/batch-data-processing-0.0.1-SNAPSHOT.jar --spring.batch.job.names=preTrimestraleJob
# Eseguire il job AppoContratti (include RicodificaMassiva)
java -jar target/batch-data-processing-0.0.1-SNAPSHOT.jar --spring.batch.job.names=appoContrattiJob
# Eseguire solo il job RicodificaMassiva
java -jar target/batch-data-processing-0.0.1-SNAPSHOT.jar --spring.batch.job.names=ricodificaMassivaJob
```
```plaintext
src/main/java/com/armundia/bulk/
├── BatchApplication.java # Classe principale dell'applicazione
└── config/
└── BatchDispachConfig.java # Configurazione del batch job
```
## Configurazione
### Database
Il progetto utilizza:
#### Database Principale (C6StampeCentralizzate)
- Server: localhost
- Database: C6StampeCentralizzate
- Username: F701264
- Schema utilizzati:
- C6MartPeriodico: contiene tab_semaforo e SP_Valorizza_Stati_semaforo_TRIM
- C6StagingPeriodico: contiene RP_ST_APPO_CONTRATTI e RP_ST_CONTRATTIPRETRIMESTRALE
- Spring Boot 3.2.0
- Spring Batch
- Database SQL Server
#### Database Secondario (SEIReport)
- Server: localhost
- Database: SEIReport
- Username: F701264
- Stored Procedure:
- srv_change_codfiscaleMassiva_CUPRETRIMESTRALE
## Come Eseguire
### Email
Utilizzare lo script `build.bat` per compilare ed eseguire l'applicazione:
- SMTP: smtp.gmail.com
- Porta: 587
- SSL/TLS: abilitato
- Mittente: configurato in application.properties
- Destinatari: configurabili in application.properties (supporta multiple destinazioni)
1. Compilare il progetto:
### Batch
```batch
build.bat compile
```
- I job batch non partono automaticamente (spring.batch.job.enabled=false)
- Le tabelle batch vengono create automaticamente se non esistono
1. Eseguire l'applicazione:
### Stored Procedures
```batch
build.bat run
```
#### C6StampeCentralizzate
L'applicazione avvierà automaticamente il job batch che inserirà una riga su LogN.
- `C6MartPeriodico.SP_Valorizza_Stati_semaforo_TRIM`: Avvia l'elaborazione trimestrale
- `C6StagingPeriodico.RP_ST_CONTRATTIPRETRIMESTRALE`: Congela i contratti SEI
- `C6StagingPeriodico.RP_ST_APPO_CONTRATTI`: Crea la tabella APPO_CONTRATTI
- `srv_change_codfiscaleMassiva_CU`: Ricodifica i codici fiscali
## Dettagli Implementazione
#### SEIReport
- Il job (`dispachJob`) contiene due step in sequenza:
1. `ciaoStep`: inserisce una riga su LogN nel database C6StampeCentralizzate
2. `seiReportStep`: interagisce con il database SEIReport
- Ogni step utilizza il proprio JdbcTemplate dedicato per il database corrispondente
- Il job viene eseguito automaticamente all'avvio dell'applicazione grazie alla configurazione `spring.batch.job.enabled=true`
- `srv_change_codfiscaleMassiva_CU`: Ricodifica i codici fiscali
### Gestione delle Dipendenze
L'applicazione utilizza l'iniezione delle dipendenze di Spring per gestire i JdbcTemplate:
```java
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "c6stampeJdbcTemplate")
public JdbcTemplate c6stampeJdbcTemplate(DataSource c6stampeDataSource) {
return new JdbcTemplate(c6stampeDataSource);
}
}
@Configuration
public class BatchDispachConfig {
public BatchDispachConfig(JdbcTemplate c6stampeJdbcTemplate) {
this.c6stampeJdbcTemplate = c6stampeJdbcTemplate;
}
}
```
Spring risolve le dipendenze in questo modo:
1. Cerca un bean di tipo `JdbcTemplate`
2. Se trova più bean dello stesso tipo:
- Controlla se uno è marcato come `@Primary`
- Controlla se il nome del bean corrisponde al nome del parametro
- Usa `@Qualifier` se specificato
## Flusso dell'Applicazione
1. L'applicazione parte da `BatchApplication` (classe principale con `@SpringBootApplication`)
2. Spring Boot esegue la scansione del package `com.armundia.bulk` e trova:
- `BatchDispachConfig` (annotata con `@Configuration`)
- Crea automaticamente i bean definiti in `BatchDispachConfig`
3. `BatchApplication` utilizza il job attraverso:
```java
@Autowired
private Job dispachJob;
```
4. Il job viene eseguito automaticamente dal `CommandLineRunner` che:
- Crea i parametri del job (timestamp)
- Lancia il job usando `jobLauncher.run(dispachJob, params)`

27
build.bat Normal file
View File

@ -0,0 +1,27 @@
@echo off
setlocal
rem Imposta JAVA_HOME
set JAVA_HOME=C:\Dev2012\BUILDERS\java\jdk-21.0.6
rem Aggiungi java al PATH
set PATH=%JAVA_HOME%\bin;%PATH%
if "%1"=="compile" (
echo Compilazione del progetto...
call mvn clean package
goto :eof
)
if "%1"=="run" (
echo Avvio dell'applicazione...
if not exist target\pdcreport-bulk-0.0.1-SNAPSHOT.jar (
call mvn clean package
)
java -jar target\pdcreport-bulk-0.0.1-SNAPSHOT.jar --spring.batch.job.name=dispachJob >run.log 2>&1
goto :eof
)
echo Utilizzo:
echo build.bat compile - Compila il progetto
echo build.bat run - Esegue l'applicazione

43
create_user.sql Normal file
View File

@ -0,0 +1,43 @@
-- Connessione al master database per creare il login
USE [master];
GO
-- Creazione del login a livello di SQL Server
IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = 'c6stampa')
BEGIN
CREATE LOGIN [c6stampa] WITH PASSWORD = 'centrsei',
DEFAULT_DATABASE = [C6StampeCentralizzate],
CHECK_EXPIRATION = OFF,
CHECK_POLICY = OFF;
END
GO
-- Configurazione per C6StampeCentralizzate
USE [C6StampeCentralizzate];
GO
-- Creazione dell'utente nel database C6StampeCentralizzate
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = 'c6stampa')
BEGIN
CREATE USER [c6stampa] FOR LOGIN [c6stampa];
-- Aggiunta ai ruoli necessari
ALTER ROLE [db_datareader] ADD MEMBER [c6stampa];
ALTER ROLE [db_datawriter] ADD MEMBER [c6stampa];
END
GO
-- Configurazione per SEIReport
USE [SEIReport];
GO
-- Creazione dell'utente nel database SEIReport
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = 'c6stampa')
BEGIN
CREATE USER [c6stampa] FOR LOGIN [c6stampa];
-- Aggiunta ai ruoli necessari
ALTER ROLE [db_datareader] ADD MEMBER [c6stampa];
ALTER ROLE [db_datawriter] ADD MEMBER [c6stampa];
END
GO

65
pom.xml
View File

@ -4,24 +4,21 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fideuram</groupId>
<artifactId>batch-data-processing</artifactId>
<groupId>com.armundia</groupId>
<artifactId>pdcreport-bulk</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Batch Data Processing</name>
<description>Spring Boot Batch Data Processing Application</description>
<name>pdcreport-bulk</name>
<description>PDC Report Bulk</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.13</version>
<version>3.2.0</version>
<relativePath/>
</parent>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>21</java.version>
</properties>
<dependencies>
@ -31,37 +28,21 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -69,30 +50,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.fideuram.batch.BatchApplication</mainClass>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -1,13 +0,0 @@
@echo off
echo Starting Sample Job...
:: Check if JAVA_HOME is set
if not defined JAVA_HOME (
echo Error: JAVA_HOME is not set
exit /b 1
)
:: Run the Spring Boot application with the job parameter
mvn spring-boot:run -Dspring-boot.run.arguments="--spring.batch.job.names=helloWorldJob"
echo Job execution completed.

View File

@ -0,0 +1,12 @@
package com.armundia.bulk;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BatchApplication {
public static void main(String[] args) {
SpringApplication.run(BatchApplication.class, args);
}
}

View File

@ -0,0 +1,68 @@
package com.armundia.bulk.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.transaction.PlatformTransactionManager;
import com.armundia.bulk.mail.BatchMailMessage;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public abstract class AbstractBatchConfig {
protected final JdbcTemplate c6stampeJdbcTemplate;
protected final JdbcTemplate seireportJdbcTemplate;
protected final Logger logger;
@Autowired
protected JavaMailSender mailSender;
@Autowired
protected BatchMailMessage mailMessage;
protected AbstractBatchConfig(
@Qualifier("c6stampeJdbcTemplate") JdbcTemplate c6stampeJdbcTemplate,
@Qualifier("seireportJdbcTemplate") JdbcTemplate seireportJdbcTemplate) {
this.c6stampeJdbcTemplate = c6stampeJdbcTemplate;
this.seireportJdbcTemplate = seireportJdbcTemplate;
this.logger = LoggerFactory.getLogger(this.getClass());
}
protected Step createNotificationStep(
String stepName,
String subject,
String messageTemplate,
JobRepository jobRepository,
PlatformTransactionManager transactionManager) {
logger.info("Configurazione dello step {}", stepName);
return new StepBuilder(stepName, jobRepository)
.tasklet((contribution, chunkContext) -> {
try {
String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
String message = String.format(messageTemplate, now);
mailMessage.clone()
.withSubject(subject)
.withText(message)
.send(mailSender);
logger.info("Mail inviata con successo per lo step {}", stepName);
} catch (Exception e) {
logger.error("Errore nell'invio della mail per lo step {}: {}", stepName, e.getMessage());
// Non blocchiamo l'esecuzione se la mail fallisce
}
return RepeatStatus.FINISHED;
}, transactionManager)
.build();
}
}

View File

@ -1,58 +1,56 @@
package com.fideuram.batch.config;
package com.armundia.bulk.config;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Configuration
public class AppoContrattiJobConfig {
public class AppoContrattiJobConfig extends AbstractBatchConfig {
private static final Logger logger = LoggerFactory.getLogger(AppoContrattiJobConfig.class);
@Autowired
private JdbcTemplate jdbcTemplate;
public AppoContrattiJobConfig(
@Qualifier("c6stampeJdbcTemplate") JdbcTemplate c6stampeJdbcTemplate,
@Qualifier("seireportJdbcTemplate") JdbcTemplate seireportJdbcTemplate) {
super(c6stampeJdbcTemplate, seireportJdbcTemplate);
}
@Autowired
private Job ricodificaMassivaJob;
@Bean
public Job appoContrattiJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder("appoContrattiJob")
.start(ricodificaMassivaFlow(jobRepository, transactionManager))
.next(creaAppoContrattiStep(jobRepository, transactionManager))
public Job appoContrattiJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, Step ricodificaMassivaFlow, Step creaAppoContrattiStep) {
return new JobBuilder("appoContrattiJob", jobRepository)
.incrementer(new RunIdIncrementer())
.start(ricodificaMassivaFlow)
.next(creaAppoContrattiStep)
.build();
}
@Bean
public Step ricodificaMassivaFlow(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("ricodificaMassivaFlow")
.repository(jobRepository)
.transactionManager(transactionManager)
return new StepBuilder("ricodificaMassivaFlow", jobRepository)
.job(ricodificaMassivaJob)
.build();
}
@Bean
public Step creaAppoContrattiStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("creaAppoContrattiStep")
.repository(jobRepository)
.transactionManager(transactionManager)
return new StepBuilder("creaAppoContrattiStep", jobRepository)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione C6StagingPeriodico.RP_ST_APPO_CONTRATTI");
jdbcTemplate.execute("EXEC C6StagingPeriodico.RP_ST_APPO_CONTRATTI");
c6stampeJdbcTemplate.execute("EXEC C6StagingPeriodico.RP_ST_APPO_CONTRATTI");
logger.info("Completata esecuzione C6StagingPeriodico.RP_ST_APPO_CONTRATTI");
return RepeatStatus.FINISHED;
})
}, transactionManager)
.build();
}
}

View File

@ -0,0 +1,104 @@
package com.armundia.bulk.config;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.beans.factory.annotation.Qualifier;
@Configuration
public class BatchDispachConfig extends AbstractBatchConfig {
public BatchDispachConfig(
@Qualifier("c6stampeJdbcTemplate") JdbcTemplate c6stampeJdbcTemplate,
@Qualifier("seireportJdbcTemplate") JdbcTemplate seireportJdbcTemplate) {
super(c6stampeJdbcTemplate, seireportJdbcTemplate);
}
@Bean
public Job dispachJob(JobRepository jobRepository, Step ciaoStep, Step seiReportStep, Step notifySampleEndStep) {
logger.info("Configurazione del job dispachJob");
return new JobBuilder("dispachJob", jobRepository)
.incrementer(new RunIdIncrementer())
.start(ciaoStep)
.next(seiReportStep)
.next(notifySampleEndStep)
.build();
}
@Bean
public Step seiReportStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
logger.info("Configurazione dello step seiReportStep");
return new StepBuilder("seiReportStep", jobRepository)
.tasklet((contribution, chunkContext) -> {
logger.debug("Inizio esecuzione tasklet SEIReport");
try {
logger.info("Verifica connessione al database SEIReport...");
seireportJdbcTemplate.queryForObject("SELECT 1", Integer.class);
logger.info("Connessione al database SEIReport OK");
logger.info("Esecuzione query di inserimento...");
String sql = "INSERT INTO SEIReport.dbo.EventoLog (Codice, Testo) select coalesce(max(codice)+1,1), concat('Prova del ',CONVERT(VARCHAR, GETDATE(), 101)) from SEIReport.dbo.EventoLog";
logger.info("Query da eseguire: {}", sql);
seireportJdbcTemplate.update(sql);
logger.info("Inserimento su SEIReport completato");
return RepeatStatus.FINISHED;
} catch (Exception e) {
logger.error("Errore durante l'esecuzione dello step SEIReport: {}", e.getMessage(), e);
throw e;
}
}, transactionManager)
.build();
}
@Bean
public Step ciaoStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
logger.info("Configurazione dello step ciaoStep");
return new StepBuilder("ciaoStep", jobRepository)
.tasklet((contribution, chunkContext) -> {
logger.debug("Inizio esecuzione tasklet");
try {
logger.info("Verifica connessione al database...");
c6stampeJdbcTemplate.queryForObject("SELECT 1", Integer.class);
logger.info("Connessione al database OK");
logger.info("Esecuzione query di inserimento...");
String sql = "INSERT INTO C6StampeCentralizzate.dbo.LogN (Application, Logged, [Level], Message) VALUES('sampleStep',getDate(), 0, 'Avvio')";
logger.info("Query da eseguire: {}", sql);
int rowsAffected = c6stampeJdbcTemplate.update(sql);
logger.info("Inserimento completato con successo. Righe inserite: {}", rowsAffected);
// Verifica che l'inserimento sia avvenuto
Integer count = c6stampeJdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM C6StampeCentralizzate.dbo.LogN WHERE Application = 'sampleStep'",
Integer.class
);
logger.info("Verifica post-inserimento: trovate {} righe con Application='sampleStep'", count);
return RepeatStatus.FINISHED;
} catch (Exception e) {
logger.error("Errore durante l'esecuzione del batch: {}", e.getMessage(), e);
throw e;
}
}, transactionManager)
.build();
}
@Bean
public Step notifySampleEndStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return createNotificationStep(
"notifySampleEndStep",
"Fine processo Sample Batch",
"Il processo Sample Batch è terminato in data %s",
jobRepository,
transactionManager
);
}
}

View File

@ -0,0 +1,58 @@
package com.armundia.bulk.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Value("${spring.datasource.c6stampe.url}")
private String c6stampeUrl;
@Value("${spring.datasource.c6stampe.username}")
private String c6stampeUsername;
@Value("${spring.datasource.c6stampe.password}")
private String c6stampePassword;
@Value("${spring.datasource.seireport.url}")
private String seireportUrl;
@Value("${spring.datasource.seireport.username}")
private String seireportUsername;
@Value("${spring.datasource.seireport.password}")
private String seireportPassword;
@Primary
@Bean(name = "c6stampeDataSource")
public DataSource c6stampeDataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl(c6stampeUrl);
ds.setUsername(c6stampeUsername);
ds.setPassword(c6stampePassword);
return ds;
}
@Bean(name = "seireportDataSource")
public DataSource seireportDataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl(seireportUrl);
ds.setUsername(seireportUsername);
ds.setPassword(seireportPassword);
return ds;
}
@Primary
@Bean(name = "c6stampeJdbcTemplate")
public JdbcTemplate c6stampeJdbcTemplate(DataSource c6stampeDataSource) {
return new JdbcTemplate(c6stampeDataSource);
}
@Bean(name = "seireportJdbcTemplate")
public JdbcTemplate seireportJdbcTemplate(DataSource seireportDataSource) {
return new JdbcTemplate(seireportDataSource);
}
}

View File

@ -0,0 +1,97 @@
package com.armundia.bulk.config;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
public class PreTrimestraleJobConfig extends AbstractBatchConfig {
public PreTrimestraleJobConfig(
@Qualifier("c6stampeJdbcTemplate") JdbcTemplate c6stampeJdbcTemplate,
@Qualifier("seireportJdbcTemplate") JdbcTemplate seireportJdbcTemplate) {
super(c6stampeJdbcTemplate, seireportJdbcTemplate);
}
@Bean
public Job preTrimestraleJob(JobRepository jobRepository, Step notifyStartStep, Step truncateStep, Step avvioTrimestraleStep, Step congelamentoContrattiStep, Step notifyEndStep) {
logger.info("Configurazione del job preTrimestraleJob");
return new JobBuilder("preTrimestraleJob", jobRepository)
.incrementer(new RunIdIncrementer())
.start(notifyStartStep)
.next(truncateStep)
.next(avvioTrimestraleStep)
.next(congelamentoContrattiStep)
.next(notifyEndStep)
.build();
}
@Bean
public Step notifyStartStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return createNotificationStep(
"notifyStartStep",
"Inizio processo PreTrimestrale",
"Il processo PreTrimestrale è stato avviato in data %s",
jobRepository,
transactionManager
);
}
@Bean
public Step truncateStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("truncateStep", jobRepository)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione truncate table C6MartPeriodico.tab_semaforo");
c6stampeJdbcTemplate.execute("truncate table C6MartPeriodico.tab_semaforo");
logger.info("Completata esecuzione truncate");
return RepeatStatus.FINISHED;
}, transactionManager)
.build();
}
@Bean
public Step avvioTrimestraleStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("avvioTrimestraleStep", jobRepository)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione Avvio Trimestrale");
c6stampeJdbcTemplate.execute(
"exec C6MartPeriodico.SP_Valorizza_Stati_semaforo_TRIM trim_start,SEI; " +
"delete from C6MartPeriodico.tab_semaforo where id_milestone>8");
logger.info("Completata esecuzione Avvio Trimestrale");
return RepeatStatus.FINISHED;
}, transactionManager)
.build();
}
@Bean
public Step congelamentoContrattiStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("congelamentoContrattiStep", jobRepository)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione C6StagingPeriodico.RP_ST_CONTRATTIPRETRIMESTRALE");
c6stampeJdbcTemplate.execute("EXEC [C6StagingPeriodico].[RP_ST_CONTRATTIPRETRIMESTRALE]");
logger.info("Completata esecuzione C6StagingPeriodico.RP_ST_CONTRATTIPRETRIMESTRALE");
return RepeatStatus.FINISHED;
}, transactionManager)
.build();
}
@Bean
public Step notifyEndStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return createNotificationStep(
"notifyEndStep",
"Fine processo PreTrimestrale",
"Il processo PreTrimestrale è terminato in data %s",
jobRepository,
transactionManager
);
}
}

View File

@ -1,65 +1,57 @@
package com.fideuram.batch.config;
package com.armundia.bulk.config;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Configuration
public class RicodificaMassivaJobConfig {
public class RicodificaMassivaJobConfig extends AbstractBatchConfig {
private static final Logger logger = LoggerFactory.getLogger(RicodificaMassivaJobConfig.class);
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("seiReportJdbcTemplate")
private JdbcTemplate seiReportJdbcTemplate;
public RicodificaMassivaJobConfig(
@Qualifier("c6stampeJdbcTemplate") JdbcTemplate c6stampeJdbcTemplate,
@Qualifier("seireportJdbcTemplate") JdbcTemplate seireportJdbcTemplate) {
super(c6stampeJdbcTemplate, seireportJdbcTemplate);
}
@Bean
public Job ricodificaMassivaJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder("ricodificaMassivaJob")
.start(ricodificaMassivaDBReportStep(jobRepository, transactionManager))
.next(ricodificaMassivaContrattoSeiStep(jobRepository, transactionManager))
public Job ricodificaMassivaJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, Step ricodificaMassivaDBReportStep, Step ricodificaMassivaContrattoSeiStep) {
return new JobBuilder("ricodificaMassivaJob", jobRepository)
.incrementer(new RunIdIncrementer())
.start(ricodificaMassivaDBReportStep)
.next(ricodificaMassivaContrattoSeiStep)
.build();
}
@Bean
public Step ricodificaMassivaDBReportStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("ricodificaMassivaDBReportStep")
.repository(jobRepository)
.transactionManager(transactionManager)
return new StepBuilder("ricodificaMassivaDBReportStep", jobRepository)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione srv_change_codfiscaleMassiva_CU su SEIReport");
seiReportJdbcTemplate.execute("exec srv_change_codfiscaleMassiva_CU");
seireportJdbcTemplate.execute("exec srv_change_codfiscaleMassiva_CU");
logger.info("Completata esecuzione srv_change_codfiscaleMassiva_CU su SEIReport");
return RepeatStatus.FINISHED;
})
}, transactionManager)
.build();
}
@Bean
public Step ricodificaMassivaContrattoSeiStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("ricodificaMassivaContrattoSeiStep")
.repository(jobRepository)
.transactionManager(transactionManager)
return new StepBuilder("ricodificaMassivaContrattoSeiStep", jobRepository)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione srv_change_codfiscaleMassiva_CU su C6StampeCentralizzate");
jdbcTemplate.execute("exec srv_change_codfiscaleMassiva_CU");
c6stampeJdbcTemplate.execute("exec srv_change_codfiscaleMassiva_CU");
logger.info("Completata esecuzione srv_change_codfiscaleMassiva_CU su C6StampeCentralizzate");
return RepeatStatus.FINISHED;
})
}, transactionManager)
.build();
}
}

View File

@ -1,4 +1,4 @@
package com.fideuram.batch.mail;
package com.armundia.bulk.mail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;

View File

@ -1,13 +0,0 @@
package com.fideuram.batch;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
@SpringBootApplication
@EnableBatchProcessing
public class BatchApplication {
public static void main(String[] args) {
SpringApplication.run(BatchApplication.class, args);
}
}

View File

@ -1,34 +0,0 @@
package com.fideuram.batch.config;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
public class BatchConfig {
@Bean
public Job sampleJob(JobRepository jobRepository, Step sampleStep) {
return new JobBuilder("helloWorldJob")
.start(sampleStep)
.build();
}
@Bean
public Step sampleStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("step1")
.repository(jobRepository)
.transactionManager(transactionManager)
.tasklet((contribution, chunkContext) -> {
System.out.println("Executing sample step...");
return RepeatStatus.FINISHED;
})
.build();
}
}

View File

@ -1,80 +0,0 @@
package com.fideuram.batch.config;
import javax.sql.DataSource;
import org.springframework.lang.NonNull;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.JobExplorerFactoryBean;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@EnableBatchProcessing
public class BatchConfiguration implements BatchConfigurer {
private final DataSource dataSource;
private final PlatformTransactionManager transactionManager;
private JobRepository jobRepository;
private JobLauncher jobLauncher;
private JobExplorer jobExplorer;
public BatchConfiguration(
@Qualifier("primaryDataSource") DataSource dataSource,
@Qualifier("transactionManager") PlatformTransactionManager transactionManager) {
this.dataSource = dataSource;
this.transactionManager = transactionManager;
}
@Override
@NonNull
public JobRepository getJobRepository() throws Exception {
if (jobRepository == null) {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource);
factory.setTransactionManager(transactionManager);
factory.setIsolationLevelForCreate("ISOLATION_READ_COMMITTED");
factory.setTablePrefix("BATCH_");
factory.afterPropertiesSet();
jobRepository = factory.getObject();
}
return jobRepository;
}
@Override
@NonNull
public JobLauncher getJobLauncher() throws Exception {
if (jobLauncher == null) {
SimpleJobLauncher launcher = new SimpleJobLauncher();
launcher.setJobRepository(getJobRepository());
launcher.afterPropertiesSet();
jobLauncher = launcher;
}
return jobLauncher;
}
@Override
@NonNull
public JobExplorer getJobExplorer() throws Exception {
if (jobExplorer == null) {
JobExplorerFactoryBean factory = new JobExplorerFactoryBean();
factory.setDataSource(dataSource);
factory.setTablePrefix("BATCH_");
factory.afterPropertiesSet();
jobExplorer = factory.getObject();
}
return jobExplorer;
}
@Override
@NonNull
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
}

View File

@ -1,43 +0,0 @@
package com.fideuram.batch.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class DatabaseConfig {
@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource primaryDataSource() {
return DataSourceBuilder.create()
.type(com.zaxxer.hikari.HikariDataSource.class)
.build();
}
@Bean(name = "seiReportDataSource")
@ConfigurationProperties(prefix = "spring.second-datasource.hikari")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create()
.type(com.zaxxer.hikari.HikariDataSource.class)
.build();
}
@Primary
@Bean
public JdbcTemplate jdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean
public JdbcTemplate seiReportJdbcTemplate(@Qualifier("seiReportDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}

View File

@ -1,134 +0,0 @@
package com.fideuram.batch.config;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.transaction.PlatformTransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.fideuram.batch.mail.BatchMailMessage;
@Configuration
public class PreTrimestraleJobConfig {
private static final Logger logger = LoggerFactory.getLogger(PreTrimestraleJobConfig.class);
@Autowired
private JavaMailSender mailSender;
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private BatchMailMessage mailMessage;
@Bean
public Job preTrimestraleJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder("preTrimestraleJob")
.start(notifyStartStep(jobRepository, transactionManager))
.next(truncateStep(jobRepository, transactionManager))
.next(avvioTrimestraleStep(jobRepository, transactionManager))
.next(congelamentoContrattiStep(jobRepository, transactionManager))
.next(notifyEndStep(jobRepository, transactionManager))
.build();
}
@Bean
public Step notifyStartStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("notifyStartStep")
.repository(jobRepository)
.transactionManager(transactionManager)
.tasklet((contribution, chunkContext) -> {
try {
String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
BatchMailMessage message = mailMessage.clone()
.withSubject("Inizio processo PreTrimestrale")
.withText("Il processo PreTrimestrale è stato avviato in data " + now);
mailSender.send(message);
logger.info("Mail di inizio processo inviata con successo");
} catch (Exception e) {
logger.error("Errore nell'invio della mail di inizio processo: " + e.getMessage());
// Non blocchiamo l'esecuzione se la mail fallisce
}
return RepeatStatus.FINISHED;
})
.build();
}
@Bean
public Step truncateStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("truncateStep")
.repository(jobRepository)
.transactionManager(transactionManager)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione truncate table C6MartPeriodico.tab_semaforo");
jdbcTemplate.execute("truncate table C6MartPeriodico.tab_semaforo");
logger.info("Completata esecuzione truncate");
return RepeatStatus.FINISHED;
})
.build();
}
@Bean
public Step avvioTrimestraleStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("avvioTrimestraleStep")
.repository(jobRepository)
.transactionManager(transactionManager)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione Avvio Trimestrale");
jdbcTemplate.execute(
"exec C6MartPeriodico.SP_Valorizza_Stati_semaforo_TRIM trim_start,SEI; " +
"delete from C6MartPeriodico.tab_semaforo where id_milestone>8");
logger.info("Completata esecuzione Avvio Trimestrale");
return RepeatStatus.FINISHED;
})
.build();
}
@Bean
public Step congelamentoContrattiStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("congelamentoContrattiStep")
.repository(jobRepository)
.transactionManager(transactionManager)
.tasklet((contribution, chunkContext) -> {
logger.info("Esecuzione C6StagingPeriodico.RP_ST_CONTRATTIPRETRIMESTRALE");
jdbcTemplate.execute("EXEC [C6StagingPeriodico].[RP_ST_CONTRATTIPRETRIMESTRALE]");
logger.info("Completata esecuzione C6StagingPeriodico.RP_ST_CONTRATTIPRETRIMESTRALE");
return RepeatStatus.FINISHED;
})
.build();
}
@Bean
public Step notifyEndStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("notifyEndStep")
.repository(jobRepository)
.transactionManager(transactionManager)
.tasklet((contribution, chunkContext) -> {
try {
String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
mailMessage.clone()
.withSubject("Fine processo PreTrimestrale")
.withText("Il processo PreTrimestrale è terminato in data " + now)
.send(mailSender);
logger.info("Mail di fine processo inviata con successo");
} catch (Exception e) {
logger.error("Errore nell'invio della mail di fine processo: " + e.getMessage());
}
return RepeatStatus.FINISHED;
})
.build();
}
}

View File

@ -1,26 +1,32 @@
# Primary Database configuration (C6StampeCentralizzate)
spring.datasource.hikari.jdbc-url=jdbc:sqlserver://localhost;databaseName=C6StampeCentralizzate;trustServerCertificate=true
spring.datasource.hikari.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.hikari.username=F701264
spring.datasource.hikari.password=contrsei
# Configurazione Spring Batch
spring.batch.job.enabled=true
spring.batch.jdbc.initialize-schema=always
# SEIReport Database configuration
spring.second-datasource.hikari.jdbc-url=jdbc:sqlserver://localhost;databaseName=SEIReport;trustServerCertificate=true
spring.second-datasource.hikari.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.second-datasource.hikari.username=F701264
spring.second-datasource.hikari.password=contrsei
# Configurazione Database SQL Server - C6StampeCentralizzate
spring.datasource.c6stampe.url=jdbc:sqlserver://localhost;databaseName=C6StampeCentralizzate;encrypt=false
spring.datasource.c6stampe.username=c6stampa
spring.datasource.c6stampe.password=centrsei
# JPA/Hibernate
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect
# Configurazione Database SQL Server - SEIReport
spring.datasource.seireport.url=jdbc:sqlserver://localhost;databaseName=SEIReport;encrypt=false
spring.datasource.seireport.username=c6stampa
spring.datasource.seireport.password=centrsei
# Debug e logging
logging.level.root=INFO
logging.level.com.armundia.bulk=TRACE
logging.level.org.springframework.batch=INFO
logging.level.org.springframework.jdbc=INFO
logging.level.org.springframework.transaction=INFO
# Configurazione JPA
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
spring.jpa.hibernate.ddl-auto=none
# SQL initialization
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:schema.sql
# Batch
spring.batch.jdbc.initialize-schema=never
spring.batch.job.enabled=false
# Forza esecuzione del job all'avvio
spring.batch.job.enabled=true
# Specifica quale job eseguire di default
spring.batch.job.name=dispachJob
# Email Configuration
spring.mail.host=smtp.gmail.com
@ -31,4 +37,4 @@ spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
# Batch Mail Configuration
batch.mail.to=g.savo@armundia.com,g.mucciariello@armundia.com
batch.mail.to=g.savo@armundia.com

View File

@ -0,0 +1,118 @@
-- Tabelle Spring Batch per SQL Server
-- Drop delle tabelle esistenti se presenti
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_STEP_EXECUTION_CONTEXT]') AND type in (N'U'))
DROP TABLE BATCH_STEP_EXECUTION_CONTEXT;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_EXECUTION_CONTEXT]') AND type in (N'U'))
DROP TABLE BATCH_JOB_EXECUTION_CONTEXT;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_STEP_EXECUTION]') AND type in (N'U'))
DROP TABLE BATCH_STEP_EXECUTION;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_EXECUTION_PARAMS]') AND type in (N'U'))
DROP TABLE BATCH_JOB_EXECUTION_PARAMS;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_EXECUTION]') AND type in (N'U'))
DROP TABLE BATCH_JOB_EXECUTION;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_INSTANCE]') AND type in (N'U'))
DROP TABLE BATCH_JOB_INSTANCE;
-- Drop delle sequenze esistenti se presenti
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_SEQ]') AND type in (N'SO'))
DROP SEQUENCE BATCH_JOB_SEQ;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_EXECUTION_SEQ]') AND type in (N'SO'))
DROP SEQUENCE BATCH_JOB_EXECUTION_SEQ;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_STEP_EXECUTION_SEQ]') AND type in (N'SO'))
DROP SEQUENCE BATCH_STEP_EXECUTION_SEQ;
-- Sequence per BATCH_JOB_SEQ
CREATE SEQUENCE BATCH_JOB_SEQ START WITH 1 INCREMENT BY 1 NO CACHE NO CYCLE;
-- Sequence per BATCH_JOB_EXECUTION_SEQ
CREATE SEQUENCE BATCH_JOB_EXECUTION_SEQ START WITH 1 INCREMENT BY 1 NO CACHE NO CYCLE;
-- Sequence per BATCH_STEP_EXECUTION_SEQ
CREATE SEQUENCE BATCH_STEP_EXECUTION_SEQ START WITH 1 INCREMENT BY 1 NO CACHE NO CYCLE;
-- Tabella BATCH_JOB_INSTANCE
CREATE TABLE BATCH_JOB_INSTANCE (
JOB_INSTANCE_ID BIGINT NOT NULL PRIMARY KEY,
VERSION BIGINT,
JOB_NAME VARCHAR(100) NOT NULL,
JOB_KEY VARCHAR(32) NOT NULL,
CONSTRAINT JOB_INST_UN UNIQUE (JOB_NAME, JOB_KEY)
);
-- Tabella BATCH_JOB_EXECUTION
CREATE TABLE BATCH_JOB_EXECUTION (
JOB_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY,
VERSION BIGINT,
JOB_INSTANCE_ID BIGINT NOT NULL,
CREATE_TIME DATETIME NOT NULL,
START_TIME DATETIME DEFAULT NULL,
END_TIME DATETIME DEFAULT NULL,
STATUS VARCHAR(10),
EXIT_CODE VARCHAR(2500),
EXIT_MESSAGE VARCHAR(2500),
LAST_UPDATED DATETIME,
constraint JOB_INST_EXEC_FK foreign key (JOB_INSTANCE_ID)
references BATCH_JOB_INSTANCE(JOB_INSTANCE_ID)
);
-- Tabella BATCH_JOB_EXECUTION_PARAMS
CREATE TABLE BATCH_JOB_EXECUTION_PARAMS (
JOB_EXECUTION_ID BIGINT NOT NULL,
PARAMETER_NAME VARCHAR(100) NOT NULL,
PARAMETER_TYPE VARCHAR(100) NOT NULL,
PARAMETER_VALUE VARCHAR(2500),
IDENTIFYING CHAR(1) NOT NULL,
constraint JOB_EXEC_PARAMS_FK foreign key (JOB_EXECUTION_ID)
references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID)
);
-- Tabella BATCH_STEP_EXECUTION
CREATE TABLE BATCH_STEP_EXECUTION (
STEP_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY,
VERSION BIGINT NOT NULL,
STEP_NAME VARCHAR(100) NOT NULL,
JOB_EXECUTION_ID BIGINT NOT NULL,
CREATE_TIME DATETIME NOT NULL,
START_TIME DATETIME DEFAULT NULL,
END_TIME DATETIME DEFAULT NULL,
STATUS VARCHAR(10),
COMMIT_COUNT BIGINT,
READ_COUNT BIGINT,
FILTER_COUNT BIGINT,
WRITE_COUNT BIGINT,
READ_SKIP_COUNT BIGINT,
WRITE_SKIP_COUNT BIGINT,
PROCESS_SKIP_COUNT BIGINT,
ROLLBACK_COUNT BIGINT,
EXIT_CODE VARCHAR(2500),
EXIT_MESSAGE VARCHAR(2500),
LAST_UPDATED DATETIME,
constraint JOB_EXEC_STEP_FK foreign key (JOB_EXECUTION_ID)
references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID)
);
-- Tabella BATCH_STEP_EXECUTION_CONTEXT
CREATE TABLE BATCH_STEP_EXECUTION_CONTEXT (
STEP_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY,
SHORT_CONTEXT VARCHAR(2500) NOT NULL,
SERIALIZED_CONTEXT TEXT,
constraint STEP_EXEC_CTX_FK foreign key (STEP_EXECUTION_ID)
references BATCH_STEP_EXECUTION(STEP_EXECUTION_ID)
);
-- Tabella BATCH_JOB_EXECUTION_CONTEXT
CREATE TABLE BATCH_JOB_EXECUTION_CONTEXT (
JOB_EXECUTION_ID BIGINT NOT NULL PRIMARY KEY,
SHORT_CONTEXT VARCHAR(2500) NOT NULL,
SERIALIZED_CONTEXT TEXT,
constraint JOB_EXEC_CTX_FK foreign key (JOB_EXECUTION_ID)
references BATCH_JOB_EXECUTION(JOB_EXECUTION_ID)
);

View File

@ -1,118 +0,0 @@
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_INSTANCE]') AND type = N'U')
BEGIN
CREATE TABLE [dbo].[BATCH_JOB_INSTANCE] (
[JOB_INSTANCE_ID] BIGINT NOT NULL PRIMARY KEY,
[VERSION] BIGINT,
[JOB_NAME] VARCHAR(100) NOT NULL,
[JOB_KEY] VARCHAR(32) NOT NULL
)
END;
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_EXECUTION]') AND type = N'U')
BEGIN
CREATE TABLE [dbo].[BATCH_JOB_EXECUTION] (
[JOB_EXECUTION_ID] BIGINT NOT NULL PRIMARY KEY,
[VERSION] BIGINT,
[JOB_INSTANCE_ID] BIGINT NOT NULL,
[CREATE_TIME] DATETIME NOT NULL,
[START_TIME] DATETIME DEFAULT NULL,
[END_TIME] DATETIME DEFAULT NULL,
[STATUS] VARCHAR(10),
[EXIT_CODE] VARCHAR(2500),
[EXIT_MESSAGE] VARCHAR(2500),
[LAST_UPDATED] DATETIME,
CONSTRAINT [JOB_INST_EXEC_FK] FOREIGN KEY ([JOB_INSTANCE_ID])
REFERENCES [BATCH_JOB_INSTANCE] ([JOB_INSTANCE_ID])
)
END;
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_EXECUTION_PARAMS]') AND type = N'U')
BEGIN
CREATE TABLE [dbo].[BATCH_JOB_EXECUTION_PARAMS] (
[JOB_EXECUTION_ID] BIGINT NOT NULL,
[TYPE_CD] VARCHAR(6) NOT NULL,
[KEY_NAME] VARCHAR(100) NOT NULL,
[STRING_VAL] VARCHAR(250),
[DATE_VAL] DATETIME DEFAULT NULL,
[LONG_VAL] BIGINT,
[DOUBLE_VAL] FLOAT,
[IDENTIFYING] CHAR(1) NOT NULL,
CONSTRAINT [JOB_EXEC_PARAMS_FK] FOREIGN KEY ([JOB_EXECUTION_ID])
REFERENCES [BATCH_JOB_EXECUTION] ([JOB_EXECUTION_ID])
)
END;
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_STEP_EXECUTION]') AND type = N'U')
BEGIN
CREATE TABLE [dbo].[BATCH_STEP_EXECUTION] (
[STEP_EXECUTION_ID] BIGINT NOT NULL PRIMARY KEY,
[VERSION] BIGINT NOT NULL,
[STEP_NAME] VARCHAR(100) NOT NULL,
[JOB_EXECUTION_ID] BIGINT NOT NULL,
[START_TIME] DATETIME NOT NULL,
[END_TIME] DATETIME DEFAULT NULL,
[STATUS] VARCHAR(10),
[COMMIT_COUNT] BIGINT,
[READ_COUNT] BIGINT,
[FILTER_COUNT] BIGINT,
[WRITE_COUNT] BIGINT,
[READ_SKIP_COUNT] BIGINT,
[WRITE_SKIP_COUNT] BIGINT,
[PROCESS_SKIP_COUNT] BIGINT,
[ROLLBACK_COUNT] BIGINT,
[EXIT_CODE] VARCHAR(2500),
[EXIT_MESSAGE] VARCHAR(2500),
[LAST_UPDATED] DATETIME,
CONSTRAINT [JOB_EXEC_STEP_FK] FOREIGN KEY ([JOB_EXECUTION_ID])
REFERENCES [BATCH_JOB_EXECUTION] ([JOB_EXECUTION_ID])
)
END;
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_STEP_EXECUTION_CONTEXT]') AND type = N'U')
BEGIN
CREATE TABLE [dbo].[BATCH_STEP_EXECUTION_CONTEXT] (
[STEP_EXECUTION_ID] BIGINT NOT NULL PRIMARY KEY,
[SHORT_CONTEXT] VARCHAR(2500) NOT NULL,
[SERIALIZED_CONTEXT] TEXT,
CONSTRAINT [STEP_EXEC_CTX_FK] FOREIGN KEY ([STEP_EXECUTION_ID])
REFERENCES [BATCH_STEP_EXECUTION] ([STEP_EXECUTION_ID])
)
END;
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BATCH_JOB_EXECUTION_CONTEXT]') AND type = N'U')
BEGIN
CREATE TABLE [dbo].[BATCH_JOB_EXECUTION_CONTEXT] (
[JOB_EXECUTION_ID] BIGINT NOT NULL PRIMARY KEY,
[SHORT_CONTEXT] VARCHAR(2500) NOT NULL,
[SERIALIZED_CONTEXT] TEXT,
CONSTRAINT [JOB_EXEC_CTX_FK] FOREIGN KEY ([JOB_EXECUTION_ID])
REFERENCES [BATCH_JOB_EXECUTION] ([JOB_EXECUTION_ID])
)
END;
IF NOT EXISTS (SELECT * FROM sys.sequences WHERE [name] = N'BATCH_JOB_EXECUTION_SEQ')
BEGIN
CREATE SEQUENCE [dbo].[BATCH_JOB_EXECUTION_SEQ]
START WITH 1
INCREMENT BY 1
MINVALUE 1
NO CYCLE
END;
IF NOT EXISTS (SELECT * FROM sys.sequences WHERE [name] = N'BATCH_JOB_SEQ')
BEGIN
CREATE SEQUENCE [dbo].[BATCH_JOB_SEQ]
START WITH 1
INCREMENT BY 1
MINVALUE 1
NO CYCLE
END;
IF NOT EXISTS (SELECT * FROM sys.sequences WHERE [name] = N'BATCH_STEP_EXECUTION_SEQ')
BEGIN
CREATE SEQUENCE [dbo].[BATCH_STEP_EXECUTION_SEQ]
START WITH 1
INCREMENT BY 1
MINVALUE 1
NO CYCLE
END;