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 ;
@@ -37,8 +38,29 @@ public StorageServiceImpl(@Value("${app.storage.base-path}") Path basePath) thro
3738 throw new IllegalArgumentException ("app.storage.base-path must not be null" );
3839 }
3940
40- log .info ("Using storage base path: {}" , basePath .toAbsolutePath ().normalize ());
4141 this .basePath = basePath .toAbsolutePath ().normalize ();
42+ log .info ("Storage base path configured: {}" , this .basePath );
43+ }
44+
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 () {
51+ try {
52+ Files .createDirectories (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+ }
60+ } catch (IOException e ) {
61+ log .error ("Failed to create storage directory: {}" , this .basePath , e );
62+ throw new IllegalStateException ("Cannot create storage directory: " + this .basePath , e );
63+ }
4264 }
4365
4466 /**
@@ -56,7 +78,12 @@ public Path save(String relativeFileName, byte[] content) throws StorageSecurity
5678
5779 try {
5880 var targetPath = safeResolve (relativeFileName );
59- 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+
6087 Files .write (targetPath , content , StandardOpenOption .CREATE , StandardOpenOption .TRUNCATE_EXISTING );
6188 log .debug ("Saved file: {} ({} bytes)" , targetPath , content .length );
6289 return targetPath ;
0 commit comments