3

I created a ApplicationScoped bean that have a PostConstruct method named start. Whenever i want to get instance of FacesContext in the start method and it returns null:

@ManagedBean
@ApplicationScoped
public class RemoveOldFilesScheduler implements Serializable {

    @PostConstruct
    private void start() {
        final FacesContext facesContext = FacesContext.getCurrentInstance();
        if(facesContext != null) {
            String realDownloadDirName = facesContext.getExternalContext().getRealPath("/") + DOWNLOAD_DIRECTORY;
        File downloadDir = new File(realDownloadDirName);
        if (downloadDir.exists()) {
            removeOldFiles(downloadDir.listFiles());
        }
}
}

How can i access to facesContext in this situation?

I want to get real path of my download directory in the start method and i don't know how to get path of my directory without using FaceContext.

Is there another way to do it?

Mostafa Jamareh
  • 1,389
  • 4
  • 22
  • 54
Hosein Masbough
  • 431
  • 1
  • 4
  • 19

1 Answers1

0

I implementing my class as Listener and it worked and i can access to ServletContext in contextInitialized method :

    public class RemoveOldFilesListener implements ServletContextListener {

    public ServletContext servletContext;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        servletContext = sce.getServletContext();
        String realDownloadDirName = servletContext.getRealPath("/") + DOWNLOAD_DIRECTORY;
        File downloadDir = new File(realDownloadDirName);
        if (downloadDir.exists()) {
            removeOldFiles(downloadDir.listFiles());
        }
}
Hosein Masbough
  • 431
  • 1
  • 4
  • 19
  • This is probably a better and more logical way to do it, since the logic sits outside the JSF application proper (which it should) – kolossus Oct 12 '14 at 18:19