com.ovea.tadjin.util.fs.FileSystemWatcherModule Maven / Gradle / Ivy
The newest version!
/**
* Copyright (C) 2011 Ovea
*
* 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 com.ovea.tadjin.util.fs;
import com.google.common.base.Predicates;
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.spi.InjectionListener;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;
import com.ovea.tadjin.util.properties.PropertySettings;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Provider;
import java.io.File;
import java.util.logging.Logger;
/**
* @author Mathieu Carbou ([email protected])
*/
public final class FileSystemWatcherModule extends AbstractModule {
private static final Logger LOGGER = Logger.getLogger(FileSystemWatcherModule.class.getName());
private final FileSystemWatcher watcher = new FrequencyFileSystemWatcher();
@Override
protected void configure() {
requireBinding(PropertySettings.class);
requestInjection(this);
bindListener(new AbstractMatcher>() {
@Override
public boolean matches(TypeLiteral> type) {
return FileListener.class.isAssignableFrom(type.getRawType());
}
}, new TypeListener() {
@Override
public void hear(TypeLiteral type, TypeEncounter encounter) {
final Provider props = encounter.getProvider(PropertySettings.class);
encounter.register(new InjectionListener() {
@Override
public void afterInjection(I injectee) {
WatchFile watchFile = injectee.getClass().getAnnotation(WatchFile.class);
if (watchFile != null && watchFile.property().trim().length() > 0 && props.get().has(watchFile.property().trim())) {
File file = props.get().getPath(watchFile.property().trim());
LOGGER.info("Watching versionning file " + file);
watcher.watchFile(watchFile.frequency(), watchFile.unit(), file);
watcher.addListener(new FilteredFileListener((FileListener) injectee, Predicates.equalTo(file)));
}
}
});
}
}
);
}
@PostConstruct
public void start() {
watcher.start();
}
@PreDestroy
public void stop() {
watcher.stop();
}
}