http://jira.mfd.msk:8088/browse/BKI-3207 Get rid of tmp folders
This commit is contained in:
parent
a1a602d9e8
commit
f34a7be0a1
5 changed files with 32 additions and 46 deletions
|
|
@ -157,6 +157,7 @@ public class SignalFacade {
|
||||||
packageId = signalService.registerPackage(monitoringRequest);
|
packageId = signalService.registerPackage(monitoringRequest);
|
||||||
log.info("Package registered. PackageId {}. Status: {}", packageId, Status.PROCESSING.name());
|
log.info("Package registered. PackageId {}. Status: {}", packageId, Status.PROCESSING.name());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
CTUtil.removeFile(filePath);
|
||||||
if (e instanceof SignalClientException) {
|
if (e instanceof SignalClientException) {
|
||||||
throw (SignalClientException) e;
|
throw (SignalClientException) e;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -30,11 +30,10 @@ public class MonitoringErrorProcesingService {
|
||||||
if (StringUtils.isNotBlank(filePath)) {
|
if (StringUtils.isNotBlank(filePath)) {
|
||||||
try {
|
try {
|
||||||
signalService.updateSubjectsErrors(filePath, packageId);
|
signalService.updateSubjectsErrors(filePath, packageId);
|
||||||
CTUtil.removeFile(filePath);
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Ошибка при записи сообщений об ошибках в сформированных субъектах для мониторинга. Файл ошибок не будет удален. filePath = {}, Package_id = {}",
|
log.error("Ошибка при записи сообщений об ошибках в сформированных субъектах для мониторинга. Package_id = {}", packageId, e);
|
||||||
fileName, packageId, e);
|
}
|
||||||
}
|
CTUtil.removeFile(filePath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -112,21 +112,21 @@ public class MonitoringService {
|
||||||
|
|
||||||
for (String newReport : fileNames) {
|
for (String newReport : fileNames) {
|
||||||
try {
|
try {
|
||||||
String reportPath = null;
|
String loadedReportPath = null;
|
||||||
if (StringUtils.isBlank(userPackage.getLastDownloadedReport())) {
|
if (StringUtils.isBlank(userPackage.getLastDownloadedReport())) {
|
||||||
reportPath = loadReport(userPackage.getId(), newReport); // по этому пакету еще не было загруженных отчетов, продолжаем работу с полученным
|
loadedReportPath = loadReport(userPackage.getId(), newReport); // по этому пакету еще не было загруженных отчетов, продолжаем работу с полученным
|
||||||
} else if (lastDownloadedReportDate != null) {
|
} else if (lastDownloadedReportDate != null) {
|
||||||
LocalDateTime newReportDate = CTUtil.parseDateFromReportFileName(newReport);
|
LocalDateTime newReportDate = CTUtil.parseDateFromReportFileName(newReport);
|
||||||
if (newReportDate.isAfter(lastDownloadedReportDate)) {
|
if (newReportDate.isAfter(lastDownloadedReportDate)) {
|
||||||
reportPath = loadReport(userPackage.getId(), newReport); // полученный отчет новее записанного в базу
|
loadedReportPath = loadReport(userPackage.getId(), newReport); // полученный отчет новее записанного в базу
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (reportPath == null) {
|
if (loadedReportPath == null) {
|
||||||
log.info("Report was not loaded for package {}", userPackage.getPackageName());
|
log.info("Report was not loaded for package {}", userPackage.getPackageName());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
String responsePath = generateResponse(userPackage, reportPath);
|
String responsePath = generateResponse(userPackage, loadedReportPath);
|
||||||
String fileName = null;
|
String fileName = null;
|
||||||
if (responsePath != null) {
|
if (responsePath != null) {
|
||||||
fileName = createResponseFile(userPackage, responsePath);
|
fileName = createResponseFile(userPackage, responsePath);
|
||||||
|
|
@ -150,11 +150,12 @@ public class MonitoringService {
|
||||||
* Формирует результирующий xml файл для конечного пользователя на основе файла из официального сервиса сигналов
|
* Формирует результирующий xml файл для конечного пользователя на основе файла из официального сервиса сигналов
|
||||||
* @return Путь к временному рещультирующему файлу
|
* @return Путь к временному рещультирующему файлу
|
||||||
*/
|
*/
|
||||||
private String generateResponse(UserPackage userPackage, String reportPath) {
|
private String generateResponse(UserPackage userPackage, String loadedReportPath) {
|
||||||
AtomicBoolean generateResponse = new AtomicBoolean(false); // Выставляется в true, если хотя бы один субъект с мониторинга подошел под условие срабатывания сигнала. В этом случае отчет сохраняется
|
AtomicBoolean generateResponse = new AtomicBoolean(false); // Выставляется в true, если хотя бы один субъект с мониторинга подошел под условие срабатывания сигнала. В этом случае отчет сохраняется
|
||||||
|
|
||||||
String folderPath = config.getLoadDir() + File.separator + "tmp_folder" + File.separator + userPackage.getId() + File.separator;
|
String folderPath = config.getLoadDir() + File.separator + "tmp_folder" + File.separator;
|
||||||
String responsePath = folderPath + UUID.randomUUID() + "_response_output.xml";
|
String responsePath = folderPath + UUID.randomUUID() + "_response_output.xml";
|
||||||
|
CTUtil.createFolder(folderPath);
|
||||||
|
|
||||||
MonitoringSignalResponse response = new MonitoringSignalResponse();
|
MonitoringSignalResponse response = new MonitoringSignalResponse();
|
||||||
response.setPackageName(userPackage.getPackageName()); // Имя пакета, переданного при установке
|
response.setPackageName(userPackage.getPackageName()); // Имя пакета, переданного при установке
|
||||||
|
|
@ -163,7 +164,7 @@ public class MonitoringService {
|
||||||
MonitoringSignalResponseStaxXmlWriter staxXmlWriter = new MonitoringSignalResponseStaxXmlWriter(config.getEncoding());
|
MonitoringSignalResponseStaxXmlWriter staxXmlWriter = new MonitoringSignalResponseStaxXmlWriter(config.getEncoding());
|
||||||
staxXmlWriter.writeWithStax(responsePath, response,
|
staxXmlWriter.writeWithStax(responsePath, response,
|
||||||
writer -> {
|
writer -> {
|
||||||
try (BufferedInputStream in = new BufferedInputStream(Files.newInputStream(Path.of(reportPath)), 8 * 1024 * 1024)) {
|
try (BufferedInputStream in = new BufferedInputStream(Files.newInputStream(Path.of(loadedReportPath)), 8 * 1024 * 1024)) {
|
||||||
staxXmlProcessor.read(in, Persons.class,
|
staxXmlProcessor.read(in, Persons.class,
|
||||||
personsData -> { // как только считали пачку Persons сразу записали ее в результирующий файл
|
personsData -> { // как только считали пачку Persons сразу записали ее в результирующий файл
|
||||||
List<Subject> subjectsBatch = processPersons(personsData.getPersons());
|
List<Subject> subjectsBatch = processPersons(personsData.getPersons());
|
||||||
|
|
@ -182,18 +183,11 @@ public class MonitoringService {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
|
||||||
Files.delete(Path.of(reportPath));
|
CTUtil.removeFile(loadedReportPath);
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("File {} hasn't been deleted", reportPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!generateResponse.get()) { // ни один субъект не подошел под условие, удаляем временный отчет
|
if (!generateResponse.get()) { // ни один субъект не подошел под условие, удаляем временный отчет
|
||||||
try {
|
CTUtil.removeFile(responsePath);
|
||||||
Files.delete(Path.of(responsePath));
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("File {} hasn't been deleted", responsePath);
|
|
||||||
}
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -241,15 +235,15 @@ public class MonitoringService {
|
||||||
try {
|
try {
|
||||||
String fileName = CTUtil.generateResponseReportFileName(userPackage.getUserId(), userPackage.getPackageName());
|
String fileName = CTUtil.generateResponseReportFileName(userPackage.getUserId(), userPackage.getPackageName());
|
||||||
Thread.sleep(1000); // Если отчеты формируются слишком быстро, нужно подождать секунду, тк в имени отчета LocalDateTime до секунд
|
Thread.sleep(1000); // Если отчеты формируются слишком быстро, нужно подождать секунду, тк в имени отчета LocalDateTime до секунд
|
||||||
String filePath = config.getLoadDir() + File.separator + userPackage.getUserId().substring(0, 6) + File.separator;
|
String folderPath = config.getLoadDir() + File.separator + userPackage.getUserId().substring(0, 6) + File.separator;
|
||||||
|
|
||||||
File folder = new File(filePath);
|
File folder = new File(folderPath);
|
||||||
if (!folder.exists()) {
|
if (!folder.exists()) {
|
||||||
folder.mkdir();
|
folder.mkdir();
|
||||||
}
|
}
|
||||||
|
|
||||||
try (BufferedInputStream in = new BufferedInputStream(Files.newInputStream(Path.of(responsePath)), 8 * 1024 * 1024);
|
try (BufferedInputStream in = new BufferedInputStream(Files.newInputStream(Path.of(responsePath)), 8 * 1024 * 1024);
|
||||||
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath + fileName + ".zip"));
|
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(folderPath + fileName + ".zip"));
|
||||||
ZipOutputStream zos = new ZipOutputStream(bos)) {
|
ZipOutputStream zos = new ZipOutputStream(bos)) {
|
||||||
|
|
||||||
ZipEntry zipEntry = new ZipEntry(fileName + ".xml");
|
ZipEntry zipEntry = new ZipEntry(fileName + ".xml");
|
||||||
|
|
@ -269,11 +263,7 @@ public class MonitoringService {
|
||||||
log.error("Ошибка при записи отчета пользователя в файл: ", e);
|
log.error("Ошибка при записи отчета пользователя в файл: ", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
CTUtil.removeFile(responsePath);
|
||||||
Files.delete(Path.of(responsePath));
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("File {} hasn't been deleted", responsePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
@ -310,11 +300,7 @@ public class MonitoringService {
|
||||||
throw new RuntimeException("Error while and updating hits", e);
|
throw new RuntimeException("Error while and updating hits", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
CTUtil.removeFile(responsePath); // удалям результирующий xml файл с диска (Он уже заархивирован к этому моменту)
|
||||||
Files.delete(Path.of(responsePath)); // удалям результирующий xml файл с диска (Он уже заархивирован к этому моменту)
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("File {} hasn't been deleted", responsePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info("Signal hits updated for package {}", userPackage.getPackageName());
|
log.info("Signal hits updated for package {}", userPackage.getPackageName());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -207,9 +207,8 @@ public class SignalService {
|
||||||
* @return Путь к файлу запроса к официальному сервису сигналов на постановку на мониторинг
|
* @return Путь к файлу запроса к официальному сервису сигналов на постановку на мониторинг
|
||||||
*/
|
*/
|
||||||
public String writeSignals(Integer packageId) {
|
public String writeSignals(Integer packageId) {
|
||||||
String folderPath = config.getLoadDir() + File.separator + "tmp_folder" + File.separator + packageId + File.separator;
|
String folderPath = config.getLoadDir() + File.separator + "tmp_folder" + File.separator;
|
||||||
String filePath = folderPath + UUID.randomUUID() + "_output.xml";
|
String filePath = folderPath + UUID.randomUUID() + "_output.xml";
|
||||||
|
|
||||||
CTUtil.createFolder(folderPath);
|
CTUtil.createFolder(folderPath);
|
||||||
|
|
||||||
Signals signals = buildSignals(packageId);
|
Signals signals = buildSignals(packageId);
|
||||||
|
|
|
||||||
|
|
@ -19,12 +19,16 @@ import ru.nbch.credit_tracker.service.xml.jaxb.IXmlProcessor;
|
||||||
import ru.nbch.credit_tracker.service.xml.stax.StaxXmlProcessor;
|
import ru.nbch.credit_tracker.service.xml.stax.StaxXmlProcessor;
|
||||||
import ru.nbch.credit_tracker.utils.CTUtil;
|
import ru.nbch.credit_tracker.utils.CTUtil;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
|
import java.util.UUID;
|
||||||
import java.util.zip.GZIPInputStream;
|
import java.util.zip.GZIPInputStream;
|
||||||
import java.util.zip.GZIPOutputStream;
|
import java.util.zip.GZIPOutputStream;
|
||||||
|
|
||||||
|
|
@ -81,12 +85,8 @@ public class SignalRestService {
|
||||||
|
|
||||||
if (response.getStatusCode().value() == 302) {
|
if (response.getStatusCode().value() == 302) {
|
||||||
// good response
|
// good response
|
||||||
try {
|
CTUtil.removeFile(path);
|
||||||
Files.delete(Path.of(path));
|
CTUtil.removeFile(path + ".gz");
|
||||||
Files.delete(Path.of(path + ".gz"));
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("File {} hasn't been deleted", path);
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
} else if (response.getStatusCode().value() == 200 && response.getBody() != null) {
|
} else if (response.getStatusCode().value() == 200 && response.getBody() != null) {
|
||||||
SgnlReport error = staxProcessor.read(response.getBody(), SgnlReport.class);
|
SgnlReport error = staxProcessor.read(response.getBody(), SgnlReport.class);
|
||||||
|
|
@ -95,7 +95,8 @@ public class SignalRestService {
|
||||||
} else {
|
} else {
|
||||||
log.error("неизвестная ошибка при постановке пакета на мониторинг в официальный сервис сигналов: {}", response.getBody());
|
log.error("неизвестная ошибка при постановке пакета на мониторинг в официальный сервис сигналов: {}", response.getBody());
|
||||||
}
|
}
|
||||||
log.info("Files will not be deleted: {}, {}", path, path + ".gz");
|
CTUtil.removeFile(path);
|
||||||
|
CTUtil.removeFile(path + ".gz");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
|
|
@ -259,8 +260,8 @@ public class SignalRestService {
|
||||||
log.error("Неизвестная ошибка при скачивание отчета. fNameReport={}", reportName);
|
log.error("Неизвестная ошибка при скачивание отчета. fNameReport={}", reportName);
|
||||||
return null;
|
return null;
|
||||||
} else {
|
} else {
|
||||||
String folderPath = config.getLoadDir() + File.separator + "tmp_folder" + File.separator + packageId + File.separator;
|
String folderPath = config.getLoadDir() + File.separator + "tmp_folder" + File.separator;
|
||||||
String filePath = folderPath + reportName + ".xml";
|
String filePath = folderPath + UUID.randomUUID() + reportName + ".xml";
|
||||||
CTUtil.createFolder(folderPath);
|
CTUtil.createFolder(folderPath);
|
||||||
|
|
||||||
try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(response.getBody()));
|
try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(response.getBody()));
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue