PersistenceJPAConfig.java

/*
 * +====================================================================+
 * |         Copyright (C) 2015 Rochester Institute of Technology,      |
 * |            103 Lomb Memorial Drive, Rochester, NY - 14623          |
 * |                        All Rights Reserved.                        |
 * +====================================================================+
 *   FILENAME
 *    PersistenceJPAConfig.java
 *
 *   AUTHOR
 *    @author Khanh Ho (kchisd at rit.edu)
 *
 * =====================================================================
 */

package edu.rit.coopeval.config;

import javax.sql.DataSource;

import edu.rit.coopeval.security.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Configuration
@EnableTransactionManagement
@EnableJpaAuditing
public class PersistenceJPAConfig {

    @Autowired
    private CoopEvalDatasourceSettings dsProps;

    @Bean
    public DataSource dataSource() {
        if (dsProps.getJndiName() != null) {
            JndiDataSourceLookup lookup = new JndiDataSourceLookup();
            lookup.setResourceRef(true);
            return lookup.getDataSource(dsProps.getJndiName());
        } else {
            DriverManagerDataSource ds = new DriverManagerDataSource();
            ds.setDriverClassName(dsProps.getDriverClassName());
            ds.setUrl(dsProps.getUrl());
            ds.setUsername(dsProps.getUsername());
            ds.setPassword(dsProps.getPassword());
            return ds;
        }
    }

    /**
     * Provides auditing information to JPA repositories.
     *
     * @return a provider that knows the current user
     */
    @Bean
    public AuditorAware<String> auditorProvider() {
        return () -> {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return null;
            }
            if (authentication.getClass() == AnonymousAuthenticationToken.class) {
                return "anonymous";
            }
            return ((SecurityUser) authentication.getPrincipal()).getUsername();
        };
    }
}