JPA, spring-boot, configuring entity Manager with old not annotated classes - spring

I have a brand-new Spring-Boot project using the most recent technologies, just one configuration file application.yml, otherwise I configured all via annotations.
I just have a dependency to some old not annotated entity classes, and when I start the project it crashes because of:
Caused by: org.hibernate.boot.MappingException: Association [old.entity1.SomeOldEntity] references an unmapped entity [old.entity1.SomeOldEntity] : origin(old/entity1/SomeOldEntity.xml)
This is the JPA configuration class:
#Configuration
#EnableJpaRepositories(basePackages = "actual.repositories", entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager")
#EnableTransactionManagement
public class JpaConfiguration {
#Autowired
private Environment environment;
#Value("${my.maxPoolSize:10}")
private int maxPoolSize;
/*
* Populate SpringBoot DataSourceProperties object directly from application.yml based on prefix.Thanks to .yml, Hierachical data is mapped out of the box
* with matching-name properties of DataSourceProperties object].
*/
#Bean
#Primary
#ConfigurationProperties(prefix = "datasource.myApp")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
/*
* Configure HikariCP pooled DataSource.
*/
#Bean
public DataSource dataSource() {
DataSourceProperties dataSourceProperties = dataSourceProperties();
HikariDataSource dataSource = (HikariDataSource) DataSourceBuilder.create(dataSourceProperties.getClassLoader())
.driverClassName(dataSourceProperties.getDriverClassName()).url(dataSourceProperties.getUrl()).username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword()).type(HikariDataSource.class).build();
dataSource.setMaximumPoolSize(maxPoolSize);
return dataSource;
}
/*
* Entity Manager Factory setup.
*/
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan(
new String[] { "some.new.model", "old.entity1", "old.entity2" });
factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
factoryBean.setJpaProperties(jpaProperties());
return factoryBean;
}
/*
* Provider specific adapter.
*/
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
return hibernateJpaVendorAdapter;
}
/*
* Here you can specify any provider specific properties.
*/
private Properties jpaProperties() {
Properties properties = new Properties();
// Datasource option
String dialect = environment.getRequiredProperty("my.dialect");
String method = environment.getRequiredProperty("my.method");
String show_sql = environment.getRequiredProperty("my.show_sql");
String format_sql = environment.getRequiredProperty("my.format_sql");
String defaultSchema = environment.getRequiredProperty("my.schema");
// Set options
properties.put("hibernate.dialect", dialect);
properties.put("hibernate.hbm2ddl.auto", method);
properties.put("hibernate.show_sql", show_sql);
properties.put("hibernate.format_sql", format_sql);
if (StringUtils.isNotEmpty(defaultSchema)) {
properties.put("hibernate.default_schema", defaultSchema);
}
return properties;
}
#Bean
#Autowired
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(emf);
return txManager;
}
}
EDIT 22.06
here the xml mapping SomeOldEntity:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="old.entity1">
<class name="SomeOldEntity" table="entity1" lazy="false">
<id name="id" column="ID" type="long" access="field">
<generator class="assigned" />
</id>
<property name="moreId" column="MORE_ID" type="long" access="field" />
<property name="aPrefix" column="A_PREFIX" type="java.lang.String" access="field" />
<property name="aKey" column="A_KEY" type="java.lang.String" access="field" />
<property name="active" column="IS_ACTIVE" type="boolean" access="field" />
<one-to-one name="SomeMoreEntity" access="field" fetch="join" />
<one-to-one name="another1OldEntity" property-ref="someOtherId" access="field" fetch="join" />
<one-to-one name="another2OldEntity" property-ref="someOtherId" access="field" fetch="join" />
<one-to-one name="another3OldEntity" property-ref="someOtherId" access="field" fetch="join" />
<list name="impressumList" access="field" lazy="true" fetch="select">
<key column="FK_SOMEID" not-null="true" />
<list-index column="INDEX_ORDER" />
<one-to-many class="some.other.entity.outside.package.SomeEntity" />
</list>
</class>
</hibernate-mapping>

Ok, I think I found the solution, old not Annotated classes has always a xml mapping the class to database entities, well than if I pass the xml like this:
// Old Not Annotated class must be passed as xml to MappingResource
String Entity1 = " old.Entity1.xml";
factoryBean.setMappingResources(Entity1);
Instead of this:
// Annotated classes can be passed as entities throught setPackagesToScan
String Entity1 = "old.Entity1";
factoryBean.setPackagesToScan(new String[] { Entity1 });
IT WORKS!!!

Related

NullPointerException in Spring Autowiring Repository

I'm getting an NPE when I'm trying to auto wiring a Repository in my managed bean. This is my first project trying to use java configurations instead of xml configurations.
I'm not instantiating my self the repository and all the packages are in the spring context, even I can see in the log the instantiating of the repository.
Please, someone, give me a hand to figure out what's missing in my configuration
Using spring version 5.1.0.RELEASE and
<dependency>
<groupId>com.googlecode.genericdao</groupId>
<artifactId>dao-hibernate</artifactId>
<version>1.2.0</version>
</dependency>
1) WebMvcConfig
#Configuration
#EnableWebMvc
#ComponentScan({
"com.config","com.gedificios",
})
public class WebMvcConfig implements WebMvcConfigurer {
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new
InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
2) PersistenceJPAConfig
#Configuration
#EnableTransactionManagement
#PropertySource({"classpath:database.properties"})
#ComponentScan({"com.config","com.gedificios.core", "com.gedificios.persistence", "com.gedificios.view"})
#EntityScan("com.gedificios.persistence.entities")
#EnableJpaRepositories(basePackages = "com.gedificios.core.repository")
public class PersistenceJPAConfig {
#Autowired
private Environment env;
public PersistenceJPAConfig() {
super();
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setPersistenceXmlLocation("classpath*:WEB-INF/persistence.xml");
entityManagerFactoryBean.setPersistenceUnitName("persistenceUnit");
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setJpaProperties(additionalProperties());
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform(env.getProperty("hibernate.dialect"));
vendorAdapter.setShowSql(Boolean.getBoolean(env.getProperty("hibernate.show_sql")));
vendorAdapter.setGenerateDdl(Boolean.getBoolean(env.getProperty("hibernate.generateDdl")));
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
return entityManagerFactoryBean;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
return hibernateProperties;
}
#Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("hibernate.connection.driver_class"));
dataSource.setUrl(env.getProperty("hibernate.connection.url"));
dataSource.setUsername(env.getProperty("hibernate.connection.username"));
dataSource.setPassword(env.getProperty("hibernate.connection.password"));
return dataSource;
}
#Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
#Primary
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
#Bean
public JPAAnnotationMetadataUtil getMetadataUtil() {
return new JPAAnnotationMetadataUtil();
}
#Bean
public JPASearchProcessor getJPASearchProcessor(JPAAnnotationMetadataUtil jpaAnnotationMetadataUtil) {
return new JPASearchProcessor(jpaAnnotationMetadataUtil);
}
}
3) Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source/>
<class>com.gedificios.persistence.entities.Contrato</class>
<class>com.gedificios.persistence.entities.Edificio</class>
<class>com.gedificios.persistence.entities.ubigeo.Pais</class>
<class>com.gedificios.persistence.entities.ubigeo.Departamento</class>
<class>com.gedificios.persistence.entities.ubigeo.Provincia</class>
<class>com.gedificios.persistence.entities.ubigeo.Distrito</class>
<properties>
<property name="hibernate.dialect" value="${hibernate.dialect}"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence>
4) PaisRepository
#Repository
public class PaisRepository extends BaseDAO<PaisDTO, String> {
#Autowired
DataSource dataSource;
private static final Logger LOG = LoggerFactory.getLogger(PaisRepository.class);
#PostConstruct
public void init() {
LOG.info("\n/***************** INICIALIZANDO REPOSITORY DE PAÍS /*****************\n");
}
public List<PaisDTO> getAllPaises() {
List< PaisDTO> items = null;
StringBuffer sql = new StringBuffer();
sql.append(" SELECT ");
sql.append(" P.id_pais \"idPais\" , ");
sql.append(" P.nombre_pais \"nombrePais\" ");
sql.append(" FROM ubigeo_pais as P order by p.nombre_pais");
System.out.println(sql);
org.hibernate.Query<PaisDTO> query = em().unwrap(Session.class).createSQLQuery(sql.toString()).setResultTransformer(new JpaHbmBeanResultTransformer(PaisDTO.class));
items = query.list();
return items;
}
}
4.1) Log evidence
06:24:50.197 [localhost-startStop-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'getJPASearchProcessor'
06:24:50.198 [localhost-startStop-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'getMetadataUtil'
06:24:50.198 [localhost-startStop-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'getJPASearchProcessor' via factory method to bean named 'getMetadataUtil'
06:24:50.199 [localhost-startStop-1] INFO com.gedificios.core.repository.PaisRepository -
/***************** INICIALIZANDO REPOSITORY DE PAÍS /*****************
06:24:50.201 [localhost-startStop-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'DTOMapperServiceDozerImpl'
06:24:50.201 [localhost-startStop-1] DEBUG org.dozer.DozerInitializer - Tried to perform initialization when Dozer was already started.
06:24:50.201 [localhost-startStop-1] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean mapper.
5) ManagedBean
#ManagedBean
#Scope("view")
#Component
public class AdminEdificios extends FindCrudBeanBase {
#Autowired
ApplicationContext applicationContext;
#Autowired
PaisRepository paisRepository;
private static final Logger LOG = LoggerFactory.getLogger(AdminEdificios.class);
private List<PaisDTO> listaPaises;
private List<DepartamentoDTO> listaDepartamentos;
private List<ProvinciaDTO> listaDistritos;
private List<DistritoDTO> listaProvincias;
private String codigoPaisSeleccionado;
private String codigoDepartamentoSeleccionado;
private String codigoProvinciaSeleccionada;
private String codigoDistritoSeleccionado;
#PostConstruct
public void init() {
listaPaises = paisRepository.findAll();
listaDepartamentos = new ArrayList<DepartamentoDTO>();
listaDepartamentos.add(new DepartamentoDTO("001","001","Lima"));
}
...
getters & setters
}
The NPE is exactly here
listaPaises = paisRepository.findAll();

Bean Required for Spring MVC xml file for Amazon S3

What should be the beans in xml file for this same java based configuration?
#Configuration
#ComponentScan(basePackageClasses = Application.class, excludeFilters = #Filter({Controller.class, Configuration.class}))
public class ApplicationConfig {
#Value("${aws_access_key_id}")
private String awsId;
#Value("${aws_secret_access_key}")
private String awsKey;
#Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocations(new Resource[] {
new ClassPathResource("/amazon.properties")
});
return ppc;
}
#Bean
public AWSCredentials credential() {
return new BasicAWSCredentials(awsId, awsKey);
}
#Bean
public AmazonS3 s3client() {
return new AmazonS3Client(credential());
}
}
<context:property-placeholder
ignore-resource-not-found="true" ignore-unresolvable="true"
system-properties-mode="OVERRIDE" order="0"
location="classpath:amazon.properties"/>
<bean id="credential" class="com.amazonaws.auth.BasicAWSCredentials">
<constructor-arg name="accessKey" value="${aws_access_key_id}"/>
<constructor-arg name="secretKey" value="${aws_secret_access_key}"/>
</bean>
<bean id="s3client" class="com.amazonaws.services.s3.AmazonS3Client">
<constructor-arg ref="credential"/>
</bean>

ApplicationObjectSupport instance [org.springframework.web.servlet.view.InternalResourceViewResolver#6d5f2797] does not run in an ApplicationContext

I want to implement a different view resolution strategy,so i do this
public class MultiViewResolver implements ViewResolver {
private Map<String,ViewResolver> resolverMap = new HashMap<>();
public void setResolverMap(Map<String, ViewResolver> resolverMap) {
this.resolverMap = resolverMap;
}
#Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
try {
String[] viewNameAndSuffix = viewName.split("\\.");
ViewResolver resolver = resolverMap.get(viewNameAndSuffix[1]);
return resolver.resolveViewName(viewNameAndSuffix[0], locale);
}catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
}
#Configuration
#EnableWebMvc
#ComponentScan(basePackageClasses = ControllerMarkInterface.class)
public class ServletConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver(){
MultiViewResolver multiViewResolver = new MultiViewResolver();
InternalResourceViewResolver jspViewResolver = new InternalResourceViewResolver();
jspViewResolver.setPrefix("/WEB-INF/JSP/");
jspViewResolver.setSuffix(".jsp");
jspViewResolver.setExposeContextBeansAsAttributes(true);
InternalResourceViewResolver htmlViewResolver = new InternalResourceViewResolver();
htmlViewResolver.setPrefix("/WEB-INF/HTML/");
htmlViewResolver.setSuffix(".html");
Map<String,ViewResolver> resolverMap = new HashMap<>();
resolverMap.put("jsp", jspViewResolver);
resolverMap.put("html", htmlViewResolver);
multiViewResolver.setResolverMap(resolverMap);
return multiViewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}
#Controller
#RequestMapping("/home")
public class HomeController {
#RequestMapping(value = "/profile", method = RequestMethod.GET)
public String toProfile(){
return "profile.jsp";
}
}
when i do like this,console output "ApplicationObjectSupport instance [org.springframework.web.servlet.view.InternalResourceViewResolver#39d8e214] does not run in an ApplicationContext"
then,i use .xml to config viewResolver,it's work well,why?why?
if i want to use java to config viewResolver,how should i do?
<bean id="viewResolver" class="com.demo.config.MultiViewResolver">
<property name="resolverMap">
<map>
<entry key="jsp">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="contentType" value="text/html" />
<property name="prefix" value="/WEB-INF/JSP/" />
<property name="suffix" value=".jsp" />
</bean>
</entry>
<entry key="html">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="contentType" value="text/html" />
<property name="prefix" value="/WEB-INF/HTML/" />
<property name="suffix" value=".html" />
</bean>
</entry>
</map>
</property>
Looks like the problem is because of InternalResourceViewResolver jspViewResolver = new InternalResourceViewResolver(); and InternalResourceViewResolver htmlViewResolver = new InternalResourceViewResolver();
As InternalResourceViewResolver is managed by spring, you can autowire it directly in ServletConfig class as shown below. Spring will inject the instances.
#Configuration
#EnableWebMvc
#ComponentScan(basePackageClasses = ControllerMarkInterface.class)
public class ServletConfig extends WebMvcConfigurerAdapter{
#Autowired
private InternalResourceViewResolver jspViewResolver;
#Autowired
private InternalResourceViewResolver htmlViewResolver;
#Bean
public ViewResolver viewResolver(){
MultiViewResolver multiViewResolver = new MultiViewResolver();
jspViewResolver.setPrefix("/WEB-INF/JSP/");
jspViewResolver.setSuffix(".jsp");
jspViewResolver.setExposeContextBeansAsAttributes(true);
htmlViewResolver.setPrefix("/WEB-INF/HTML/");
htmlViewResolver.setSuffix(".html");
Map<String,ViewResolver> resolverMap = new HashMap<>();
resolverMap.put("jsp", jspViewResolver);
resolverMap.put("html", htmlViewResolver);
multiViewResolver.setResolverMap(resolverMap);
return multiViewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}
Hope this helps!

Mapping hibernate table entities through java configuration

How do we map hibernate table resources when we are configuring through java instead of xml config files - appreciate help.
xml-mapping for hibernate resource:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>/config/Stock.hbm.xml</value>
</list>
</property>
</bean>
Java-mapping?
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:persistence-sql.properties" })
#ComponentScan({......."})
public class PersistenceConfig {
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] {...... });
sessionFactory.setHibernateProperties(hibernateProperties());
(HOW DO WE INTRODUCE mappingResources HERE?)
return sessionFactory;
}
The #Entity on the model object solved the problem.
The xml configuration option had not needed this annotation.
you can edit your configuration at runtime like this:
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
or for class like this:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
reference here
Here is the minimal working Hibernate+JPA setup you are interested in:
#Configuration
#EnableTransactionManagement
public class DaoConfiguration {
#Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.setProperty(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
properties.setProperty(Environment.DRIVER, "org.hsqldb.jdbcDriver");
properties.setProperty(Environment.URL, "jdbc:hsqldb:mem:testdb");
properties.setProperty(Environment.USER, "sa");
properties.setProperty(Environment.PASS, "");
properties.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "org.springframework.orm.hibernate4.SpringSessionContext");
properties.setProperty(Environment.STATEMENT_BATCH_SIZE, "30");
properties.setProperty(Environment.SHOW_SQL, "true");
properties.setProperty(Environment.HBM2DDL_AUTO, "update");
return properties;
}
#Bean
public HibernateEntityManagerFactory entityManagerFactory() {
Ejb3Configuration config = new Ejb3Configuration();
return (HibernateEntityManagerFactory) config.addProperties(hibernateProperties()).
addAnnotatedClass(User.class).
buildEntityManagerFactory();
}
#Bean
public SessionFactory sessionFactory() {
return entityManagerFactory().getSessionFactory();
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
#Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
}

Spring Social + Spring Security HTTPS/HTTP

How can I make the remember me cookie and session accessible through http when requesting a facebook login from either http or https with spring social. Currently if a user logs in through https the cookie is not readable through http pages (no user logged in). I am using use-secure-cookie="false" but that doesn't help.
<s:remember-me key="mykey" services-ref="rememberMeServices" use-secure-cookie="false"/>
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<property name="userDetailsService" ref="userService" />
<property name="tokenRepository" ref="persistentTokenRepository" />
<property name="key" value="mykey" />
<property name="cookieName" value="rmb" />
<property name="useSecureCookie" value="false" />
<property name="tokenValiditySeconds" value="946708560" />
<property name="alwaysRemember" value="true"></property>
</bean>
My Social Config:
#Configuration
public class SocialConfig {
#Inject
private Environment environment;
#Inject
private DataSource dataSource;
#Inject
private TextEncryptor textEncryptor;
#Value("${app.url}")
private String applicationUrl;
#Value("${facebook.clientId}")
private String facebookClientId;
#Value("${facebook.clientSecret}")
private String facebookClientSecret;
#Bean
public ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new FacebookConnectionFactory(
facebookClientId,
facebookClientSecret));
return registry;
}
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return usersConnectionRepository().createConnectionRepository(authentication.getName());
}
#Bean
public UsersConnectionRepository usersConnectionRepository() {
JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(
dataSource, connectionFactoryLocator(), textEncryptor);
repository.setConnectionSignUp(connectionSignUp());
return repository;
}
#Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
#Bean
public ConnectController connectController() {
ConnectController controller = new ConnectController(
connectionFactoryLocator(), connectionRepository());
controller.setApplicationUrl(applicationUrl);
return controller;
}
#Bean
public ProviderSignInController providerSignInController(RequestCache requestCache) {
ProviderSignInController controller = new ProviderSignInController(connectionFactoryLocator(),
usersConnectionRepository(), signInAdapter());
controller.setSignUpUrl("/register");
controller.setSignInUrl("/socialSignIn");
controller.setPostSignInUrl("socialSignIn");
controller.addSignInInterceptor(new RedirectAfterConnectInterceptor());
return controller;
}
#Bean
public SignInAdapter signInAdapter() {
return new SignInAdapterImpl();
}
#Bean
public ConnectionSignUp connectionSignUp() {
return new ConnectionSignUpImpl();
}
}

Resources