EzDevInfo.com

jaxb interview questions

Top jaxb frequently asked interview questions

JAXB - Remove 'standalone="yes"' from generated XML

Do you know of a JAXB setting to prevent standalone="yes" from being generated in the resulting XML?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

Source: (StackOverflow)

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

After upgrading to JDK 1.7 I am getting below exception:

java.lang.VerifyError: Expecting a stackmap frame at branch target 71 in method com.abc.domain.myPackage.MyClass$JaxbAccessorM_getDescription_setDescription_java_lang_String.get(Ljava/lang/Object;)Ljava/lang/Object; at offset 20
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2413)
    at java.lang.Class.getConstructor0(Class.java:2723)
    at java.lang.Class.newInstance0(Class.java:345)
    at java.lang.Class.newInstance(Class.java:327)
    at com.sun.xml.internal.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.instanciate(OptimizedAccessorFactory.java:184)
    at com.sun.xml.internal.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.get(OptimizedAccessorFactory.java:129)
    at com.sun.xml.internal.bind.v2.runtime.reflect.Accessor$GetterSetterReflection.optimize(Accessor.java:384)
    at com.sun.xml.internal.bind.v2.runtime.property.SingleElementLeafProperty.<init>(SingleElementLeafProperty.java:72)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:113)
    at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:166)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:494)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:311)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:126)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1148)
    at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:130)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:248)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:235)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:445)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:637)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
    at com.abc.domain.myPackage.MyClass.marshalFacetsTest(MyClass.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:128)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1203)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1128)
    at org.testng.TestNG.run(TestNG.java:1036)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

Source: (StackOverflow)

Advertisements

Difference of Maven JAXB plugins

I have determined that two JAXB plugins for Maven 2 exist, with some different configurations.

The one is from Sun: http://jaxb.dev.java.net/jaxb-maven2-plugin/, the other from Mojohaus: http://mojohaus.org/jaxb2-maven-plugin/

Which of these two plugins can be recommended?


Thanks Matt. On my little research project, I found that there's quite another plugin comming from the sunners:

<groupId>com.sun.tools.xjc.maven2</groupId>  
<artifactId>maven-jaxb-plugin</artifactId>  

and that one:

<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>

and still the one from Codehouse.


Source: (StackOverflow)

JAXB - Property "Value" is already defined. Use to resolve this conflict

Using JAXB to generate XML binding classes.

The schema is based on a set of legacy XML files, and includes this snippet:

<xs:complexType name="MetaType">
    <xs:simpleContent>
        <xs:extension base="xs:string">
            <xs:attribute type="xs:string" name="Name" />
            <xs:attribute type="xs:string" name="Scheme" />
            <xs:attribute type="xs:string" name="Value" />
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

The 'Value' attribute conflicts with the 'value' property of xs:string, and the code generation fails with the error:

com.sun.istack.SAXParseException2: Property "Value" is already defined. Use &lt;jaxb:property> to resolve this conflict. 

Source: (StackOverflow)

JAXB Marshalling with null fields

This is a pretty simple request, but I just didn't find a way to do it.

I'm basically trying to set up a role in JAXB which says that whenever an null field is encountered, instead of ignoring it in the output, set it to an empty value. So for the class :

@XMLRootElement
Class Foo {
   Integer num;
   Date date;
….
}

When this has been marshalled into the XML file if the date field is null, my output does not have that element in it. What I want to do is include all the fields in the output; and if they are null, replace them with - say a blank. So the output should be :

<foo>
  <num>123</num>
  <date></date>
</foo>

Thanks,

Jalpesh.


Source: (StackOverflow)

Using JAXB to unmarshal/marshal a List

I'm trying to create a very simple REST server. I just have a test method that will return a List of Strings. Here's the code:


@GET
@Path("/test2")
public List test2(){
    List list=new Vector();
    list.add("a");
    list.add("b");
    return list;
}

It gives the following error:

SEVERE: A message body writer for Java type,
class java.util.Vector, and MIME media type,
application/octet-stream, was not found

I was hoping JAXB had a default setting for simple types like String, Integer, etc. I guess not. Here's what I imagined:


<Strings>
  <String>a</String>
  <String>b</String>
</Strings>

What's the easiest way to make this method work?


Source: (StackOverflow)

How do I prevent JAXBElement from being generated in a CXF Web Service client?

I'm trying to create a web service client using CXF to consume a WCF web service. When I use wsdl2java it generates objects with JAXBElement types instead of String.

I read about using a jaxb bindings.xml file to set generateElementProperty="false" to try to fix the problem, but the web service I'm consuming contains 7 imported schemas.

How can I specify the generateElementProperty="false" on all seven schemas, or is there a way to apply it to all schemas?


Source: (StackOverflow)

Why can't JAXB find my jaxb.index when running inside Apache Felix?

It's right there, in the package that it should be indexing. Still, when I call

JAXBContext jc = JAXBContext.newInstance("my.package.name");

I get a JAXBException saying that

"my.package.name" doesnt contain ObjectFactory.class or jaxb.index

although it does contain both.

What does work, but isn't quite what I want, is

JAXBContext jc = JAXBContext.newInstance(my.package.name.SomeClass.class);

This question from various other people appears on quite some mailing lists and forums but seemingly doesn't get answers.

I'm running this on OpenJDK 6, so I got the source packages and stepped my debugger into the library. It starts by looking for jaxb.properties, then looks for system properties and failing to find either, it tries to create the default context using com.sun.internal.xml.bind.v2.ContextFactory. In there, the Exception gets thrown (inside ContextFactor.createContext(String ClassLoader, Map)), but I can't see what's going on because the source isn't here.

ETA:

Judging from the source code for ContentFactory, I found here, this is probably the piece of code that fails to work as intended:

/**
 * Look for jaxb.index file in the specified package and load it's contents
 *
 * @param pkg package name to search in
 * @param classLoader ClassLoader to search in
 * @return a List of Class objects to load, null if there weren't any
 * @throws IOException if there is an error reading the index file
 * @throws JAXBException if there are any errors in the index file
 */
private static List<Class> loadIndexedClasses(String pkg, ClassLoader classLoader) throws IOException, JAXBException {
    final String resource = pkg.replace('.', '/') + "/jaxb.index";
    final InputStream resourceAsStream = classLoader.getResourceAsStream(resource);

    if (resourceAsStream == null) {
        return null;
    }

From my previous experience, I'm guessing that this has to do with the class loading mechanisms of the OSGi container that this is running in. Unfortunately, I am still a little out of my depth here.


Source: (StackOverflow)

JAXB: How to marshal objects in lists?

Perhaps a stupid question: I have a List of type <Data> which I want to marshal into a XML file. This is my class Database containing an ArrayList...

@XmlRootElement
public class Database
{
    List<Data> records = new ArrayList<Data>();

    public List<Data> getRecords()                   { return records; }
    public void       setRecords(List<Data> records) { this.records = records; }
}

...and this is class Data:

// @XmlRootElement
public class Data 
{
    String name;
    String address;

    public String getName()            { return name;      }
    public void   setName(String name) { this.name = name; }

    public String getAddress()               { return address;         }
    public void   setAddress(String address) { this.address = address; }
}

Using the following test class...

public class Test
{
    public static void main(String args[]) throws Exception
    {
        Data data1 = new Data();
             data1.setName("Peter");
             data1.setAddress("Cologne");

        Data data2 = new Data();
             data2.setName("Mary");
             data2.setAddress("Hamburg");

        Database database = new Database();
                 database.getRecords().add(data1);
                 database.getRecords().add(data2);

        JAXBContext context = JAXBContext.newInstance(Database.class);
        Marshaller marshaller = context.createMarshaller();
                   marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                   marshaller.marshal(database, new FileWriter("test.xml"));       
    }
}

...I got the result:

<database>
    <records>
        <address>Cologne</address>
        <name>Peter</name>
    </records>
    <records>
        <address>Hamburg</address>
        <name>Mary</name>
    </records>
</database>

But that's not what I was expecting, i.e. all tags for <Data> objects are missing. I am looking for a way to export the data in the following structure, but I don't know how to achieve this:

<database>
    <records>
        <data>
            <address>Cologne</address>
            <name>Peter</name>
        </data>
        <data>
            <address>Hamburg</address>
            <name>Mary</name>
        </data>
    </records>
</database>

One additional question: if I want to deal with the problem without using @XmlElementWrapper and @XmlElement annotations, I can introduce an intermediary class

public class Records
{
    List<Data> data = new ArrayList<Data>();

    public List<Data> getData()                { return data; }
    public void       setData(List<Data> data) { this.data = data; }
}

used by the modified base class

@XmlRootElement
public class Database
{
    Records records = new Records();

    public Records getRecords()                { return records; }
    public void    setRecords(Records records) { this.records = records; }
}

in a slightly modified Test class:

...
Database database = new Database();
database.getRecords().getData().add(data1);
database.getRecords().getData().add(data2);
...

The result also is:

<database>
    <records>
        <data>
            <address>Cologne</address>
            <name>Peter</name>
        </data>
        <data>
            <address>Hamburg</address>
            <name>Mary</name>
        </data>
    </records>
</database>

Is this the recommended way to create a Java class structure according to the XML file structure above?


Source: (StackOverflow)

JAXB and property ordering

I want the serialized XML output from my Java class to honor the ordering of the properties in the Java class.

It seems that JAXB orders alphabetically.

I can override this by using @XmlType with propOrder and specifying ALL of the properties, but I have a class with many properties and these are not yet finalized.

I read that specifying an empty propOrder would do it but it don't.

My example class:

package test;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement
//@XmlType(propOrder={"company", "scheme", "agreementNumber"})
@XmlType(propOrder={}) // makes no difference - still alphabetical in XML 
public class CustomerPlan2 {

    private String company;
    private String scheme;
    private String agreementNumber;

    @XmlElement(name="Company")
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }

    @XmlElement(name="Scheme")
    public String getScheme() {
        return scheme;
    }
    public void setScheme(String scheme) {
        this.scheme = scheme;
    }

    @XmlElement(name="AgreementNumber")
    public String getAgreementNumber() {
        return agreementNumber;
    }
    public void setAgreementNumber(String agreementNumber) {
        this.agreementNumber = agreementNumber;
    }
}

My serialize code:

    CustomerPlan2 cp2 = new CustomerPlan2();

    cp2.setCompany("company");
    cp2.setScheme("scheme");
    cp2.setAgreementNumber("agreementnumber");
    JAXBContext context = JAXBContext.newInstance(CustomerPlan2.class);
    Marshaller marshaller = context.createMarshaller();

    marshaller.marshal(cp2, new FileWriter("C:\\temp\\out.xml"));

Output:

    <customerPlan2>
      <AgreementNumber>agreementnumber</AgreementNumber> 
      <Company>company</Company> 
      <Scheme>scheme</Scheme> 
    </customerPlan2>

I want my output to be (as the property order of my class):

    <customerPlan2>
      <Company>company</Company>
      <Scheme>scheme</Scheme> 
      <AgreementNumber>agreementnumber</AgreementNumber> 
    </customerPlan2>

Thanks for any help on this.


Source: (StackOverflow)

How do you specify the date format used when JAXB marshals xsd:dateTime?

When JAXB marshals a date object (XMLGregorianCalendar) into an xsd:dateTime element how can you specify the format of the resulting XML?

For example: The default data format is uses milliseconds <StartDate>2012-08-21T13:21:58.000Z</StartDate> I need to omit the milliseconds. <StartDate>2012-08-21T13:21:58Z</StartDate>

How can I specify the output form/date format that I want it to use? I'm using javax.xml.datatype.DatatypeFactory to create the XMLGregorianCalendar object.

XMLGregorianCalendar xmlCal = datatypeFactory.newXMLGregorianCalendar(cal);

Source: (StackOverflow)

JAXB: how to marshall map into value

The question is about JAXB Map marshalling - there is plenty of examples on how to marhsall a Map into a structure like follows:

<map>
  <entry>
    <key> KEY </key>
    <value> VALUE </value>
  </entry>
  <entry>
    <key> KEY2 </key>
    <value> VALUE2 </value>
  </entry>
  <entry>
  ...
</map>

In fact, this is natively supported by JAXB. What I need, however, is the XML where key is the element name, and value is its content:

<map>
  <key> VALUE </key>
  <key2> VALUE2 </key2>
 ...
</map>

I didn't succeed implementing my Map adapter the way it is recommended by JAXB developers (https://jaxb.dev.java.net/guide/Mapping_your_favorite_class.html), as I need, he - dynamic attribute name :)

Is there any solution for that?

P.S. Currently I have to create a dedicated container class for each typical set of key-value pairs I want to marshall to XML - it works, but I have to create way too many of these helper containers.


Source: (StackOverflow)

How do i instantiate a JAXBElement object?

I need to create one of these as the interface requires it...can someone please let me know how to create one, as there doesnt seem to be a c'tor defined?


Source: (StackOverflow)

Is there a way to avoid undeployment memory leaks in Tomcat?

This question is for anyone who's ever tested the "Find leaks" button in the Tomcat manager and got some results like this:

The following web applications were stopped (reloaded, undeployed), but their classes from previous runs are still loaded in memory, thus causing a memory leak (use a profiler to confirm):
/leaky-app-name

I'm assuming this has something to do with that "Perm Gen space" error you often get with frequent redeployments.

So what I'm seeing in jconsole when I deploy is that my loaded classes goes from about 2k to 5k. Then you would think an undeployment should drop them back down to 2k but they remain at 5k.

I've also tried using the following JVM options:

-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled

I did see VERY minor dips in the amount of Perm Gen space used but not what I expected and the loaded class counts did not drop.

So is there a way to configure Tomcat or design your app to unload better on an undeployment? Or are we stuck with restarting the server after some major debugging sessions?

Tomcat version output:

Server version: Apache Tomcat/6.0.29
Server built: July 19 2010 1458
Server number: 6.0.0.29
OS Name: Windows 7
OS Version: 6.1
Architecture: x86
JVM Version: 1.6.0_18-b07
JVM Vendor: Sun Microsystems Inc.

Update:

Thanks to celias' answer I decided to do a little more digging and I think I determined the culprit to be in my application thanks to CXF, Spring and JAXB.

After I learned how to profile a Java application, I pointed the profiler at Tomcat and took some heap dumps and snapshots to see what the objects and classes looked like in memory. I discovered that some of the enumerations from my XML schema used in my CXF/JAXB (wsdl2java) generated classes were lingering after an undeployment. According to my heap dump it looks like the objects were tied to a Map. Disclaimer: I admit I'm still a little green with profiling and tracing an object's call tree can be challenging in Java.

Also I should mention that I didn't even invoke the service, just deployed then undeployed it. The objects themselves appeared to be loaded via reflection initiated from Spring on deployment. I believe I followed the convention for setting up a CXF service in Spring. So I'm not 100% sure if this is Spring/CXF, JAXB, or reflection's fault.

As a side note: the application in question is a web service using Spring/CXF and the XML happens to be a rather complex schema (an extension of NIEM).


Source: (StackOverflow)

How can I tell jaxb / Maven to generate multiple schema packages?

Example:

</plugin>       
       <plugin>
           <groupId>org.jvnet.jaxb2.maven2</groupId>
           <artifactId>maven-jaxb2-plugin</artifactId>
           <version>0.7.1</version>
           <executions>
             <execution>
               <goals>
                 <goal>generate</goal>
               </goals>
             </execution>
           </executions>
            <configuration>
             <schemaDirectory>src/main/resources/dir1</schemaDirectory>
              <schemaIncludes>
                  <include>schema1.xsd</include>
              </schemaIncludes>
              <generatePackage>schema1.package</generatePackage>
           </configuration>
         </plugin>
          <plugin>
           <groupId>org.jvnet.jaxb2.maven2</groupId>
           <artifactId>maven-jaxb2-plugin</artifactId>
           <version>0.7.1</version>
           <executions>
             <execution>
               <goals>
                 <goal>generate</goal>
               </goals>
             </execution>
           </executions>
            <configuration>
             <schemaDirectory>src/main/resources/dir2</schemaDirectory>
              <schemaIncludes>
                  <include>schema2.xsd</include>
              </schemaIncludes>
              <generatePackage>schema2.package</generatePackage>
           </configuration>
         </plugin>
       </plugins>

What happened: Maven executes the the first plugin. Then deletes the target folder and creates the second package, which then is visible.

I tried to set target/somedir1 for the first configuration and target/somedir2 for the second configuration. But the behavior does not not change? Any ideas? I do not want to generate the packages directly in the src/main/java folder, because these packages are genereated and should not be mixed with manual created classes.


Source: (StackOverflow)