001package org.javasimon.spring;
002
003import java.io.FileNotFoundException;
004import java.io.IOException;
005import java.io.InputStream;
006import java.io.InputStreamReader;
007import java.io.Reader;
008
009import org.javasimon.Manager;
010import org.javasimon.SimonManager;
011import org.javasimon.SwitchingManager;
012
013import org.springframework.beans.factory.InitializingBean;
014
015/**
016 * Spring bean that configures Simon manager using {@link org.javasimon.ManagerConfiguration} facility.
017 *
018 * @author <a href="mailto:virgo47@gmail.com">Richard "Virgo" Richter</a>
019 */
020public class SimonConfigurationBean implements InitializingBean {
021        private Manager simonManager = SimonManager.manager();
022        private String configurationPath;
023
024        public Manager getSimonManager() {
025                return simonManager;
026        }
027
028        public void setSimonManager(Manager simonManager) {
029                this.simonManager = simonManager;
030        }
031
032        /**
033         * Creates new {@link org.javasimon.SwitchingManager} instead of using {@link org.javasimon.SimonManager#manager()}.
034         */
035        public void setNewManager() {
036                simonManager = new SwitchingManager();
037        }
038
039        /**
040         * Loads configuration for the manager from the specified resource path.
041         *
042         * @param configurationPath resource path to the configuration XML
043         * @throws IOException thrown if the resource is not found or the configuration XML is not well formed
044         */
045        public void setConfiguration(String configurationPath) throws IOException {
046                this.configurationPath = configurationPath;
047        }
048
049        @Override
050        public void afterPropertiesSet() throws Exception {
051                if (configurationPath != null) {
052                        InputStream is = getClass().getClassLoader().getResourceAsStream(configurationPath);
053                        if (is == null) {
054                                throw new FileNotFoundException(configurationPath);
055                        }
056                        try (Reader reader = new InputStreamReader(is)) {
057                                simonManager.configuration().readConfig(reader);
058                        }
059                }
060        }
061}