Skip to content

Commit

Permalink
Adds manual backup creation
Browse files Browse the repository at this point in the history
  • Loading branch information
Ludy87 committed Dec 17, 2024
1 parent eb13014 commit 051cd2d
Show file tree
Hide file tree
Showing 42 changed files with 128 additions and 24 deletions.
7 changes: 0 additions & 7 deletions DATABASE.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
# New Database Backup and Import Functionality

> [!IMPORTANT]
> **Full activation will take place on approximately January 5th, 2025!**
Why is the waiting time six months?

There are users who only install updates sporadically; if they skip the preparation, it can/will lead to data loss in the database.

## Functionality Overview

The newly introduced feature enhances the application with robust database backup and import capabilities. This feature is designed to ensure data integrity and provide a straightforward way to manage database backups. Here's how it works:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import stirling.software.SPDF.utils.FileInfo;

public interface DatabaseBackupInterface {

void exportDatabase() throws IOException;

boolean importDatabase();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

import lombok.extern.slf4j.Slf4j;
Expand All @@ -34,24 +35,28 @@
@Controller
@RequestMapping("/api/v1/database")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@Tag(name = "Database", description = "Database APIs")
@Tag(name = "Database", description = "Database APIs for backup, import, and management")
public class DatabaseController {

@Autowired DatabaseBackupHelper databaseBackupHelper;

@Hidden
@PostMapping(consumes = "multipart/form-data", value = "import-database")
@Operation(
summary = "Import database backup",
description = "This endpoint imports a database backup from a SQL file.")
summary = "Import a database backup file",
description = "Uploads and imports a database backup SQL file.")
@PostMapping(consumes = "multipart/form-data", value = "import-database")
public String importDatabase(
@RequestParam("fileInput") MultipartFile file, RedirectAttributes redirectAttributes)
throws IllegalArgumentException, IOException {
@Parameter(description = "SQL file to import", required = true)
@RequestParam("fileInput")
MultipartFile file,
RedirectAttributes redirectAttributes)
throws IOException {

if (file == null || file.isEmpty()) {
redirectAttributes.addAttribute("error", "fileNullOrEmpty");
return "redirect:/database";
}
log.info("Received file: {}", file.getOriginalFilename());

Path tempTemplatePath = Files.createTempFile("backup_", ".sql");
try (InputStream in = file.getInputStream()) {
Files.copy(in, tempTemplatePath, StandardCopyOption.REPLACE_EXISTING);
Expand All @@ -69,9 +74,15 @@ public String importDatabase(
}

@Hidden
@Operation(
summary = "Import database backup by filename",
description = "Imports a database backup file from the server using its file name.")
@GetMapping("/import-database-file/{fileName}")
public String importDatabaseFromBackupUI(@PathVariable String fileName)
throws IllegalArgumentException, IOException {
public String importDatabaseFromBackupUI(
@Parameter(description = "Name of the file to import", required = true) @PathVariable
String fileName)
throws IOException {

if (fileName == null || fileName.isEmpty()) {
return "redirect:/database?error=fileNullOrEmpty";
}
Expand All @@ -85,6 +96,7 @@ public String importDatabaseFromBackupUI(@PathVariable String fileName)
return "redirect:/database?error=fileNotFound";
}
log.info("Received file: {}", fileName);

if (databaseBackupHelper.importDatabaseFromUI(fileName)) {
log.info("File {} imported to database", fileName);
return "redirect:/database?infoMessage=importIntoDatabaseSuccessed";
Expand All @@ -93,12 +105,14 @@ public String importDatabaseFromBackupUI(@PathVariable String fileName)
}

@Hidden
@GetMapping("/delete/{fileName}")
@Operation(
summary = "Delete a database backup file",
description =
"This endpoint deletes a database backup file with the specified file name.")
public String deleteFile(@PathVariable String fileName) {
description = "Deletes a specified database backup file from the server.")
@GetMapping("/delete/{fileName}")
public String deleteFile(
@Parameter(description = "Name of the file to delete", required = true) @PathVariable
String fileName) {

if (fileName == null || fileName.isEmpty()) {
throw new IllegalArgumentException("File must not be null or empty");
}
Expand All @@ -117,12 +131,13 @@ public String deleteFile(@PathVariable String fileName) {
}

@Hidden
@GetMapping("/download/{fileName}")
@Operation(
summary = "Download a database backup file",
description =
"This endpoint downloads a database backup file with the specified file name.")
public ResponseEntity<?> downloadFile(@PathVariable String fileName) {
description = "Downloads the specified database backup file from the server.")
@GetMapping("/download/{fileName}")
public ResponseEntity<?> downloadFile(
@Parameter(description = "Name of the file to download", required = true) @PathVariable
String fileName) {
if (fileName == null || fileName.isEmpty()) {
throw new IllegalArgumentException("File must not be null or empty");
}
Expand All @@ -141,4 +156,22 @@ public ResponseEntity<?> downloadFile(@PathVariable String fileName) {
.build();
}
}

@Operation(
summary = "Create a database backup",
description =
"This endpoint triggers the creation of a database backup and redirects to the"
+ " database management page.")
@GetMapping("/createDatabaseBackup")
public String createDatabaseBackup() {
try {
log.info("Starting database backup creation...");
databaseBackupHelper.exportDatabase();
log.info("Database backup successfully created.");
} catch (IOException e) {
log.error("Error creating database backup: {}", e.getMessage(), e);
return "redirect:/database?error=" + e.getMessage();
}
return "redirect:/database?infoMessage=backupCreated";
}
}
2 changes: 2 additions & 0 deletions src/main/resources/messages_ar_AR.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=تاريخ الإنشاء
database.fileSize=حجم الملف
database.deleteBackupFile=حذف ملف النسخ الاحتياطي
database.importBackupFile=استيراد ملف النسخ الاحتياطي
database.createBackupFile=Create Backup File
database.downloadBackupFile=تنزيل ملف النسخ الاحتياطي
database.info_1=عند استيراد البيانات، من الضروري ضمان الهيكل الصحيح. إذا كنت غير متأكد مما تفعله، اطلب المشورة والدعم من محترف. يمكن أن يؤدي الخطأ في الهيكل إلى حدوث أعطال في التطبيق، حتى عدم القدرة على تشغيل التطبيق بالكامل.
database.info_2=لا يهم اسم الملف عند التحميل. سيتم إعادة تسميته بعد ذلك لاتباع التنسيق backup_user_yyyyMMddHHmm.sql، مما يضمن اتساق تسمية متناسق.
database.submit=استيراد النسخة الاحتياطية
database.importIntoDatabaseSuccessed=تم استيراد قاعدة البيانات بنجاح
database.backupCreated=Database backup successful
database.fileNotFound=لم يتم العثور على الملف
database.fileNullOrEmpty=يجب ألا يكون الملف فارغًا أو خاليًا
database.failedImportFile=فشل استيراد الملف
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_az_AZ.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Yaradılma tarixi
database.fileSize=Fayl Ölçüsü
database.deleteBackupFile=Yedək Faylını Sil
database.importBackupFile=Yedək Faylını Daxil Et
database.createBackupFile=Create Backup File
database.downloadBackupFile=Yedək Faylını Yüklə
database.info_1=Məlumatı daxil edərkən doğru strukturun mövcudluğundan əmin olmaq vacibdir. Əgər nə etdiyinizdən əmin deyilsinizsə, professional birindən məsləhət və yardım alın. Strukturdakı xəta proqramdakı nasazlıqlardan proqramı çalışdırma qabiliyyətinin tamamilə aradan qalxmasına qədər bir sıra problemlərə səbəb ola bilər.
database.info_2=Faylın adı fayl yüklənərkən önəmli deyildir. Faylın adı sonradan sabit adlandırmanın varlığından əmin olmaq məqsədilə backup_user_yyyyMMddHHmm.sql tərzində formata dəyişdiriləcəkdir.
database.submit=Yedəkləməni Daxil Et
database.importIntoDatabaseSuccessed=Verilənlər bazasına daxil etmə uğurla nəticələndi
database.backupCreated=Database backup successful
database.fileNotFound=Fayl Tapılmadı
database.fileNullOrEmpty=Fayl boş və ya "null" olmamalıdır
database.failedImportFile=Faylı daxil etmək alınmadı
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_bg_BG.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Дата на създаване
database.fileSize=Размер на файла
database.deleteBackupFile=Изтриване на архивен файл
database.importBackupFile=Импортиране на архивен файл
database.createBackupFile=Create Backup File
database.downloadBackupFile=Изтеглете архивен файл
database.info_1=Когато импортирате данни, е от решаващо значение да осигурите правилната структура. Ако не сте сигурни в това, което правите, потърсете съвет и подкрепа от професионалист. Грешка в структурата може да причини неизправност на приложението, включително пълна невъзможност за стартиране на приложението.
database.info_2=Името на файла няма значение при качване. След това ще бъде преименуван, за да следва формата backup_user_yyyyMMddHHmm.sql, осигурявайки последователна конвенция за именуване.
database.submit=Импортиране на резервно копие
database.importIntoDatabaseSuccessed=Импортирането в базата данни бе успешно
database.backupCreated=Database backup successful
database.fileNotFound=Файлът не е намерен
database.fileNullOrEmpty=Файлът не трябва да е нулев или празен
database.failedImportFile=Неуспешно импортиране на файл
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_ca_CA.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Data de Creació
database.fileSize=Mida del Fitxer
database.deleteBackupFile=Elimina el Fitxer de Còpia de Seguretat
database.importBackupFile=Importa el Fitxer de Còpia de Seguretat
database.createBackupFile=Create Backup File
database.downloadBackupFile=Descarrega el Fitxer de Còpia de Seguretat
database.info_1=Quan importis dades, és crucial assegurar-se que l'estructura sigui correcta. Si no estàs segur del que fas, busca l'assessorament d'un professional. Un error en l'estructura pot causar malfuncionaments de l'aplicació, fins i tot impossibilitar-ne l'execució.
database.info_2=El nom del fitxer no importa quan es puja. Es renombrarà després per seguir el format backup_user_yyyyMMddHHmm.sql, assegurant una convenció de nomenclatura consistent.
database.submit=Importa la Còpia de Seguretat
database.importIntoDatabaseSuccessed=Importació a la base de dades completada amb èxit
database.backupCreated=Database backup successful
database.fileNotFound=Fitxer no trobat
database.fileNullOrEmpty=El fitxer no ha de ser nul o buit
database.failedImportFile=Error en la importació del fitxer
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_cs_CZ.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Datum vytvoření
database.fileSize=Velikost souboru
database.deleteBackupFile=Smazat záložní soubor
database.importBackupFile=Import zálohy souboru
database.createBackupFile=Create Backup File
database.downloadBackupFile=Stáhnout zálohový soubor
database.info_1=Při importu dat je důležité zajistit správnou strukturu. Pokud jste nejistí, jak se chovat, hledajte konzultaci a podporu od profesionala. Chyba v struktuře může vést k selhání aplikace, dokonce i k tomu, že by aplikace nemohla být spuštěna.
database.info_2=Název souboru nezáleží při nahrávání. Bude jeho zpětně znovu pojmenován podle formáту backup_user_yyyyMMddHHmm.sql, což zajišťuje konzistentní pravidlo označení.
database.submit=Import zálohy
database.importIntoDatabaseSuccessed=Import do databáze byl úspěšný
database.backupCreated=Database backup successful
database.fileNotFound=File not Found
database.fileNullOrEmpty=Soubor nemůže být null nebo prázdný
database.failedImportFile=Failed Import File
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_da_DK.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Oprettelsesdato
database.fileSize=Filstørrelse
database.deleteBackupFile=Slet Backup-fil
database.importBackupFile=Importér Backup-fil
database.createBackupFile=Create Backup File
database.downloadBackupFile=Download Backup-fil
database.info_1=Ved import af data er det afgørende at sikre den korrekte struktur. Hvis du er usikker på, hvad du gør, søg råd og støtte fra en professionel. En fejl i strukturen kan forårsage applikationsfejl, op til og med fuldstændig manglende evne til at køre applikationen.
database.info_2=Filnavnet er ligegyldigt ved upload. Det vil blive omdøbt bagefter for at følge formatet backup_user_yyyyMMddHHmm.sql, hvilket sikrer en konsistent navngivningskonvention.
database.submit=Importér Backup
database.importIntoDatabaseSuccessed=Import i database lykkedes
database.backupCreated=Database backup successful
database.fileNotFound=Fil ikke fundet
database.fileNullOrEmpty=Fil må ikke være null eller tom
database.failedImportFile=Kunne ikke importere fil
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_de_DE.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Erstellungsdatum
database.fileSize=Dateigröße
database.deleteBackupFile=Sicherungsdatei löschen
database.importBackupFile=Sicherungsdatei importieren
database.createBackupFile=Sicherungsdatei erstellen
database.downloadBackupFile=Sicherungsdatei herunterladen
database.info_1=Beim Importieren der Daten ist es von größter Bedeutung, die korrekte Struktur zu gewährleisten. Wenn Sie nicht sicher sind, was Sie tun, suchen Sie Rat und Unterstützung von einem Fachmann. Ein Fehler in der Struktur kann zu Fehlfunktionen der Anwendung führen, bis hin zur vollständigen Nicht-Lauffähigkeit der Anwendung.
database.info_2=Der Dateiname spielt beim Hochladen keine Rolle. Dieser wird nachträglich in das Format backup_user_yyyyMMddHHmm.sql geändert, um eine einheitliche Benennung zu gewährleisten.
database.submit=Sicherungsdatei importieren
database.importIntoDatabaseSuccessed=Import in die Datenbank erfolgreich
database.backupCreated=Datenbanksicherung erfolgreich
database.fileNotFound=Datei nicht gefunden
database.fileNullOrEmpty=Datei darf nicht null oder leer sein
database.failedImportFile=Dateiimport fehlgeschlagen
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_el_GR.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Ημερομηνία δημιουργίας
database.fileSize=Μέγεθος αρχείου
database.deleteBackupFile=Διαγραφή Προγράμματος Ανασυγκρότησης
database.importBackupFile=Εισάγωντας Προγράμματος Ανασυγκρότησης
database.createBackupFile=Create Backup File
database.downloadBackupFile=Κατέβασμα Προγράμματος Ανασυγκρότησης
database.info_1=Όταν εισάγετε δεδομένα, είναι σημαντικό να εξασφαλίσετε τη σωστή μορφοποίηση. Αν δεν είστε σίγουροι για το ποια πράγματα κάνετε, αιτήστε υποβολή και υποστήριξη από ευελίκτω. Μια σφάλμα στη μορφοποίηση μπορεί να προκαλέσει καταστάσεις λάθους στην εφαρμογή, αν όχι ολόκληρη την αποχώρηση της εφαρμογής.
database.info_2=Το ονόμα του αρχείου δεν έχει σημασία όταν ξεκινάτε μια επέμβαση. Αλλαγήται αργότερα για να ακολουθήσει το σχήμα backup_ωςώντας_YYYYMMDDHHmm.sql, επιτρέποντας μια συνεχές κατάληψη ονόματος.
database.submit=Εισάγωντας Προγράμματος Ανασυγκρότησης
database.importIntoDatabaseSuccessed=Τελείωση εισαγωγής στη βάση δεδομένων.
database.backupCreated=Database backup successful
database.fileNotFound=File not Found
database.fileNullOrEmpty=Το αρχείο δεν μπορεί να είναι τυχόν ή κενό.
database.failedImportFile=Failed Import File
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_en_GB.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Creation Date
database.fileSize=File Size
database.deleteBackupFile=Delete Backup File
database.importBackupFile=Import Backup File
database.createBackupFile=Create Backup File
database.downloadBackupFile=Download Backup File
database.info_1=When importing data, it is crucial to ensure the correct structure. If you are unsure of what you are doing, seek advice and support from a professional. An error in the structure can cause application malfunctions, up to and including the complete inability to run the application.
database.info_2=The file name does not matter when uploading. It will be renamed afterward to follow the format backup_user_yyyyMMddHHmm.sql, ensuring a consistent naming convention.
database.submit=Import Backup
database.importIntoDatabaseSuccessed=Import into database successed
database.backupCreated=Database backup successful
database.fileNotFound=File not found
database.fileNullOrEmpty=File must not be null or empty
database.failedImportFile=Failed to import file
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/messages_en_US.properties
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,13 @@ database.creationDate=Creation Date
database.fileSize=File Size
database.deleteBackupFile=Delete Backup File
database.importBackupFile=Import Backup File
database.createBackupFile=Create Backup File
database.downloadBackupFile=Download Backup File
database.info_1=When importing data, it is crucial to ensure the correct structure. If you are unsure of what you are doing, seek advice and support from a professional. An error in the structure can cause application malfunctions, up to and including the complete inability to run the application.
database.info_2=The file name does not matter when uploading. It will be renamed afterward to follow the format backup_user_yyyyMMddHHmm.sql, ensuring a consistent naming convention.
database.submit=Import Backup
database.importIntoDatabaseSuccessed=Import into database successed
database.backupCreated=Database backup successful
database.fileNotFound=File not Found
database.fileNullOrEmpty=File must not be null or empty
database.failedImportFile=Failed Import File
Expand Down
Loading

0 comments on commit 051cd2d

Please sign in to comment.