com.dominion.salud.nomenclator.configuration.NOMENCLATORJpaConfiguration.java Source code

Java tutorial

Introduction

Here is the source code for com.dominion.salud.nomenclator.configuration.NOMENCLATORJpaConfiguration.java

Source

/*
 * Copyright (C) 2015 Dominion Global
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.dominion.salud.nomenclator.configuration;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.jndi.JndiTemplate;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.dominion.salud.nomenclator.negocio.repositories")
public class NOMENCLATORJpaConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(NOMENCLATORJpaConfiguration.class);

    @Autowired
    private Environment environment;

    @Bean
    @Autowired
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        JpaDialect jpaDialect = new HibernateJpaDialect();
        txManager.setEntityManagerFactory(entityManagerFactory());
        txManager.setJpaDialect(jpaDialect);
        return txManager;
    }

    @Bean
    @Autowired
    public EntityManagerFactory entityManagerFactory() {
        logger.info("INICIANDO EL MODULO");
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setGenerateDdl(Boolean.getBoolean(environment.getRequiredProperty("hibernate.generate_ddl")));
        adapter.setShowSql(Boolean.getBoolean(environment.getRequiredProperty("hibernate.show_sql")));
        adapter.setDatabasePlatform(environment.getRequiredProperty("hibernate.dialect"));

        logger.info("     Iniciando conexion a base de datos");
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dataSource());
        factory.setJpaVendorAdapter(adapter);
        factory.setPackagesToScan("com.dominion.salud.nomenclator.negocio.entities");
        factory.afterPropertiesSet();
        factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
        logger.info("     Conexion a base de datos iniciada correctamente");
        return factory.getObject();
    }

    @Bean
    public DataSource dataSource() {
        if (StringUtils.isNotBlank(environment.getProperty("jdbc.jndi"))) {
            return JNDIDataSource();
        } else {
            return JDBCDataSource();
        }
    }

    public DataSource JNDIDataSource() {
        DataSource dataSource = null;
        JndiTemplate jndi = new JndiTemplate();
        try {
            logger.info("          jdbc.jndi: " + environment.getProperty("jdbc.jndi"));
            dataSource = (DataSource) jndi.lookup(environment.getRequiredProperty("jdbc.jndi"));
        } catch (NamingException e) {
            logger.error("No se ha podido establecer la conexion a base de datos: " + e.toString());
        }
        return dataSource;
    }

    public DataSource JDBCDataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(environment.getRequiredProperty("jdbc.driverClassName"));
            dataSource.setJdbcUrl(environment.getRequiredProperty("jdbc.url"));
            dataSource.setUser(environment.getRequiredProperty("jdbc.username"));
            dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));

            //Opcionales
            dataSource.setInitialPoolSize(StringUtils.isNotBlank(environment.getProperty("jdbc.initialPoolSize"))
                    ? NumberUtils.toInt(environment.getProperty("jdbc.initialPoolSize"), 5)
                    : 5);
            dataSource.setAcquireIncrement(StringUtils.isNotBlank(environment.getProperty("jdbc.acquireIncrement"))
                    ? NumberUtils.toInt(environment.getProperty("jdbc.acquireIncrement"), 5)
                    : 5);
            dataSource.setMinPoolSize(StringUtils.isNotBlank(environment.getProperty("jdbc.minPoolSize"))
                    ? NumberUtils.toInt(environment.getProperty("jdbc.minPoolSize"), 5)
                    : 5);
            dataSource.setMaxPoolSize(StringUtils.isNotBlank(environment.getProperty("jdbc.maxPoolSize"))
                    ? NumberUtils.toInt(environment.getProperty("jdbc.maxPoolSize"), 25)
                    : 25);
            dataSource.setAcquireRetryAttempts(
                    StringUtils.isNotBlank(environment.getProperty("jdbc.acquireRetryAttempts"))
                            ? NumberUtils.toInt(environment.getProperty("jdbc.acquireRetryAttempts"), 10)
                            : 10);
            dataSource
                    .setAcquireRetryDelay(StringUtils.isNotBlank(environment.getProperty("jdbc.acquireRetryDelay"))
                            ? NumberUtils.toInt(environment.getProperty("jdbc.acquireRetryDelay"), 500)
                            : 500);
            dataSource.setCheckoutTimeout(StringUtils.isNotBlank(environment.getProperty("jdbc.checkoutTimeout"))
                    ? NumberUtils.toInt(environment.getProperty("jdbc.checkoutTimeout"), 5000)
                    : 5000);

            logger.info("          jdbc.driverClassName: " + dataSource.getDriverClass());
            logger.info("          jdbc.url: " + dataSource.getJdbcUrl());
            logger.info("          jdbc.username: " + dataSource.getUser());
            logger.info("          [Configuracion opcional]");
            logger.info("          jdbc.initialPoolSize: " + dataSource.getInitialPoolSize());
            logger.info("          jdbc.acquireIncrement: " + dataSource.getAcquireIncrement());
            logger.info("          jdbc.minPoolSize: " + dataSource.getMinPoolSize());
            logger.info("          jdbc.maxPoolSize: " + dataSource.getMaxPoolSize());
            logger.info("          jdbc.acquireRetryAttempts: " + dataSource.getAcquireRetryAttempts());
            logger.info("          jdbc.acquireRetryDelay: " + dataSource.getAcquireRetryDelay());
            logger.info("          jdbc.checkoutTimeout: " + dataSource.getCheckoutTimeout());
        } catch (IllegalStateException | PropertyVetoException e) {
            logger.error("No se ha podido establecer la conexion a base de datos: " + e.toString());
        }
        return dataSource;
    }
}