1 //
2 // ========================================================================
3 // Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
17 //
18
19 package org.eclipse.jetty.jndi;
20
21 import java.lang.reflect.Method;
22 import java.sql.Connection;
23 import java.sql.Statement;
24
25 import javax.sql.DataSource;
26
27 import org.eclipse.jetty.util.component.ContainerLifeCycle;
28 import org.eclipse.jetty.util.component.Destroyable;
29 import org.eclipse.jetty.util.log.Log;
30 import org.eclipse.jetty.util.log.Logger;
31
32 /**
33 * Close a DataSource.
34 * Some {@link DataSource}'s need to be close (eg. Atomikos). This bean is a {@link Destroyable} and
35 * may be added to any {@link ContainerLifeCycle} so that {@link #destroy()}
36 * will be called. The {@link #destroy()} method calls any no-arg method called "close" on the passed DataSource.
37 *
38 */
39 public class DataSourceCloser implements Destroyable
40 {
41 private static final Logger LOG = Log.getLogger(DataSourceCloser.class);
42
43 final DataSource _datasource;
44 final String _shutdown;
45
46 public DataSourceCloser(DataSource datasource)
47 {
48 if (datasource==null)
49 throw new IllegalArgumentException();
50 _datasource=datasource;
51 _shutdown=null;
52 }
53
54 public DataSourceCloser(DataSource datasource,String shutdownSQL)
55 {
56 if (datasource==null)
57 throw new IllegalArgumentException();
58 _datasource=datasource;
59 _shutdown=shutdownSQL;
60 }
61
62 @Override
63 public void destroy()
64 {
65 try
66 {
67 if (_shutdown!=null)
68 {
69 LOG.info("Shutdown datasource {}",_datasource);
70 try (Connection connection = _datasource.getConnection();
71 Statement stmt = connection.createStatement())
72 {
73 stmt.executeUpdate(_shutdown);
74 }
75 }
76 }
77 catch (Exception e)
78 {
79 LOG.warn(e);
80 }
81
82 try
83 {
84 Method close = _datasource.getClass().getMethod("close", new Class[]{});
85 LOG.info("Close datasource {}",_datasource);
86 close.invoke(_datasource, new Object[]{});
87 }
88 catch (Exception e)
89 {
90 LOG.warn(e);
91 }
92 }
93 }