How can I make this work in unit tests using Hibernate 3.3.1ga and HSQLDB:
#Entity
#Table(name="CATEGORY", schema="TEST")
public static class Category { ... }
The problem is that Hibernate expects the schema to exist. The second problem is that Hibernate issues the CREATE TABLE TEST.CATEGORY before any of my code runs (this happens deep inside Spring's test setup), so I can't get a connection to the DB before Hibernate and create the schema manually.
But I need the schema because I have to access different databases in the real code. What should I do?
Hibernate 3.3.1ga, HSQLDB, Spring 2.5
You could write a class that implements InitializingBean:
public class SchemaCreator implements InitializingBean {
private String schema;
private DataSource dataSource;
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public void afterPropertiesSet() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("CREATE SCHEMA " + schema + " AUTHORIZATION DBA");
}
}
You then have to define a bean in your bean definition file of this class (I'm taking a shot in the dark as to what your existing bean definitions look like).
<bean id="dataSource" class="...">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:test"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="sessionFactory" depends-on="schemaCreator" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
...
</bean>
<bean id="schemaCreator" class="SchemaCreator">
<property name="dataSource" ref="dataSource"/>
<property name="schema" value="TEST"/>
</bean>
By using the depends-on attribute of Hibernate's bean, Spring will ensure that the schemaCreator bean will be initialized first, causing the schema to exist just in time. This should also make your intentions clearer.
My current solution looks like this:
#Override
protected String[] getConfigLocations() {
createHSQLDBSchemas ();
return new String[]{
"test-spring-config.xml"
};
}
private static boolean hsqldbSchemasCreated = false;
public static void createHSQLDBSchemas ()
{
if (hsqldbSchemasCreated)
return;
try
{
log.info ("createHSQLDBSchemas");
Class.forName("org.hsqldb.jdbcDriver").newInstance();
Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:test", "sa", "");
Statement stmt = c.createStatement ();
String sql;
sql = "CREATE SCHEMA xxx AUTHORIZATION DBA";
log.info (sql);
stmt.execute (sql);
stmt.close ();
c.close ();
}
catch (Exception e)
{
throw new ShouldNotHappenException (e);
}
hsqldbSchemasCreated = true;
}
but that feels like a really ugly hack. Isn't there a better solution?
Below is an example of how you can create spring config with test hslqdb
It automaticly detects all your schemas from #Table(schema =...) and creates them for you.
If it is just for testing this should work for you:
import org.reflections.Reflections; //maven artifact: 'org.reflections:reflections:0.9.9-RC1'
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import javax.persistence.Table;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
#Configuration
#ComponentScan("com.test.collection")
public class CollectionConfig {
private static final String[] ENTITY_PACKAGES = { "com.test.collection.domain.dao" };
private static final String CONFIGURATION_LOCATION = "/movie-collection-hibernate.cfg.xml";
#Bean( name = "testSessionFactory" )
#Lazy
public LocalSessionFactoryBean getTestSessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setPackagesToScan( ENTITY_PACKAGES );
Properties hibernateProperties = getHibernateHsqlTestDbProperties();
sessionFactory.setHibernateProperties( hibernateProperties );
createNonStandardSchemas( hibernateProperties );
return sessionFactory;
}
private void createNonStandardSchemas( Properties properties ) {
final String DEFAULT_SCHEMA = "";
Set<String> schemas = new HashSet<>();
Reflections reflections = new Reflections( ENTITY_PACKAGES );
Set<Class<?>> annotatedClasses =
reflections.getTypesAnnotatedWith( Table.class );
for ( Class<?> clazz : annotatedClasses ) {
Table table = clazz.getAnnotation( Table.class );
if ( !DEFAULT_SCHEMA.equals( table.schema() ) ) {
schemas.add( table.schema() );
}
}
if ( !schemas.isEmpty() ) {
DriverManagerDataSource driverManager = new DriverManagerDataSource();
driverManager.setDriverClassName( properties.getProperty( "hibernate.connection.driver_class" ) );
driverManager.setUrl( properties.getProperty( "hibernate.connection.url" ) );
driverManager.setUsername( properties.getProperty( "hibernate.connection.username" ) );
driverManager.setPassword( properties.getProperty( "hibernate.connection.password" ) );
JdbcTemplate jdbcTemplate = new JdbcTemplate( driverManager );
for ( String schemaName : schemas ) {
jdbcTemplate.execute(
String.format( "DROP SCHEMA IF EXISTS %s", schemaName)
);
jdbcTemplate.execute(
String.format( "CREATE SCHEMA %s AUTHORIZATION DBA", schemaName)
);
}
}
}
private Properties getHibernateHsqlTestDbProperties() {
Properties prop = new Properties();
prop.setProperty( "hibernate.connection.driver_class", "org.hsqldb.jdbcDriver" );
prop.setProperty( "hibernate.connection.url", "jdbc:hsqldb:mem:test" );
prop.setProperty( "hibernate.connection.username", "sa" );
prop.setProperty( "hibernate.connection.password", "test" );
prop.setProperty( "hibernate.connection.pool_size", "5" );
prop.setProperty( "hibernate.dialect", "org.hibernate.dialect.HSQLDialect" );
prop.setProperty( "hibernate.current_session_context_class", "thread" );
prop.setProperty( "hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCachingRegionFactory" );
prop.setProperty( "hibernate.show_sql", "false" );
prop.setProperty( "hibernate.format_sql", "false" );
prop.setProperty( "hibernate.use_sql_comments", "false" );
prop.setProperty( "hibernate.hbm2ddl.auto", "create-drop" );
return prop;
}
}
And here is a test sample:
#ContextConfiguration( classes = CollectionConfig.class )
#DirtiesContext( classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD )
public class DaoMappingTest extends AbstractTestNGSpringContextTests {
#Autowired
private SessionFactory testSessionFactory;
#Test
public void thatMovieIsSaved() {
Movie killBill = getKillBillMovie0();
saveToDb( Arrays.asList(killBill) );
Session querySession = testSessionFactory.openSession();
List<Movie> movies = querySession.createQuery( "from Movie" ).list();
querySession.close();
assertThat( movies ).containsExactly( killBill );
}
#Test
public void that2MoviesIsSaved() {
Movie killBill = getKillBillMovie0();
Movie terminator = getTerminatorMovie1();
saveToDb( Arrays.asList( killBill, terminator ) );
Session querySession = testSessionFactory.openSession();
List<Movie> movies = querySession.createQuery( "from Movie" ).list();
querySession.close();
assertThat( movies ).containsOnly( killBill, terminator );
}
private void saveToDb( List<?> objects ) {
Session session = testSessionFactory.openSession();
session.beginTransaction();
for( Object obj : objects) {
session.save( obj );
}
session.getTransaction().commit();
session.close();
}
#AfterSuite
public void tearDown() {
testSessionFactory.close();
}
}
It looks to me like you have a reproducible bug in the Hibernate DDL creation code. You should report a bug - it's a long term solution but it's the way things are done in open source. Of course you might want to produce a patch, but I never found the Hibernate code base easy to hack.
I ran into the same problem where MS SQL Server wants the catalog and schema defined, but HSQLDB does not. My solution was to load a custom orm.xml file (via persistence.xml) specifically for MS SQL Server that sets the catalog and schema.
1.Only specify the #Table name (omit any catalog or schema info) for your entity:
#Entity
#Table(name="CATEGORY")
public static class Category { ... }
2.Specify two persistence-unit nodes in your META-INF/persistence.xml file
<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">
<!--
| For production and integration testing we use MS SQL Server, which needs
| the catalog and schema set (see orm-mssql.xml).
|-->
<persistence-unit name="com.mycompany.prod">
<mapping-file>META-INF/orm-mssql.xml</mapping-file>
</persistence-unit>
<!--
| For unit testing we use HSQLDB, which does not need the catalog or schema.
|-->
<persistence-unit name="com.mycompany.test" />
</persistence>
3.Specify the default catalog and schema in the orm-mssql.xml file:
<entity-mappings version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd">
<persistence-unit-metadata>
<!--
| Set the catalog and schema for MS SQL Server
|-->
<persistence-unit-defaults>
<schema>MYSCHEMA</schema>
<catalog>MYCATALOG</catalog>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
4.I'm using Spring to configure JPA, so I use a property-placeholder for the value of the persistenceUnitName:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="persistenceUnitName" value="${entityManagerFactory.persistenceUnitName}" />
</bean>
For unit tests, use 'com.mycompany.test' and for integration-tests/production deployments, use 'com.mycompany.prod'.
Related
I created a small SpringBoot App which is used together with Hibernate to work with our Oracle Databse.
But I ran into the following Problem:
Whenever I load an Object from the database with SessionFactory.createQuery() and then query.getResultList(). I do get a List of Results with the correct Class annotations (when looking at the code in debug mode). But I cannot do MyClass x = list.get(0), even though the list is a List of MyClass. I can only get an Object but cannot "cast" to the correct class.
Uidnr is a simple Class with no join tables or any other dependencies on other tables form the database. Its only BigDecimal's, String's and Timestamp's.
Here is the code and configs of everything:
POST Endpoint:
#RequestMapping(value = "/e10", method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE)
#ResponseBody
public String e10() {
Database db = new Database();
List<Uidnr> bel = db.getUidnrList(new BigDecimal("1009316"));
Uidnr element = bel.get(0); //CLASSCASTEXCEPTION HERE!!!
return element.getNr();
}
Method to get the Class from Database:
public List<Uidnr> getUidnrList(BigDecimal id) {
SessionFactory factory = null;
List<Uidnr> uidnr = new ArrayList<Uidnr>();
Session session = null;
try {
factory = getSessionFactory();
session = factory.openSession();
Query<Uidnr> query = session.createQuery("from Uidnr where adrid=:sblid", Uidnr.class);
query.setParameter("sblid", id);
uidnr = query.getResultList(); //This is a List<Uidnr
} catch (HibernateException ex) {
logger.error("Error loading Sendungen.", ex);
} finally {
close(factory, session);
}
return uidnr;
}
SessionFactory:
private SessionFactory getSessionFactory() {
SessionFactory sf = null;
File optextconf = new File("conf/hibernate.cfg.xml");
Configuration c = new Configuration();
if (optextconf.exists()) {
c.configure(optextconf);
c.addResource("eu/lbase/invsvc/app/model/internal/Uidnr.hbm.xml");
sf = c.buildSessionFactory();
logger.info("Session factory loaded from external file {}.", optextconf.getAbsolutePath());
} else {
logger.error("Configuration {} not found. Can not connect to database.", optextconf.getAbsolutePath());
}
return sf;
}
Uidnr.hbm.xml file located under src/main/resources, in a package called eu.lbase.invsvc.app.model.internal:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="eu.lbase.invsvc.app.model.internal.Uidnr" table="SUID_UIDNR">
<composite-id>
<key-property name="adrid" column="UID_ADRID" />
<key-property name="staid" column="UID_STAID" />
</composite-id>
<property name="nr" column="UID_NR"/>
<property name="stnr" column="UID_STNR"/>
<property name="deflt" column="UID_DEFLT"/>
<property name="aend" column="UID_AEND"/>
<property name="usrid" column="UID_USRID"/>
<property name="stktonr" column="UID_STKTONR"/>
<property name="zoktonr" column="UID_ZOKTONR"/>
<property name="vollmacht" column="UID_VOLLMACHT"/>
</class>
</hibernate-mapping>
Exception:
java.lang.ClassCastException: eu.lbase.invsvc.app.model.internal.Uidnr cannot be cast to eu.lbase.invsvc.app.model.internal.Uidnr
at eu.lbase.invsvc.app.controller.WebController.e10(WebController.java:91) ~[main/:na]
Some Tests:
System.out.println(bel.getClass()); //class java.util.ArrayList
Object test = bel.get(0);
System.out.println(test.getClass()); //class eu.lbase.invsvc.app.model.internal.Uidnr
System.out.println(bel.get(0) instanceof eu.lbase.invsvc.app.model.internal.Uidnr); //false
I have using Spring Mvc Jdbc template for calling procedures and functions.But the database connection is not close after the function call.Every time new database user instance create.Could anyone please give me the solution for solving this big problem.
#Autowired
#Qualifier("dbDataSource")
public DataSource dataSource;
public SimpleJdbcCall procReadData;
public PersonDTO readPersonData(Principal principal) throws SQLException {
List<PersonDTO> personDTOList = null;
Map<String,Object> results = null;
procReadData = new SimpleJdbcCall(dataSource).withProcedureName("GET_PAWS_PERSON_DETAILS");
procReadData.addDeclaredParameter(new SqlParameter("AV_USER_NAME", OracleTypes.VARCHAR));
procReadData.addDeclaredParameter( new SqlOutParameter( "CUR_GENERIC", OracleTypes.CURSOR,new PersonRowMapper()));
SqlParameterSource in = new MapSqlParameterSource().addValue("AV_USER_NAME", principal.getName());
results = procReadData.execute(in);
Set<String> keys = results.keySet();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
personDTOList = (List<PersonDTO>) results.get(key);
}
return personDTOList.get(0);
}
Database Configuration:
<Resource driverClassName="oracle.jdbc.OracleDriver" maxActive="300" maxIdle="100" maxWait="5000" name="jdbc/epaws" global="jdbc/epaws"
password="polusneu" type="javax.sql.DataSource" url="jdbc:oracle:thin:#192.168.1.60:1521:coeusnew"
username="polusneu" validationQuery="select 1 from dual"/>
applicationcontext.xml configuration
<bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/epaws"/>
<property name="resourceRef" value="true"/>
</bean>
I'm new in MDB and EE. Please tell me there is i'm wrong.
My app must interaction with Websphere MQ (wait a messaege in queue, do something and reply).
I'm using NetBeans 7.3 ,GlassFish 3.1, Websphere MQ 6.2, resorce adapter wmq.jmsra.rar. Interaction must be not in jms format is, only Web MQ nature.
I'm deploy adapter and create Connecton pool and Administrated Object.
In domain.xml
<connector-connection-pool description="" name="cpMqAdapter" resource-adapter-name="wmq.jmsra" connection-definition-name="javax.jms.QueueConnectionFactory" transaction-support="LocalTransaction">
<property name="port" value="1414"></property>
<property name="CCSID" value="866"></property>
<property name="hostName" value="192.168.0.11"></property>
<property name="queueManager" value="QM"></property>
<property name="channel" value="SrvConn"></property>
<property description="CLIENT - mq on other computer" name="transportType" value="CLIENT"></property>
</connector-connection-pool>
<admin-object-resource enabled="false" res-adapter="wmq.jmsra" res-type="javax.jms.Queue" description="" jndi-name="wmqJmsAOR" class-name="com.ibm.mq.connector.outbound.MQQueueProxy">
<property name="priority" value="APP"></property>
<property name="failIfQuiesce" value="true"></property>
<property name="baseQueueManagerName" value="QM"></property>
<property name="CCSID" value="1208"></property>
<property name="persistence" value="APP"></property>
<property name="encoding" value="NATIVE"></property>
<property name="baseQueueName" value="TEST"></property>
<property name="targetClient" value="MQ"></property>
<property name="expiry" value="APP"></property>
</admin-object-resource>
'
In netbeans i'm create EE project and message driven bean. i'm gett this code '
#MessageDriven(mappedName = "wmqJmsAOR", activationConfig = {
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-
acknowledge"),
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class NewMessage implements MessageListener {
public NewMessage() {
super();
System.out.println("I created");
}
#Override
public void onMessage(Message message) {
System.out.println("I'm getting message");
}
`
Please tell me why this MDB is not listenig a queue (i'm put test message in Websphere MQ console). May be i'm must write something in config (now project as default netbeans created).
Alexei
I have a solution that works. It is not the best solution but it does work extremely well.
What we have done is to create a very simple ActivationSpecWrapper class to extend the IBM com.ibm.mq.connector.inbound.ActivationSpecImpl class. This wrapper class has one public set/get property (asJNDI). The purpose if the class is to read via JNDI context the Properties class defined in the App server that contains all the properties to be assigned in the activation of the MDB.
First, create the new ActivationSpecWrapper class. you can put this in any package of your choosing.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import com.ibm.mq.connector.inbound.ActivationSpecImpl;
public class ActivationSpecWrapper extends ActivationSpecImpl
{
private static final long serialVersionUID = -529716553593856979L;
private static final String sourceClass = ActivationSpecWrapper.class.getName();
private static final Logger log = Logger.getLogger(sourceClass);
private String asJNDI = null;
public void setAsJNDI(String asJNDI)
{
log.config("asJNDI = " + asJNDI);
this.asJNDI = asJNDI;
try
{
final InitialContext ctx = new InitialContext();
final Properties properties = (Properties) ctx.lookup(asJNDI);
for (final Object key : properties.keySet())
{
try
{
final String value = properties.getProperty((String) key);
final Object field = getSetter((String) key);
if (field != null)
{
if (field instanceof Field)
{
log.fine("Setting " + key + " via Field " + (String) key + " = " + value);
((Field) field).set(this, value);
}
else
{
log.fine("Setting " + key + " via Method " + (String) key + " = " + value);
((Method) field).invoke(this, value);
}
log.config(key + " = " + value);
}
else
{
log.warning("Invalid ActivationSpec Field: " + key);
}
}
catch (final NoSuchFieldException e)
{
log.throwing(sourceClass, "setAsJNDI", e);
}
}
}
catch (final Exception e)
{
log.log(Level.SEVERE, "Error looking up " + asJNDI, e);
return;
}
}
public String getAsJNDI()
{
return asJNDI;
}
private static Object getField(String fieldName) throws NoSuchFieldException
{
return ActivationSpecWrapper.class.getField(fieldName);
}
private static Object getSetter(String fieldName) throws NoSuchFieldException
{
try
{
final StringBuilder sb = new StringBuilder(fieldName.length() + 3).append("set").append(fieldName);
sb.setCharAt(3, Character.toUpperCase(sb.charAt(3)));
return ActivationSpecWrapper.class.getMethod(sb.toString(), String.class);
}
catch (final NoSuchMethodException e)
{
return getField(fieldName);
}
}
}
To implement the class you just need to modify the META-INF/ra.xml file inside the wmq.jmsra.rar file. Change the one occurrence of the ActivationSpecImpl class to your class. This will be your new incoming connection factory's ActivationSpecWrapper class that it uses. So now your wrapper class can look to the app server for the properties to use.
I do this as follows:
: jar -xvf wmq.jmsra.rar META-INF/ra.xml
: perl -pi -e 's/com\.ibm\.mq\.connector\.inbound\.ActivationSpecImpl/your.new.package.ActivatonSpecWrapper/g' META-INF/ra.xml
: jar -uvf wmq.jmsra.rar META-INF/ra.xml
Before modifying the META-INF/ra.xml looks like:
<activationspec>
<activationspec-class>
com.ibm.mq.connector.inbound.ActivationSpecImpl
</activationspec-class>
<required-config-property>
<config-property-name>destination</config-property-name>
</required-config-property>
<required-config-property>
<config-property-name>destinationType</config-property-name>
</required-config-property>
</activationspec>
After the change, the META-INF/ra.xml should like like:
<activationspec>
<activationspec-class>
your.new.package.ActivatonSpecWrapper
</activationspec-class>
<required-config-property>
<config-property-name>destination</config-property-name>
</required-config-property>
<required-config-property>
<config-property-name>destinationType</config-property-name>
</required-config-property>
</activationspec>
Now you will need to add your new package to the RAR file. It should be in standard directory structure. like this:
: jar -uvf wmq.jmsra.rar your/new/package/ActivationSpecWrapper.class
The problem stems from IBM placing the host/port/queue manager/channel (etc.) into the activation spec instead of the administration object. It belongs in the administration object since that is the connection factory for MDB queues. IBM only allows two properties there.
Also if you are using glassfish, oracle really botched things up for MDB classes that need resource adapters, because the glassfish #MessageDriven annotation assumes the app containers default resource adapter (OpenMQ) for JMS. This means the vendor specific ActivationSpecImpl does not work, and thus IMB's custom parameters for host/port and other activation config properties are not supported via annotations until after the resource adaptor is switch via the glassfish-ejb-jar.xml.
JBoss allows for the #ResourceAdapter annotation to change the resource adapter but Glassfish only allows this via the glassfish-ejb-jar.xml file. And when this is used, you only need to annotate your MDB with three activation config properties (the destinationType). Everything else you will place in your JNDI published Properties.
The glassfish-ejb-jar.xml should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<glassfish-ejb-jar>
<enterprise-beans >
<unique-id>1</unique-id>
<ejb>
<ejb-name>MyMDB</ejb-name>
<mdb-resource-adapter>
<resource-adapter-mid>wmq.jmsra</resource-adapter-mid>
<activation-config>
<activation-config-property>
<activation-config-property-name>asJNDI</activation-config-property-name>
<activation-config-property-value>mq/InboundMessages</activation-config-property-value>
</activation-config-property>
</activation-config>
</mdb-resource-adapter>
</ejb>
</enterprise-beans>
</glassfish-ejb-jar>
The MDB #MessageDriven annotation will look something like this:
#MessageDriven(activationConfig =
{
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "jms/InboundMessage_queue"),
#ActivationConfigProperty(propertyName = "useJNDI", propertyValue = "true") })
public class MyMDB implement MessageListener
{
public void onMessage(Message message)
{
// message handler code goes here...
}
}
The last step to make this work, is to add the mq/InboundMessages properties to JDNI, to define the factory properties for the MQ listener resource. This is how it is defined in the domain.xml file:
<custom-resource res-type="java.util.Properties" jndi-name="mq/InboundMessages" factory-class="org.glassfish.resources.custom.factory.PropertiesFactory">
<property name="hostName" value="mqserver"></property>
<property name="port" value="1422"></property>
<property name="queueManager" value="MQMNGR"></property>
<property name="channel" value="MQMNGR.SM.S1"></property>
<property name="transportType" value="CLIENT"></property>
</custom-resource>
I hope this helps. This isn't the easiest solution but it is simple enough, and once it has been established, it is very portable, and allows the app server administrator to manage the connection details to the MQ, instead of the developer.
Is there anything that can achieve the equivalent of the below:
<import resource="a.xml">
<prop name="key" value="a"/>
</import>
<import resource="a.xml">
<prop name="key" value="b"/>
</import>
Such that the beans defined in resouce a would see the property key with two different values? The intention would be that this would be used to name the beans in the imports such that resource a.xml would appear:
<bean id="${key}"/>
And hence the application would have two beans named a and b now available with the same definition but as distinct instances. I know about prototype scope; it is not intended for this reason, there will be many objects created with interdepednencies that are not actually prototypes. Currently I am simply copying a.xml, creating b.xml and renaming all the beans using the equivalent of a sed command. I feel there must be a better way.
I suppose that PropertyPlaceholderConfigurers work on a per container basis, so you can't achieve this with xml imports.
Re The application would have two beans named a and b now available with the same definition but as distinct instances
I think you should consider creating additional application contexts(ClassPathXmlApplicationContext for example) manually, using your current application context as the parent application context.
So your many objects created with interdependencies sets will reside in its own container each.
However, in this case you will not be able to reference b-beans from a-container.
update you can postprocess the bean definitions(add new ones) manually by registering a BeanDefinitionRegistryPostProcessor specialized bean, but this solution also does not seem to be easy.
OK, here's my rough attempt to import xml file manually:
disclaimer: I'm very bad java io programmer actually so double check the resource related code :-)
public class CustomXmlImporter implements BeanDefinitionRegistryPostProcessor {
#Override
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
private Map<String, String> properties;
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public Map<String, String> getProperties() {
return properties;
}
private void readXml(XmlBeanDefinitionReader reader) {
InputStream inputStream;
try {
inputStream = new ClassPathResource(this.classpathXmlLocation).getInputStream();
} catch (IOException e1) {
throw new AssertionError();
}
try {
Scanner sc = new Scanner(inputStream);
try {
sc.useDelimiter("\\A");
if (!sc.hasNext())
throw new AssertionError();
String entireXml = sc.next();
PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${",
"}", null, false);
Properties props = new Properties();
props.putAll(this.properties);
String newXml = helper.replacePlaceholders(entireXml, props);
reader.loadBeanDefinitions(new ByteArrayResource(newXml.getBytes()));
} finally {
sc.close();
}
} finally {
try {
inputStream.close();
} catch (IOException e) {
throw new AssertionError();
}
}
}
private String classpathXmlLocation;
public void setClassPathXmlLocation(String classpathXmlLocation) {
this.classpathXmlLocation = classpathXmlLocation;
}
public String getClassPathXmlLocation() {
return this.classpathXmlLocation;
}
#Override
public void postProcessBeanDefinitionRegistry(
BeanDefinitionRegistry registry) throws BeansException {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry);
readXml(reader);
}
}
XML configuration:
<bean class="CustomXmlImporter">
<property name="classPathXmlLocation" value="a.xml" />
<property name="properties">
<map>
<entry key="key" value="a" />
</map>
</property>
</bean>
<bean class="CustomXmlImporter">
<property name="classPathXmlLocation" value="a.xml" />
<property name="properties">
<map>
<entry key="key" value="b" />
</map>
</property>
</bean>
this code loads the resources from classpath. I would think twice before doing something like that, anyway, you can use this as a starting point.
I'm trying to create a multiaction web controller using Spring annotations. This controller will be responsible for adding and removing user profiles and preparing reference data for the jsp page.
#Controller
public class ManageProfilesController {
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(UserAccount.class,"account", new UserAccountPropertyEditor(userManager));
binder.registerCustomEditor(Profile.class, "profile", new ProfilePropertyEditor(profileManager));
logger.info("Editors registered");
}
#RequestMapping("remove")
public void up( #RequestParam("account") UserAccount account,
#RequestParam("profile") Profile profile) {
...
}
#RequestMapping("")
public ModelAndView defaultView(#RequestParam("account") UserAccount account) {
logger.info("Default view handling");
ModelAndView mav = new ModelAndView();
logger.info(account.getLogin());
mav.addObject("account", account);
mav.addObject("profiles", profileManager.getProfiles());
mav.setViewName(view);
return mav;
}
...
}
Here is the part of my webContext.xml file:
<context:component-scan base-package="ru.mirea.rea.webapp.controllers" />
<context:annotation-config/>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
...
/home/users/manageProfiles=users.manageProfilesController
</value>
</property>
</bean>
<bean id="users.manageProfilesController" class="ru.mirea.rea.webapp.controllers.users.ManageProfilesController">
<property name="view" value="home\users\manageProfiles"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
However, when i open the mapped url, i get exception:
java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [ru.mirea.rea.model.UserAccount]: no matching editors or conversion strategy found
I use spring 2.5.6 and plan to move to the Spring 3.0 in some not very distant future. However, according to this JIRA https://jira.springsource.org/browse/SPR-4182 it should be possible already in spring 2.5.1.
The debug shows that the InitBinder method is correctly called.
What am i doing wrong?
Update:
public class UserAccountPropertyEditor extends PropertyEditorSupport {
static Logger logger = Logger.getLogger(UserAccountPropertyEditor.class);
public UserAccountPropertyEditor(IUserDAO dbUserManager) {
this.dbUserManager = dbUserManager;
}
private IUserDAO dbUserManager;
public String getAsText() {
UserAccount obj = (UserAccount) getValue();
if (null==obj) {
return "";
} else {
return obj.getId().toString();
}
}
public void setAsText(final String value) {
try {
Long id = Long.parseLong(value);
UserAccount acct = dbUserManager.getUserAccountById(id);
if (null!=acct) {
super.setValue(acct);
} else {
logger.error("Binding error. Cannot find userAccount with id ["+value+"]");
throw new IllegalArgumentException("Binding error. Cannot find userAccount with id ["+value+"]");
}
} catch (NumberFormatException e) {
logger.error("Binding error. Invalid id: " + value);
throw new IllegalArgumentException("Binding error. Invalid id: " + value);
}
}
}
There are no errors logged from UserAccountPropertyEditor.
I don't think you want to be specifying the field argument to WebDataBinder.registerCustomEditor(). This intended to work alongside form-backing objects, and you're not using that.
Try the simpler 2-arg method instead, and it should work:
binder.registerCustomEditor(UserAccount.class, new UserAccountPropertyEditor(userManager));
binder.registerCustomEditor(Profile.class, new ProfilePropertyEditor(profileManager));