-
Notifications
You must be signed in to change notification settings - Fork 9
/
FileManagementTasklet.java
255 lines (221 loc) · 10.3 KB
/
FileManagementTasklet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package it.gov.pagopa.rtd.transaction_filter.batch.step.tasklet;
import it.gov.pagopa.rtd.transaction_filter.service.TransactionWriterService;
import java.security.SecureRandom;
import java.util.UUID;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.Assert;
import java.io.File;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* implementation of the {@link Tasklet}, in which the execute method contains the logic for processed file archival,
* based on the status of conclusion for every processed file
*/
@Data
@Slf4j
public class FileManagementTasklet implements Tasklet, InitializingBean {
private TransactionWriterService transactionWriterService;
private Boolean deleteProcessedFiles;
private String deleteOutputFiles;
private String manageHpanOnSuccess;
private String successPath;
private String uploadPendingPath;
private String hpanDirectory;
private String outputDirectory;
private String logsDirectory;
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
/**
*
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
String assertionMessage = "directory must be set";
Assert.notNull(resolver.getResources("file:" + successPath + "*.pgp"),
assertionMessage);
Assert.notNull(resolver.getResources("file:" + uploadPendingPath + "*.pgp"),
assertionMessage);
Assert.notNull(resolver.getResources(hpanDirectory),
assertionMessage);
}
/**
* Method that contains the logic for file archival, based on the exit status of each step obtained from the
* ChunkContext that contains a filename key in the {@link ExecutionContext}
* @param stepContribution
* @param chunkContext
* @return Status of the tasklet execution
* @throws Exception
*/
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
closeAllFileChannels();
boolean executionWithErrors = false;
List<String> errorFilenames = new ArrayList<>();
hpanDirectory = makePathSystemIndependent(hpanDirectory);
List<String> hpanResources = getHpanFiles();
Collection<StepExecution> stepExecutions = chunkContext.getStepContext().getStepExecution().getJobExecution()
.getStepExecutions();
// Since more steps can process the same input file we must keep track
// of already processed files to avoid trying to archive/delete twice
// the same one (and thus failing the second time).
List<String> alreadyProcessedFiles = new ArrayList<>();
for (StepExecution stepExecution : stepExecutions) {
if (stepExecution.getExecutionContext().containsKey("fileName")) {
String file = stepExecution.getExecutionContext().getString("fileName");
if(alreadyProcessedFiles.contains(file)) {
log.info("Already managed file: {}", file);
continue;
} else {
alreadyProcessedFiles.add(file);
}
String path = null;
try {
path = resolver.getResource(file).getFile().getAbsolutePath();
} catch (Exception e) {
log.error(e.getMessage(),e);
path = file.replace("file:/", "");
}
try {
boolean isComplete = BatchStatus.COMPLETED.equals(stepExecution.getStatus()) &&
stepExecution.getFailureExceptions().isEmpty();
executionWithErrors = executionWithErrors || !isComplete;
if (!isComplete) {
String[] filename = makePathSystemIndependent(file).split("/");
ArrayList<String> filePartsArray = new ArrayList<>(Arrays.asList(
filename[filename.length - 1].split("\\.")));
if (filePartsArray.size() == 1) {
errorFilenames.add(filePartsArray.get(0));
} else {
filePartsArray.remove(filePartsArray.size()-1);
String[] fileParts = new String[0];
fileParts = filePartsArray.toArray(fileParts);
errorFilenames.add(String.join(".", fileParts));
}
}
boolean isHpanFile = hpanResources.contains(makePathSystemIndependent(path));
boolean isOutputFile = path.contains(getOutputDirectoryAbsolutePath());
if (Boolean.TRUE.equals(deleteProcessedFiles) || (isComplete && isHpanFile && manageHpanOnSuccess.equals("DELETE"))) {
log.info("Removing processed file: {}", file);
FileUtils.forceDelete(FileUtils.getFile(path));
} else if (!isOutputFile && (!isHpanFile || !isComplete || manageHpanOnSuccess.equals("ARCHIVE"))) {
log.info("Archiving processed file: {}", file);
archiveFile(file, path, isComplete);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
if ("ALWAYS".equals(deleteOutputFiles) || ("ERROR".equals(deleteOutputFiles) && executionWithErrors)) {
List<Resource> outputDirectoryResources =
Arrays.asList(resolver.getResources(makePathSystemIndependent(outputDirectory) + "/*"));
outputDirectoryResources.forEach(outputDirectoryResource ->
{
if (deleteOutputFiles.equals("ALWAYS") || (errorFilenames.stream().anyMatch(
errorFilename -> {
try {
return outputDirectoryResource.getFile().getAbsolutePath().contains(errorFilename);
} catch (IOException e) {
log.error(e.getMessage(),e);
return false;
}
}))
) {
try {
log.info("Deleting output file: {}", outputDirectoryResource.getFile());
FileUtils.forceDelete(outputDirectoryResource.getFile());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
});
}
deleteEmptyLogFiles();
return RepeatStatus.FINISHED;
}
@SneakyThrows
private String getOutputDirectoryAbsolutePath() {
return Arrays.stream(resolver.getResources(outputDirectory)).map(resource -> {
try {
return makePathSystemIndependent(resource.getFile().getAbsolutePath());
} catch (IOException e) {
log.error(e.getMessage(), e);
return "";
}
}).findAny().orElse(null);
}
@SneakyThrows
private List<String> getHpanFiles() {
return Arrays.stream(resolver.getResources(hpanDirectory)).map(resource -> {
try {
return makePathSystemIndependent(resource.getFile().getAbsolutePath());
} catch (IOException e) {
log.error(e.getMessage(),e);
return null;
}
}).collect(Collectors.toList());
}
String makePathSystemIndependent(String path) {
return path.replace("\\", "/");
}
private void closeAllFileChannels() {
if (transactionWriterService != null) {
transactionWriterService.closeAll();
}
}
@SneakyThrows
private void archiveFile(String file, String path, boolean isCompleted) {
File destinationFile = getDestionationFileByStatus(file, isCompleted);
FileUtils.moveFile(FileUtils.getFile(path), destinationFile);
}
@SneakyThrows
private File getDestionationFileByStatus(String sourceFilePath, boolean isCompleted) {
sourceFilePath = makePathSystemIndependent(sourceFilePath);
String[] pathSplitted = sourceFilePath.split("/");
String filename = pathSplitted[pathSplitted.length - 1];
String destinationPath;
if (isCompleted) {
String archivalPath = resolver.getResources(successPath)[0].getFile().getAbsolutePath();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
destinationPath = archivalPath + File.separator + UUID.randomUUID().toString().replace("-", "").substring(0, 20) +
"_" + OffsetDateTime.now().format(fmt) + "_" + filename;
} else {
String archivalPath = resolver.getResources(uploadPendingPath)[0].getFile().getAbsolutePath();
destinationPath = archivalPath + File.separator + filename;
}
return FileUtils.getFile(destinationPath);
}
@SneakyThrows
private void deleteEmptyLogFiles() {
if (logsDirectory == null) {
return;
}
FileUtils.listFiles(
resolver.getResources(logsDirectory)[0].getFile(), new String[]{"csv"},false)
.stream()
.filter(file -> FileUtils.sizeOf(file) == 0)
.forEach(file -> {
log.debug("Removing empty log file: {}", file.getName());
FileUtils.deleteQuietly(file);
});
}
}