/*
* Copyright 2014 Simon FLandergan
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.sflan.file.symlinker.schedule;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.sflan.file.symlinker.SyncProcess;
import de.sflan.file.symlinker.config.Config;
import de.sflan.file.symlinker.config.SyncPair;
/**
* Class running processes for synchronizing folder sync pairs.
* - At first starts a one time synchronization job: {@link SyncProcess}</li>
* - Then starts monitors for each pair {@link FolderWatchProcess}
* @author simon.flandergan
*
*/
public class FolderWatcher {
private Config config;
private ExecutorService executor;
private List<FolderWatchProcess> processes = new LinkedList<>();
private static Logger logger = Logger.getLogger(FolderWatcher.class.getSimpleName());
public FolderWatcher(Config config){
this.config = config;
executor = Executors.newFixedThreadPool(config.getSyncPair().size());
}
public void start() {
for (SyncPair pair : config.getSyncPair()){
try {
/*
* initial run
*/
logger.info("Running initial sync for pair: "+pair);
new SyncProcess(pair).call();
/*
* register watch service
*/
logger.info("Registering watch process for pair: "+pair);
FolderWatchProcess process = new FolderWatchProcess(pair);
this.executor.submit(process);
this.processes.add(process);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error on sync job", e);
}
}
}
public void stop() {
logger.info("Got shutdown signal");
/*
* stop processes
*/
for (FolderWatchProcess process : processes){
process.stop();
}
/*
* shutdown the executor
*/
executor.shutdown();
boolean isTerminated = false;
try {
isTerminated = executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
/*
* ignore
*/
}
if (!isTerminated){
logger.warning("Failed to terminate sync proceses");
}
}
}