How do i access an object in validation.xml in bean validation framework - spring-modules

My class:
public class Employee {
private String firstName;
private String lastName;
private Department department;
//with getters and setters
}
My employee-validation.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<validation xmlns="http://www.springmodules.org/validation/bean" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://localhost:8080/BVF http://localhost:8080/BVF/validation.xsd">
<class name="Employee">
<validator class="EmployeeValidator"/>
<property name="firstName">
<not-blank message="FirstName cannot be left blank"/>
<length min="5" max="20" message="First Name Length cannot be less than 5 or more than 20"/>
</property>
<property name="lastName">
<not-blank message="LastName cannot be left balnk"/>
<length min="5" max="20" message="Last Name Length cannot be less than 5 or more than 20"/>
</property>
<property name="department.name">
<not-blank message="Name cannot be blank"/>
<length min="5" max="20" message="Name Length cannot be less than 5 or more than 20"/>
</property>
<property name="department.pinCode">
<not-blank message="Pin Code cannot be left blank"/>
<regexp expression="^[A-Z\d{1}]\d{4}[\s\-]*\d*$" message="PinCode is invalid"/>
<length min="5" max="10" message="Pincode length should be between 5 and 10"/>
</property>
</class>
</validation>
can someone tell me how i can access the elements of department object, i.e. this part
<property name="department.pinCode">

i have found the solution, which is to use the cascade attribute.

Related

How to execute a spring batch job by clicking on a button in a jsp page?

I'm a newbie in spring batch and spring Mvc, and I want that a batch job (which extracts data from a database and writes it in another database) is executed from a jsp page by clicking on a button (or a link if it's possible) I'm using spring Mvc. This is my job configuration:
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="oracle" />
</bean>
<bean id="itemReader"
class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="dataSource" />
<property name="sql"
value="select id,name,qual from users" />
<property name="rowMapper">
<bean class="tn.com.spring.UserRowMapper" />
</property>
</bean>
<bean id="oracleitemWriter"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into users2(id,name,qual)
values (:id,:name,:qual)
]]>
</value>
</property>
<property name="itemSqlParameterSourceProvider">
<bean
class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
</property>
</bean>
<batch:job id="Job" job-repository="jobRepository">
<batch:step id="step1">
<batch:tasklet transaction-manager="transactionManager">
<batch:chunk reader="itemReader" writer="oracleitemWriter"
commit-interval=" 10">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script
location="org/springframework/batch/core/schema-drop-oracle10g.sql" />
<jdbc:script location="org/springframework/batch/core/schema-oracle10g.sql" />
</jdbc:initialize-database>
and this is my job controller (I found it in the net but still not working!)
#Component
#Controller()
public class JobController {
#Autowired
#Qualifier("JobLauncher")
private JobLauncher jobLauncher;
#Autowired
#Qualifier("Job")
private Job job;
#RequestMapping(value = "/job")
public void job() {
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
and here is the button
<form action=" <%=application.getContextPath()%>/job" method="get">
<input type="submit" value="execute My job" />
</form>
Could you please help me ? Whats's missing in my configuration?
I'm confused !
Thanks in advance.
As a solution for this problem, I have made this javascript code which will invoke the execution of the job :
$(function() {
$('#JobBtn').click(function() {
$.get('${batchJobUrl}');
});
});
and in the jsp page you need to specify the Id of the button writen in the javascript code:
<input type="button" value="execute job " id='JobBtn' class="btn" />
I Hope it will help someOne..

How can a Spring Webflow application be configured to use Xslt to render its viewstates

I would like my Spring Webflow app to render its views using XSLT. I managed to get a pure Spring MVC app to render with xslt by configuring an XSLTviewresolver and a controller method that returned an already prepared xml as a source.
But I'm not sure how to apply that to the webflow app.
I've added the configuration for the XSLT view resolver and set the view state to the xsl, then I call the controller method that returns the xml source in the on-render of the view state.So far I only get the xsl back as the output and not the transformed xml or even the raw xml.
EDIT
flow.xml-full
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
<view-state id="messageChoice" view="start1">
<transition on="chooseA" to="messageA"/>
<transition on="chooseB" to="messageB"/>
</view-state>
<view-state id="messageA" view="messageA">
<transition on="start" to="messageChoice"/>
</view-state>
<view-state id="messageB" view="xsltview">
<on-render>
<evaluate expression="sampleController.viewXSLT(externalContext.getNativeRequest(),externalContext.getNativeResponse())" result="requestScope.xmlSource"/>
</on-render>
<transition on="start" to="messageChoice"/>
</view-state>
<end-state id="finish"/>
</flow>
controller-snippet
#RequestMapping(value="/viewxslt")
public ModelAndView viewXSLT(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// builds absolute path of the XML file
String xmlFile = "/WEB-INF/xml/thexml.xml";
String contextPath = request.getSession().getServletContext().getRealPath(xmlFile);
String xmlFilePath = ""+contextPath + File.separator + xmlFile;
Source source = new StreamSource(new File(contextPath));
// adds the XML source file to the model so the XsltView can detect
ModelAndView model = new ModelAndView("xsltview");
model.addObject("xmlSource", source);
return model;
}
EDIT
flow-config-full
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
<context:annotation-config />
<context:component-scan base-package="com.genkey.derek" />
<mvc:view-controller path="/start" />
<mvc:view-controller path="/messageHome" />
<mvc:resources location="/" mapping="/resources/**" />
<faces:resources />
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="flowRegistry" />
<property name="order" value="3" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean id="xsltviewresolver" class="org.springframework.web.servlet.view.xslt.XsltViewResolver">
<property name="order" value="1"/>
<property name="sourceKey" value="xmlSource"/>
<property name="viewClass" value="org.springframework.web.servlet.view.xslt.XsltView"/>
<property name="viewNames">
<array>
<value>xsltview</value>
</array>
</property>
<property name="prefix" value="/WEB-INF/xsl/" />
<property name="suffix" value=".xsl" />
</bean>
<bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers">
<list>
<ref bean="xsltviewresolver"/>
<ref bean="faceletsViewResolver" />
</list>
</property>
</bean>
<bean id="faceletsViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.faces.mvc.JsfView"/>
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".xhtml" />
<property name="order">
<value>2</value>
</property>
</bean>
<bean class="org.springframework.faces.webflow.JsfFlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor" />
</bean>
<webflow:flow-executor id="flowExecutor">
<webflow:flow-execution-listeners>
<webflow:listener ref="facesContextListener"/>
</webflow:flow-execution-listeners>
</webflow:flow-executor>
<webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices" >
<webflow:flow-location path="WEB-INF/flows/startFlow.xml"/>
</webflow:flow-registry>
<faces:flow-builder-services id="flowBuilderServices" view-factory-creator="viewFactoryCreator" development="true" />
<bean id="facesContextListener" class="org.springframework.faces.webflow.FlowFacesContextLifecycleListener"/>
</beans>

Thymeleaf View not recognizing the specified action view

I am facing an issue with viewresolver. Thymeleaf viewresolver not picking up the specified view in my controller action method and it is taking action name as view path instead.
Below is my thymeleaf configuration and controller code.
Controller :
#ModelAttribute("user")
#RequestMapping(method = RequestMethod.POST, value = "/register")
public String register(Model model, #Valid User user, BindingResult result, HttpServletRequest request, final Locale locale) {if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
for (ObjectError error : errors) {
log.error("Errors are :: " + error.getDefaultMessage());
}
return "registration/indexed";
}else{------my operations------return "profile/index"}}
thymeleaf config..
<!-- THYMELEAF: Template Resolver for email templates -->
<bean id="emailTemplateResolver"
class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
<property name="prefix" value="mail/" />
<property name="templateMode" value="HTML5" />
<property name="order" value="2" />
<!-- Template cache is true by default. Set to false if you want -->
<!-- templates to be automatically updated when modified. -->
<property name="cacheable" value="true" />
</bean>
<!-- Thymeleaf template resolver -->
<bean id="webTemplateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="order" value="1" />
</bean>
<!-- THYMELEAF: Template Engine (Spring3-specific version) -->
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="emailTemplateResolver" />
<ref bean="webTemplateResolver" />
</set>
</property>
</bean>
<bean id="thymeleafViewResolver" class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="1" />
<property name="characterEncoding" value="UTF-8" />
</bean>
But my Thymeleaf not recognizing "registration/index" and it is searching for "registration/register"
Would anybody please suggest what I have to do??
Thanks & Regards,
Gupta Katakam
Finally I figured out the problem. The problem is due to #ModelAttribute("user") . When I removed this line on top of my action method the problem got resolved.
Thanks & Regards,
Gupta Katakam

Spring MVC 3.2 - XStreamAlias Ignored

Person.java:
#XStreamAlias("person")
public class Person {
#XStreamAlias("id")
private Long personProfileId;
private String lastName;
private String firstName;
private String middleName;
private String nameSuffix;
private String namePrefix;
// etc ...
}
Spring configuration:
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true" />
<property name="ignoreAcceptHeader" value="true" />
<property name="useJaf" value="false" />
<property name="defaultContentType" value="application/xml" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="contentNegotiationManager" ref="contentNegotiationManager" />
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
</constructor-arg>
</bean>
</list>
</property>
</bean>
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager" />
A call to http://mycompany.com:8080/myapp/persons?format=xml returns:
<?xml version="1.0" encoding="UTF-8"?>
<list>
<com.example.myapp.model.Person>
<personProfileId>1</personProfileId>
<lastName>McCartney</lastName>
<firstName>James</firstName>
<middleName>Paul</middleName>
</com.example.myapp.model.Person>
<com.example.myapp.model.Person>
<personProfileId>2</personProfileId>
<lastName>Lennon</lastName>
<firstName>John</firstName>
<middleName>Winston</middleName>
</com.example.myapp.model.Person>
<com.example.myapp.model.Person>
<personProfileId>3</personProfileId>
<lastName>Starkey</lastName>
<firstName>Richard</firstName>
</com.example.myapp.model.Person>
<com.example.myapp.model.Person>
<personProfileId>4</personProfileId>
<lastName>Harrison</lastName>
<firstName>George</firstName>
</com.example.myapp.model.Person>
</list>
I would expect it to return:
<?xml version="1.0" encoding="UTF-8"?>
<list>
<Person>
<id>1</id>
<lastName>McCartney</lastName>
<firstName>James</firstName>
<middleName>Paul</middleName>
</Person>
<Person>
<id>2</id>
<lastName>Lennon</lastName>
<firstName>John</firstName>
<middleName>Winston</middleName>
</Person>
<Person>
<id>3</id>
<lastName>Starkey</lastName>
<firstName>Richard</firstName>
</Person>
<Person>
<id>4</id>
<lastName>Harrison</lastName>
<firstName>George</firstName>
</Person>
</list>
It seems like XStream is correctly being called to marshall the object to XML, but that the #XStreamAlias annotations are being ignored. Is there some further configuration needed to get this to work?
I was trying to figure out this same thing (though with a Spring Boot project) and found an alternative: autodetectAnnotations.
xstreamMarshaller.setAutodetectAnnotations(true);
See this project, add the above line to the Application.java.
Figured it out. The annotated classes need to be explicitly identified to the XStreamMarshaller.
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="annotatedClasses">
<array>
<value>com.example.myapp.model.Person</value>
</array>
</property></bean>
</constructor-arg>
</bean>
</list>
</property>
As per XStream documentation https://x-stream.github.io/annotations-tutorial.html
you have to use xstream.processAnnotations(MyPOJO.class);

Not able to wire entityManager with applicationContext bean

I am facing a problem to wire entity manager with the bean present in application context.
whenever i do some operation it gives NullPointerException.
this is my applicationContext.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.ajit.retail"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost/retail"/>
<property name="username" value="retail_user"/>
<property name="password" value="password"/>
</bean>
<bean id="entityManagerOne" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQL82Dialect"/>
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerOne"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
this is the java file in which i am creating the entity manager
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class AbstractRepository {
#PersistenceContext
EntityManager entityManager;
}
so whenever i use this entity manager it gives null pointer exception
please help!
Your entity manager bean is called enetityManagerOne, but the variable is called entityManager. Maybe renamme your bean in your XML file:
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
Another solution could be you forgot the following bean declarations:
For the support for transaction:
<tx:annotation-driven/>
The support for parsing JPA annotations:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
my application context was not on the correct place (src/main/resources). Now I put that there and its working.
Use this code in your dispatcher-servlet.xml
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"/>
<property name="persistenceUnitName" value="etray"/>
</bean>
<jee:jndi-lookup id="dataSource" jndi-name="java:/prateek" />
<!-- we plan to use JTA transactions and declare them using annotations -->
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager" />
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- to inject instances of EntityManager using #PersistenceContext annotation -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
it resolve my problem, hope it will help.

Resources