001/*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * Sonar is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019 */
020package org.sonar.batch.bootstrap;
021
022import java.sql.Driver;
023import java.sql.DriverManager;
024import java.sql.SQLException;
025import java.util.ArrayList;
026import java.util.Enumeration;
027import java.util.HashSet;
028import java.util.List;
029
030/**
031 * Companion of {@link JdbcDriverHolder} and allows it to deregister JDBC drivers.
032 * <p>
033 * Some hacks are involved in the loading of the class - see {@link JdbcDriverHolder#stop()},
034 * so this class can refer to classes only from java.* package and must not be referred from other classes.
035 * Placement and naming of this class and methods are very important, since it loaded and invoked via reflection.
036 * </p>
037 */
038public class JdbcLeakPrevention {
039
040  /**
041   * @return list of names of deregistered drivers
042   */
043  public List<String> clearJdbcDriverRegistrations() throws SQLException {
044    List<String> driverNames = new ArrayList<String>();
045    HashSet<Driver> originalDrivers = new HashSet<Driver>();
046    Enumeration<Driver> drivers = DriverManager.getDrivers();
047    while (drivers.hasMoreElements()) {
048      originalDrivers.add(drivers.nextElement());
049    }
050    drivers = DriverManager.getDrivers();
051    while (drivers.hasMoreElements()) {
052      Driver driver = drivers.nextElement();
053      if (driver.getClass().getClassLoader() != this.getClass().getClassLoader()) {
054        continue;
055      }
056      if (originalDrivers.contains(driver)) {
057        driverNames.add(driver.getClass().getCanonicalName());
058      }
059      DriverManager.deregisterDriver(driver);
060    }
061    return driverNames;
062  }
063
064}