Commit c49a3892 by Wilson Castro

reestructuracion de proyecto, se añade endpoint para control de Batch y Job,…

reestructuracion de proyecto, se añade endpoint para control de Batch y Job, estructura de Jobs consecutivos con start, next y end
parent 4e77ec0a
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ec.edu.epn</groupId>
<artifactId>ConsumoSriAutorizacion</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>ConsumoSriAutorizacion</name>
<description>ConsumoSriAutorizacion</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ec.gob.firmadigital</groupId>
<artifactId>sri.cliente-ws-offline</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.3.5</version>
</dependency>
<!--<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>1.5.1</version>
</dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ec.edu.epn</groupId>
<artifactId>ConsumoSriAutorizacion</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>ConsumoSriAutorizacion</name>
<description>ConsumoSriAutorizacion</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ec.gob.firmadigital</groupId>
<artifactId>sri.cliente-ws-offline</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.3.5</version>
</dependency>
<!--<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>1.5.1</version>
</dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package ec.edu.epn.consumosriautorizacion;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionException;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@SpringBootApplication
@EnableAsync
public class ConsumoSriAutorizacionApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ConsumoSriAutorizacionApplication.class);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ConsumoSriAutorizacionApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ConsumoSriAutorizacionApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(ConsumoSriAutorizacionApplication.class, args);
}
}
package ec.edu.epn.consumosriautorizacion.Tasks;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
public class Tarea3 implements Tasklet {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
System.out.println("tarea3 ejecutado");
return RepeatStatus.FINISHED;
}
}
package ec.edu.epn.consumosriautorizacion.Tasks;
import ec.edu.epn.consumosriautorizacion.service.FTPService;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
public class Task_Ftp implements Tasklet {
private FTPService ftpService;
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
ftpService.connectToFTP();
//TODO: se deben obtener el path remoto de las facturas a enviar
String pathFtp = "/facturas/";
//TODO: añadir el listado de los archivos ftp en multipart para el envio
List<MultipartFile> files = new ArrayList<>();
List<String> fileNames = new ArrayList<>();
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
ftpService.uploadFileToFTP(file.getInputStream(), pathFtp, fileName);
fileNames.add(fileName);
}
ftpService.disconnectFTP();
return RepeatStatus.FINISHED;
}
}
\ No newline at end of file
package ec.edu.epn.consumosriautorizacion.Tasks;
import ec.edu.epn.consumosriautorizacion.service.EmailService;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
public class Task_SendEmail implements Tasklet {
private EmailService emailService = new EmailService();
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
System.out.println("tarea2 ejecutado");
//TODO: recuperar los emails para enviar
List<String> to = Arrays.asList("wilson.castro@epn.edu.ec", "orochi_cris@yahoo.com");
String subject = "Correo electrónico masivo de prueba";
String text = "Este es un correo electrónico masivo de prueba enviado desde Spring Boot.";
emailService.sendEmail(to, subject, text);
System.out.println("Estado del trabajo: ");
return RepeatStatus.FINISHED;
}
}
package ec.edu.epn.consumosriautorizacion.config;
import ec.edu.epn.consumosriautorizacion.Tasks.Tarea3;
import ec.edu.epn.consumosriautorizacion.Tasks.Task_Ftp;
import ec.edu.epn.consumosriautorizacion.Tasks.Task_SendEmail;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableBatchProcessing
@EnableScheduling
public class BatchTareasConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Step step1() {
return stepBuilderFactory.get("paso1").tasklet(new Task_Ftp()).build();
}
@Bean
public Step step2() {
return stepBuilderFactory.get("paso2").tasklet(new Task_SendEmail()).build();
}
@Bean
public Step step3() {
return stepBuilderFactory.get("paso3").tasklet(new Tarea3()).build();
}
@Bean
Job autorizacionLotesJob() {
return jobBuilderFactory.get("autorizacionLotesJob")
.start(step3())
//.next(step2())
//.next(step3())
.build();
}
}
\ No newline at end of file
package ec.edu.epn.consumosriautorizacion.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;
@Configuration
public class EmailConfig {
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.port}")
private int port;
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
@Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setUsername(username);
mailSender.setPassword(password);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
}
package ec.edu.epn.consumosriautorizacion.controller;
import ec.edu.epn.consumosriautorizacion.dto.RequestJob;
import ec.edu.epn.consumosriautorizacion.service.TaskDefinitionBean;
import ec.edu.epn.consumosriautorizacion.service.TaskSchedulingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/batch")
public class JobController {
@Autowired
private TaskSchedulingService taskSchedulingService;
@Autowired
private TaskDefinitionBean taskDefinitionBean;
@PostMapping("/inciarCron")
public String iniciar(@RequestBody RequestJob taskDefinition) {
taskDefinitionBean.setTaskDefinition(taskDefinition);
return taskSchedulingService.scheduleATask(taskDefinitionBean, taskDefinition.getCronExpression());
}
@PostMapping(path = "/stopCron/{jobid}")
public String removeJob(@PathVariable String jobid) {
taskSchedulingService.removeScheduledTask(jobid);
return "TAREA " + jobid + " DETENIDA";
}
@PostMapping("/stopJob")
public String startBatch() {
taskSchedulingService.removeAllScheduledTask();
return "CRON-JOB DETENIDO";
}
@GetMapping("/allJobs")
public ResponseEntity<?> getAllJObs() {
return new ResponseEntity<>(taskSchedulingService.getAllJobs(), HttpStatus.OK);
}
}
package ec.edu.epn.consumosriautorizacion;
package ec.edu.epn.consumosriautorizacion.controller;
import ec.edu.epn.facturacionOffline.FacturacionOfflineDTO;
import ec.edu.epn.consumosriautorizacion.dto.FacturacionOfflineDTO;
import ec.gob.sri.comprobantes.ws.RecepcionComprobantesOffline;
import ec.gob.sri.comprobantes.ws.RecepcionComprobantesOfflineService;
import ec.gob.sri.comprobantes.ws.aut.AutorizacionComprobantesOffline;
......
package ec.edu.epn.facturacionOffline;
package ec.edu.epn.consumosriautorizacion.dto;
import java.sql.Timestamp;
......
package ec.edu.epn.consumosriautorizacion.dto;
public class MailDTO {
private String from;
private String to;
private String subject;
private String content;
public MailDTO() {
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Mail{" + "from='" + from + '\'' + ", to='" + to + '\'' + ", subject='" + subject + '\'' + ", content='"
+ content + '\'' + '}';
}
}
package ec.edu.epn.consumosriautorizacion.dto;
public class RequestJob {
private String cronExpression;
private String actionType;
private String data;
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getActionType() {
return actionType;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
package ec.edu.epn.consumosriautorizacion.exceptions;
public class ErrorMessage {
private int errorcode;
private String errormessage;
public ErrorMessage(int errorcode, String errormessage) {
this.errorcode = errorcode;
this.errormessage = errormessage;
}
public int getErrorcode() {
return errorcode;
}
public String getErrormessage() {
return errormessage;
}
@Override
public String toString() {
return "ErrorMessage{" +
"errorcode=" + errorcode +
", errormessage='" + errormessage + '\'' +
'}';
}
}
package ec.edu.epn.consumosriautorizacion.exceptions;
public class FTPErrors extends Exception {
private ErrorMessage errorMessage;
public FTPErrors(ErrorMessage errorMessage) {
super(errorMessage.getErrormessage());
}
public ErrorMessage getErrorMessage() {
return errorMessage;
}
}
package ec.edu.epn.consumosriautorizacion.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Properties;
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.port}")
private int port;
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
@Async
public void sendEmail(List<String> to, String subject, String text) {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
javaMailSender.setPort(port);
javaMailSender.setUsername(username);
javaMailSender.setPassword(password);
Properties props = javaMailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to.toArray(new String[to.size()]));
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}
package ec.edu.epn.consumosriautorizacion.service;
import ec.edu.epn.consumosriautorizacion.exceptions.FTPErrors;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
@Service
public interface FTPService {
void connectToFTP() throws FTPErrors, FTPErrors;
void uploadFileToFTP(InputStream input, String ftpHostDir, String serverFilename) throws FTPErrors;
void downloadFileFromFTP(String ftpRelativePath, String copytoPath) throws FTPErrors;
void disconnectFTP() throws FTPErrors;
byte[] downFileByte(String remotePath, String fileName) throws FTPErrors, IOException;
}
package ec.edu.epn.consumosriautorizacion.service;
import ec.edu.epn.consumosriautorizacion.exceptions.ErrorMessage;
import ec.edu.epn.consumosriautorizacion.exceptions.FTPErrors;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.*;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.io.*;
import java.text.Normalizer;
@Service
public class FileServiceImp implements FTPService {
/**
* FTP connection handler
*/
@Value("${ftp.server}")
String ftpServer;
@Value("${ftp.port}")
String ftpPort;
@Value("${ftp.userName}")
String ftpUserName;
@Value("${ftp.userPassword}")
String ftpuserPassword;
FTPClient ftpconnection;
private Logger logger = LoggerFactory.getLogger(FileServiceImp.class);
private final static String localpath = "c:/"; // Descarga a la unidad c
private final static String fileSeparator = System.getProperty("file.separator");
/**
* Method that implement FTP connection.
*
* @param ftpServer IP of FTP server
* @param ftpUserName FTP valid user
* @param ftpuserPassword FTP valid pass for user
*/
@Override
public void connectToFTP() throws FTPErrors {
ftpconnection = new FTPClient();
ftpconnection.setControlEncoding("UTF-8");
ftpconnection.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
try {
ftpconnection.connect(ftpServer);
} catch (IOException e) {
ErrorMessage errorMessage = new ErrorMessage(-1, "No fue posible conectarse al FTP a través del host=" + ftpServer);
logger.error(errorMessage.toString());
throw new FTPErrors(errorMessage);
}
reply = ftpconnection.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
try {
ftpconnection.disconnect();
} catch (IOException e) {
ErrorMessage errorMessage = new ErrorMessage(-2, "No fue posible conectarse al FTP, el host=" + ftpServer + " entregó la respuesta=" + reply);
logger.error(errorMessage.toString());
throw new FTPErrors(errorMessage);
}
}
try {
ftpconnection.login(ftpUserName, ftpuserPassword);
} catch (IOException e) {
ErrorMessage errorMessage = new ErrorMessage(-3, "El usuario=" + ftpUserName + ", y el pass=**** no fueron válidos para la autenticación.");
logger.error(errorMessage.toString());
throw new FTPErrors(errorMessage);
}
try {
ftpconnection.setFileType(FTP.BINARY_FILE_TYPE);
} catch (IOException e) {
ErrorMessage errorMessage = new ErrorMessage(-4, "El tipo de dato para la transferencia no es válido.");
logger.error(errorMessage.toString());
throw new FTPErrors(errorMessage);
}
ftpconnection.enterLocalPassiveMode();
}
public String stripAccents(String s)
{
/*Salvamos las ñ*/
s = s.replace('ñ', 'n');
s = s.replace('Ñ', 'N');
s = Normalizer.normalize(s, Normalizer.Form.NFD);
s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
/*Volvemos las ñ a la cadena*/
//s = s.replace('\001', 'ñ');
// s = s.replace('\002', 'Ñ');
return s;
}
/**
* Method that allow upload file to FTP
*
* @param input File object of file to upload
* @param ftpHostDir FTP host internal directory to save file
* @param serverFilename Name to put the file in FTP server.
* @throws FTPErrors Set of possible errors associated with upload process.
*/
// @Async("threadPoolTaskExecutor")
@Async
@Override
public void uploadFileToFTP(InputStream input, String ftpHostDir, String serverFilename) throws FTPErrors {
try {
serverFilename = new String(serverFilename.getBytes("utf-8"));
this.ftpconnection.storeFile(ftpHostDir + serverFilename, input);
} catch (Exception e) {
ErrorMessage errorMessage = new ErrorMessage(-5, "No se pudo subir el archivo al servidor.");
logger.error(errorMessage.toString());
throw new FTPErrors(errorMessage);
}
}
/**
* Method for download files from FTP.
*
* @param ftpRelativePath Relative path of file to download into FTP server.
* @param copytoPath Path to copy the file in download process.
* @throws FTPErrors Set of errors associated with download process.
*/
@Override
public void downloadFileFromFTP(String ftpRelativePath, String copytoPath) throws FTPErrors {
FileOutputStream fos;
try {
fos = new FileOutputStream(copytoPath);
} catch (FileNotFoundException e) {
ErrorMessage errorMessage = new ErrorMessage(-6, "No se pudo obtener la referencia a la carpeta relativa donde guardar, verifique la ruta y los permisos.");
logger.error(errorMessage.toString());
throw new FTPErrors(errorMessage);
}
try {
this.ftpconnection.retrieveFile(ftpRelativePath, fos);
} catch (IOException e) {
ErrorMessage errorMessage = new ErrorMessage(-7, "No se pudo descargar el archivo.");
logger.error(errorMessage.toString());
throw new FTPErrors(errorMessage);
}
}
/**
* Method for release the FTP connection.
*
* @throws FTPErrors Error if unplugged process failed.
*/
@Override
public void disconnectFTP() throws FTPErrors {
if (this.ftpconnection.isConnected()) {
try {
this.ftpconnection.logout();
this.ftpconnection.disconnect();
} catch (IOException f) {
throw new FTPErrors(new ErrorMessage(-8, "Ha ocurrido un error al realizar la desconexión del servidor FTP"));
}
}
}
@Override
public byte[] downFileByte(String remotePath, String fileName) throws FTPErrors, IOException {
byte[] return_arraybyte = null;
if (remotePath != null && !remotePath.equals("")) {
remotePath = remotePath;
this.ftpconnection.changeWorkingDirectory(remotePath);
}
try {
FTPFile[] files = this.ftpconnection.listFiles();
for (FTPFile file : files) {
String remoteFileName = new String(file.getName().getBytes("utf-8")); // Evitar caracteres confusos
if (remoteFileName.equals(fileName)) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
this.ftpconnection.retrieveFile(remotePath + fileName, baos);
return_arraybyte = baos.toByteArray();
baos.close();
return return_arraybyte;
}
}
} catch (Exception e) {
ErrorMessage errorMessage = new ErrorMessage(-9, "No se pudo descargar el archivo.");
}
return return_arraybyte;
}
}
package ec.edu.epn.consumosriautorizacion.service;
import ec.edu.epn.consumosriautorizacion.dto.RequestJob;
import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TaskDefinitionBean implements Runnable {
private RequestJob taskDefinition;
@Autowired
private JobLauncher jobLauncher;
public JobExecution jobExecution;
@Autowired
private Job job;
@Override
public void run() {
System.out.println("Ejecutando Accion: " + taskDefinition.getActionType());
System.out.println("Info Adicional: " + taskDefinition.getData());
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.addString("info", "Batch EN CRON")
.toJobParameters();
try {
jobExecution = jobLauncher.run(job, jobParameters);
} catch (JobExecutionAlreadyRunningException e) {
throw new RuntimeException(e);
} catch (JobRestartException e) {
throw new RuntimeException(e);
} catch (JobInstanceAlreadyCompleteException e) {
throw new RuntimeException(e);
} catch (JobParametersInvalidException e) {
throw new RuntimeException(e);
}
}
public RequestJob getTaskDefinition() {
return taskDefinition;
}
public void setTaskDefinition(RequestJob taskDefinition) {
this.taskDefinition = taskDefinition;
}
}
package ec.edu.epn.consumosriautorizacion.service;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
@Service
public class TaskSchedulingService {
@Autowired
private TaskScheduler taskScheduler;
Map<String, ScheduledFuture<?>> jobsMap = new HashMap<>();
public String scheduleATask(Runnable tasklet, String cronExpression) {
UUID uuid = UUID.randomUUID();
String jobId = uuid.toString();
System.out.println("Cron con job id: " + jobId + " y cron : " + cronExpression);
ScheduledFuture<?> scheduledTask = taskScheduler.schedule(tasklet, new CronTrigger(cronExpression, TimeZone.getTimeZone(TimeZone.getDefault().getID())));
jobsMap.put(jobId, scheduledTask);
return "CRON-JOB:{id: " + jobId + ", cron : " + cronExpression + "}";
}
public void removeScheduledTask(String jobId) {
ScheduledFuture<?> scheduledTask = jobsMap.get(jobId);
if (scheduledTask != null) {
scheduledTask.cancel(true);
jobsMap.put(jobId, null);
}
}
public void removeAllScheduledTask() {
for (Map.Entry<String, ScheduledFuture<?>> entry : jobsMap.entrySet()) {
ScheduledFuture<?> scheduledTask = entry.getValue();
if (scheduledTask != null) {
scheduledTask.cancel(true);
jobsMap.put(entry.getKey(), null);
}
}
}
public Map<String, ScheduledFuture<?>> getAllJobs() {
return jobsMap;
}
public String detenerJob(JobExecution jobExecution) {
if (jobExecution != null) {
jobExecution.stop();
return "Proceso batch detenido";
} else {
return "No hay proceso batch en ejecución";
}
}
public String pauseJob(JobExecution jobExecution) {
if (jobExecution != null) {
jobExecution.setStatus(BatchStatus.STOPPING);
return "Proceso batch pausado";
} else {
return "No hay proceso batch en ejecución";
}
}
}
package ec.edu.epn.consumosriautorizacion.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
public Boolean validaremail(String correo) {
// Patrón para validar el email
Pattern pattern = Pattern.compile(
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
Matcher mather = pattern.matcher(correo);
if (mather.find() == true) {
return true;
} else {
return false;
}
}
}
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.main.allow-bean-definition-overriding=true
spring.main.allow-circular-references=true
##### SOPORTE EMAIL #####
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.quitwait=false
spring.mail.properties.mail.smtp.from=smtp.office365.com
##### SMTP #####
spring.mail.host=smtp.office365.com
spring.mail.port=587
spring.mail.username=desarrollo.dgip@epn.edu.ec
spring.mail.password=Generico2022**
##### CONEXION FTP #####
#Multipart file config
spring.servlet.multipart.enabled=true
# Threshold after which files are written to disk.
spring.servlet.multipart.file-size-threshold=2KB
# Max file size.
spring.servlet.multipart.max-file-size=800MB
# Max Request Size
spring.servlet.multipart.max-request-size=800MB
ftp.server=localhost
ftp.port=21
ftp.userName=epnFtp
ftp.userPassword=epn-test
spring.messages.encoding=UTF-8
server.tomcat.uri-encoding=UTF-8
#### PARA LOS SCHEDULE #####
# ------- 0 * * * * * se traduce en:
# El método se ejecutará cuando los segundos sean igual a 0
# En cada minuto (* en el segundo campo)
# En cualquier hora (* en el campo de la hora)
# En cualquier día del mes (* en el campo de día del mes)
# En cualquier mes (* en el campo de mes)
# En cualquier día de la semana (* en el campo de día de la semana)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment