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 contextDestroyed(ServletContextEvent event) {
53 HotDeployUtil.fireUndeployEvent(
54 new HotDeployEvent(
55 event.getServletContext(),
56 Thread.currentThread().getContextClassLoader()));
57
58 try {
59 if (!_bindLiferayPool) {
60 return;
61 }
62
63 _bindLiferayPool = false;
64
65 if (_log.isDebugEnabled()) {
66 _log.debug("Dynamically unbinding the Liferay data source");
67 }
68
69 Context ctx = new InitialContext();
70
71 ctx.unbind(_JNDI_JDBC_LIFERAY_POOL);
72
73 ctx.destroySubcontext(_JNDI_JDBC);
74 }
75 catch (Exception e) {
76 if (_log.isWarnEnabled()) {
77 _log.warn(
78 "Unable to dynamically unbind the Liferay data source: "
79 + e.getMessage());
80 }
81 }
82 }
83
84 public void contextInitialized(ServletContextEvent event) {
85 _classLoader = Thread.currentThread().getContextClassLoader();
86 _servletContext = event.getServletContext();
87
88 PortalInitableUtil.init(this);
89 }
90
91 public void portalInit() {
92 HotDeployUtil.fireDeployEvent(
93 new HotDeployEvent(_servletContext, _classLoader));
94
95 try {
96 if (_log.isDebugEnabled()) {
97 _log.debug("Dynamically binding the Liferay data source");
98 }
99
100 DataSource dataSource = PortalJNDIUtil.getDataSource();
101
102 if (dataSource == null) {
103 if (_log.isDebugEnabled()) {
104 _log.debug(
105 "Abort dynamically binding the Liferay data source " +
106 "because it is not available");
107 }
108
109 return;
110 }
111
112 Context ctx = new InitialContext();
113
114 ctx.createSubcontext(_JNDI_JDBC);
115
116 ctx.bind(_JNDI_JDBC_LIFERAY_POOL, PortalJNDIUtil.getDataSource());
117
118 _bindLiferayPool = true;
119 }
120 catch (Exception e) {
121 if (_log.isWarnEnabled()) {
122 _log.warn(
123 "Unable to dynamically bind the Liferay data source: "
124 + e.getMessage());
125 }
126 }
127 }
128
129 private static final String _JNDI_JDBC = "java_liferay:jdbc";
130
131 private static final String _JNDI_JDBC_LIFERAY_POOL =
132 _JNDI_JDBC + "/LiferayPool";
133
134 private static Log _log =
135 LogFactoryUtil.getLog(PortletContextListener.class);
136
137 private ClassLoader _classLoader;
138 private ServletContext _servletContext;
139 private boolean _bindLiferayPool;
140
141 }