001package com.dev9.mvnwatcher; 002 003import com.dev9.mvnwatcher.event.DirectoryEventWatcherImpl; 004import com.dev9.mvnwatcher.event.FileChangeSubscriber; 005import com.google.common.eventbus.EventBus; 006 007import java.io.IOException; 008import java.nio.file.Path; 009import java.util.List; 010import java.util.Objects; 011 012/** 013 * Responsible for the overall lifecycle of a monitored project 014 */ 015public class MvnWatcher { 016 017 private final List<Path> pathsToWatch; 018 private final Path projectPath; 019 private final Path targetPath; 020 private final List<Task> tasks; 021 022 private MvnRunner runner; 023 024 /** 025 * Set to false to terminate 026 */ 027 public boolean terminate = false; 028 029 public MvnWatcher(List<Path> pathsToWatch, Path projectPath, Path targetPath, List<Task> tasks) { 030 this.pathsToWatch = Objects.requireNonNull(pathsToWatch); 031 032 this.projectPath = Objects.requireNonNull(projectPath); 033 this.targetPath = Objects.requireNonNull(targetPath); 034 this.tasks = Objects.requireNonNull(tasks); 035 } 036 037 /** 038 * Configure and start watching the project 039 * 040 * @throws IOException most likely if there are invalid paths 041 */ 042 public void startUpWatcher() throws IOException { 043 EventBus eventBus; 044 DirectoryEventWatcherImpl dirWatcher; 045 FileChangeSubscriber subscriber; 046 047 eventBus = new EventBus(); 048 dirWatcher = new DirectoryEventWatcherImpl(eventBus); 049 050 for (Path p : pathsToWatch) 051 dirWatcher.add(p); 052 053 dirWatcher.start(); 054 runner = new MvnRunner(projectPath, targetPath, tasks); 055 subscriber = new FileChangeSubscriber(dirWatcher, runner); 056 eventBus.register(subscriber); 057 runner.start(); 058 } 059 060 /** 061 * Start a sleeping loop waiting for a cancel. 062 */ 063 public void waitForCancel() { 064 065 while (!terminate) { 066 try { 067 Thread.sleep(1000); 068 069 if (!runner.running()) 070 terminate = true; 071 072 } catch (InterruptedException e) { 073 e.printStackTrace(); 074 } 075 } 076 } 077 078}