View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.configuration.reloading;
19  
20  import static org.junit.Assert.assertEquals;
21  import static org.junit.Assert.assertFalse;
22  import static org.junit.Assert.assertNotNull;
23  import static org.junit.Assert.assertNull;
24  import static org.junit.Assert.assertTrue;
25  
26  import java.io.ByteArrayOutputStream;
27  import java.io.File;
28  import java.io.FileWriter;
29  import java.net.URL;
30  
31  import org.apache.commons.configuration.ConfigurationException;
32  import org.apache.commons.configuration.PropertiesConfiguration;
33  import org.apache.commons.configuration.XMLConfiguration;
34  import org.apache.log4j.Appender;
35  import org.apache.log4j.Layout;
36  import org.apache.log4j.Level;
37  import org.apache.log4j.Logger;
38  import org.apache.log4j.PatternLayout;
39  import org.apache.log4j.WriterAppender;
40  import org.junit.Test;
41  
42  /**
43   * Test case for the ReloadableConfiguration class.
44   *
45   * @author Emmanuel Bourg
46   * @version $Id: TestFileChangedReloadingStrategy.java 1225906 2011-12-30 20:01:37Z oheger $
47   */
48  public class TestFileChangedReloadingStrategy
49  {
50      /** Constant for the name of a test properties file.*/
51      private static final String TEST_FILE = "test.properties";
52  
53      @Test
54      public void testAutomaticReloading() throws Exception
55      {
56          // create a new configuration
57          File file = new File("target/testReload.properties");
58  
59          if (file.exists())
60          {
61              file.delete();
62          }
63  
64          // create the configuration file
65          FileWriter out = new FileWriter(file);
66          out.write("string=value1");
67          out.flush();
68          out.close();
69  
70          // load the configuration
71          PropertiesConfiguration config = new PropertiesConfiguration("target/testReload.properties");
72          FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
73          strategy.setRefreshDelay(500);
74          config.setReloadingStrategy(strategy);
75          assertEquals("Initial value", "value1", config.getString("string"));
76  
77          Thread.sleep(2000);
78  
79          // change the file
80          out = new FileWriter(file);
81          out.write("string=value2");
82          out.flush();
83          out.close();
84  
85          // test the automatic reloading
86          assertEquals("Modified value with enabled reloading", "value2", config.getString("string"));
87      }
88  
89      @Test
90      public void testNewFileReloading() throws Exception
91      {
92          // create a new configuration
93          File file = new File("target/testReload.properties");
94  
95          if (file.exists())
96          {
97              file.delete();
98          }
99  
100         PropertiesConfiguration config = new PropertiesConfiguration();
101         config.setFile(file);
102         FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
103         strategy.setRefreshDelay(500);
104         config.setReloadingStrategy(strategy);
105 
106         assertNull("Initial value", config.getString("string"));
107 
108         // change the file
109         FileWriter out = new FileWriter(file);
110         out.write("string=value1");
111         out.flush();
112         out.close();
113 
114         Thread.sleep(2000);
115 
116         // test the automatic reloading
117         assertEquals("Modified value with enabled reloading", "value1", config.getString("string"));
118     }
119 
120     @Test
121     public void testGetRefreshDelay()
122     {
123         FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
124         strategy.setRefreshDelay(500);
125         assertEquals("refresh delay", 500, strategy.getRefreshDelay());
126     }
127 
128     /**
129      * Tests if a file from the classpath can be monitored.
130      */
131     @Test
132     public void testFromClassPath() throws Exception
133     {
134         PropertiesConfiguration config = new PropertiesConfiguration();
135         config.setFileName(TEST_FILE);
136         config.load();
137         assertTrue(config.getBoolean("configuration.loaded"));
138         FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
139         config.setReloadingStrategy(strategy);
140         assertEquals(config.getURL().toExternalForm(), strategy.getFile().toURI().toURL().toExternalForm());
141     }
142 
143     /**
144      * Tests to watch a configuration file in a jar. In this case the jar file
145      * itself should be monitored.
146      */
147     @Test
148     public void testFromJar() throws Exception
149     {
150         XMLConfiguration config = new XMLConfiguration();
151         // use some jar: URL
152         config.setURL(new URL("jar:" + new File("conf/resources.jar").getAbsoluteFile().toURI().toURL() + "!/test-jar.xml"));
153         FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
154         config.setReloadingStrategy(strategy);
155         File file = strategy.getFile();
156         assertNotNull("Strategy's file is null", file);
157         assertEquals("Strategy does not monitor the jar file", "resources.jar", file.getName());
158     }
159 
160     /**
161      * Tests calling reloadingRequired() multiple times before a reload actually
162      * happens. This test is related to CONFIGURATION-302.
163      */
164     @Test
165     public void testReloadingRequiredMultipleTimes()
166             throws ConfigurationException
167     {
168         FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy()
169         {
170             @Override
171             protected boolean hasChanged()
172             {
173                 // signal always a change
174                 return true;
175             }
176         };
177         strategy.setRefreshDelay(100000);
178         PropertiesConfiguration config = new PropertiesConfiguration(TEST_FILE);
179         config.setReloadingStrategy(strategy);
180         assertTrue("Reloading not required", strategy.reloadingRequired());
181         assertTrue("Reloading no more required", strategy.reloadingRequired());
182         strategy.reloadingPerformed();
183         assertFalse("Reloading still required", strategy.reloadingRequired());
184     }
185 
186     @Test
187     public void testFileDeletion() throws Exception
188     {
189         Logger logger = Logger.getLogger(FileChangedReloadingStrategy.class.getName());
190         Layout layout = new PatternLayout("%p - %m%n");
191         ByteArrayOutputStream os = new ByteArrayOutputStream();
192         Appender appender = new WriterAppender(layout, os);
193         logger.addAppender(appender);
194         logger.setLevel(Level.WARN);
195         logger.setAdditivity(false);
196         // create a new configuration
197         File file = new File("target/testReload.properties");
198 
199         if (file.exists())
200         {
201             file.delete();
202         }
203 
204         // create the configuration file
205         FileWriter out = new FileWriter(file);
206         out.write("string=value1");
207         out.flush();
208         out.close();
209 
210         // load the configuration
211         PropertiesConfiguration config = new PropertiesConfiguration("target/testReload.properties");
212         FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
213         strategy.setRefreshDelay(500);
214         config.setReloadingStrategy(strategy);
215         assertEquals("Initial value", "value1", config.getString("string"));
216 
217         Thread.sleep(2000);
218 
219         // Delete the file.
220         file.delete();
221         //Old value should still be returned.
222         assertEquals("Initial value", "value1", config.getString("string"));
223         logger.removeAppender(appender);
224         String str = os.toString();
225         //System.out.println(str);
226         assertTrue("No error was logged", str != null && str.length() > 0);
227     }
228 }