44import com .example .springprojectsteganographytool .exceptions .data .StorageFileNotFoundException ;
55import com .example .springprojectsteganographytool .exceptions .data .StorageSecurityException ;
66import com .example .springprojectsteganographytool .services .StorageService ;
7+ import jakarta .annotation .PostConstruct ;
78import lombok .extern .slf4j .Slf4j ;
89import org .springframework .beans .factory .annotation .Value ;
910import org .springframework .core .io .Resource ;
@@ -38,14 +39,27 @@ public StorageServiceImpl(@Value("${app.storage.base-path}") Path basePath) thro
3839 }
3940
4041 this .basePath = basePath .toAbsolutePath ().normalize ();
42+ log .info ("Storage base path configured: {}" , this .basePath );
43+ }
4144
42- // **KEY CHANGE: Ensure the base directory exists**
45+ /**
46+ * Post-construct initialization to ensure the storage directory exists.
47+ * This method is called after dependency injection is complete and BEFORE lazy initialization.
48+ */
49+ @ PostConstruct
50+ public void init () {
4351 try {
4452 Files .createDirectories (this .basePath );
45- log .info ("Using storage base path: {}" , this .basePath );
53+ log .info ("Storage directory initialized successfully: {}" , this .basePath );
54+
55+ // Verify write permissions
56+ if (!Files .isWritable (this .basePath )) {
57+ log .error ("Storage directory is not writable: {}" , this .basePath );
58+ throw new IllegalStateException ("Storage directory is not writable: " + this .basePath );
59+ }
4660 } catch (IOException e ) {
47- log .error ("Failed to create storage base path : {}" , this .basePath , e );
48- throw new IllegalArgumentException ("Cannot create storage directory: " + this .basePath , e );
61+ log .error ("Failed to create storage directory : {}" , this .basePath , e );
62+ throw new IllegalStateException ("Cannot create storage directory: " + this .basePath , e );
4963 }
5064 }
5165
@@ -64,7 +78,12 @@ public Path save(String relativeFileName, byte[] content) throws StorageSecurity
6478
6579 try {
6680 var targetPath = safeResolve (relativeFileName );
67- Files .createDirectories (targetPath .getParent ());
81+
82+ // Ensure parent directory exists (though basePath should already exist from init())
83+ if (targetPath .getParent () != null && !Files .exists (targetPath .getParent ())) {
84+ Files .createDirectories (targetPath .getParent ());
85+ }
86+
6887 Files .write (targetPath , content , StandardOpenOption .CREATE , StandardOpenOption .TRUNCATE_EXISTING );
6988 log .debug ("Saved file: {} ({} bytes)" , targetPath , content .length );
7089 return targetPath ;
0 commit comments