Spring-mvc validation error not being picked from property file - spring

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" />

Related

Spring mvc dispatcher configuration

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]'

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>

Spring ContentNegotiatingViewResolver - How to use bean name for jsp view not full url with path parameters

My servlet-context file has
<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<beans:property name="useNotAcceptableStatusCode"
value="false" />
<beans:property name="contentNegotiationManager">
<beans:bean
class="org.springframework.web.accept.ContentNegotiationManager">
<beans:constructor-arg>
<beans:bean
class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<beans:constructor-arg>
<beans:map>
<beans:entry key="html" value="text/html" />
<beans:entry key="json" value="application/json" />
</beans:map>
</beans:constructor-arg>
</beans:bean>
</beans:constructor-arg>
</beans:bean>
</beans:property>
<beans:property name="viewResolvers">
<beans:list>
<beans:bean
class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<beans:bean id="jspView"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/jsp/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:list>
</beans:property>
<beans:property name="defaultViews">
<beans:list>
<beans:bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
</beans:list>
</beans:property>
</beans:bean>
My Controller File has
#Controller("resources")
public class Resources {
#RequestMapping(value = "/resources/{name}", method = RequestMethod.GET)
public Map getResource(#PathVariable String name) {
return new HashMap();
}
}
But whenever i try to access /server/resources/myfilename.html
Server throws 404 saying /server/WEB-INF/jsp/resources/myfilename.jsp is not found.
But it should load /server/WEB-INF/jsp/resources.jsp as im using BeanNameViewResolver. Please help.
What you get:
Controller return a null view name, so DefaultRequestToViewNameTranslator generates one from URI = path from servlet path without slashes and filename extension: resources/myfilename
BeanNameViewResolver try to get a View from context named resources/myfilename, seem that fails and chain to next ViewResolver
InternalResourceViewResolver return a JstlView pointing to jsp prefix + viewName + suffix = /WEB-INF/jsp/resources/myfilename.jsp
So BeanNameViewResolver seems that don't resolve the view and the return of InternalResourceViewResolver is the expected one.
What you want (I think)
You want to remove the filename from the default view name, not only the extension.
Implements a RequestToViewNameTranslator and declare it in the DispatcherServlet context with name viewNameTranslator.
For example:
public class StripFileNameViewNameTranslator extends DefaultRequestToViewNameTranslator {
#Override
protected String transformPath(String lookupPath) {
String path = super.transformPath(lookupPath);
return StringUtils.substringBeforeLast(path, "/");
}
}

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.

spring 3 my converter is not used

...but registered
Using Spring 3
I have two converters registered as follows:
<beans:bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<beans:property name="converters">
<beans:list>
<beans:bean class="mypackage.CalendarToStringConverter" />
<beans:bean class="mypackage.StringToCalendarConverter" />
</beans:list>
</beans:property>
</beans:bean>
The converters look like this:
public class StringToCalendarConverter implements Converter< String, Calendar > {
public Calendar convert( String value ) {
return Calendar.getInstance();
}
}
public class CalendarToStringConverter implements Converter< Calendar, String > {
public String convert( Calendar arg0 ) {
return "23.10.1985";
}
}
The problem is that they are not used during conversion in post and get requests.
What am I doing wrong?
What do I havt to do to get this working?
THX!
Are you using <mvc:annotation-driven> and if so, are you pointing to conversionService in the conversion-service attribute?
Here's the converters configuration that works for me. The differences you might try changing:
I pass in a set instead of a list. (setConverters takes a Set parameter)
I use FormattingConversionServiceFactoryBean instead of ConversionServiceFactoryBean. (Should not matter)
My converters are defined as top level beans and referenced. (Also should not matter)
Hopefully one of this will fix your problem.
<util:set id="converters" >
<ref bean="userDao" />
<ref bean="orderDao" />
<util:set>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters" ref="converters"/>
</bean>

Resources