Mult Tenant per Schema - not calling getConnection() - java

I'm implementing mult-tenancy per schema in my application and I'm having trouble switching the schema.
I'll put the flow step by step:
1 - I make the request to the API, passing X-TENANT-ID in the header
package br.com.braxxy.brxm.server.multtenant.hibernate;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import lombok.extern.slf4j.Slf4j;
#Slf4j
public class TenantInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("TENANT: " + request.getHeader("X-TENANT-ID"));
Optional.ofNullable(request.getHeader("X-TENANT-ID")).map(String::toUpperCase)
.ifPresent(Tenant::setIdentificador);
return true;
}
}
2 - The resolveCurrentTenantIdentifier method of the CurrentTenantIdentifierResolver interface is overridden and returns the data I passed in the X-TENANT-ID.
package br.com.braxxy.brxm.server.multtenant.hibernate;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
public class SchemaCurrentTenantIdentifierResolver implements CurrentTenantIdentifierResolver {
#Override
public String resolveCurrentTenantIdentifier() {
System.out.println("resolveCurrentTenantIdentifier : " + Tenant.getIdentificador());
return Tenant.getIdentificador();
}
#Override
public boolean validateExistingCurrentSessions() {
System.out.println("validateExistingCurrentSessions : " + Tenant.getIdentificador());
return false;
}
}
3 - This is the step I'm having trouble with. In theory, hibernate should call the getConnection method passing the tenant, but this method is not called when I make the request and consequently does not change the schema.
package br.com.braxxy.brxm.server.multtenant.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
public class SchemaMultiTenantConnectionProvider implements
MultiTenantConnectionProvider, ServiceRegistryAwareService {
/**
*
*/
private static final long serialVersionUID = 1L;
private ConnectionProvider connectionProvider = null;
#Override
public Connection getAnyConnection() throws SQLException {
return connectionProvider.getConnection();
}
#Override
public void releaseAnyConnection(Connection connection) throws SQLException {
connectionProvider.closeConnection(connection);
}
#Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
Connection connection = getAnyConnection();
System.out.println("getConnection :" + tenantIdentifier);
try {
connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'");
} catch (SQLException e) {
throw new HibernateException("Could not change to schema " + tenantIdentifier + ".", e);
}
return connection;
}
#Override
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
releaseAnyConnection(connection);
}
#Override
public boolean supportsAggressiveRelease() {
return false;
}
#Override
public boolean isUnwrappableAs(Class unwrapType) {
return false;
}
#Override
public <T> T unwrap(Class<T> unwrapType) {
return null;
}
#Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
Map<String, String> settings = serviceRegistry
.getService(ConfigurationService.class)
.getSettings();
connectionProvider = new DriverManagerConnectionProviderImpl();
((DriverManagerConnectionProviderImpl) connectionProvider)
.injectServices(serviceRegistry);
((DriverManagerConnectionProviderImpl) connectionProvider)
.configure(settings);
}
}
I've tried to do it in several ways, but I always fall into the same problem. Does anyone know how to solve?
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="brxTenant">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.provider" value="org.hibernate.ejb.HibernatePersistence" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="braxxy" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="hibernate.archive.autodetection" value="class, hbm" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.multiTenancy" value="SCHEMA" />
<property name="hibernate.multi_tenant_connection_provider" value="br.com.braxxy.brxm.server.multtenant.hibernate.SchemaMultiTenantConnectionProvider"/>
<property name="hibernate.tenant_identifier_resolver" value="br.com.braxxy.brxm.server.multtenant.hibernate.SchemaCurrentTenantIdentifierResolver"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
</persistence>

After a hard day's work, I managed to solve my problem.
It had nothing to do with the Multitenancy implementation itself.
It was necessary for me to add #Transactional in the controller and it worked.

Related

Java EntityManager throwing NullPointerException

When I try to run the Unit test for this DAO class, I am getting NullPointerException at getById return statement. I know that the class does not initialize the EntityManager, but I don’t understand why? - I can’t tell whether my persistence.xml configuration is wrong or the DB credentials are incorrect.
I saw two or more StackOverflow threads but had had little luck. I am using Intellij IDE.
package com.beetlehand.model.dao;
import com.beetlehand.model.AttributeEntity;
import org.apache.commons.lang.StringUtils;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
#Stateless
public class AttributeDao extends AbstractDao<AttributeEntity> {
#PersistenceContext(unitName = "NewPersistenceUnit")
protected EntityManager entityManager;
public AttributeEntity getById(Long id) {
if(id == null) return null;
return entityManager.find(AttributeEntity.class, id);
}
/*** more code ***/
}
Persistence configuration file
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit">
<class>com.beetlehand.model.AttributeEntity</class>
<class>com.beetlehand.model.AttributeValueEntity</class>
<class>com.beetlehand.model.AuditEntity</class>
<class>com.beetlehand.model.CategoryEntity</class>
<class>com.beetlehand.model.CustomerEntity</class>
<class>com.beetlehand.model.DepartmentEntity</class>
<class>com.beetlehand.model.OrderDetailEntity</class>
<class>com.beetlehand.model.OrdersEntity</class>
<class>com.beetlehand.model.ProductEntity</class>
<class>com.beetlehand.model.ProductAttributeEntity</class>
<class>com.beetlehand.model.ProductCategoryEntity</class>
<class>com.beetlehand.model.ReviewEntity</class>
<class>com.beetlehand.model.ShippingEntity</class>
<class>com.beetlehand.model.ShippingRegionEntity</class>
<class>com.beetlehand.model.ShoppingCartEntity</class>
<class>com.beetlehand.model.TaxEntity</class>
<properties>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.jdbc.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
You need to mock the entityManager then you need to do stub for entityManager.find() as shown below.
#Mock // Mocking enitt
private EntityManager entityManager;
public AttributeEntity entity = new AttributeEntity();
// Stubbing for entityManager.find()
Mockito.when(entityManager.find(Mockito.any(AttributeEntity.class), Mockito.any())).thenReturn(entity);

Jersey API with Spring SessionFactory NullpointerException

Images of All Jars
This is the error image from the console.
I am trying to use the Jersey API along with Spring and Hibernate. However, defining session factory says NullPointerException. Can anybody help me to solve this? Added Full configuration with spring, hibernate and Jersey. Images of error and jar on top.
---------------------Dao Class:
package com.org.restservice.bo.user;
import java.util.List;
import com.org.restservice.common.Dao;
public interface AuthenticationDao extends Dao{
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception;
}
---------------------DaoHibernate Class:
package com.org.restservice.bo.user;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.type.StringType;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.org.restservice.common.BaseDaoHibernate;
import com.org.restservice.common.Constant;
public class AuthenticationDaoHibernate extends BaseDaoHibernate implements AuthenticationDao{
private Log log = LogFactory.getLog(AuthenticationDaoHibernate.class);
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception{
System.out.println("Called Me>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
List<AuthenticationVo> findlist = new ArrayList<AuthenticationVo>();
final String sqlQuery = "SELECT USER_ID, ROLE_ID from STTM_USER_MASTER";
System.out.println("sqlQuery: "+sqlQuery);
List results = (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
SQLQuery sq = session.createSQLQuery(sqlQuery);
sq.addScalar("USER_ID", StringType.INSTANCE);
sq.addScalar("ROLE_ID", StringType.INSTANCE);
return sq.list();
}
});
try {
if (results.size() > 0) {
Iterator itr = results.iterator();
while (itr.hasNext()) {
authenticationVo = new AuthenticationVo();
Object[] row = (Object[]) itr.next();
authenticationVo.setUser_id((String) row[0]);
authenticationVo.setRole_id((String) row[1]);
findlist.add(authenticationVo);
}
}
} catch (Exception e) {
System.out.println("FunctonVos error:" + e.getMessage());
}
System.out.println("Size of User List is: "
+ findlist.size());
System.out.println("Procedure call ended.");
return findlist;
}
}
---------------------Facade Class:
package com.org.restservice.bo.user;
import java.util.List;
import com.org.restservice.common.Facade;
public interface AuthenticationFacade extends Facade{
public void setAuthenticationDao(AuthenticationDao authenticationDao);
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception;
}
---------------------FacadeImpl Class:
package com.org.restservice.bo.user;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.org.restservice.common.BaseFacade;
public class AuthenticationFacadeImpl extends BaseFacade implements AuthenticationFacade{
private static final Log log = LogFactory.getLog(AuthenticationFacadeImpl.class);
private AuthenticationDao authenticationDao;
public void setAuthenticationDao(AuthenticationDao authenticationDao) {
this.authenticationDao = authenticationDao;
}
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception{
return authenticationDao.userInfo(authenticationVo);
}
}
---------------------Business Object Class:
package com.org.restservice.bo.user;
import com.org.restservice.common.BaseObject;
public class AuthenticationVo extends BaseObject{
private static final long serialVersionUID = 1L;
private String user_id;
private String role_id;
public AuthenticationVo(String user_id, String role_id) {
super();
this.user_id = user_id;
this.role_id = role_id;
}
public AuthenticationVo() {
super();
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getRole_id() {
return role_id;
}
public void setRole_id(String role_id) {
this.role_id = role_id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((role_id == null) ? 0 : role_id.hashCode());
result = prime * result + ((user_id == null) ? 0 : user_id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AuthenticationVo other = (AuthenticationVo) obj;
if (role_id == null) {
if (other.role_id != null)
return false;
} else if (!role_id.equals(other.role_id))
return false;
if (user_id == null) {
if (other.user_id != null)
return false;
} else if (!user_id.equals(other.user_id))
return false;
return true;
}
#Override
public String toString() {
return "AuthenticationVo [user_id=" + user_id + ", role_id=" + role_id + "]";
}
}
---------------------Action Class Declaration:
package com.org.restservice.portal.user;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.org.restservice.bo.user.AuthenticationFacade;
import com.org.restservice.bo.user.AuthenticationVo;
#Path("userService")
public class UserAction{
private final Log log = LogFactory.getLog(UserAction.class);
AuthenticationVo authenticationVo = new AuthenticationVo();
private AuthenticationFacade authenticationFacade = null;
private List<AuthenticationVo> listofUsers = new ArrayList<AuthenticationVo>();
public AuthenticationVo getAuthenticationVo() {
return authenticationVo;
}
public void setAuthenticationVo(AuthenticationVo authenticationVo) {
this.authenticationVo = authenticationVo;
}
public AuthenticationFacade getAuthenticationFacade() {
return authenticationFacade;
}
public void setAuthenticationFacade(AuthenticationFacade authenticationFacade) {
this.authenticationFacade = authenticationFacade;
}
public List<AuthenticationVo> getListofUsers() {
return listofUsers;
}
public void setListofUsers(List<AuthenticationVo> listofUsers) {
this.listofUsers = listofUsers;
}
#GET
#Produces( "application/json" )
public List<AuthenticationVo> customAction(){
if (log.isDebugEnabled()) {
log.debug("Entering into loadusers Method of AuthenticationAction: " +authenticationFacade);
}
try {
listofUsers = authenticationFacade.userInfo(authenticationVo);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>>>>>>>>>>>>>>" +listofUsers.size());
/*authenticationVo.setUser_id("1234");
authenticationVo.setRole_id("134352");
listofUsers.add(authenticationVo);*/
return listofUsers;
}
}
---------------------Spring Beans Declaration:
<!-- <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Database connection using jndi properties-->
<import resource="config/applicationContext-jndi.xml"/>
<import resource="config/applicationContext.xml"/>
<!-- List and Setup -->
<import resource="config/applicationContext-auth.xml"/>
</beans>
---------------------Application Context Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</prop>
</props>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- Transaction template for Facade -->
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<!-- DAO bean -->
<!-- Generic DAO - can be used when doing standard CRUD -->
<bean id="dao" class="com.org.restservice.common.BaseDaoHibernate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Generic Facade that can be used to do basic CRUD operations on any
objects -->
<bean id="facade" parent="txProxyTemplate">
<property name="target">
<bean class="com.org.restservice.common.BaseFacade">
<property name="Dao" ref="dao" />
</bean>
</property>
</bean>
</beans>
--------------------- Context Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- Transaction declarations for business services. -->
<bean id="authenticationFacade" parent="txProxyTemplate">
<property name="target">
<bean
class="com.org.restservice.bo.user.AuthenticationFacadeImpl">
<property name="authenticationDao">
<ref bean="authenticationDao" />
</property>
</bean>
</property>
</bean>
<!-- authenticationDao: Hibernate implementation -->
<bean id="authenticationDao"
class="com.org.restservice.bo.user.AuthenticationDaoHibernate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
</beans>
---------------------Jndi Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<!-- author: Sarkar Zahir Ahamed <ahamed.sarkar#dbbl.com.bd> -->
<beans>
<!-- ========================= PERSISTENCE DEFINITIONS ========================= -->
<!-- JNDI DataSource for J2EE environments -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:/comp/env/jndi/orcl</value>
</property>
</bean>
</beans>
---------------------Web XML Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>RestWebService</display-name>
<!-- Spring Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Jersey Servlet -->
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.org.restservice</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- loading Spring Context for registering beans with ApplicationContext -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/classes/SpringBeans.xml</param-value>
</context-param>
<!-- welcome file -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

spring3 - application context - bean property name and reference - null pointer exception

All - In the Spring 3.0, in the applicationContext.xml .... are we supposed to have the bean property name and the reference value to be the same ? If I give a different value, it returns null object. But on giving the same value, it works. For my project, i am supposed to give different values for them. Kindly help. bye, HS
This works: (same values)
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="cacheDelegate" />
</property>
</bean>
This doesn't work: (different values)
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="MNCCacheDelegate" />
</property>
</bean>
bye, HS
My Full Code here:
WIRAdminBaseAction.java ---> my base action
AuthenticateAction.java ---> my java file that calls the bean here
applicationContext.xml --> system's applicationcontext file
applicationContext_MNC.xml ---> my applicationContext for a specific company ... this is getting loaded by my java file, which gets invoked by the web.xml file.
CacheDelegate.java
StatusDBDAO.java
PreXMLWebApplicationContext.java ----> loads my applicationContext file for the specific company.
****** applicationContext.xml ******
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<bean name="exceptionHandler" class="com.megasoft.wir.eStatement.web.interceptor.WIRExceptionHandlerInterceptor"/>
<bean name="security" class="com.megasoft.wir.eStatement.web.interceptor.SecurityInterceptor"/>
<bean name="permission" class="com.megasoft.wir.eStatement.web.interceptor.PermissionInterceptor"/>
<!-- AutoProxies -->
<bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>base</value>
<value>exceptionHandler</value>
<value>security</value>
<value>permission</value>
</list>
</property>
</bean>
</beans>
****** applicationContext_MNC.xml ******
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="MNCCacheDelegate" />
</property>
</bean>
<bean id="MNCCacheDelegate" class="com.megasoft.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="MNCStatusDBDAO" /></property>
</bean>
<bean id="MNCStatusDBDAO" class="com.megasoft.wiradmin.dao.StatusDBDAO">
<property name="dataSource">
<ref bean="MNCAdminDataSource" />
</property>
</bean>
<!-- database configuration from property file -->
<bean id="MNCAdminDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" lazy-init="default" autowire="default" dependency-check="default">
<property name="driverClass" value="${jdbc.driver}" ></property>
<property name="jdbcUrl" value="${admin.jdbc.url}" ></property>
<property name="user" value="${admin.jdbc.user}" ></property>
<property name="password" value="${admin.jdbc.password}" ></property>
<property name="initialPoolSize" value="3" ></property>
<property name="minPoolSize" value="3" ></property>
<property name="maxPoolSize" value="25" ></property>
<property name="acquireIncrement" value="1" ></property>
<property name="acquireRetryDelay" value="1000" ></property>
<property name="debugUnreturnedConnectionStackTraces" value="true" ></property>
<property name="maxIdleTime" value="300" ></property>
<property name="unreturnedConnectionTimeout" value="300000" ></property>
<property name="preferredTestQuery" value="SELECT COUNT(*) FROM LOCALE_CODE" ></property>
<property name="checkoutTimeout" value="300000" ></property>
<property name="idleConnectionTestPeriod" value="600000" ></property>
</bean>
<!-- this bean is set to map the constants which needs to be configured as per
the environment to the java constants file -->
<bean id="envConstantsConfigbean" class="com.megasoft.wiradmin.util.constants.Environm entConstantsSetter">
<property name="loginUrl" value="${login.url}"/>
<property name="logoutIR" value="${logout.from.image.retrieval}"/>
<property name="adminModuleUrl" value="${admin.url}"/>
<property name="adminUrlSym" value="${admin.url.sym}"/>
<property name="envProperty" value="${env.property}"/>
</bean>
</beans>
****** AuthenticateAction.java ******
package com.megasoft.wiradmin.web.action;
import java.net.UnknownHostException;
import java.sql.SQLException;
import org.bouncycastle.crypto.CryptoException;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.web.context.support.WebApplica tionContextUtils;
import com.megasoft.wiradmin.delegate.ICacheDelegate;
public class AuthenticateAction extends WIRAdminBaseAction {
private static final long serialVersionUID = 1L;
public String authenticate() throws UnknownHostException, CryptoException,
DataAccessException, SQLException{
/** This way of calling works...... This is not encouraged, as we should not use applicationContext always **/
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContex t(getServletRequest().getSession().getServletConte xt());
ICacheDelegate cacheAction = (ICacheDelegate) applicationContext.getBean("MNCCacheDelegate");
/** The below way of calling does NOT work .... returns null value.... Please help...
* I assume that, since I have extended the WIRAdminBaseAction, i should be able to call the getCacheDelegate directly
* and it should return my cacheDelegate object ...
* Again, Please note.....if I change my applicationContext_MNC.xml as below, the below way of calling works fine...
* but, i don't want to change my applicationContext_MNC.xml as below, due to some necessity.
*
<bean id="MNCWIRAdminBaseAction" class="com.megasoft.wiradmin.web.action.WIRAdminBaseAction">
<property name="cacheDelegate">
<ref bean="cacheDelegate" />
</property>
</bean>
*
<bean id="cacheDelegate" class="com.megasoft.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="MNCStatusDBDAO" /></property>
</bean>
*
... is it that the name and bean should have the same value.... ??? No Need to be.....Am i right ? Please advise.
*
* **/
getCacheDelegate().getActorAction(1); // this way of calling doesn't work and returns null value. please help.
return "success";
}
}
****** WIRAdminBaseAction.java ******
package com.megasoft.wiradmin.web.action;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.config.entities.Parameteri zable;
import com.megasoft.wiradmin.delegate.ICacheDelegate;
public class WIRAdminBaseAction extends ActionSupport implements Preparable, ParameterAware, Parameterizable, SessionAware,RequestAware {
private HttpServletRequest request;
private static final long serialVersionUID = 1L;
private HttpServletResponse response;
private ICacheDelegate cacheDelegate;
private Map session;
private Map<String, String> params;
private Map parameters;
public void prepare() throws Exception {
}
public String execute() throws Exception {
return SUCCESS;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getServletRequest() {
return this.request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public HttpServletResponse getServletResponse() {
return this.response;
}
public ICacheDelegate getCacheDelegate() {
return cacheDelegate;
}
public void setCacheDelegate(ICacheDelegate cacheDelegate) {
this.cacheDelegate = cacheDelegate;
}
public void addParam(final String key, final String value) {
this.params.put(key, value);
}
public Map getParams() {
return params;
}
public void setParams(final Map<String, String> params) {
this.params = params;
}
public Map getSession() {
return this.session;
}
public void setSession(final Map session) {
this.session = session;
}
public void setParameters(final Map param) {
this.parameters = param;
}
}
PreXMLWebApplicationContext.java **
package com.megasoft.wiradmin.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.XmlWebApplicationContext;
public class PreXMLWebApplicationContext extends XmlWebApplicationContext {
/**
* This initializes the Logger.
*/
private static Log logger = LogFactory.getLog(PreXMLWebApplicationContext.class);
protected String[] getDefaultConfigLocations() {
String environment = System.getProperty("envProperty");
String webirConfig = System.getProperty("webirConfig");
String fi = System.getProperty("FI");
String preHostConfiguration =null;
logger.info("The environment is "+environment);
logger.info("The webirConfig is "+webirConfig);
logger.info("The fi is "+fi);
if(environment != null && webirConfig != null && fi != null) {
preHostConfiguration = DEFAULT_CONFIG_LOCATION_PREFIX +
"classes/applicationContext" + "_" + fi.toUpperCase() +
DEFAULT_CONFIG_LOCATION_SUFFIX;
}
return new String[]{DEFAULT_CONFIG_LOCATION, preHostConfiguration};
}
/**
* This is close API.
*
* #see org.springframework.context.support.AbstractApplicationContext
* #close()
*/
public void close() {
this.doClose();
logger.info("Login-->into the closed");
}
}
<property name="userDelegate" ref="userDelegate" />
name is the field name in your class. When name is userDelegate, it means that WIRAdminBaseAction has a field named userDelegate (and probably a setter setUserDelegate())
ref is the bean name you want to set this field to. In your example, you should have another bean, named userDelegate or bmoUserDelegate which should be set as userDelegate in WIRAdminBaseAction.
So if you want to use the second configuration:
You just need to create a bean with id bmoUserDelegate:
<bean id="bmoUserDelegate" class="mypackage.BmoUserDelegateClass"/>

JPA/HSQLDB Persistence class not found error

I'm pretty new to JPA and HSQLDB, and I'm havin a weird error when I'm trying to create my EntityManagerFactory. Its a Web Dynamic project in Eclipse (with Tomcat 6.0 as web server) and I imported all the libraries in the the WEB-INF/lib. I'm trying to create the Entity manager Factory in a servlet but in just gives me a class not found exception on the line
emf = Persistence.createEntityManagerFactory("manager1");
Here is the code I used in my servlet:
package view;
import java.io.IOException;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.ThemeLivre;
public class AjouterTheme extends HttpServlet {
//private static final long serialVersionUID = 1L;
#PersistenceUnit(unitName ="DB")
private EntityManagerFactory emf;
public AjouterTheme() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
emf = Persistence.createEntityManagerFactory("DB");
EntityManager em = emf.createEntityManager();
String nomTheme = request.getParameter("nomtheme");
String descTheme = request.getParameter("desctheme");
EntityTransaction tx = em.getTransaction();
tx.begin();
ThemeLivre thml = new ThemeLivre(nomTheme, descTheme);
em.persist(thml);
tx.commit();
}
}
Here is my persistence.xml
<persistence version="1.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_1_0.xsd">
<persistence-unit name="DB" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<class>model.ThemeLivre</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost/"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
Please tell me what I did wrong, or if there is something I can do.
Thank you
In your servlet code you used
#PersistenceUnit(unitName ="DB")
private EntityManagerFactory emf;
but you declare
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
change either the one or the other persistence unit name.
Following your input above
Try to add the hibernate persistence provider lib. You add only the specification (API). The implementation itself (hibernate) is needed, to create an Entity Manager.

"org.apache.openjpa.persistence.PersistenceException: null" error

I've been trying to make a simple class in Java run with JPA to no avail. Help?
The title is the error I'm getting.
I've been trying to make a simple class in Java run with JPA to no avail. Help?
The title is the error I'm getting.
My persistence.xml:
<persistence 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_1_0.xsd"
version="1.0">
<persistence-unit name="geronimo" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>label.entities.Discography</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:sqlite:C:\\sqlitedb\\repo.db" />
<property name="openjpa.ConnectionDriverName" value="org.sqlite.JDBC" />
<property name="openjpa.ConnectionUserName" value="" />
<property name="openjpa.ConnectionPassword" value="" />
<property name="openjpa.Log" value="SQL=TRACE" />
</properties>
</persistence-unit>
My JPA class:
package label.implementations;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import label.entities.Discography;
public class Disconfigurator {
public static void main(String[] args) {
String persistenceUnit = "geronimo";
EntityManagerFactory eFactory = Persistence.createEntityManagerFactory(persistenceUnit);
EntityManager eManager = eFactory.createEntityManager();
EntityTransaction eTransaction = eManager.getTransaction();
eTransaction.begin();
Discography discography = new Discography();
discography.setArtist("Kings Of Leon");
discography.setSong("Radioactive");
eManager.persist(discography);
eTransaction.commit();
eManager.close();
eFactory.close();
}
}
My Entity class:
package label.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
#Entity(name="discography")
public class Discography {
#Column(name="artist",length=1000,nullable=true)
String artist;
#Column(name="song",length=1000,nullable=true)
String song;
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
}
The error trace:
31 geronimo INFO [main] openjpa.Runtime - Starting OpenJPA 1.2.1
Exception in thread "main" <openjpa-1.2.1-r752877:753278 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: null
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:196)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:142)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:192)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:145)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:56)
at label.implementations.Disconfigurator.main(Disconfigurator.java:16)
Caused by: java.lang.NullPointerException
at org.sqlite.JDBC.connect(JDBC.java:63)
at org.apache.openjpa.jdbc.schema.SimpleDriverDataSource.getConnection(SimpleDriverDataSource.java:81)
at org.apache.openjpa.jdbc.schema.SimpleDriverDataSource.getConnection(SimpleDriverDataSource.java:60)
at org.apache.openjpa.lib.jdbc.DelegatingDataSource.getConnection(DelegatingDataSource.java:106)
at org.apache.openjpa.lib.jdbc.DecoratingDataSource.getConnection(DecoratingDataSource.java:87)
at org.apache.openjpa.jdbc.sql.DBDictionaryFactory.newDBDictionary(DBDictionaryFactory.java:91)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:562)
at org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1265)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:505)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:430)
at org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:103)
at org.apache.openjpa.conf.MetaDataRepositoryValue.instantiate(MetaDataRepositoryValue.java:68)
at org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:83)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:863)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:854)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:638)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:183)
... 5 more
You're trying to persist the Transaction and not your entity object.
This is what your code SHOULD look like --
EntityManagerFactory eFactory = Persistence.createEntityManagerFactory("geronimo");
EntityManager eManager = eFactory.createEntityManager();
EntityTransaction eTransaction = eManager.getTransaction();
//eManager.persist(eTransaction); <--- DO NOT DO THIS
eTransaction.begin();
Discography discography = new Discography();
discography.setArtist("Kings Of Leon");
discography.setSong("Radioactive");
eManager.persist(discography); // DO THIS INSTEAD. PERSIST THE ENTITY
eTransaction.commit();
eManager.close();
eFactory.close();

Categories