Sun/Oracle JAXB RI bug? - jaxb

EDIT #1: I used JAXB RI 2.2.6 (latest as of today 12/06/12), and I
observe the same behavior :-(
I am using JAXB for unmarshalling XML payloads.
When I pass an invalid payload for the first time via Unmarshaller, I get the following type of error:
javax.xml.bind.UnmarshalException: Unable to create an instance of foo.bar.FooBarType
- with linked exception:
[java.lang.InstantiationException]
On the next line in my code (in the catch() block), I try the same Unmarshaller instance and give a valid payload, where I get following type of error:
java.lang.ClassCastException: foo.bar.SomeAType cannot be cast to foo.bar.SomeBType
On the next line (again in the subsequent catch()), I try the same Unmarshaller instance and again give the same valid payload, which unmarshals fine!
Has anyone experienced this kind of behavior with JAXB? Am I hitting a bug here? Where to look/dig?
Here are the details of the manifest of JAXB jar that I am using:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0
Created-By: 1.5.0_12-b04 (Sun Microsystems Inc.)
Specification-Title: Java Architecture for XML Binding
Specification-Version: 2.1
Specification-Vendor: Sun Microsystems, Inc.
Implementation-Title: JAXB Reference Implementation
Implementation-Version: 2.1.12
Implementation-Vendor: Sun Microsystems, Inc.
Implementation-Vendor-Id: com.sun
Extension-Name: com.sun.xml.bind
Build-Id: hudson-jaxb-ri-2.1-833
Class-Path: jaxb-api.jar activation.jar jsr173_1.0_api.jar jaxb1-impl.jar
Name: com.sun.xml.bind.v2.runtime
Implementation-Version: hudson-jaxb-ri-2.1-833
Thank you much in advance!
EDIT #2: It's not possible to paste everything, but here's the gist of what it is looking like:
final JAXBContext jaxbContext = JAXBContext.newInstance(FooRequestType.class);
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<FooRequestType> result = null;
try {
//try unmarshalling invalid payload.
result = unmarshaller.unmarshal(invalidPayload.getDocumentElement(), FooRequestType.class);
}catch(Exception e1){
try {
//now try unmarshalling valid payload . ##NOTE: If you try unmarshalling Invalid Payload here, it will fail again.
result = unmarshaller.unmarshal(validPayload.getDocumentElement(), FooRequestType.class);
} catch(Exception e2){
//try again unmarshalling valid payload
result = unmarshaller.unmarshal(validPayload.getDocumentElement(), FooRequestType.class);
System.out.println("Result:=" + result.getValue());
System.out.println("Successfully unmarshalled. Exiting with (0)");
System.exit(0);
}
}
System.out.println("Not expecting to reach here.Exiting with (1)");
System.exit(1);
EDIT #3: Ran the same piece of code by using EclipseLink MOXy as the JAXB Impl; and it behaves correctly.
I opened a bug on Sun/Oracle JAXB RI: http://java.net/jira/browse/JAXB-931

Related

Premature end of file while marshaling xml

I am facing strange issue "Premature end of file." exception for last few days on one of our azure application. Its a spring boot application. I am using spring boot version 2.6.3 (embedded tomcat). This code has been working for past 8 months but its not working anymore. Only changes I did for Java 8 to Java 11 version update on the azure app service.
We are using "Java 11 on JAVA SE linux stack" in app service.
We are getting an exception on below line (setting new schema),
Schema schema = sf.newSchema(file);
Here is the Java code which was working before.
public static <T> String marshal(Class<T> beanClass, Object object, String xsdSchemaPath)
throws JAXBException, SAXException{
JAXBContext jaxbContext = JAXBContext.newInstance(beanClass);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
File file = new File(xsdSchemaPath);
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaPath);
try {
FileUtils.copyInputStreamToFile(in, file);
} catch (IOException e) {
logger.error("Error occured in Marshalling the object", e.getMessage());
throw new SriException(xsdSchemaPath + " not found ");
}
Schema schema = sf.newSchema(file);
jaxbMarshaller.setSchema(schema);
I have already verified xsd and its valid.
Please let me know if there are any leads.
the only thing I can think about it's a max size issue or timeout. Take a look in the following and try changing the parameters:
In conf\server.xml
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="67589953" />
In webapps\manager\WEB-INF\web.xml
<multipart-config>
<!-- 52MB max -->
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
HttpRequest maximum allowable size in tomcat?

Is there mongodb mapping converter for generic message

Is there mongodb mapping converter for generic message.
No argument constructor not available for generic message.
.11:47:30.937 [http-nio-9080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.messaging.MessageHandlingException: error occurred in message handler [messageHandler]; nested exception is org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate org.springframework.messaging.support.GenericMessage using constructor NO_CONSTRUCTOR with arguments ] with root cause
java.lang.NoSuchMethodException: org.springframework.messaging.support.GenericMessage.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:104)
at org.springframework.data.convert.ReflectionEntityInstantiator.createInstance(ReflectionEntityInstantiator.java:61)
at org.springframework.data.convert.ClassGeneratingEntityInstantiator.createInstance(ClassGeneratingEntityInstantiator.java:83)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:251)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:231)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1186)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.access$200(MappingMongoConverter.java:78)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1134)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1097)
Also I am trying following config of mongotemplate
Please advise if correct
public MongoTemplate messagingMongoTemplate() throws Exception {
MongoTemplate mongoTemplate=null;
try {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingContext mappingContext = new MongoMappingContext();
MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(dbRefResolver,mappingContext);
CustomConversions customConversions = new CustomConversions(Arrays.asList(new MongoDbMessageBytesConverter()));
mappingMongoConverter.setCustomConversions(customConversions);
mongoTemplate=new MongoTemplate(mongoDbFactory,mappingMongoConverter);
Starting with version 3.0 it is recommended to use ConfigurableMongoDbMessageStore as that provides more options for customization, including a Converter for Message.
Out-of-the-box Spring Integration provides MongoDbMessageBytesConverter, which has become public since 4.2.10 and is used by default if there is no any external customization for the ConfigurableMongoDbMessageStore.

Groovy: WSClient throwing JAXBException

I am trying to call a simple public Web Service with WSClient in a Groovy script, but it explodes when initializing ...
TestService.groovy:
#Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSClient
def proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader)
proxy.initialize();
def result = proxy.CelsiusToFahrenheit(0)
println "You are probably freezing at ${result} degrees Farhenheit"
The error message:
SEVERE: Could not compile java files for http://www.w3schools.com/webservices/tempconvert.asmx?WSDL.
Caught: java.lang.IllegalStateException: Unable to create JAXBContext for generated packages: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index
java.lang.IllegalStateException: Unable to create JAXBContext for generated pack
ages: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: jav
ax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or j
axb.index
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:343)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:196)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:175)
at groovyx.net.ws.AbstractCXFWSClient.createClient(AbstractCXFWSClient.java:229)
at groovyx.net.ws.WSClient.initialize(WSClient.java:108)
at groovyx.net.ws.IWSClient$initialize.call(Unknown Source)
at TestService.run(TestService.groovy:5)
Caused by: javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index - with linked exception:
[javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.classor jaxb.index]
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:340)
... 6 more
Caused by: javax.xml.bind.JAXBException: "org.tempuri" doesnt contain ObjectFactory.class or jaxb.index
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:197)
... 7 more
Any hint? Why should I have a jaxb.index?
Just discovered that the problem occurs with Java 1.7 (jdk1.7.0_21)... it's OK when running with Java 6 (jdk1.6.0_31)
Any hint to work with Java 7?
As noted on the GroovyWS page, GroovyWS is currently dormant. You could do the same thing (albeit with a wordier syntax) using the groovy-wslite library:
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='0.8.0')
import wslite.soap.*
def client = new SOAPClient('http://www.w3schools.com/webservices/tempconvert.asmx')
def response = client.send(SOAPAction:'http://tempuri.org/CelsiusToFahrenheit') {
body {
CelsiusToFahrenheit('xmlns':'http://tempuri.org/') {
Celsius('0')
}
}
}
def result = response.CelsiusToFahrenheitResponse.CelsiusToFahrenheitResult.text()
println "You are probably freezing at ${result} degrees Farhenheit"
Note that this requires you to look at the WSDL to get the SOAP message namespace, unlike the GroovyWS version of the code. But it works!

JAXB MOXy Binder issue when using #XmlAnyElement annotation

I have an issue when using the Binder implementation in MOXy.
Here is the input XML document (input.xml)
<?xml version="1.0" encoding="utf-8"?>
<root>
<unmapped />
</root>
And now, here is the source code used to unmarshal XML into a Binder instance and then update the XML from the corresponding Java object:
JAXBContext context = JAXBContext.newInstance(Input.class);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document document = builder.parse(new File("input.xml"));
Binder<Node> binder = context.createBinder(Node.class);
Input input = (Input) binder.unmarshal(document);
binder.updateXML(input);
In the end, the very simple Input class file:
#XmlRootElement(name = "root")
public class Input {
#XmlAnyElement
protected Object[] elements;
}
When the updateXML() method is invoked, the following exception is thrown:
java.lang.NullPointerException
at org.eclipse.persistence.internal.jaxb.DomHandlerConverter.convertObjectValueToDataValue(DomHandlerConverter.java:97)
We have been able to confirm this issue and it looks like it will be a very quick fix. You can use the link below to track our progress on this issue.
http://bugs.eclipse.org/391237
UPDATE
A fix has been checked into the EclipseLink 2.5.0 stream, a nightly download can be obtained from the following location:
http://www.eclipse.org/eclipselink/downloads/nightly.php
We have also checked in a fix to the EclipseLink 2.4.2 stream. A nightly download can be obtained from the above location starting October 12, 2012.

XmlJavaTypeAdapter throw user defined exception

Is there a way to throw user defined exception in XmlAdapter and catch them when JAXB marshalles/unmarshalls? I mean, I can throw my own exception but JAXB just ignores this exception and throws his own from which I can not get to my exception message or the exception object.
try {
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
jaxbUnmarshaller.unmarshal(inputStream);
}
catch (UserDefinedException e) {
// Do something.
}
Sorry for not posting the correct exception that JAXB throwed instead of mine. At this moment, I can not get to the code. Currentlly I am using JAXB-RI, but I used EclipseLink MoXY and encountered this problem.
I will post additional data when I am able to get the hand of the code. But till then, maybe someone knows what am I talking about. Some code example of correct usage of XmlAdapter is also great.
Thanks.
The expectation of a JAXB (JSR-222) implementation is that it throws a JAXBException. This means that any exceptions thrown within something like an XmlAdapter is going to end up getting wrapped. You could potentially use a stateful XmlAdapter to handle this use case:
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
MyXmlAdpater myXmlAdapter = new MyXmlAdapter();
jaxbUnmarshaller.setAdatper(myXmlAdapter);
jaxbUnmarshaller.unmarshal(inputStream);
if(myXmlAdapter.hasException() {
// Do something.
}
For an Example of using a stateful XmlAdapter see:
http://blog.bdoughan.com/2011/09/mixing-nesting-and-references-with.html

Resources