Spring Server automatically deletes files stored in the application. Folder

I have a Spring server running as a bootable application.

I am using h2 driver to save various objects using JPA. All these objects are updated OK.

I am using this class to manage all the files that will be updated on the server:

public class LocalFileManager {
/**
 * This static factory method creates and returns a 
 * ImageFileManager object to the caller. Feel free to customize
 * this method to take parameters, etc. if you want.
 * 
 * @return
 * @throws IOException
 */
public static LocalFileManager get() throws IOException {
    return new LocalFileManager();
}
private Path targetDir_ = Paths.get("locals");
// The ImageFileManager.get() method should be used
// to obtain an instance
private LocalFileManager() throws IOException{
    if(!Files.exists(targetDir_)){
        Files.createDirectories(targetDir_);
    }
}
// Private helper method for resolving Image file paths
private Path getLocalPath(Postosaude g, int PictureNumberByLocal){
    assert(g != null);
    return targetDir_.resolve("picture"+"-"+g.getId()+"-"+PictureNumberByLocal+".jpg");
}
/**
 * This method returns true if the specified Image has binary
 * data stored on the file system.
 * 
 * @param v
 * @return
 */
public boolean hasLocalData(Postosaude g,int i){
    Path source = getLocalPath(g, i);
    return Files.exists(source);
}
/**
 * This method copies the binary data for the given Image to
 * the provided output stream. The caller is responsible for
 * ensuring that the specified Image has binary data associated
 * with it. If not, this method will throw a FileNotFoundException.
 * 
 * @param v 
 * @param out
 * @throws IOException 
 */
public void copyGiftData(Postosaude g,int i, OutputStream out) throws IOException {
    Path source = getLocalPath(g,i);
    if(!Files.exists(source)){
        throw new FileNotFoundException("Unable to find the referenced gift file for giftId:"+g.getId());
    }
    Files.copy(source, out);
}
/**
 * This method reads all of the data in the provided InputStream and stores
 * it on the file system. The data is associated with the Image object that
 * is provided by the caller.
 * 
 * @param v
 * @param ImageData
 * @throws IOException
 */
public void saveLocalData(Postosaude g,int i, InputStream localData) throws IOException{
    assert(localData != null);
    Path target = getLocalPath(g,i);
    Files.copy(localData, target, StandardCopyOption.REPLACE_EXISTING);
}
public void deleteImageFromLocal(Postosaude g, int i) throws IOException
{
    Path target = getLocalPath(g,i);
    Files.delete(target);
}

      

}

This code works fine. Saves all files (images) that I update in the folder /locals/

, but if you restart the server , they are automatically deleted .

This code from the Application class might help you find out about the error:

@EntityScan(basePackages= "palmaslab.mapas.repository")
@EnableJpaRepositories(basePackages= "palmaslab.mapas.repository"/*.PostoSaudeRepository.class*/)
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages="palmaslab.mapas.controller")
@Import({palmaslab.mapas.security.SecurityConfiguration.class})
@EnableWebMvc
@PropertySource("application.properties")
public class Application extends WebMvcConfigurerAdapter{
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
    "classpath:/META-INF/resources/", "classpath:/resources/",
    "classpath:/static/", "classpath:/public/" };
public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
     }
 @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
        lef.setDataSource(dataSource);
        lef.setJpaVendorAdapter(jpaVendorAdapter);
        lef.setPackagesToScan("palmaslab.mapas.controller");
        return lef;
    }
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setShowSql(true);
        hibernateJpaVendorAdapter.setGenerateDdl(true); //Auto creating scheme when true
        hibernateJpaVendorAdapter.setDatabase(Database.H2);//Database type
        return hibernateJpaVendorAdapter;
    }
    @Bean 
    public SpringTemplateEngine templateEngine() { 
        SpringTemplateEngine engine = new SpringTemplateEngine();
        Set<IDialect> dialects = new HashSet<IDialect>();
        dialects.add(new SpringSecurityDialect());
        dialects.add(new LayoutDialect());
        engine.setAdditionalDialects(dialects);
        LinkedHashSet<ITemplateResolver> templateResolvers = new LinkedHashSet<ITemplateResolver>(2);
        templateResolvers.add(templateResolverServlet());
        templateResolvers.add(layoutTemplateResolverServlet());
        engine.setTemplateResolvers(templateResolvers);
        return engine;
    } 
   @Bean 
    public ServletContextTemplateResolver layoutTemplateResolverServlet() { 
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/layout/");
        templateResolver.setSuffix("");
        templateResolver.setTemplateMode("LEGACYHTML5");
        templateResolver.setOrder(1);
        templateResolver.setCacheable(false);
        return templateResolver;
    } 
     @Bean 
    public ServletContextTemplateResolver templateResolverServlet() { 
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/view/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("LEGACYHTML5");
        templateResolver.setOrder(2);
        templateResolver.setCacheable(false);
        return templateResolver;
    } 
   @Bean 
     public ViewResolver thymeleafViewResolver() { 
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setOrder(1);
        resolver.setCharacterEncoding("ISO-8859-1");
        resolver.setCache(false);
        return resolver;
    }     
@Bean
public ServletRegistrationBean dispatcherRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet());
    registration.addUrlMappings("/");
    registration.setLoadOnStartup(1);
    return registration;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}
@Bean
public DispatcherServlet dispatcherServlet() {
    return new DispatcherServlet();
}
@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setMaxFileSize("999999KB");
    factory.setMaxRequestSize("999999KB");
    return factory.createMultipartConfig();
}
 @Bean
  public MultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setMaxUploadSize(1000000000);
    return resolver;
  }
@Bean
public CommonsMultipartResolver filterMultipartResolver() {
    CommonsMultipartResolver resolver=new CommonsMultipartResolver();
    resolver.setDefaultEncoding("ISO-8859-1");
    resolver.setMaxUploadSize(500000000);
    resolver.setMaxInMemorySize(500000000);
    return resolver;
}
@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
    factory.setPort(8080);
    factory.setSessionTimeout(1, TimeUnit.MINUTES);
    //factory.addErrorPages(new ErrorPage(HttpStatus.404, "/notfound.html"));
    return factory;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!registry.hasMappingForPattern("/webjars/**")) {
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }
    if (!registry.hasMappingForPattern("/locals/**")) {
        registry.addResourceHandler("/locals/**").addResourceLocations(
                 "classpath:/locals");
      }
}

      

Can anyone find my error?

Thank,

+3


source to share


1 answer


If you create or modify files in which the application is deployed, they will be removed when the server is restarted because the application will be redistributed.



If you want the files to survive redeployments, your storage database directory must be outside the application folder (for example /srv/myapp/locals

).

+3


source







All Articles