Search code examples
javaspring-bootspring-batchassert

Assert.state deprecated in Spring?


I trying to delete a file which located at Desktop/outputs/

public class FileDeleteTasklet implements Tasklet,InitializingBean {

    @Value("${fileName}")
    private String fileName;

    @Value("home/xxx/Desktop/outputs/")
    private Resource directory;


    @Override
    public RepeatStatus execute(StepContribution sc, ChunkContext cc) throws Exception {

        String file = fileName+ time()+".csv";
        try {
            File dir = directory.getFile();
            Assert.state(dir.isDirectory());

            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {

                if (files[i].getName().equalsIgnoreCase(file)) {
                    boolean rename = files[i].delete();
                    if (!rename) {
                        System.out.println("Could not delete");
                        throw new UnexpectedJobExecutionException("Could not delete file " + files[i].getPath());
                    } else {
                        System.out.println(files[i].getPath() + " is deleted!");
                        break;
                    }
                }
            }
            return RepeatStatus.FINISHED;

        } catch (Exception ex) {
            System.out.println("=========== Could not delete file " + file+ " *** failed *** due to " + ex.getMessage());
        }
        return RepeatStatus.FINISHED;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
         Assert.notNull(directory, "directory must be set");
    }

}

Error

=========== Could not delete file Reporting_2018-02-22.csv *** failed *** due to [Assertion failed] - this state invariant must be true

I realize Assert.state deprecated in Java ? Is it why the error happened ?


Solution

  • No, it isn't why the error happened. The error happened because it wasn't a directory, just like the code says.

    But you don't need the assert (which should never have been an assertion in the first place, as it isn't an invariant of the code), or the pointless and wasteful directory search either. Just use

    boolean deleted = new File(file).delete();
    

    assuming you can control the case issue, which you should be able to do.