Unable to get JAXB context - jaxb

I have java classes generated by XSD.
But when am trying to get JAXB context (while unmarshlling) it hits a dead end.
No errors,no print statements will be executed after this line. Nothing happens.
I have tried following methods
JAXBContext jc = JAXBContext.newInstance(package)
JAXBContext jc = JAXBContext.newInstance(class)
JAXBContext jc = JAXBContext.newInstance(package,contextloader)
but every option is failing.
Kindly suggest.

JAXBContext.newInstance will return you an instance of JAXBContext. From that you need to create instances of Unmarshaller to convert XML to objects, and instances of Marshaller to convert those objects back to XML.

Related

How to keep IDREF link when unmarshalling an object with JAXB for cloning?

I defined objects with XSD model and I used Jaxb to create corresponding classes, to be able to load XML files on instance of classes and to generate XML files from instance of classes.
My elements defined on the XSD model are complex with several hierarchical level, using list, ID and IDREF.
One command of my program is to duplicate elements.
I can't use the clone method cause classes of element are generated by JAXB.
So i have tried to do deep copy with BeanUtils.cloneBean, next with SerializationUtils.clone from Apache but both methods don't work correctly with all my objects because of their complexity.
I found a solution that work, using JAXB to create a clone unmarshalling my element :
public ObjectXML duplicate(ObjectXML objectXML) throws JAXBException {
JAXBContext sourceJaxbContext = JAXBContext.newInstance(objectXML.getClass());
JAXBContext targetJaxbContext = JAXBContext.newInstance(objectXML.getClass());
Unmarshaller unmarshaller = targetJaxbContext.createUnmarshaller();
ObjectXML objectCopy = (ObjectXML) unmarshaller.unmarshal(new JAXBSource(sourceJaxbContext, objectXML));
return objectCopy;
}
ObjectXML is my parent class from all elements generated by JAXB. All elements inherit directly or indirectly from this class.
This method work fine except with IDREF attributes that link to another object : JAXB don't know the element that have the corresponding ID when I unmarshall an individual object, so it assign null to the attribute.
Have someone a solution to keep IDREF on the copy when linked object are not supplied to the unmarshal of JAXB?
Thank you for advance.
Few hints.
Try the copyable plugin from JAXB2-Basics. This plugin generates deep reflection-free copying methods which handle JAXB structures very well, and you can also specify your own copying strategy. Disclaimer: I'm the author.
Implement and register your own IDResolver, see this blog post. This would allow you to plug your own ID resolution strategy.

UnMarshallException doesnt contain ObjectFactory.class or jaxb.index

JAXBContext context = JAXBContext.newInstance( "com.example.abcd", ObjectFactory.class.getClassLoader());
if i run this, i am getting error that ""com.example.abcd" doesnt contain ObjectFactory.class or jaxb.index"
But this package has ObjectFactory class. I am just wondering why this is showing me the error.
You need to ensure the ObjectFactory class is annotated with #XmlRegistry.

JAXB: classes generated by JAXB not recognised in context

I am encountering this problem. Is there a fix somewhere?
Here is my file structure:
package jaxb_conainer_class;
package loader_class;
Main.java imports both loader_class and jaxb_conainer_class;
In the loader_class, a call to
JAXBContext context = JAXBContext.newInstance(xxxx.class);
gives me the crash above
Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
There's no ObjectFactory with an #XmlElementDecl for the element {}default.
When you generate classes from an XML schema you should create the JAXBContext on the generated package name. This will ensure that the ObjectFactory and everything else will be picked up correctly.
JAXBContext jc = JAXBContext.newInstance("com.example.foo");
If there are more than one package than you can use : as the delimiter.
JAXBContext jc = JAXBContext.newInstance("com.example.foo:org.example.bar");
Alternatively you can include the ObjectFactory class in the classes used to bootstrap the JAXBContext, but my recommendation is to use the package name(s).

Use JAXB to marshall bean in the service layer

I use Jersey with JAXB to convert my response to XML. I have several methods that consume XML from the Request Body. I can specify the bean as a parameter to the method being called and JAXB will be used to automatically transform the request body data to that bean, or fail if it's not compatible.
This works great for the majority of all my cases, and I have not had the need to write a MessageBodyReader or MessageBodyWriter to handle the transformation to and from. I have this one instance where I need the request body to be mapped to the bean, but I also need the original XML that was in the body of the request. I need to store that in the DB.
I've tried getting to the request body through the HttpContext, and can't figure out how - I just see the header values and URI values. I tried through the HTTPServletContext as well ending in the same result.
Is there a way to capture the request body as it is before it's transformed or after? Will I need to create a MessageBodyReader to handle this case? It seemed like those were used to map the contents to a bean, which I already have functioning, so I didn't think that was the solution. But, perhaps in the MessageBodyReader I can put the request body into some variable and pass it along while still transforming the data to the beans. That still seems kind of more work than is needed. I would think I could get to the body through the request somehow.
Update:
I tried getting the body from ContainerRequest object using the getEntity method.
String xmlString = request.getEntity(String.class);
And, that worked great. The request body is captured in that property and I can add it to the request properties to access later in the resource, etc. The problem is, and I think it's because the entity is a stream, it clears out the body. So by the time the jaxb mapping to the beans happen, there is nothing to transform and I'm given a bad request response.
That didn't work but I wanted to throw it out there as a possibility if someone could get it working better.
Here is what I ended up doing, and it would be nice to not have to do it this way. I'm basically marshalling what was unmarshalled, in my service class.
final StringWriter st = new StringWriter();
try
{
final JAXBContext jaxbContext = JAXBContext.newInstance(full.classpath.and.classname.of.root.bean);
final Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(unmarshalled object, st);
} catch (final JAXBException je)
{
// TODO Auto-generated catch block
je.printStackTrace();
}
final String xml = st.toString();
So you can see - I basically take the object, the root bean that the body was unmarshalled to, and marshal it, giving the location of the annotated root bean to use in marhsalling.
It seems a bit redonkulous to have to marshal what was already unmarshalled, and if that is the response, maybe marshalled again on the way out. I would like a solution where I could grab a copy of the body before the unmarshalling happens. But in the meantime, this will have to work.
I ran into the same scenario and ended with similar conclusions, except I do it the other way around by getting it as a String and then marshal manually to avoid unnecessary JAXB work, e.g.:
String xmlString = request.getEntity(String.class);
Reader sReader = new StringReader(xmlString);
return (T)jaxbCtx.createUnmarshaller().unmarshal(sReader);

how to pass jaxb object to camelconfig xml file

I am trying to use jaxb in camel routing.I have tried to load router from xml using jaxb and got it done. Inside a method I have created jaxb object and unmarshaller the router in xml(loaded router from xml).
my code:
JAXBContext jaxb = JAXBContext.newInstance(Constants.JAXB_CONTEXT_PACKAGES);
Unmarshaller unmarshaller = jaxb.createUnmarshaller();
Resource rs = new ClassPathResource("cameltest.xml");
Object value = unmarshaller.unmarshal(rs.getInputStream());
RoutesDefinition routes = (RoutesDefinition) value;
context.addRouteDefinitions(routes.getRoutes());
Requirement:
Instead of doing it in java file. I need when a method in a service is called, the jaxb object inside the method should trigger off the xml which contains the flow (router concept). help me........
Using JAXB in a Camel route is quite easy, as is shown in JAXB. Unless the processing is very complex it can be done in Spring and requires a minimal amount of code.
What it looks like you are trying to do from the code is extract the routes using JAXB from the Camel xml file, perhaps you are wanting to create dynamic router - I would suggest looking at the EIP Patterns that Camel implements and picking something like the Content Based Router or Dynamic Router.

Resources