io.springagora.store.ApplicationConfig.java Source code

Java tutorial

Introduction

Here is the source code for io.springagora.store.ApplicationConfig.java

Source

/*
 * Spring Agora 
 * https://github.com/ThiagoUriel/spring-agora-web
 * Copyright (C) 2014 - Thiago Uriel M. Garcia
 *
 * 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 2 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, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package io.springagora.store;

import java.sql.SQLException;
import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableSpringConfigured
@PropertySource("classpath:application.properties")
@EnableJpaRepositories("io.springagora.core.domain.repository")
@EnableTransactionManagement(proxyTargetClass = true, mode = AdviceMode.ASPECTJ)
public class ApplicationConfig {
    /** Configuration property: Database host. */
    @Value("${db.connectionUrl}")
    String connectionUrl;

    /** Configuration property: Database username. */
    @Value("${db.username}")
    String username;

    /** Configuration property: Database password. */
    @Value("${db.password}")
    String password;

    /** Configuration property: Generate (create/update) the DDL? */
    @Value("${db.generateDDL}")
    Boolean generateDDL;

    /** Configuration property: Show SQL queries? */
    @Value("${db.showSQL}")
    Boolean showSQL;

    /** Generate statistics for query execution? */
    @Value("${db.showStatistics}")
    Boolean showStatistics;

    /**
     * Bean definition.
     * 
     * Datasource used to retrieve connections for the persistence layer. It's
     * configured following definitions written in {@code application.properties}.
     * 
     * @return
     *      The {@code Datasource} object, that will act as the connection pool,
     *      providing connections to the application. 
     * 
     * @throws SQLException
     *      If any error occurs during the connection attempt, it will be thrown
     *      as a {@code SQLException}.
     */
    @Bean
    public DataSource dataSource() throws SQLException {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl(connectionUrl);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setInitialSize(5);
        ds.setMaxActive(20);
        ds.setDefaultAutoCommit(false);
        return ds;
    }

    @Bean
    @Autowired
    public EntityManagerFactory entityManagerFactory(DataSource dataSource) {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(generateDDL.booleanValue());
        vendorAdapter.setShowSql(showSQL.booleanValue());
        vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
        vendorAdapter.setDatabase(Database.MYSQL);

        Properties properties = new Properties();
        properties.setProperty("hibernate.cache.use_second_level_cache", "true");
        properties.setProperty("hibernate.cache.region.factory_class",
                "org.hibernate.cache.ehcache.EhCacheRegionFactory");
        properties.setProperty("hibernate.cache.use_query_cache", "true");
        properties.setProperty("hibernate.generate_statistics", showStatistics.toString());

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("io.springagora.core.domain");
        factory.setDataSource(dataSource);
        factory.setJpaProperties(properties);
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    @Autowired
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaDialect jpaDialect = new HibernateJpaDialect();

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        txManager.setJpaDialect(jpaDialect);

        return txManager;
    }

    /**
     * Implementation of {@code PersistenceExceptionTranslator} used to convert
     * Hibernate Exceptions ({@code HibernateException}) into Spring Data Access' 
     * own exception hierarchy, based on {@code DataAccessException}.
     * 
     * @return
     *      The {@code HibernateExceptionTranslator} used for translation.
     */
    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator() {
        return new HibernateExceptionTranslator();
    }

    /**
     * Bean responsible for placeholder proper configuration, using the properties
     * file defined in as the Property Source (via {@code PropertySource} annotation.
     * 
     * @return
     *      The {@code PropertySourcesPlaceholderConfigurer} required to correctly
     *      change variables for properties defined in the configuration file. 
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}