Почему progress bar(Vaadin) не обновляется динамически при выполнении операции удаления из DB?
Файл загружается успешно. Метод deleteMsisdns - который выполняется асинхронно, отвечает за выполнение sql скрипта на удаление данных. Метод getDeletedCount - отвечает за мониторинг удаленных данных, в нем вычисляется отношение удаленных данных к общему кол-ву, которое необходимо удалить и это значение передается методу processingUpdated, в котором должно происходить обновление progress bar. По логам приложения в него на каждой итерации поступает новое значение, но обновление progress bar не происходит. В чем может быть причина?
public class ProfilesDeletionPage extends AbstractIntfPage {
private static final Logger log = LoggerFactory.getLogger(ProfilesDeletionPage.class);
static final String[] HEADERS = {"MSISDN"};
Label statusLabel;
int all = 0;
Long sequenceId;
Long totalCountToDelete;
Button submitButton;
ProgressBar progressBar;
File tempFile;
FileOutputStream fos;
@Autowired
MicaCommonDaoImpl dao;
public ProfilesDeletionPage() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
boolean btnEnabled = user.getAuthorities().contains(new SimpleGrantedAuthority(Roles.APPLICATION_ADMIN.name()));
if (!btnEnabled) {
showNotification("Only admin is allowed to delete msisdns", Notification.Type.HUMANIZED_MESSAGE);
return;
}
Upload uploadCSV = new Upload("Upload csv here", null);
final CsvReceiver receiver = new CsvReceiver();
uploadCSV.setReceiver(receiver);
final UploadListener listener = new UploadListener();
uploadCSV.addFinishedListener(listener);
progressBar = new ProgressBar();
progressBar.setVisible(false);
progressBar.setIndeterminate(true);
statusLabel = new Label();
submitButton = new Button("Delete uploaded msisdns");
submitButton.setEnabled(false);
submitButton.addClickListener((Button.ClickListener) event -> {
final AsyncDeletionProcessService deletionService = app.getBean(AsyncDeletionProcessService.class);
progressBar.setCaption("Processing...");
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
deletionService.deleteMsisdns(sequenceId, user.getId(), user.getLogin());
deletionService.getDeletedCount(totalCountToDelete, this::processingUpdated, this::processingSucceeded);
});
HorizontalLayout horLay = new HorizontalLayout();
horLay.setSpacing(true);
horLay.addComponents(submitButton);
horLay.setComponentAlignment(submitButton, Alignment.BOTTOM_LEFT);
layout.setSpacing(true);
layout.addComponents(uploadCSV, statusLabel, progressBar, horLay);
}
public void processingUpdated(Float progress) {
log.info("processingUpdated");
UI.getCurrent().access(() -> progressBar.setValue(progress));
}
public void processingSucceeded() {
log.info("processingUpdated");
UI.getCurrent().access(() -> {
progressBar.setVisible(false);
Notification.show("Done!");
});
}
class CsvReceiver implements Upload.Receiver {
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
log.info("profiles deletion file has been received");
all = 0;
submitButton.setEnabled(false);
try {
tempFile = File.createTempFile("temp", ".csv");
fos = new FileOutputStream(tempFile);
} catch (IOException e) {
e.printStackTrace();
}
return fos;
}
}
class UploadListener implements Upload.FinishedListener {
@Override
public void uploadFinished(Upload.FinishedEvent event) {
log.info("finish upload");
List<String> msisdnList = Lists.newArrayList();
try {
log.info("we are before reading the file");
BufferedReader reader = new BufferedReader(new FileReader(tempFile));
String line = reader.readLine();
log.info("we are after reading the file");
//check headers
if (line == null || !headersAreCorrect(line)){
Notification notification = new Notification("Wrong file (wrong csv headers)", Notification.Type.HUMANIZED_MESSAGE);
notification.setDelayMsec(4000);
notification.setPosition(Position.MIDDLE_CENTER);
notification.show(Page.getCurrent());
return;
}
//add msisdns to the list
log.info(all + " " + line);
while (line != null && !line.isEmpty()) {
all++;
line = reader.readLine();
log.info(all + " " + line);
if (StringUtils.isNotBlank(line)) {
msisdnList.add(line.trim());
}
}
log.info("msisdnList: " + msisdnList);
all--;
reader.close();
sequenceId = dao.insertMsisdnsInTempTable(event.getFilename(), user.getLogin(), "NEW", msisdnList);
totalCountToDelete = dao.getTotalCountToDelete();
log.info("sequenceId {}, OK, totalCountToDelete {} ", sequenceId, totalCountToDelete);
statusLabel.setValue("File loading success.");
submitButton.setEnabled(true);
} catch(IOException e) {
e.printStackTrace();
}
}
}
private boolean headersAreCorrect(String line) {
String[] headers = line.split(",");
return Arrays.equals(HEADERS, headers);
}
}
@Service(value = "asyncDeletionProcessService")
public class AsyncDeletionProcessService {
private static final Logger log = LoggerFactory.getLogger(AsyncDeletionProcessService.class);
@Autowired
MicaCommonDaoImpl dao;
@Autowired
CommonDao commonDao;
Long deletedCount = 0L;
Long remainingCount;
@Autowired
private TaskExecutor asyncDeletionProcessExecutor;
public void deleteMsisdns(Long sequenceId, Long id, String login) {
log.info("we are in deleteMsisdns method in AsyncDeletionProcessService class");
Runnable r = () -> {
int res = dao.deleteMsisdns();
log.info("res {}", res);
if (res > 0) {
String text = String.format("sequenceId %d, admin %d %s", sequenceId, id, login);
log.info(text);
commonDao.writeLog(new LogMessage(Facility.DELETE_CUSTOMERS, null, text, "new"));
dao.updateMsisdnBatchToDelete(sequenceId, "NEW", "OK");
} else {
log.info("Deletion failed");
}
};
asyncDeletionProcessExecutor.execute(r);
}
public void getDeletedCount(Long totalCountToDelete, Consumer<Float> progressListener, Runnable succeededListener) {
Runnable r = () -> {
while(deletedCount < totalCountToDelete) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Query the temporary table to get the count of remaining records
remainingCount = dao.getRemainingMsisdnCount();
deletedCount = totalCountToDelete - remainingCount;
float progress = (float)deletedCount/totalCountToDelete;
log.info("progress {}", progress);
progressListener.accept(progress);
log.info("remainingCount {}, deletedCount {}", remainingCount, deletedCount);
}
succeededListener.run();
};
asyncDeletionProcessExecutor.execute(r);
}
}