So I'm trying to parse an xml and unmarshal it into a program. This is the example xml:
<MaintenanceTransaction:provideCommunicationEvents_BatchRequest
xmlns:MaintenanceTransaction="http://www.pwx.com/Interface/CRS/MaintenanceTransaction_v02"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<MaintenanceTransaction:maintenanceTransaction>
<MaintenanceTransaction:eventInitiatedBy>
<MaintenanceTransaction:identifier>FINACLE</MaintenanceTransaction:identifier>
</MaintenanceTransaction:eventInitiatedBy>
<MaintenanceTransaction:transactionDate>2014-06-21T19:00:32.356+01:00</MaintenanceTransaction:transactionDate>
<MaintenanceTransaction:maintenanceTransactionType>PRE-NOTIFICATION
</MaintenanceTransaction:maintenanceTransactionType>
<MaintenanceTransaction:maintenanceEntries>
<MaintenanceTransaction:hasNewValues xsi:type="MaintenanceTransaction:DepositArrangement">
<MaintenanceTransaction:enterpriseId xsi:type="MaintenanceTransaction:ArrangementIdentifier">
<MaintenanceTransaction:identifier>222000000322</MaintenanceTransaction:identifier>
<MaintenanceTransaction:enterpriseIdType>Term Deposit</MaintenanceTransaction:enterpriseIdType>
</MaintenanceTransaction:enterpriseId>
<MaintenanceTransaction:maturityDate>2014-10-08</MaintenanceTransaction:maturityDate>
</MaintenanceTransaction:hasNewValues>
</MaintenanceTransaction:maintenanceEntries>
</MaintenanceTransaction:maintenanceTransaction>
</MaintenanceTransaction:provideCommunicationEvents_BatchRequest>
The xsd is defined as:
<xsd:schema xmlns:MaintenanceTransaction="http://www.pwx.com/Interface/CRS/MaintenanceTransaction_v02" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.pwx.com/Interface/CRS/MaintenanceTransaction_v02" elementFormDefault="qualified" attributeFormDefault="qualified">
<xsd:include schemaLocation="./commonIFWxsd/IFWXML.xsd" />
<xsd:include schemaLocation="./commonIFWxsd/Event.xsd" />
<xsd:include schemaLocation="./commonIFWxsd/Arrangement.xsd" />
<!-- end of TYPES REQUIRED FOR PARAMETERS -->
<xsd:complexType name="provideCommunicationEvents_BatchRequest">
<xsd:sequence>
<xsd:element name="maintenanceTransaction" type="MaintenanceTransaction:MaintenanceTransaction" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
<!-- TYPES REQUIRED FOR PARAMETERS -->
<xsd:element name="provideCommunicationEvents_BatchRequest" type="MaintenanceTransaction:provideCommunicationEvents_BatchRequest" />
</xsd:schema>
With the following setup of my StaxEventItemReader and Jaxb2Marshaller:
<bean id="uploadEventMessageReader" parent="abstractUploadEventMessageReader" scope="step">
<property name="resource" value="file:#{jobExecutionContext['fileToProcess']}"/>
<property name="fragmentRootElementName" value="maintenanceTransaction"/>
<property name="unmarshaller" ref="maintenanceTransactionUnmarshaller"/>
</bean>
<bean id="maintenanceTransactionUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" scope="step">
<property name="classesToBeBound">
<list>
<value>com.pwx.crs.informationcollection.ifw.process.model.mt.MaintenanceTransaction</value>
</list>
</property>
</bean>
The problem however is that I get the following exception.
* [javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.pwx.com/Interface/CRS/MaintenanceTransaction_v02", local:"maintenanceTransaction"). Expected elements are (none)] on step uploadEventMessages, with message: uploadEventMessagesStep.
* --stacktrace:com.pwx.crs.frwk.exp.technical.CRS2UnexpectedBatchException: An unexpected exception occurred in batch job JAXB unmarshalling exception; nested exception is javax.xml.bind.UnmarshalException
Any idea what this is about?
When I slightly change the maintenanceTransaction opening tag of the input xml like this:
<MaintenanceTransaction:maintenanceTransaction xsi:type="MaintenanceTransaction:MaintenanceTransaction">
It does work. But that is not a solution as the clients won't deliver the input xml's like that. So why is the error occuring? There seems to be a problem with determining which class maintenanceTransaction is part of.
Also tried different approaches on the marshaller bean definition:
<bean id="maintenanceTransactionUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" scope="step">
<property name="contextPath" value="com.pwx.crs.informationcollection.ifw.process.model.mt"/>
</bean>
and
<bean id="maintenanceTransactionUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" scope="step">
<property name="classesToBeBound">
<list>
<value>com.pwx.crs.informationcollection.ifw.process.model.mt.ObjectFactory</value>
</list>
</property>
</bean>
The results for both are the same and similar to the first error
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.pwx.com/Interface/CRS/MaintenanceTransaction_v02", local:"maintenanceTransaction"). Expected elements are <{http://www.pwx.com/Interface/CRS/MaintenanceTransaction_v02}AccessTokenLifecycleStatus>
... and here the whole list of classes in the package.
But the xml is perfectly valid against the xsd, as that is done beforehand. Idea's, suggestions, ... that I could try?
Here's my theory.
What mappedClass actually does is switches the unmarshalling method from unmarshaller.unmarshal(source) to unmarshaller.unmarshal(source, this.mappedClass). This is called "partial unmarshalling", i.e. you can unmarshal a known class from some element regardless of the element name.
So, as you say, this works for you. And it does not without mappedClass. This would mean that you are missing an element declaration for your root element. This also alignes well with the error you have reported:
javax.xml.bind.UnmarshalException: unexpected element
(uri:"http://www.pwx.com/Interface/CRS/MaintenanceTransaction_v02",
local:"maintenanceTransaction"). Expected elements are (none)
Which says basically the same thing.
This is also correct. As your schema does not declare a global element for the maintenanceTransaction, only for provideCommunicationEvents_BatchRequest.
So, basically you're unmarshalling the wrong element. And as your schema does not have a declaration for that, this fails. But if you specify exactly which type you want (thus providing the declaration "explicitly"), then it works.
Next, the question is, why do you you unmarshal the wrong element. My guess is that this is because you have
<property name="fragmentRootElementName" value="maintenanceTransaction"/>
This probably points the unmarshaller to use the maintenanceTransaction element as the root element. So the unmarshaller is applied to the wrong element.
Using contextPath, adding more bound classes etc. does not help as none of it adds the element declaration for the maintenanceTransaction.
Now, how to fix this. I see the following options:
Add a global element for maintenanceTransaction to your schema
(OR) Customize your schema to generate an additional #XmlRootElement for MaintenanceTransaction
(OR) Don't use the fragmentRootElementName, unmarshal provideCommunicationEvents_BatchRequest
(OR) Leave it as is with mappedClass
If you handle a specific case here, namely maintenanceTransaction then I'd use the fragmentRootElementName/mappedClass combo. Just as you do now.
So after researching through the code and debugging and much more labour I ended up with something that works. I don't exactly know why, as it was a guess, but it works.
<bean id="maintenanceTransactionUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.pwx.crs.informationcollection.ifw.process.model.mt.MaintenanceTransaction</value>
</list>
</property>
<property name="mappedClass" value="com.pwx.crs.informationcollection.ifw.process.model.mt.MaintenanceTransaction"/>
</bean>
As you can see it was not necessary to use the ObjectFactory as classesToBeBound (But it has to be noted that it would have worked as well but in my opinion this is more readable). The thing that really fixes it is adding a mappedClass.
From what I have seen in the code while debugging (I could not check the code f UnmarshallingImpl as this is part of rt.jar and this is not public even though it is part of the jre ...) The classesToBeBound parameter is used to create the jaxbContext for the unmarshaller and the mappedClass is passed to this unmarshaller as expectedType. But when this is not provided and the ObjectFactory is used as parameter the error clearly shows a list of expected classes and the one applicable is present ... Maybe a bug in the unmarshaller, maybe something that I don't understand. But my root problem is solved.
When creating a JAXBContext on a model generated from an XML Schema you should do one of the following to get all the necessary metadata:
Option #1 - Create it on the Generated ObjectFactory Class
<bean id="maintenanceTransactionUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" scope="step">
<property name="classesToBeBound">
<list>
<value>com.pwx.crs.informationcollection.ifw.process.model.mt.ObjectFactory</value>
</list>
</property>
</bean>
Option #2 - Create it on the Package Name(s) of the Generated Model
<bean id="maintenanceTransactionUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" scope="step">
<property name="contextPath" value="com.pwx.crs.informationcollection.ifw.process.model.mt"/>
</bean>
Related
Assume that I have AnimalData and AnimalListData:
<bean class="com.chang.data.AnimalData">
<property name="name" type="java.lang.String"/>
<property name="weight" type="java.lang.Integer"/>
</bean>
<bean class="com.chang.data.AnimalListData">
<property name="animals" type="java.util.List<com.chang.data.AnimalData>"/>
</bean>
If I create ZooData with a list of AnimalData, is it a better to use a List of Data objects (Approach #1) or a ListData object (Approach #2)? When should I use Approach #1 or Approach #2? How about for WsDTOs? Is the case the same?
Approach #1:
<bean class="com.chang.data.ZooData">
<property name="animals" type="java.util.List<com.chang.data.AnimalData>"/>
</bean>
Approach #2:
<bean class="com.chang.data.ZooData">
<property name="animals" type="com.chang.data.AnimalListData"/>
</bean>
It doesn't make a great deal of difference in my opinion, so some of this is personal preference. The thing I would think about is: in approach 2 you have to do zooData.getAnimals().getAnimals(), whereas in approach 1 it is zooData.getAnimals(). The same applies for the DTOs point. So approach 1 seems more intuitive to me .....
Approach #2.
Think from a real-world mapping perspective. Do you actually have a real-world object AnimalListData?AnimalData, on the other hand, is actually a real-world object that can directly be mapped to get detail of the animal. The list is just an abstract construct that you have created to simplify your programming otherwise it does not exist.
In a property file a variable test has been defined:
test=OLD_VALUE
In the following Spring-DSL definition a camel route is defined. Properties are loaded via PropertiesComponent.
<bean id="properties" class="org.apache.camel.component.properties.PropertiesComponent">
<property name="cache" value="false"/>
<property name="location" value="classpath:res.properties"/>
</bean>
<camelContext id="ctx" xmlns="http://camel.apache.org/schema/spring">
<route id="toParamRoute">
<from uri="servlet:myParam"/>
HERE I WOULD LIKE TO SET THE
VARIABLE TEST WITH A NEW VALUE,
SUCH THAT THE FOLLOWING LOG MESSAGE
WILL PRINT THE NEW VALUE,
E.G: test=NEW_VALUE
<log message="{{test}}"/>
</route>
</camelContext>
I tried different approach using groovy, language script expression, external spring bean but without success. Is there a way to set and change the value of a variable loaded at startup?
What is the best way to do it?
Anyone can help me? I did not find any similar question on stackoverflow! The problem I am facing and the solution I am looking for is a basic building-block to build a WEB UI management console to change some behavior of routes on the fly. To simplify the flow I can say that after propertyPlaceholder has loaded a property file then via a UI web page the default parameters of routes can be changed, and only after the route can be started.
Properties evaluated with syntax {{property}} are resolved only once during context initialization. If you need to reflect runtime changes, use Simple language
Example:
<bean id="myProperties" class="java.util.Properties"/>
<bean id="properties" class="org.apache.camel.component.properties.PropertiesComponent">
<property name="cache" value="false"/>
<property name="location" value="classpath:res.properties"/>
<property name="overrideProperties" ref="myProperties" />
</bean>
<camelContext id="ctx" xmlns="http://camel.apache.org/schema/spring">
<route id="toParamRoute">
<from uri="timer://foo"/>
<log message="About to change property test from value ${properties:test} to value ${exchangeProperty.CamelTimerCounter}. Initial value was {{test}}"/>
<bean ref="myProperties" method="setProperty(test, ${exchangeProperty.CamelTimerCounter})" />
<log message="New value is ${properties:test}"/>
</route>
</camelContext>
Using XML configuration - I have MarshallingMessageConverter working; however, I still want to send some messages as TextMessage with simple String values.
It seems that my configuration is forcing me to go from one ditch (No automatic JAXB marshalling) into the other (JAXB marshalling only):
Here's my relevant XML configuration:
<bean id="jaxbConverter" class="org.springframework.jms.support.converter.MarshallingMessageConverter">
<property name="marshaller" ref="jaxb2Marshaller" />
<property name="unmarshaller" ref="jaxb2Marshaller" />
</bean>
<bean id="jmsListenerContainerFactory"
class="org.springframework.jms.config.DefaultJmsListenerContainerFactory">
<property name="errorHandler" ref="jmsErrorHandler" />
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destinationResolver" ref="jmsDestinationResolver"/>
<property name="messageConverter" ref="jaxbConverter" />
</bean>
The JAXB marshalling works fine, but I sometimes want to send an empty body (header properties only) message; which causes an error like so:
.UnmarshallingFailureException: JAXB unmarshalling exception; nested exception is javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.]
Which makes sense, because I'm sending a non-JAXB string (or nothing) in the body.
Is it possible to have the best of both worlds; the String, byte[], Map conversion behavior of org.springframework.jms.support.converter.SimpleMessageConverter -and- org.springframework.jms.support.converter.MarshallingMessageConverter ?
Is the only way to accomplish this by making a second container factory with the other converter and explicitly using it in my #JmsListener annotation?
Create a simple DelegatingMessageConverter(implement MessageConverter) and have it delegate to the SimpleMessageConverter, MarshallingMessageConverter (or even a MappingJackson2MessageConverter) based on a message property, e.g. message.getStringProperty("contentType") - text/plain, application/xml, application/json.
I have gone through other post of rendering the view using spring3.2.5 & tiles3
in my context-servlet.xml
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
In my tiles-servlet.xml
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/common/tiles.xml</value>
<value>/WEB-INF/tiles/common/base_tiles.xml</value>
<value>/WEB-INF/tiles/common/person_tiles.xml</value>
</list>
</property>
</bean>
In person_tiles.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="new_person" extends="base.definition">
<put-attribute name="body" value="/WEB-INF/xx/xxx/web_person.jsp" />
</definition>
</tiles-defnitions>
It throws below error
javax.servlet.ServletException: Could not resolve view with name 'new_person' in servlet with name 'project'
please help me to solve the issue.
Related issue discussing this "behavior" is SPR-11491 and is specific to Tiles v3.
It comes from SpringWildcardServletTilesApplicationContext.getResources(String) -> URLApplicationResource(String, URL) constructor -> super PostfixedApplicationResource(String localePath) constructor. When there is an underscore in definition filenames, the string after the last underscore is identified as the locale.
The Tiles section of Spring 4.0.3 reference documentation has been updated in order to make this behavior more explicit, and there are ongoing discussion with Tiles development team to get this fixed by checking the locale against Locale.getISOLanguageCodes() in order to get a less surprising default behavior.
After lot of digging I found that tiles is not loading the resources properly.
Here i am not sure whether it is a bug (spring 3.2.5 & tiles 3.0.1) or not:
But I solved this issue by following
here in my tiles-servlet.xml
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/common/tiles.xml</value>
<value>/WEB-INF/tiles/common/baseTiles.xml</value><!-- Change the base_tiles to baseTiles.xml or base.xml -->
<value>/WEB-INF/tiles/common/personTiles.xml</value><!-- Change the person_tiles.xml to personTiles.xml or person.xml-->
</list>
</property>
</bean>
Here when we have the definitions value as separated with underscore (ex: person_tiles or base_tiles) it is not loading the resource.However tiles.xml the tiles-definitions are accessible.
But I tried with tiles 2.2 & spring 3.2.5 it works correctly. Even though we give as person_tiles or base_tiles.xml.
In tiles-servlet.xml
Change the base_tiles & person_tiles to baseTiles & personTiles, and changed the file names accordingly.
OR
Change the base_tiles & person_tiles to base & person, and changed the file names accordingly.
I hope somebody can find it as useful.
I have configured content negotiation in my Spring MVC 3 app as follows:
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="0" />
<property name="favorPathExtension" value="true" />
<property name="defaultContentType">
<ref bean="htmlMediaType" />
</property>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<bean class="org.springframework.oxm.castor.CastorMarshaller" />
</property>
</bean>
</list>
</property>
<property name="viewResolvers">
<ref bean="tilesViewResolver" />
</property>
</bean>
This works very well -- all my views will render as html views with the 'normal' view templates, or as JSON or XML dumps of the view model data depending on the 'Accept' header.
However, this seems to be a bit of a security hole to me. Some of my actions are API-style actions, and are legitimately available in HTML or JSON or XML. However, some views are intended to be HTML-only. I don't really want end-users to be able to see all the view data just by adding ".json" to the url.
Is there any way to do content negotiation in Spring MVC, but only on actions which have explicitly opted-in to it? Can I set up a controller annotation like #RespondsTo("xml", "json")?
Why don't you use a filter through DelegatingFilterProxy to block users from accessing unnecessary content types ?
I was just facing the same problem. produces attribute of #RequestMapping helps for that. Although it's the opposite of what you asked for - kind of opt-out instead of opt-in, but I think it's what can please you.
#Controller
#RequestMapping("/categories")
public class CategoriesController
{
#RequestMapping(value = "/create", method = RequestMethod.GET, produces = "application/xhtml+xml")
public String createForm(Model model)
{
}
}
/create - works fine by displaying JSP view
/create.json - 406 Error
One way to do it would be to use Spring Security to restrict which pages can be seen based on the content-type (or whatever other method(s) you are using for content negotiation.