1 |
package dk.daoas.adressevedligehold; |
2 |
|
3 |
|
4 |
import java.io.FileInputStream; |
5 |
import java.io.IOException; |
6 |
import java.io.InputStreamReader; |
7 |
import java.io.Reader; |
8 |
import java.nio.charset.Charset; |
9 |
import java.util.Properties; |
10 |
|
11 |
import javax.servlet.ServletContext; |
12 |
import javax.servlet.ServletContextEvent; |
13 |
import javax.servlet.ServletContextListener; |
14 |
import javax.servlet.ServletRegistration; |
15 |
import javax.servlet.annotation.WebListener; |
16 |
|
17 |
import org.apache.commons.lang3.SystemUtils; |
18 |
|
19 |
import dk.thoerup.webconfig.ConfigServlet; |
20 |
import dk.thoerup.webconfig.PropertiesConfigLoader; |
21 |
|
22 |
/** |
23 |
* Application Lifecycle Listener implementation class ContextListener |
24 |
* |
25 |
*/ |
26 |
@WebListener |
27 |
public class ContextListener implements ServletContextListener { |
28 |
|
29 |
|
30 |
|
31 |
|
32 |
public ContextListener() { |
33 |
// TODO Auto-generated constructor stub |
34 |
} |
35 |
|
36 |
public void contextDestroyed(ServletContextEvent ctxtEvt) { |
37 |
// TODO Auto-generated method stub |
38 |
} |
39 |
|
40 |
@Override |
41 |
public void contextInitialized(ServletContextEvent ctxtEvt) { |
42 |
System.out.println("Starting DAO Context"); |
43 |
|
44 |
|
45 |
|
46 |
ServletContext ctxt = ctxtEvt.getServletContext(); |
47 |
|
48 |
try { |
49 |
initConfig(ctxt); |
50 |
} catch (IOException e) { |
51 |
System.out.println("Error loading config " + e.getMessage()); |
52 |
throw new RuntimeException(e); |
53 |
} |
54 |
|
55 |
|
56 |
System.out.println("DAO Context done"); |
57 |
} |
58 |
|
59 |
|
60 |
|
61 |
|
62 |
private ServiceConfig initConfig(ServletContext ctxt) throws IOException { |
63 |
|
64 |
final String CONF_FILE_NAME = "daoadressevedligehold.conf"; |
65 |
|
66 |
|
67 |
ServiceConfig conf = ServiceConfig.getInstance(); |
68 |
|
69 |
String file = null; |
70 |
if (SystemUtils.IS_OS_WINDOWS) { |
71 |
file = "C:\\" + CONF_FILE_NAME; |
72 |
} else { |
73 |
file = "/etc/" + CONF_FILE_NAME; |
74 |
} |
75 |
|
76 |
Properties propsFile = new Properties(); |
77 |
try ( Reader reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")) ) { |
78 |
propsFile.load(reader); |
79 |
} |
80 |
|
81 |
|
82 |
new PropertiesConfigLoader(propsFile).loadConfig(conf); |
83 |
|
84 |
|
85 |
ctxt.setAttribute("config", conf); |
86 |
|
87 |
// ///////////////////////////////////// |
88 |
ConfigServlet servlet = new ConfigServlet(); |
89 |
servlet.setConfigObject( conf ); |
90 |
ServletRegistration.Dynamic dynconf = ctxt.addServlet("webconfig", servlet ); |
91 |
dynconf.addMapping("/ConfigServlet"); |
92 |
|
93 |
return conf; |
94 |
} |
95 |
|
96 |
|
97 |
} |