Spring mvc dispatcher configuration - spring

I have a problem with my dispatcher servlet when I try to add to my dispatcher
<beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="persistenceUnitManager" ref="persistenceUnitManager"/>
<beans:property name="persistenceUnitName" value="entityManager"/>
</beans:bean>
I have a problem Multiple 'annotations found at this line:
Class 'org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean' not found
Class 'org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean' not found [config set: NOVEC_App/web-
context]'

Related

We want to get all the records in Database using HQL in terms of Spring and Hibernate

Here i tried 2 write cod 2 get list from Mysql Database using spring nd Hibernate.
But problem is here that how initialize **org.hibernate.Session se through "applicationContext.xml" file by bean class....
public void getList(**Session se**){
String liststudent="from StudentList stud";
Query q=se.createQuery(liststudent);
List<Object> list=q.list();
for(Object obj:list){
Object studarr[]=(Object[])obj;
System.out.println("Data at Zero Index"+studarr[0]);
}
}
As here property name **template** has been initialized by the ref template.
Is there any way to initialize Session se.
<bean name="mydao" class="dao.MyDao">
<property name="template" ref="template"></property>
</bean>
using your context.xml file
define sessionFactory
<bean id="sessionFactory" class="LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--define other properties...mapping files
</bean>
define hibernateTemplate
<bean id="template" class="*HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
then
<bean name="mydao" class="dao.MyDao">
<property name="template" ref="template"></property>
</bean>
NOTE: the class package has been ommitted

Spring-mvc validation error not being picked from property file

Using spring-mvc build in JSR303 bean validation and its working fine except for one issue, messages are not being picked from property file.
My Web-application is being created with maven and this is current structure
Main
-java
-resources
-bundles
-message.properties
-webapp
XML file
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basenames">
<beans:list>
<beans:value>bundles/messages</beans:value>
<beans:value>bundles/shipping</beans:value>
<beans:value>bundles/payment</beans:value>
</beans:list>
</beans:property>
</beans:bean>
--
validator
<beans:bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<beans:property name="validationMessageSource" ref="messageSource"/>
</beans:bean>
annotation-driven
<annotation-driven>
<message-converters>
<beans:bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<beans:property name="supportedMediaTypes">
<beans:list>
<beans:value>image/jpeg</beans:value>
<beans:value>image/gif</beans:value>
<beans:value>image/png</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</message-converters>
</annotation-driven>
Java File
#NotEmpty(message="{registration.firstName.invalid}")
public String getFirstName() {
return firstName;
}
Some how on my JSP page, I am getting these messages This field is required, not sure what is issue
My Data class is having following structure
PersistableCustomer extends SecuredCustomer
SecuredCustomer extends CustomerEntity
Even after passing message source to validator, its not picking up message from custom property file.
I am taking a wild guess here... usually JSR-303 message interpolator is taking messages from ValidationMessages.properties. If you want your validator to use Spring's message source, you need to configure it that way:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource" />
</bean>
<mvc:annotation-driven validator="validator" />

outbound-gateway with Basic Authentication in spring-integration

With spring-integration I would like to call an outbound-gateway with an Basic Authentication.
I have something like this :
<int-http:inbound-gateway id="versionRequestGateway"
supported-methods="POST" request-channel="requestVersionChannel"
reply-channel="requestTransformerVersionChannel"
path="/consultersite" reply-timeout="10000" request-payload-type="java.lang.String">
</int-http:inbound-gateway>
<int-http:outbound-gateway order="1" request-channel="requestVersionChannel"
url-expression="#urlExpressionGateway.getUrlFor(payload) + '/consultersite'"
reply-channel="responseVersionChannel"
http-method="POST"
expected-response-type="java.lang.String" >
</int-http:outbound-gateway>
The URL of outbound-gateway is dynamic.
I decide to use rest-template attribute on the outbound-gateway, with this :
<bean id="httpClientParams" class="org.apache.commons.httpclient.params.HttpClientParams">
<property name="authenticationPreemptive" value="true"/>
<property name="connectionManagerClass" value="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"/>
</bean>
<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
<constructor-arg ref="httpClientParams"/>
</bean>
<bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
<constructor-arg ref="httpClient"/>
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="httpClientFactory"/>
</bean>
It's work when I inject an UsernamePasswordCredentials in an ApplicationListener after spring application context is loaded.
HttpClient client = ctx.getBean("httpClient", HttpClient.class);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(AuthScope.ANY, credentials);
But according the url of outbound-gateway, username and password are different.
How can I do to use the good username/password according the url outbound-gateway ?
It was necessary to implement my own BasicSecureSimpleClientHttpRequestFactory extends SimpleClientHttpRequestFactory to map information Credentials according to the URL of connection. Hope an implementation Spring will be available one day ...
Thanks.
Do not type any Java code you can use a combination of Spring WS HttpComponentsMessageSender and Spring WEB HttpComponentsClientHttpRequestFactory:
<bean id="httpComponentsMessageSender" class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<property name="credentials">
<bean class="org.apache.commons.httpclient.UsernamePasswordCredentials">
<constructor-arg value="userName"/>
<constructor-arg value="password"/>
</bean>
</property>
</bean>
<bean id="clientHttpRequestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="httpClient" value="#{httpComponentsMessageSender.httpClient}"/>
</bean>
<int-http:outbound-gateway url-expression="#urlExpressionGateway.getUrlFor(payload) + '/consultersite'"
request-factory="clientHttpRequestFactory"/>
I can believe, that my answer might not be full for your case.
However I hope it can help a bit.
Maybe there is need to implement your own HttpComponentsClientHttpRequestFactory#createRequest to authenticate at runtime and do this:
method.addRequestHeader(new Header(WWW_AUTH_RESP, authstring, true));
Take a look into source code of HttpMethodDirector#authenticateHost
you should use org.apache.http.auth.UsernamePasswordCredentials implementation instead of org.apache.commons.httpclient.UsernamePasswordCredentials
<beans:bean id="httpComponentsMessageSender" class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<beans:property name="credentials">
<beans:bean class="org.apache.http.auth.UsernamePasswordCredentials">
<beans:constructor-arg value="user"/>
<beans:constructor-arg value="password"/>
</beans:bean>
</beans:property>
</beans:bean>

Hibernate-Spring Web container error

Hello I'm new to Hibernate.
I have generated with Hibernate Tools a database access module. The generator generates the code of the DAOS and Hibernate Beans.
When I test this module in a simple Java application all works fine, but when I test it in a Spring Web application I get a very strange error. Since my module is an independent jar it should access the database without regarding the circumstance of being executed in a simple Java application or a Web application. The code of my web application is:
#Controller
#RequestMapping("/")
public class Controller implements ApplicationContextAware
{
private ApplicationContext applicationContext;
#RequestMapping(value = "/purchased/songs", method = RequestMethod.GET)
public String home(Model model)
{
SessionManager.startOperation();
ChargeTryDAOBase ctdb=new ChargeTryDAOBase();
List <ChargeTry> data=ctdb.findByRemoteId("dsfsdfsdf8");
SessionManager.endOperation();
model.addAttribute("result", "data" );
return "home";
}
#Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException
{
this.applicationContext = arg0;
}
}
When running this code on Tomcat I get following error:
org.springframework.web.util.NestedServletException: Handler processing
nested exception is java.lang.NoSuchMethodError:
org.hibernate.SessionFactory.getCurrentSession()Lorg/hibernate/Session;
.....
java.lang.NoSuchMethodError:
org.hibernate.SessionFactory.getCurrentSession()Lorg/hibernate/Session;
When I change some Hibernate dependencies I get following error:
java.lang.IllegalStateException: Could not locate SessionFactory in JNDI
When I test the above code in a simple Java application all works fine.
Is this a spring-hibernate configuration problem?
Thank you for your help.
Please study
1: http://www.javatpoint.com/hibernate-and-spring-integration
and
2 http://viralpatel.net/blogs/spring3-mvc-hibernate-maven-tutorial-eclipse-example/
to get insight of Spring MVC and Hibernate Integration.
You can work with Hibernate Configuration file - here is the link -
Spring and hibernate.cfg.xml
But as your application is within a spring managed container, We will highly recommend to use applicationcontext.xml for better maintenance and management of codebase and performance.
thank you for your help finally I got all working. I followed your link and googled a little bit. The problem was that I didn't enable in my hibernate.cfg.xml file the datasource parameter, I also have configured C3P0 jdbc connection provider.
My final hibernate.cfg.xml file is:
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">true</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="hibernate.connection.username">userdb</property>
<property name="hibernate.connection.password">12345</property>
<property name="hibernate.connection.datasource">java:comp/env/jdbc/mydb</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hibernate.connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.numHelperThreads">4</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">1800</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<hibernate-configuration>
<session-factory>
In my web.xml I have added following lines:
<resource-ref>
<description>This is a MySQL database connection</description>
<res-ref-name>jdbc/mydb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
In the Spring context file I have added following lines:
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<beans:property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<beans:property name="username" value="userdb"/>
<beans:property name="password" value="12345"/>
</beans:bean>
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="configLocation">
<beans:value>classpath:hibernate.cfg.xml</beans:value>
</beans:property>
</beans:bean>
The strange thing is, that with the default Hibernate connection provider, the above solution didn't work but when I configured C3P0 all started to work.
Thank you for your help.

Multiple property file

How to handle multiple property files in spring with placeholderconfigurer?
I have an application context in Common project with following bean entry:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:database.properties" />
</bean>
And in Service layer project I have another application context file with this bean entry:
<beans:bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<beans:property name="location" value="classpath:kestrel.properties" />
</beans:bean>
The entries in property file are like :
database proprties:
URL= xxx
USERNAME = xxx
PWD = xxx
kestrel.properties:
mediacast.url = xxx
With these setting, when I start my tomcat server I get expection like:
Could not resolve placeholder 'mediacast.url' from kestrel.properties - property file.
Thanks in advance for any help!
On my application, I do that:
<bean id="envPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>one/path/to/file</value>
<value>another/path/to/file</value>
</list>
</property>
</bean>

Resources