How to access openshift contained hsqldb server port publicly? - spring

We are using HSQL Database Engine 2.3.2 with Spring 4.2.0.RELEASE while my spring configuration is as following:
Here is applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx" 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-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<bean class="com.chorke.spring.bootstarp.HyperSqlDbServer" id="hsqldb" init-method="start">
<constructor-arg>
<props>
<prop key="server.port">55511</prop>
<prop key="server.dbname.0">chorke</prop>
<prop key="server.remote_open">true</prop>
<prop key="server.database.0">file:~/.hsqldb/chorke/data;sql.syntax_mys=true;user=admin;password=pa55word</prop>
<prop key="hsqldb.default_table_type">text</prop>
<prop key="hsqldb.reconfig_logging">false</prop>
</props>
</constructor-arg>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
<property name="url" value="jdbc:hsqldb:hsql://localhost:55511/chorke" />
<property name="username" value="admin" />
<property name="password" value="pa55word" />
</bean>
</beans>
Here is com.chorke.spring.bootstarp.HyperSqlDbServer
package com.chorke.spring.bootstarp;
import java.io.IOException;
import java.util.Properties;
import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl.AclFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
public class HyperSqlDbServer implements SmartLifecycle {
private final Logger logger = LoggerFactory.getLogger(HyperSqlDbServer.class);
private HsqlProperties properties;
private Server server;
private boolean running = false;
public HyperSqlDbServer(Properties props) {
properties = new HsqlProperties(props);
}
#Override
public boolean isRunning() {
if (server != null)
server.checkRunning(running);
return running;
}
#Override
public void start() {
if (server == null) {
logger.info("Starting HSQL server...");
server = new Server();
try {
server.setProperties(properties);
server.start();
running = true;
} catch (AclFormatException afe) {
logger.error("Error starting HSQL server.", afe);
} catch (IOException e) {
logger.error("Error starting HSQL server.", e);
}
}
}
#Override
public void stop() {
logger.info("Stopping HSQL server...");
if (server != null) {
server.stop();
running = false;
}
}
#Override
public int getPhase() {
return 0;
}
#Override
public boolean isAutoStartup() {
return true;
}
#Override
public void stop(Runnable runnable) {
stop();
runnable.run();
}
}
Edited:
As the following code snippet we are able to start hsqldb server on port 55511 in my local PC. But unable to start using Openshift JBoss EWS 2.0 inside spring context. Where there is an error occurred as following:
[Server#15a1792]: Initiating startup sequence...
[Server#15a1792]: [Thread[HSQLDB Server #15a1792,5,main]]: run()/openServerSocket():
java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at org.hsqldb.server.HsqlSocketFactory.createServerSocket(Unknown Source)
at org.hsqldb.server.Server.openServerSocket(Unknown Source)
at org.hsqldb.server.Server.run(Unknown Source)
at org.hsqldb.server.Server.access$000(Unknown Source)
at org.hsqldb.server.Server$ServerThread.run(Unknown Source)
[Server#15a1792]: Initiating shutdown sequence...
[Server#15a1792]: Shutdown sequence completed in 4 ms.
[Server#15a1792]: 2016-03-23 23:41:21.881 SHUTDOWN : System.exit() was not called
Regarding this issue my questionnaires are as following:
How to achieve permission to open an custom server port Like hsqldb, h2db, MLLP, ActiveMQ, HornetQ?
Do we need extra configuration to access custom server port if we are able to open an custom server port?
If there is an configuration required, would you please provide us any guide line regarding this issue?
Finally I beg your help to open an custom server port Like hsqldb, h2db, MLLP, ActiveMQ, HornetQ and access it publicly from Openshift Gear/Cartridge.

Related

Problems with testing JdbcDao by DBUnit

I have AuthorJDBCDAO class with basic CRUD methods which extends AbstractJDBCDAO class and implements AuthorDAO interface.
I tested all methods via psv main() method and everything was fine.
But Now I have to test it's methods using DBUnit. And here my troubles start.
I try to test just only create() method and it isn't working properly.
I'm using Unitils, Spring DI, Oracle DB to create my application.
I inject bean DataSource(dbcp2) to beanAuthorJDBCDAO. I use XML configuration for injection beans.
Here's my source code and configuration files.
Test class.
#SpringApplicationContext({"spring-test-config.xml"})
#DataSet(value = "AuthorDAOTest.xml", loadStrategy = CleanInsertLoadStrategy.class)
public class AuthorDAOTest extends UnitilsJUnit4 {
#SpringBean("authorJDBCDAO")
private AuthorJDBCDAO authorDAO;
#Test
public void testCreate() throws DAOException {
Author expected = new Author();
expected.setName("BLABLABLA");
expected.setExpiredDate(Timestamp.valueOf(LocalDateTime.now()));
Author result = null;
result = authorDAO.create(expected);
assertEquals(expected.getId(), result.getId());
System.out.println("Hello from test");
}
Here's stacktrace from execution of Test class.
newsportal.exception.DAOException: java.sql.SQLException: Connection is null.
at newsportal.dao.impl.AbstractJDBCDAO.create(AbstractJDBCDAO.java:115)
at com.epam.ivanou.newsportal.dao.impl.AuthorJDBCDAOTest.testCreate(AuthorJDBCDAOTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:108)
at org.unitils.UnitilsJUnit4TestClassRunner$TestListenerInvokingMethodRoadie.runTestMethod(UnitilsJUnit4TestClassRunner.java:204)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.unitils.UnitilsJUnit4TestClassRunner$TestListenerInvokingMethodRoadie.runBeforesThenTestThenAfters(UnitilsJUnit4TestClassRunner.java:186)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.unitils.UnitilsJUnit4TestClassRunner.invokeTestMethod(UnitilsJUnit4TestClassRunner.java:95)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:59)
at org.unitils.UnitilsJUnit4TestClassRunner.access$000(UnitilsJUnit4TestClassRunner.java:42)
at org.unitils.UnitilsJUnit4TestClassRunner$1.run(UnitilsJUnit4TestClassRunner.java:60)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.unitils.UnitilsJUnit4TestClassRunner.run(UnitilsJUnit4TestClassRunner.java:67)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.sql.SQLException: Connection is null.
at org.apache.commons.dbcp2.DelegatingConnection.checkOpen(DelegatingConnection.java:608)
at org.apache.commons.dbcp2.DelegatingConnection.prepareStatement(DelegatingConnection.java:286)
at com.epam.ivanou.newsportal.dao.impl.AbstractJDBCDAO.create(AbstractJDBCDAO.java:106)
... 29 more
Fragment of code of AbstractJDBCDAO class. In which I get this exception. I tried to debug it and found, that in the second try-catch-with-resources block connection is null. But I can't understand, how does it occur if I try to get connection from DataSource which is BasicDataSource and support connection pooling.
#Override
public T create(T object) throws DAOException {
T persistInstance;
// Add the record
String sql = getCreateQuery();
String idName = getIdString();
String tableName = getTableName();
try (Connection connection = DataSourceUtils.getConnection(dataSource);
PreparedStatement statement = connection.prepareStatement(sql)) {
System.out.println("connection: "+ connection + " data source: " + dataSource);
prepareStatementForInsert(statement, object);
int count = statement.executeUpdate();
if (count != 1) {
throw new DAOException("On persist modify more then 1 record: " + count);
}
} catch (Exception e) {
throw new DAOException(e);
}
// Get recently inserted record
sql = getSelectQuery() + " WHERE " + idName + " = (SELECT MAX(" + idName + ") FROM "
+ tableName + ")";
try (Connection connection = DataSourceUtils.getConnection(dataSource);
PreparedStatement statement = connection.prepareStatement(sql)) //here is connection is null and SQLException is thrown {
System.out.println("connection: "+ connection + " data source: " + dataSource); //TODO connection is null in test method, but is good when using main() method
ResultSet rs = statement.executeQuery();
List<T> list = parseResultSet(rs);
if ((list == null) || (list.size() != 1)) {
throw new DAOException("Exception on findByPK new persist data.");
}
persistInstance = list.iterator().next();
} catch (Exception e) {
throw new DAOException(e);
}
return persistInstance;
}
here're configuration files for my beans:
dao-beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<bean id="authorJDBCDAO" class="newsportal.dao.impl.AuthorJDBCDAO">
<constructor-arg ref="dataSource"/>
</bean>
database-test-config.xml
<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-4.2.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>db_test.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="maxWaitMillis" value="${jdbc.maxWaitMillis}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
spring-test-config.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="database-test-config.xml" />
<import resource="dao-beans.xml" />
</beans>
db_test.properties
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#localhost:1521:xe
jdbc.username=Yahor_test
jdbc.password=1234
jdbc.maxIdle=100
jdbc.minIdle=10
jdbc.maxWaitMillis=10000
jdbc.initialSize=10
And here's Simple java class for testing:
public class Test {
public static void main(String[] args) throws DAOException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
AuthorJDBCDAO authorDAO = (AuthorJDBCDAO) ctx.getBean("authorJDBCDAO");
Author author = new Author();
author.setName("Yahor");
author = authorDAO.create(author);
System.out.println(author.getId());
}
And it's working fine =)
May be smth wrong with transactional configurations in my DBUnit Test class?
Problem is solved. I should close connection via DataSourceUtils.doReleaseConnection(). Otherwise connection will be closed physically. It was the keystone of my trouble.

How to perform Hsqldb SET Operation dynamically in Spring

We are using HSQL Database Engine 2.3.2 with Spring 4.1.0.RELEASE while my spring configuration is as following:
Here is applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx" 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-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<bean class="com.chorke.spring.bootstarp.HyperSqlDbServer" id="hsqldb" init-method="start">
<constructor-arg>
<props>
<prop key="server.port">9002</prop>
<prop key="server.dbname.0">chorke</prop>
<prop key="server.remote_open">true</prop>
<prop key="server.database.0">file:~/.hsqldb/chorke/data;sql.syntax_mys=true;user=admin;password=pa55word</prop>
<prop key="hsqldb.default_table_type">text</prop>
<prop key="hsqldb.reconfig_logging">false</prop>
</props>
</constructor-arg>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver" />
<property name="url" value="jdbc:hsqldb:hsql://localhost:9002/chorke" />
<property name="username" value="admin" />
<property name="password" value="pa55word" />
</bean>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:schema.sql"/>
<jdbc:script location="classpath:data.sql"/>
</jdbc:initialize-database>
</beans>
Here is com.chorke.spring.bootstarp.HyperSqlDbServer
package com.chorke.spring.bootstarp;
import java.io.IOException;
import java.util.Properties;
import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl.AclFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
public class HyperSqlDbServer implements SmartLifecycle {
private final Logger logger = LoggerFactory.getLogger(HyperSqlDbServer.class);
private HsqlProperties properties;
private Server server;
private boolean running = false;
public HyperSqlDbServer(Properties props) {
properties = new HsqlProperties(props);
}
#Override
public boolean isRunning() {
if (server != null)
server.checkRunning(running);
return running;
}
#Override
public void start() {
if (server == null) {
logger.info("Starting HSQL server...");
server = new Server();
try {
server.setProperties(properties);
server.start();
running = true;
} catch (AclFormatException afe) {
logger.error("Error starting HSQL server.", afe);
} catch (IOException e) {
logger.error("Error starting HSQL server.", e);
}
}
}
#Override
public void stop() {
logger.info("Stopping HSQL server...");
if (server != null) {
server.stop();
running = false;
}
}
#Override
public int getPhase() {
return 0;
}
#Override
public boolean isAutoStartup() {
return true;
}
#Override
public void stop(Runnable runnable) {
stop();
runnable.run();
}
}
Here is schema.sql
CREATE TABLE IF NOT EXISTS t001i001(pf_id INTEGER,df_name VARCHAR(20));
--SET TABLE t001i001 SOURCE 't001i001.csv;fs=|;vs=.';
Here is data.sql
insert into t001i001(pf_id, df_name) values(1, 'Shefat Hossain');
Where I want to add some script to perform some SET operation dynamically as like as what was commented in schema.sql on second line. using spring.
Any way to perform SET operation logically/dynamically inside Spring Application Context?
Here is wrong assumption of me as As I declared the property at applicationContext.xml on hsqldb bean as below:
<prop key="hsqldb.default_table_type">text</prop>
It's suppose to me that it would be help us to defaulting database table engine TEXT instead of MEMORY. As the table default engine was MEMORY so the 2nd line of schema.sql not executing. after editing schema.sql it working fine, no problem on SET operation as following:
CREATE TEXT TABLE IF NOT EXISTS t001i001(pf_id INTEGER,df_name VARCHAR(20));
SET TABLE t001i001 SOURCE 't001i001.csv;fs=|;vs=.';

How to get spring configuration from database

I'm using Eclipse Juno, JDK 7, tomcat 7.0.29, hibernate 4.1.5 and Spring 3.1.2.
I'm trying to load Spring configuration info from database. This is what I could do until now:
WEB.XML
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/context-beans.xml
</param-value>
</context-param>
jdbc.properties
jdbc.driver_class=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost;databaseName=mydbname;
jdbc.username=<my_usr>
jdbc.password=<my_pwd>
context-beans.xml
<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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<!-- Configure which package will contain our components -->
<context:component-scan base-package="com.xxx" />
<context:annotation-config />
<mvc:annotation-driven />
<mvc:resources mapping="/static/**" location="/static/" />
<tx:annotation-driven />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="appPersistenceUnit" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
p:url="jdbc:sqlserver://localhost;databaseName=appDB" p:username="theUserName" p:password="thePassword" destroy-method="close"/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" lazy-init="false" >
<property name="dataSource" ref="dataSource" />
<property name="lazyInit" value="false" />
</bean>
<bean id="appProperties" class="com.xxx.web.util.MyAppPropertyPlaceholderConfigurer">
<property name="nameColumn" value="key" />
<property name="valueColumn" value="value" />
<property name="tableName" value="app_params" />
<property name="whereClause" value="param_type = 'GLOBAL'" />
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<!-- Files path configuration -->
<mvc:resources mapping="/iconfiles/**" location="file:/${PATH.ICON_FILES}" />
</beans>
Please consider table app_params contains 1 record where key="PATH.ICON_FILES", value="c:/temp/icons/" and param_type="GLOBAL".
MyAppPropertyPlaceholderConfigurer
package com.xxx.web.util;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
public class MyAppPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private JdbcTemplate jdbcTemplate;
private String nameColumn;
private String valueColumn;
private String tableName;
private String whereClause;
public MyAppPropertyPlaceholderConfigurer() {
super();
setPlaceholderPrefix("${");
}
#Override
protected void loadProperties(final Properties props) throws IOException {
if (null == props) {
throw new IOException("No properties passed by Spring framework - cannot proceed.");
}
String sql = String.format("SELECT [%s], [%s] FROM [%s] %s", nameColumn, valueColumn, tableName, whereClause);
logger.info("Reading configuration properties from database. Query=" + sql);
try {
jdbcTemplate.query(sql, new RowCallbackHandler() {
#Override
public void processRow(ResultSet rs) throws SQLException {
String name = rs.getString(nameColumn);
String value = rs.getString(valueColumn);
if (null == name || null == value) {
throw new SQLException("Configuration database contains empty data. Name='" + (name == null ? "" : name)
+ "', Value='" + (value == null ? "" : value) + "'.");
}
props.setProperty(name, value);
}
});
} catch (Exception e) {
logger.fatal("There is an error in either 'application.properties' or the configuration database.");
throw new IOException(e);
}
if (props.size() == 0) {
logger.fatal("The configuration database could not be reached or does not contain any properties in '" + tableName
+ "'.");
} else {
logger.info("Application config info loaded from configuration database.");
}
}
#Override
protected String convertPropertyValue(String originalValue) {
if (originalValue.startsWith("!!")) {
// TODO ex: return EncryptUtil.decrypt(originalValue); see org.owasp.esapi.reference.crypto.EncryptedPropertiesUtils
return originalValue;
}
return originalValue;
}
public void setJdbcTemplate(JdbcTemplate newJdbcTemplate) {
this.jdbcTemplate = newJdbcTemplate;
}
public void setNameColumn(String newNameColumn) {
this.nameColumn = newNameColumn;
}
public void setValueColumn(String newValueColumn) {
this.valueColumn = newValueColumn;
}
public void setTableName(String newTableName) {
this.tableName = newTableName;
}
public void setWhereClause(String newWhereClause) {
if (newWhereClause == null || newWhereClause.trim().length() == 0) {
this.whereClause = "";
} else {
if (newWhereClause.trim().toUpperCase().startsWith("WHERE ")) {
this.whereClause = newWhereClause;
} else {
this.whereClause = "WHERE " + newWhereClause;
}
}
}
}
Doing it this way works as expected and I have variable ${PATH.ICON_FILES} properly resolved.
However, I don't want to have my dataSource bean with username, password and all stuff hard coded on the XML file. I would like to load it from another property file, preferentially encrypted.
How do I get this done?
I already tried to add another PropertyPlaceholderConfigurer with jdbc configuration (plain text at this time) by adding the code below into context-beans.xml:
<bean id="jdbcConfigurer" name="jdbcConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
Then I changed dataSource bean to read from there:
<bean id="dataSource" name="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" p:driverClassName="${jdbc.driver_class}"
p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" destroy-method="close" />
When I try to run I get the following error:
[2012-10-10 11:33:48,744] WARN (SQLErrorCodesFactory.java:227) - Error while extracting database product name - falling back to empty error codes
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class '${jdbc.driver_class}'
Any idea what I'm doing wrong here? Looks like it is instantiating MyAppPropertyPlaceholderConfigurer prior to getting the values from the regular PropertyPlaceholderConfigurer...
Thanks.

Injection of the sessionFactory not working

I'm new with Spring and I want to inject the sessionFactory and its not working at all. I'm starting a web server Jetty and then I load the context. After i start a GWT web application, I make a call on the server side and I try to get some info but I get a null pointer. There is no error at all so it make it difficult to know where the problem is. I know its suppose to work because I saw it working on a project I worked on some times ago. Any help will be appreciate. (Sorry for my possibly bad english)
Here is the context.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema
/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema
/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema
/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema
/security/spring-security-3.0.xsd">
<!-- Standard spring initialization -->
<context:component-scan base-package="com.test">
</context:component-scan>
<tx:annotation-driven transaction-manager="txManager"/>
<!-- Connection to the database-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-
method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="123456789" />
</bean>
<!-- Hibernate session factory-->
<bean id="jpaSessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.domain"/>
<property name="namingStrategy" >
<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- Hibernate session factory -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="jpaSessionFactory" />
</bean>
</beans>
Here is the main :
public static void main(String[] args) {
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[]
{ new AppContextBuilder().buildWebAppContext()});
final JettyServer jettyServer = new JettyServer();
jettyServer.setHandler(contexts);
Runnable runner = new Runnable() {
#Override
public void run() {
new ServerRunner(jettyServer);
}
};
EventQueue.invokeLater(runner);
new ClassPathXmlApplicationContext("context.xml");
}
Here is the class Test where I want the injection :
#Component("test")
public class TEST{
#Resource(name="jpaSessionFactory")
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Personne> getPersonnes() {
Session s = sessionFactory.getCurrentSession();
Query query = s.createQuery("from Person");
return query.list();
}
}
Here is the server side from the application (not shown completely)
/*** The server side implementation of the RPC service.
*/
#SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
#Resource
private TEST t;
public String greetServer(String input) throws IllegalArgumentException {
// Verify that the input is valid.
if (!FieldVerifier.isValidName(input)) {
// If the input is not valid, throw an IllegalArgumentException
back to
// the client.
throw new IllegalArgumentException(
"Name must be at least 4 characters long");
}
t.getPersons(); // NULL pointer here
.........................
The MySQL tables are created like it should, so all the scanning seems to work.
Thanks
Bob
This is because the GreetingServiceImpl class is not created by spring - it is servlet that is initialized by the container directly. Follow the instructions in this article to fix the issue. I have copied the relevant code from the article.
#Override
public void init() throws ServletException {
super.init();
final WebApplicationContext ctx =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
if (ctx == null) {
throw new IllegalStateException("No Spring web application context found");
}
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(this,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
}

Spring + Eclipselink + JtaTransactionManager = javax.persistence.TransactionRequiredException

I really hope you can help me. I've been looking all over the internet for answers and none of them works.
I use Spring 3 + JTA + EclipseLink but i'm getting a TransactionRequiredException when flushing a transaction. Now i'm very used to just defining my persistence context and injecting the EntityManager and the transaction is handled by the app server.
So here's what I've got.
persistence.xml
<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="CartouchanPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:app/jdbc/CartouchanDS</jta-data-source>
<class>com.cartouchan.locator.database.models.Authority</class>
<class>com.cartouchan.locator.database.models.AuthorityPK</class>
<class>com.cartouchan.locator.database.models.User</class>
<class>com.cartouchan.locator.database.models.UserPK</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.ddl-generation" value="none"/>
<property name="eclipselink.target-database" value="MySQL"/>
<property name="eclipselink.jdbc.native-sql" value="true"/>
<property name="eclipselink.jdbc.cache-statements" value="true"/>
</properties>
</persistence-unit>
</persistence>
spring-config.xml
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<jee:jndi-lookup jndi-name="java:app/jdbc/CartouchanDS" id="CartouchanDS" />
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="autodetectUserTransaction" value="true" />
<property name="autodetectTransactionManager" value="true" />
<property name="transactionManagerName" value="java:appserver/TransactionManager"/>
</bean>
<context:annotation-config />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="CartouchanPU" />
<property name="persistenceUnitManager">
<bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"/>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
</property>
</bean>
CreateAccount.class
import java.text.MessageFormat;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class CreateAccount implements Controller {
private static final Logger logger = Logger.getLogger(CreateAccount.class);
// #Autowired
// private JtaTransactionManager transactionManager;
#PersistenceContext
private EntityManager entityManager;
#Transactional(propagation = Propagation.REQUIRES_NEW)
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info(MessageFormat.format("Called handle request", ""));
String username = ServletRequestUtils.getRequiredStringParameter(request, "username");
logger.info(MessageFormat.format("username {0}", username));
String password = ServletRequestUtils.getRequiredStringParameter(request, "password");
logger.info(MessageFormat.format("password {0}", password));
String passwordConfirm = ServletRequestUtils.getRequiredStringParameter(request, "passwordConfirm");
logger.info(MessageFormat.format("passwordConfirm {0}", passwordConfirm));
if (!password.equals(passwordConfirm)) {
throw new ServletRequestBindingException("Passwords don't match");
}
//transactionManager.getUserTransaction().begin();
User user = new User();
//try {
UserPK userPK = new UserPK();
userPK.setUsername(username);
user.setId(userPK);
user.setPassword(passwordConfirm);
user.setEnabled((byte) 1);
logger.info(MessageFormat.format("persist the user {0}", username));
entityManager.persist(user);
entityManager.flush();
// logger.info(MessageFormat.format("Before Refresh user {0}", username));
// entityManager.refresh(user);
// transactionManager.getUserTransaction().commit();
// } catch (Exception e) {
// logger.error(MessageFormat.format("Got an exception {0}", e.getMessage()), e);
// transactionManager.getUserTransaction().rollback();
// }
// transactionManager.getUserTransaction().begin();
// AuthorityPK authorityPK = new AuthorityPK();
// //try {
// logger.info(MessageFormat.format("Refreshed user {0} = {1}", username, user.getId()));
//
// authorityPK.setUserId(user.getId().getId());
// authorityPK.setAuthority(com.cartouchan.locator.models.Authority.ROLE_USER.toString());
// Authority authority = new Authority();
// authority.setId(authorityPK);
//
// logger.info(MessageFormat.format("Save the authority {0}", com.cartouchan.locator.models.Authority.ROLE_USER.toString()));
// entityManager.persist(authority);
// transactionManager.getUserTransaction().commit();
// } catch (Exception e) {
// logger.error(MessageFormat.format("Got an exception {0}", e.getMessage()), e);
// transactionManager.getUserTransaction().rollback();
// }
logger.info(MessageFormat.format("Go to /index.zul", ""));
ModelAndView modelAndView = new ModelAndView("index");
logger.info(MessageFormat.format("Return ", ""));
return modelAndView;
}
}
So here's the deal, when I uncomment the transactionManager parts, the program operates as expected, which is I can see the insert statements. However, when using the above code, I get the following stacktrace :
INFO: Starting ZK 5.0.7.1 CE (build: 2011051910)
INFO: Parsing jndi:/server/Cartouchan/WEB-INF/zk.xml
INFO: WEB0671: Loading application [Cartouchan-Web] at [/Cartouchan]
INFO: Cartouchan-Web was successfully deployed in 1,537 milliseconds.
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] Called handle request
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] username blah
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] password test
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] passwordConfirm test
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] persist the user blah
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.2.0.v20110202-r8913
CONFIG: connecting(DatabaseLogin(
platform=>MySQLPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
CONFIG: Connected: jdbc:mysql://localhost:3306/Cartouchan
User: root#localhost
Database: MySQL Version: 5.1.51
Driver: MySQL-AB JDBC Driver Version: mysql-connector-java-5.1.11 ( Revision: ${svn.Revision} )
CONFIG: connecting(DatabaseLogin(
platform=>MySQLPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
CONFIG: Connected: jdbc:mysql://localhost:3306/Cartouchan
User: root#localhost
Database: MySQL Version: 5.1.51
Driver: MySQL-AB JDBC Driver Version: mysql-connector-java-5.1.11 ( Revision: ${svn.Revision} )
INFO: file:/Applications/NetBeans/glassfish-3.1/glassfish/domains/domain1/eclipseApps/Cartouchan-Web/WEB-INF/classes/_CartouchanPU login successful
WARNING: StandardWrapperValve[cartouchan]: PWC1406: Servlet.service() for servlet cartouchan threw exception
javax.persistence.TransactionRequiredException:
Exception Description: No externally managed transaction is currently active for this thread
at org.eclipse.persistence.internal.jpa.transaction.JTATransactionWrapper.throwCheckTransactionFailedException(JTATransactionWrapper.java:86)
at org.eclipse.persistence.internal.jpa.transaction.JTATransactionWrapper.checkForTransaction(JTATransactionWrapper.java:46)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:1666)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:744)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
at $Proxy151.flush(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy151.flush(Unknown Source)
at com.cartouchan.locator.controllers.CreateAccount.handleRequest(CreateAccount.java:56)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:680)
So as you can see, it connects correctly to the database, and it "persists" the data, but never actually execute the insert statement. Then when flushing the EM, it throws the exception.
Your help will be greatly appreciated.
Best Regards.
Ok, so I figured out how to get this working 100%.
First of all, I don't have to define any persistence(context/unit) in web.xml. Next I removed the transactionmanager and the entityManagerFactory beans. Also removed the context:driven line.
I also made my "beans" Stateless session beans. I then instantiate it through spring through jndi context lookups. This autowires the entitymanager exactly as i want it. No more worrying about transactions, the app server handles that.
so my final config is :
spring-config.xml :
<jee:jndi-lookup jndi-name="java:global/Cartouchan-Web/CategoryController" id="categoryController"/>
<jee:jndi-lookup jndi-name="java:global/Cartouchan-Web/UserController" id="userController"/>
<bean id="applicationContextProvider" class="com.cartouchan.locator.beans.CustomApplicationContext"></bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
bean sample:
import java.text.MessageFormat;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;
#Stateless
public class CategoryController {
private static final Logger logger = Logger.getLogger(CategoryController.class);
#PersistenceContext
private EntityManager entityManager;
public CategoryController() {
// TODO Auto-generated constructor stub
}
public boolean createCategory(final String name) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = new com.cartouchan.locator.database.models.Category();
category.setName(name);
entityManager.persist(category);
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not create the category {0}", name), ex);
}
return result;
}
public boolean updateCategory(final int id, final String name) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = getCategory(id);
category.setName(name);
entityManager.merge(category);
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not update for the category {0} -{1}", id, name), ex);
}
return result;
}
public boolean deleteCategory(final int id) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = getCategory(id);
entityManager.remove(entityManager.merge(category));
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not delete for the category {0}", id), ex);
}
return result;
}
public com.cartouchan.locator.database.models.Category getCategory(final int id) {
return (com.cartouchan.locator.database.models.Category) entityManager.createQuery("select p from Category p where p.id=:id").setParameter("id", id).getSingleResult();
}
public List<com.cartouchan.locator.database.models.Category> getAllCategories() {
return (List<com.cartouchan.locator.database.models.Category>) entityManager.createQuery("select p from Category p").getResultList();
}
}
Then to use the bean, just do a standard spring lookup of the bean. Easy as pie.
In order to use JTA transactions managed by the application server you need to use EntityManagerFactroy created by the application server itself.
I.e. you need to remove your LocalContainerEntityManagerFactoryBean declaration and obtain EntityManagerFactory from the application server via <jee:jndi-lookup>. Also you should configure application server to create EntityManagerFactory - see your application server documentation.
See also:
13.5.1.2 Obtaining an EntityManagerFactory from JNDI
property name="eclipselink.target-server" value="WebSphere_7"
set the server type....
hope this one should work..
refer the docs for more details
http://docs.oracle.com/middleware/1212/toplink/TLADG/websphere.htm

Resources