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 */
020 package org.sonar.jpa.session;
021
022 import org.slf4j.Logger;
023 import org.slf4j.LoggerFactory;
024 import org.sonar.core.persistence.Database;
025 import org.sonar.core.persistence.DatabaseVersion;
026 import org.sonar.core.persistence.dialect.Dialect;
027
028 import javax.persistence.EntityManager;
029 import javax.persistence.EntityManagerFactory;
030 import javax.persistence.Persistence;
031 import java.util.Map;
032 import java.util.Properties;
033
034 public abstract class AbstractDatabaseConnector implements DatabaseConnector {
035 protected static final Logger LOG = LoggerFactory.getLogger(AbstractDatabaseConnector.class);
036
037 protected Database database;
038 private EntityManagerFactory factory = null;
039
040 protected AbstractDatabaseConnector(Database database) {
041 this.database = database;
042 }
043
044 public void start() {
045 LOG.info("Initializing Hibernate");
046 factory = createEntityManagerFactory();
047
048 }
049
050 public void stop() {
051 if (factory != null && factory.isOpen()) {
052 factory.close();
053 factory = null;
054 }
055 database = null;
056 }
057
058 public EntityManagerFactory getEntityManagerFactory() {
059 return factory;
060 }
061
062 protected EntityManagerFactory createEntityManagerFactory() {
063 // other settings are stored into /META-INF/persistence.xml
064 Properties props = database.getHibernateProperties();
065 logHibernateSettings(props);
066 return Persistence.createEntityManagerFactory("sonar", props);
067 }
068
069 private void logHibernateSettings(Properties props) {
070 if (LOG.isDebugEnabled()) {
071 for (Map.Entry<Object, Object> entry : props.entrySet()) {
072 LOG.debug(entry.getKey() + ": " + entry.getValue());
073 }
074 }
075 }
076
077 public EntityManager createEntityManager() {
078 return factory.createEntityManager();
079 }
080
081 public final int getDatabaseVersion() {
082 throw new UnsupportedOperationException("Moved to " + DatabaseVersion.class.getCanonicalName());
083 }
084
085 public final Dialect getDialect() {
086 return database.getDialect();
087 }
088 }