1
22
23 package com.liferay.portal.kernel.servlet;
24
25 import com.liferay.portal.kernel.deploy.hot.HotDeployEvent;
26 import com.liferay.portal.kernel.deploy.hot.HotDeployUtil;
27 import com.liferay.portal.kernel.jndi.PortalJNDIUtil;
28 import com.liferay.portal.kernel.log.Log;
29 import com.liferay.portal.kernel.log.LogFactoryUtil;
30 import com.liferay.portal.kernel.util.PortalInitable;
31 import com.liferay.portal.kernel.util.PortalInitableUtil;
32
33 import javax.naming.Context;
34 import javax.naming.InitialContext;
35
36 import javax.servlet.ServletContext;
37 import javax.servlet.ServletContextEvent;
38 import javax.servlet.ServletContextListener;
39
40 import javax.sql.DataSource;
41
42
49 public class PortletContextListener
50 implements PortalInitable, ServletContextListener {
51
52 public void portalInit() {
53 HotDeployUtil.fireDeployEvent(new HotDeployEvent(_ctx, _classLoader));
54
55 try {
56 if (_log.isDebugEnabled()) {
57 _log.debug("Dynamically binding the Liferay data source");
58 }
59
60 DataSource dataSource = PortalJNDIUtil.getDataSource();
61
62 if (dataSource == null) {
63 if (_log.isDebugEnabled()) {
64 _log.debug(
65 "Abort dynamically binding the Liferay data source " +
66 "because it is not available");
67 }
68
69 return;
70 }
71
72 Context ctx = new InitialContext();
73
74 ctx.createSubcontext(_JNDI_JDBC);
75
76 ctx.bind(_JNDI_JDBC_LIFERAY_POOL, PortalJNDIUtil.getDataSource());
77
78 _bindLiferayPool = true;
79 }
80 catch (Exception e) {
81 if (_log.isWarnEnabled()) {
82 _log.warn(
83 "Unable to dynamically bind the Liferay data source: "
84 + e.getMessage());
85 }
86 }
87 }
88
89 public void contextInitialized(ServletContextEvent event) {
90 _classLoader = Thread.currentThread().getContextClassLoader();
91 _ctx = event.getServletContext();
92
93 PortalInitableUtil.init(this);
94 }
95
96 public void contextDestroyed(ServletContextEvent event) {
97 HotDeployUtil.fireUndeployEvent(
98 new HotDeployEvent(
99 event.getServletContext(),
100 Thread.currentThread().getContextClassLoader()));
101
102 try {
103 if (!_bindLiferayPool) {
104 return;
105 }
106
107 _bindLiferayPool = false;
108
109 if (_log.isDebugEnabled()) {
110 _log.debug("Dynamically unbinding the Liferay data source");
111 }
112
113 Context ctx = new InitialContext();
114
115 ctx.unbind(_JNDI_JDBC_LIFERAY_POOL);
116
117 ctx.destroySubcontext(_JNDI_JDBC);
118 }
119 catch (Exception e) {
120 if (_log.isWarnEnabled()) {
121 _log.warn(
122 "Unable to dynamically unbind the Liferay data source: "
123 + e.getMessage());
124 }
125 }
126 }
127
128 private static final String _JNDI_JDBC = "java_liferay:jdbc";
129
130 private static final String _JNDI_JDBC_LIFERAY_POOL =
131 _JNDI_JDBC + "/LiferayPool";
132
133 private static Log _log =
134 LogFactoryUtil.getLog(PortletContextListener.class);
135
136 private ClassLoader _classLoader;
137 private ServletContext _ctx;
138 private boolean _bindLiferayPool;
139
140 }