@WebListener prevents Vaadin application to deploy

Hello,

I have a question posted in
Stack Overflow

I have a Vaadin web application, that is deploying OK. BUT when I add a FolderWatcher service as a Listener using @WebListenerThe application fails to deploy, but it starts the thread if I disable the annotation @WebListener the application does deploy.

Here is a ContextListener class

[code]
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.vaadin.demo.dashboard.util.FolderWatchService;
import com.vaadin.demo.dashboard.util.PropertiesCache;
@WebListener
public class ContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("#### Folder watcher service destroyed");
        
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("#### Folder watcher service initialized");
         Path dir = Paths.get(PropertiesCache.getInstance().getProperty("file_input_location"));
            try {
                new FolderWatchService(dir).processEvents();
                System.out.println("#### Folder watcher service started");
            } catch (IOException e) {
                System.out.println("#### Folder watcher Problem");
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        
    }
    }

[/code]Folder watcher class

[code]
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.io.FilenameUtils;

import com.vaadin.demo.dashboard.data.Kod_SubsDataControl;
import com.vaadin.demo.dashboard.domain.Kod_subs;

public class FolderWatchService {

private final WatchService watcher;
private final Map<WatchKey, Path> keys;
private static final Logger LOGGER = Logger.getLogger( FolderWatchService.class.getName() );

/**
 * Creates a WatchService and registers the given directory
 */
public FolderWatchService(Path dir) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<WatchKey, Path>();

    walkAndRegisterDirectories(dir);
}

/**
 * Register the given directory with the WatchService; This function will be called by FileVisitor
 */
private void registerDirectory(Path dir) throws IOException 
{
    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    keys.put(key, dir);
}

/**
 * Register the given directory, and all its sub-directories, with the WatchService.
 */
private void walkAndRegisterDirectories(final Path start) throws IOException {
    // register directory and sub-directories
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            registerDirectory(dir);
            return FileVisitResult.CONTINUE;
        }
    });
}

/**
 * Process all events for keys queued to the watcher
 */
public void processEvents() {
    for (;;) {

        // wait for key to be signalled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            LOGGER.log( Level.FINE, "WatchKey not recognized!!", "" );

            System.err.println("WatchKey not recognized!!");
            continue;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            @SuppressWarnings("rawtypes")
            WatchEvent.Kind kind = event.kind();

            // Context for directory entry event is the file name of entry
            @SuppressWarnings("unchecked")
            Path name = ((WatchEvent<Path>)event).context();
            Path child = dir.resolve(name);

            // print out event

// System.out.format(“%s: %s\n”, event.kind().name(), child);
// System.out.println("New path created: " + child);
String fileContent;

            // if directory is created, and watching recursively, then register it and its sub-directories
            if (kind == ENTRY_CREATE) {
                System.out.println("File created");
                LOGGER.log( Level.FINER, "New File created", "" );
                readFile(child.toString());
            }
        }

        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);

            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}
private static void readFile(String pathname){

    try {
        File file = new File(pathname);

// System.out.println("FilePath: "+pathname);
// System.out.println("Absolute File: "+file.getAbsolutePath());
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty(“line.separator”);

        try {
            while(scanner.hasNextLine()) {
                fileContents.append(scanner.nextLine() + lineSeparator);
            }
            String fileContent = fileContents.toString();
            System.out.println("File name: "+FilenameUtils.getBaseName(pathname));
            LOGGER.log( Level.FINER, "File name: "+FilenameUtils.getBaseName(pathname), "" );
            String title = "File Title: "+fileContent.substring(0, 64).trim().lastIndexOf(System.getProperty("line.separator"))+"...";
           
        } finally {
            scanner.close();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
}

}
[/code]What am I doing wrong?

Hi,
looking at your code and at the log you posted on stackoverflow it seems you are blocking the initialization thread on
new FolderWatchService(dir).processEvents()
call.

You should start event processing in another thread (ie using an ExecutorService so you also stop the job on contextDestroyed)

HTH
Marco