Multilne xml file on Spring batch - java

i used Spring Batch to read a database an write a xml file, but i cant find some configuration to make a multiple xml line file, i need on this way:
<xmlRecord><name>RecordOne</name></xmlRecord>
<xmlRecord><name>RecordTwo</name></xmlRecord>
each record into a line
but i only can created on this way:
<xmlRecord><name>RecordOne</name></xmlRecord><xmlRecord><name>RecordTwo</name></xmlRecord>
that is my configuration:
<bean id="itemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter" scope="step">
<property name="resource"
value="file:/var/opt/result.tmp" />
<property name="marshaller" ref="userUnmarshaller" />
<property name="overwriteOutput" value="true" />
<property name="RootTagName" value="!-- --"/>
</bean>
Marshal bean configuration:
<bean id="userUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>my.jaxb.data.TCRMService</value>
</list>
</property>
<property name="marshallerProperties">
<map>
<entry>
<key><util:constant static-field="javax.xml.bind.helpers.AbstractMarshallerImpl.JAXB_SCHEMA_LOCATION"/></key>
<value>http://www.ibm.com/mdm/schema MDMDomains.xsd</value>
</entry>
</map>
</property>
</bean>
Someone can help me or provide me some configuration to solve my problem?

Use below unmarshaller configuration:-
<bean id="userUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list> your_class </list>
</property>
<property name="marshallerProperties">
<map>
<entry>
<key>
<util:constant static-field="javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT" />
</key>
<value type="java.lang.Boolean">true</value>
</entry>
</map>
</property>
</bean>
you can also do, something like below:-
<property name="marshallerProperties">
<map>
<entry key="jaxb.formatted.output">
<value type="boolean">true</value>
</entry>
</map>
</property>

Related

Weird numbers in generated CSV with Spring Batch

I am developing a Spring batch to get data from a table and into a CSV file. This is the table I am extracting data from:
CREATE TABLE TMP_SYNCHRONIZED_RSLT
(SERIAL_QA NUMBER(20) UNIQUE
, NB_RECENT VARCHAR2(10)
, NB_ARTICLE VARCHAR2(2)
);
I have my reader as follows:
<bean id="serialNumbersReader" class="org.springframework.batch.item.database.JdbcCursorItemReader" scope="step">
<property name="fetchSize" value="${batch.job.fetch.interval}" />
<property name="dataSource" ref="dataSource" />
<property name="rowMapper">
<bean class="org.springframework.jdbc.core.BeanPropertyRowMapper">
<property name="mappedClass" value="ca.org.serialNumbersGenerationBatch.batch.synchronization.dto.ExtractSerialNumbersDto" />
</bean>
</property>
<property name="sql">
<value>
<![CDATA[
SELECT SERIAL_QA, NB_RECENT, NB_ARTICLE from TMP_SYNCHRONIZED_RSLT
]]>
</value>
</property>
</bean>
And my writer:
<bean id="csvWriteSerialNumbers"
class="org.springframework.batch.item.file.FlatFileItemWriter">
<property name="lineAggregator">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="delimiter" value=";" />
<property name="fieldExtractor">
<bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names" value="serialQa, nbRecent, nbArticle" />
</bean>
</property>
</bean>
</property>
<property name="encoding" value="${csv.encoding}" />
<property name="headerCallback">
<bean class="fr.canalplus.cgaweb.batch.common.writer.StringHeaderFooterCallback">
<property name="header" value="SERIAL_QA;NB_RECENT;NB_ARTICLE" />
</bean>
</property>
<property name="resource" value="file:${tmp.dir}/serialNumbers.csv" />
</bean>
my csv.encoding = ISO-8859-1. And I put String in all of my DTO attributes.
This generates weird numbers like 2,49254E+12 instead of 24925418071 in my CSV under SERIAL_QA. Any idea on how to resolve this without changing the column type?

Could not open JDBC Connection for transaction

I would like to report a configuration problem that seems strange to me.
Here's the application context configuration file I'm using
<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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<bean id="processingStratagyContainer" class="ru.rt.mnp.translator.converter.process.ProcessingStratagyContainer">
<property name="fileProcessingStratagyMap">
<map>
<entry key="Port_Increment" value-ref="portIncrementProcessingStratagy"/>
<entry key="Return_Increment" value-ref="returnIncrementProcessingStratagy"/>
<entry key="Port_All" value-ref="portAllProcessingStratagy"/>
</map>
</property>
</bean>
<!--�������� ������������������ ������������������ ������������-->
<bean id="portIncrementProcessingStratagy"
class="ru.rt.mnp.translator.converter.process.PortIncrementProcessingStratagy">
<property name="rowSizeColumnPosition" value="11"/>
<property name="columnBindings">
<map>
<!--first has index 0-->
<entry key="1" value="number[java.lang.String]"/>
<entry key="5" value="old_route[java.lang.String]"/>
<entry key="6" value="new_route[java.lang.String]"/>
<entry key="9" value="region_code[java.lang.String]"/>
<entry key="10" value="port_date[java.util.Date]{yyyy-MM-dd'T'HH:mm:ssXXX}"/>
</map>
</property>
</bean>
<bean id="returnIncrementProcessingStratagy"
class="ru.rt.mnp.translator.converter.process.ReturnIncrementProcessingStratagy">
<property name="rowSizeColumnPosition" value="9"/>
<property name="columnBindings">
<map>
<!--first has index 0-->
<entry key="1" value="number[java.lang.String]"/>
<entry key="5" value="old_route[java.lang.String]"/>
<entry key="6" value="new_route[java.lang.String]"/>
<entry key="7" value="region_code[java.lang.String]"/>
<entry key="8" value="port_date[java.util.Date]{yyyy-MM-dd'T'HH:mm:ssXXX}"/>
</map>
</property>
</bean>
<bean id="portAllProcessingStratagy"
class="ru.rt.mnp.translator.converter.process.PortAllProcessingStratagy">
<property name="rowSizeColumnPosition" value="6"/>
<property name="columnBindings">
<map>
<!--first has index 0-->
<entry key="0" value="number[java.lang.String]"/>
<entry key="3" value="new_route[java.lang.String]"/>
<entry key="4" value="region_code[java.lang.String]"/>
<entry key="5" value="port_date[java.util.Date]{yyyy-MM-dd'T'HH:mm:ssXXX}"/>
</map>
</property>
</bean>
<bean id="postProcessingStratagyContainer" class="ru.rt.mnp.translator.converter.postprocess.PostProcessingStratagyContainer">
<property name="postProcessingStratagableMap">
<map>
<entry key="Port_Increment" value-ref="mnpTrfPartPostProcessingStratagy"/>
<entry key="Return_Increment" value-ref="mnpTrfPartPostProcessingStratagy"/>
<entry key="Port_All" value-ref="mnpTrfFullPostProcessingStratagy"/>
<entry key="IncrementCounter" value-ref="incrementCounterPostProcessingStratagy"/>
<entry key="HistoryRequestFull" value-ref="historyRequestFullPostProcessingStratagy"/>
<entry key="HistoryRequestPart" value-ref="historyRequestPartPostProcessingStratagy"/>
</map>
</property>
</bean>
<bean id="mnpTrfPartPostProcessingStratagy"
class="ru.rt.mnp.translator.converter.postprocess.MnpTrfPartPostProcessingStratagy" >
<property name="placeInPostProcessingChain" value="1"/>
</bean>
<bean id="mnpTrfFullPostProcessingStratagy"
class="ru.rt.mnp.translator.converter.postprocess.MnpTrfFullPostProcessingStratagy" >
<property name="placeInPostProcessingChain" value="2"/>
</bean>
<bean id="incrementCounterPostProcessingStratagy"
class="ru.rt.mnp.translator.converter.postprocess.IncrementCounterPostProcessingStratagy" >
<property name="placeInPostProcessingChain" value="9"/>
</bean>
<bean id="historyRequestFullPostProcessingStratagy"
class="ru.rt.mnp.translator.converter.postprocess.HistoryRequestFullPostProcessingStratagy" >
<property name="placeInPostProcessingChain" value="4"/>
</bean>
<bean id="historyRequestPartPostProcessingStratagy"
class="ru.rt.mnp.translator.converter.postprocess.HistoryRequestPartPostProcessingStratagy">
<property name="placeInPostProcessingChain" value="3"/>
</bean>
<bean id="convertTask" class="ru.rt.mnp.translator.converter.job.ConvertTask"/>
<bean id="testTask" class="ru.rt.mnp.translator.converter.job.TestTask"/>
<bean id="historyRequestTask" class="ru.rt.mnp.translator.converter.job.HistoryRequestTask"/>
**<bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="${url}"/>
<property name="username" value="****"/>
<property name="password" value="****"/>
</bean>**
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="mnpHistoryDao" class="ru.rt.mnp.translator.converter.storage.MnpHistoryDao">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
<!-- specifing class and method that is going to be called on a specified
time basis -->
<bean id="convertJob"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="convertTask"/>
<property name="targetMethod" value="execute"/>
</bean>
<bean id="convertTestJob"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="testTask"/>
<property name="targetMethod" value="execute"/>
</bean>
<bean id="historyRequestJob"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="historyRequestTask"/>
<property name="targetMethod" value="execute"/>
</bean>
<!-- simple trigger specify repeat interval and delay time -->
<bean id="cronTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="convertJob"/>
<!--<property name="cronExpression" value="0 5 0,2,4,6,8,10,12,14,16,18,20,22 ? * *"/>-->
<property name="cronExpression" value="0 15,45 * ? * *"/>
<property name="startDelay" value="1000"/>
</bean>
<bean id="cronTestTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="convertTestJob"/>
<property name="cronExpression" value="0 0/10 * ? * *"/>
<property name="startDelay" value="1000"/>
</bean>
<bean id="cronHistoryRequestTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="historyRequestJob"/>
<property name="cronExpression" value="0/10 * * ? * *"/>
<property name="startDelay" value="1000"/>
</bean>
<!-- scheduler factory bean to bind,the executing code and time intervals
together -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="configLocation" value="classpath:quartz.properties"/>
<property name="jobDetails">
<list>
<ref bean="convertJob"/>
<ref bean="convertTestJob"/>
<ref bean="historyRequestJob"/>
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
<ref bean="cronTestTrigger"/>
<ref bean="cronHistoryRequestTrigger"/>
</list>
</property>
</bean>
But when run the converting action, i have this error:
Problems with processing file /***.zip
org.springframework.transaction.CannotCreateTransactionException:
Could not open JDBC Connection for transaction; nested exception is
java.sql.SQLException: Connection was closed in
SingleConnectionDataSource. Check that user code checks shouldClose()
before closing Connections, or set 'suppressClose' to 'true'
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:241)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:417)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:255)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy5.processFile(Unknown Source)
at ru.rt.mnp.translator.converter.job.ConvertTask.execute(ConvertTask.java:69)
at sun.reflect.GeneratedMethodAccessor12.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:311)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:113)
at org.quartz.core.JobRunShell.run(JobRunShell.java:207)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:560)
Caused by: java.sql.SQLException: Connection was closed in
SingleConnectionDataSource. Check that user code checks shouldClose()
before closing Connections, or set 'suppressClose' to 'true'
at org.springframework.jdbc.datasource.SingleConnectionDataSource.getConnection(SingleConnectionDataSource.java:189)
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:203)
Can anyone explain me what is the problem ?
What should i do to fix this?
Thank you!
I had to use SingleConnectionDataSource in a web application using SpringBoot. We were also using an ORM package for all db transactions and I had this same issue even with suppressClose configured to true. It works fine during the first login, but when the connection is left idle for a long time, then the below error occurs.
The error was
java.sql.SQLException: Connection was closed in SingleConnectionDataSource. Check that user code checks shouldClose() before closing Connections, or set 'suppressClose' to 'true'
at org.springframework.jdbc.datasource.SingleConnectionDataSource.getConnection(SingleConnectionDataSource.java:167)
Finally configuring the data source as a session scoped object resolved it. It was a singleton before, re-configuring it to session scope resolved the issue.
<bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource" scope="session">

Passing URL through Spring XML in java class

I want to pass the URL in the XML file of spring and access that Url in the java class.
This file links with a java file and I want to access this file in the java class file.
Hello.XML file
<beans profile="motzie_qa">
<bean id="testProperties" class="com.motzie.TestProperties">
<property name="baseUrl" value="${10.10.5.88}" />
<property name="users">
<map>
<entry>
<key>
<util:constant static-field="com.motzie.bean.User.Role.ADMIN" />
</key>
<bean class="com.motzie.bean.User">
<constructor-arg value="testadmin#qasource.com" />
<constructor-arg value="admin" />
</bean>
</entry>
<entry>
<key>
<util:constant static-field="com.motzie.bean.User.Role.MASTER" />
</key>
<bean class="com.motzie.bean.User">
<constructor-arg value="test#qasource.com" />
<constructor-arg value="test$123" />
</bean>
</entry>
</map>
</property>
</bean>
</beans>
</beans>

Send order Confirmation Email- Broadleaf

I went through the documentation of Broadleaf to send Email confirmation
Below is my applicationcontext-email.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!-- A dummy mail sender has been set to send emails for testing purposes
only To view the emails sent use "DevNull SMTP" (download separately) with
the following setting: Port: 30000 -->
<!-- Broadleaf step 3 -->
<bean id="blServerInfo"
class="org.broadleafcommerce.common.email.service.info.ServerInfo">
<property name="serverName" value="smtp.office365.com" />
<property name="serverPort" value="587" />
</bean>
<bean id="blEmailTemplateResolver"
class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
<property name="prefix" value="emailTemplates/" />
<property name="suffix" value=".html" />
<property name="cacheable" value="${cache.page.templates}" />
<property name="cacheTTLMs" value="${cache.page.templates.ttl}" />
</bean>
<bean id="blEmailTemplateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="blEmailTemplateResolver" />
</set>
</property>
<property name="dialects">
<set>
<bean class="org.thymeleaf.spring4.dialect.SpringStandardDialect" />
<ref bean="blDialect" />
</set>
</property>
</bean>
<!-- Broadleaf email step 1 -->
<bean id="blMessageCreator"
class="org.broadleafcommerce.common.email.service.message.ThymeleafMessageCreator">
<constructor-arg ref="blEmailTemplateEngine" />
<constructor-arg ref="blMailSender" />
</bean>
<bean id="blEmailInfo"
class="org.broadleafcommerce.common.email.service.info.EmailInfo">
<property name="fromAddress">
<value>mulaygaurav3#gmail.com</value>
</property>
<property name="sendAsyncPriority">
<value>2</value>
</property>
<property name="sendEmailReliableAsync">
<value>false</value>
</property>
</bean>
<bean id="blMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>localhost</value>
</property>
<property name="port">
<value>30000</value>
</property>
<property name="protocol">
<value>smtp</value>
</property>
<property name="username">
<value>gaurav</value>
</property>
<property name="password">
<value>mypassword</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
</bean>
<bean id="blVelocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/emailTemplates/" />
<property name="velocityProperties">
<value>
resource.loader=file,class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
runtime.references.strict = false
</value>
</property>
</bean>
<bean id="blMessageCreator"
class="org.broadleafcommerce.common.email.service.message.VelocityMessageCreator">
<constructor-arg ref="blVelocityEngine" />
<constructor-arg ref="blMailSender" />
<constructor-arg>
<map>
<entry key="number">
<bean class="org.apache.velocity.tools.generic.NumberTool"
scope="prototype" />
</entry>
<entry key="date">
<bean class="org.apache.velocity.tools.generic.ComparisonDateTool"
scope="prototype" />
</entry>
<entry key="list">
<bean class="org.apache.velocity.tools.generic.ListTool"
scope="prototype" />
</entry>
<entry key="math">
<bean class="org.apache.velocity.tools.generic.MathTool"
scope="prototype" />
</entry>
<entry key="iterator">
<bean class="org.apache.velocity.tools.generic.IteratorTool"
scope="prototype" />
</entry>
<entry key="alternator">
<bean class="org.apache.velocity.tools.generic.AlternatorTool"
scope="prototype" />
</entry>
<entry key="sorter">
<bean class="org.apache.velocity.tools.generic.SortTool"
scope="prototype" />
</entry>
<entry key="esc">
<bean class="org.apache.velocity.tools.generic.EscapeTool"
scope="prototype" />
</entry>
<entry key="serverInfo" value-ref="blServerInfo" />
</map>
</constructor-arg>
</bean>
<!-- <bean id="blMessageCreator" class="org.broadleafcommerce.common.email.service.message.NullMessageCreator">
<constructor-arg ref="blMailSender"/> </bean> -->
<bean id="blRegistrationEmailInfo" parent="blEmailInfo">
<property name="subject" value="You have successfully registered!" />
<property name="emailTemplate" value="register-email" />
</bean>
<bean id="blForgotPasswordEmailInfo" parent="blEmailInfo">
<property name="subject" value="Reset password request" />
<property name="emailTemplate" value="resetPassword-email" />
</bean>
<!-- Broadleaf email step 2 -->
<bean id="orderConfirmationEmailInfo" class="org.broadleafcommerce.common.email.service.info.EmailInfo" parent="blEmailInfo" scope="prototype">
<property name="messageBody" value="This is a test email!"/>
<property name="emailType" value="ORDERCONFIRMATION"/>
<property name="subject" value="Thank You For Your Order!"/>
</bean>
</beans>
I have also created an activity as mentioned in the documentation:
package com.mycompany.worklow.emailactivity;
import javax.annotation.Resource;
import org.broadleafcommerce.core.checkout.service.workflow.CheckoutSeed;
import org.broadleafcommerce.core.checkout.service.workflow.CompleteOrderActivity;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.workflow.ProcessContext;
import com.mycompany.service.MyEmailWebService;
enter code here
public class MyCompleteOrderActivity extends CompleteOrderActivity {
#Resource(name="myEmailService")
protected MyEmailWebService myEmailService;
#Override
public ProcessContext execute(ProcessContext context) throws Exception {
CheckoutSeed seed = (CheckoutSeed) context.getSeedData();
Order order = seed.getOrder();
myEmailService.sendOrderConfirmation(order.getSubmitDate(), order.getId().toString(), order.getCustomer().getEmailAddress());
return super.execute(context);
}
}
}
Also added this activity in the applicationcontext-workflow.xml
I am getting this below exxception:
Unable to merge source and patch locations; nested exception is org.broadleafcommerce.common.extensibility.context.merge.exceptions.MergeException: java.lang.NullPointerException
Can anybody explain the step by step procedure to implement the same?
Thanks in advance
You have to beans named blMessageCreator, remove one of them. Assuming you are using version 5 demo site, which uses thymeleaf templates then try removing:
<bean id="blMessageCreator" class="org.broadleafcommerce.common.email.service.message.VelocityMessageCreator">
...
...
</bean>

Validate format parameter via config in Spring MVC

Here is my situation:
I have my mvc-config.xml file for my web service set up to have JSON as the default media type. I also have favorParameter for the ContentNegotiatingViewResolver as true. Additionally, I have useNotAcceptableStatusCode as true so that not accepted formats will return a 406.
My question is: Is there a way, in the config, to trigger the 406 status code when someone passes in an unacceptable format parameter (format=foo)? Or must that be done with code?
Here is the config file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="com.work.stuff.web.view.json.ExtendedMappingJacksonJsonView">
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
</bean>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<ref bean="Jaxb2Marshaller" />
</property>
</bean>
</list>
</property>
<property name="defaultContentType" value="application/json" />
<property name="favorParameter" value="true" />
<property name="useNotAcceptableStatusCode" value="true" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
</bean>
<ref bean="marshallingHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="Jaxb2Marshaller" />
<property name="unmarshaller" ref="Jaxb2Marshaller" />
</bean>
<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="JacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="JacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="JacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
</list>
</property>
</bean>
<bean id="Jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.work.stuff.Concepts</value>
<value>com.work.stuff.Concept</value>
<value>com.work.stuff.Terms</value>
<value>com.work.stuff.Term</value>
<value>com.work.stuff.Namespaces</value>
<value>com.work.stuff.Namespace</value>
<value>com.work.stuff.Subsets</value>
<value>com.work.stuff.Subset</value>
<value>com.work.stuff.Associations</value>
<value>com.work.stuff.Association</value>
</list>
</property>
</bean>
</beans>
ContentNegotiatingViewResolver doesn't seem to support such behaviour. For now, I think your best bet is to subclass it and override the getMediaTypeFromParameter() method to throw an exception if the media type is not supported.
You can throw any RuntimeException from that method, and if you annotate the exception class with #ResponseStatus, you can control the HTTP response code, e.g.
#ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
public class FormatNotSupportedException extends RuntimeException {
}
In the longer term, I strongly encourage you to file an issue with http://jira.springsource.org, asking for such functionality to be added to ContentNegotiatingViewResolver. They should be able to add this as an optional behavioural parameter. It's requests like these that mean Spring keeps getting better.

Categories