<< Back to previous view

[JAXB-1013] xjc:substitutable does not work in JAXB 2.2.7 anymore Created: 16/Apr/14  Updated: 16/Apr/14

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Niels Bertram Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and Niels Bertram

 Description   

The original Jira JAXB-289 proposed a solution to fix the substitution resulting in rather inconvenient JAXBElement<T> used when the type was abstract and part of a substitution group. Also the documentation at https://jaxb.java.net/2.2.7/docs/ch05.html#substitutable suggests that this feature should work.

However it does not seem to work with JAXB-RI 2.2.7 anymore.

I have attached the original test files from JAXB-289 as simple maven project using the maven-jaxb22-plugin. The project contains a default profile to show the output that is undesirable. You can run and inspect using following maven command:

mvn clean install

The profile substitutable will just trigger a generation using the annotated schema as per documentation and the Jira issue. You can run this build with following maven command:

mvn clean install -Psubstitutable

The exact stack trace error is:

com.sun.istack.SAXParseException2; systemId: file:///.../base/Model.xsd; lineNumber: 8; columnNumber: 37; compiler was unable to honor this substitutable customization. It is attached to a wrong place, or its inconsistent with other bindings.
...
com.sun.istack.SAXParseException2; systemId: file:///.../base/Model.xsd; lineNumber: 5; columnNumber: 43; (the above customization is attached to the following location in the schema)


 Comments   
Comment by Niels Bertram [ 16/Apr/14 01:05 PM ]

Tried to attach the example testcase but have no access. You can find the example on GitHub at https://github.com/bertramn/jaxb-substitutable-example .





[JAXB-1012] No default constructor found on class javax.xml.bind.JAXBElement - Need know why Created: 07/Apr/14  Updated: 08/Apr/14

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: vanekl Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Win 7 64b, JavaSE 7


Tags: unmarshalling
Participants: Iaroslav Savytskyi, laune and vanekl

 Description   

Hi,

I have generated Java code from XSD, using xjc tool, sheme is here : http://dd.eionet.europa.eu/schemas/id2011850eu/AirQualityReporting.xsd

I can marshall XML from it, and its valid against XSD: http://www.valachnet.cz/lvanek/0/CZ_E2a_hourly.xml

While unmarshall back, I get exception:

com.sun.xml.bind.v2.ClassFactory create0
INFO: No default constructor found on class javax.xml.bind.JAXBElement
java.lang.NoSuchMethodException: javax.xml.bind.JAXBElement.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at com.sun.xml.bind.v2.ClassFactory.create0(ClassFactory.java:104)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.createInstance(ClassBeanInfoImpl.java:286)

I discovered, that JAXB creates in method 'ClassBeanInfoImpl::createInstance'
jaxbType = javax.xml.bind.JAXBElement - But it's not have default constructor.

I need to know which XML fragment causes my problem, but NoSuchMethodException isn't informative.
It is possible surround calling: bean = ClassFactory.create0(jaxbType); in 'ClassBeanInfoImpl::createInstance' method with try/catch and throw more descriptive exception ?

Bye,
Lumir Vanek



 Comments   
Comment by laune [ 07/Apr/14 01:05 PM ]

The indicated XML schema loads several other xsd files from the net and does not compile, needing customizations. Please provide the customization as you have used it. Also, the top level element of the XML file gml:FeatureCollection is not defined in the schema file. Also, complete code to reproduce the unmarshalling should be provided.

Hoewever, it's very likely that this is a case of incomplete customization and/or JAXB use and should not be discussed in this JIRA, where bubs are reported. Please use the user list for further discussion since JIRA is rather inconvenient for this.

Comment by vanekl [ 08/Apr/14 05:14 AM ]

Hi,
my customization is:

http://www.valachnet.cz/lvanek/0/bindings.xjb

Ant script, that generate Java code is:

http://www.valachnet.cz/lvanek/0/generate_jaxb_code.xml

And unmarshalling code:

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

import net.opengis.gml._3.FeatureCollectionType;

public static void main(String[] args)
{
try
{
System.out.println("Creating JAXB Context");
final JAXBContext jaxbContext = JAXBContext.newInstance(FeatureCollectionType.class);

/*

  • Input XML
    */
    String fileName = ".\\output
    CZ_E2a_hourly.xml";

/*

  • Loading XSD
    */
    System.out.println("Loading XSD");
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    // Schema schema = schemaFactory.newSchema(new File("..\\AirQualityReportingModel\\XSD
    AirQualityReporting_0.3.7c.xsd"));
    Schema schema = schemaFactory.newSchema(new URL("http://dd.eionet.europa.eu/schemas/id2011850eu/AirQualityReporting.xsd"));

/*

  • Validation
    */
    System.out.println("Validating " + fileName + "...");

try

{ Validator validator = schema.newValidator(); validator.validate(new StreamSource(new File(fileName))); System.out.println("OK"); }

catch (Exception e)

{ e.printStackTrace(); return; }

/*

  • Unmarsalling
    */
    final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    unmarshaller.setSchema(schema);

unmarshaller.setEventHandler(new ValidationEventHandler()
{
@Override
public boolean handleEvent(ValidationEvent event)
{
System.out.println(event.getMessage());
return true;
}}
);

JAXBElement<FeatureCollectionType> featureCollection = unmarshaller.unmarshal(new StreamSource(fileName), FeatureCollectionType.class);
System.out.println(featureCollection.getName());

final FeatureCollectionType featureCollectionType = featureCollection.getValue();
System.out.println(featureCollectionType.getDescription());
}
catch (JAXBException | SAXException | MalformedURLException e)

{ e.printStackTrace(); }

}

Bye,
Lumir

Comment by laune [ 08/Apr/14 10:24 AM ]

Works for me, using data as posted and xjc and java from /extra/JDK7u21/jdk1.7.0_21/. Some other effect has caused validation warnings which I haven't investigated. (I'll not continue this thread via JIRA.)

Comment by vanekl [ 08/Apr/14 10:50 AM ]

Hi,
after some hours of debugging I found cause of problem:

Class (generated by jxc): net.opengis.om._2.OMObservationType

have declared:

@XmlElement(required = true, type = JAXBElement.class)
protected Object result;

After removing "type = JAXBElement.class" Unmashalling works fine.

I am still belived, that throwing more descriptive exceptions (ideally containing tag name)
in this case would be welcomed by JAXB users.

class UnmarshallingContext::createInstance( JaxBeanInfo beanInfo ) may be good place to cath
NoSuchMethodException and send it to Loader.reportError().

You can close this issue, thanks for help.

Best Regards,
Lumir Vanek





[JAXB-1011] Base complex type "AdditionalParametersBaseType" is derived by restriction, while this complex type "AdditionalParametersType" is derived by extension. OGC WCS 2.0.0 - Created: 07/Apr/14  Updated: 07/Apr/14

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: aquaglia Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7 64bit
Java 6


Tags:
Participants: aquaglia and Iaroslav Savytskyi

 Description   

Trying to generate the bindings for
http://schemas.opengis.net/wcs/2.0/wcsAll.xsd

E:\schemas\inspire\wcs\wcs-2_0_1\wcs\2.0.1>"E:\quaglan\software\jaxb-ri-2.2.7\ja
xb-ri-2.2.7\bin\xjc" wcsAll.xsd -d "E:\quaglan\projects\subversion\sdi\Geoportal
\Common\MavenProjects\INSPIREGeoportalBindings\src\main\java" -target 2.1 -b bin
dings.xjb -extension -catalog catalog.xml
parsing a schema...
[ERROR] Base complex type "AdditionalParametersBaseType" is derived by restricti
on, while this complex type "AdditionalParametersType" is derived by extension.
This is not currently handled by XJC, but we are seeking input on this issue. Pl
ease report this to the JAXB team.
line 54 of http://schemas.opengis.net/ows/2.0/owsAdditionalParameters.xsd

Failed to parse a schema.






[JAXB-828] schemagen generates schemas for the xml namespace "http://www.w3.org/XML/1998/namespace" Created: 13/Apr/11  Updated: 05/Apr/14

Status: Open
Project: jaxb
Component/s: schemagen
Affects Version/s: 2.1.11, 2.1.12, 2.1.13, 2.2, 2.2.1, 2.2.2, 2.2.3, 2.2.3u1
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: matunos Assignee: Martin Grebac
Resolution: Unresolved Votes: 1
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

File Attachments: Java Source File package-info.java     Java Source File SampleElement.java     XML File schema1.xsd     XML File schema2.xsd     File sun-jaxb.episode    
Tags:
Participants: jinahya, Martin Grebac and matunos

 Description   

If I have defined classes which use elements from the standard XML namespace "http://www.w3.org/XML/1998/namespace", and then run those through schemagen, schemagen will create a separate xsd for that namespace, and also include bindings for that namespace in the episode file, if I choose to generate one of those.

The problem is that this namespace is treated special in XML (including by xjc), but not by schemagen. For example, the resultant episode file is invalid because it contains a prefix mapping such as this:
xmlns:tns="http://www.w3.org/XML/1998/namespace"

That's illegal (you can't bind that namespace to any prefix other than 'xml'), and in fact, xjc knows this; xjc will reject the episode file if I try to include it in an invocation.

Furthermore, the generated schema for my own namespace now has an <xs:import> with a schemaLocation of the generated xml schema, rather than the well-defined schema location.

Since there is a well-defined schema already for this namespace (at http://www.w3.org/2001/xml.xsd), there is no reason for schemagen to generate one when it's generating a schema from source code. Instead, I think it should generate something like this:

<xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/xml.xsd"/>

...and then not generate another xsd for the items in the code.

The comments at http://www.java.net/node/645497 (5 years old) appear to agree with me.

A more generic approach would be to allow me to tell schemagen not generate xsds for certain namespaces of my choice, and instead to just insert an <xs:import> either with no schemaLocation, or with a schemaLocation of my choice (no schemaLocation would work for consumers who are using an XMLCatalog to find the appropriate schemas).



 Comments   
Comment by matunos [ 13/Apr/11 10:10 PM ]

I've attached 5 files. The 2 java files are for a java package named 'schemagenSample'. The two xsds and the episode file are the results of running the following command:

$ schemagen.sh -cp . -episode sun-jaxb.episode schemagenSample/*

Comment by Martin Grebac [ 22/Nov/11 10:12 AM ]

Changing to enhancement, not really an issue.

Comment by jinahya [ 05/Apr/14 07:42 PM ]

I've never use `xml:xxx` attributes so far. And I just got this issue with Java 1.8.0.
What if anyone is intending to use those generated (two xsd documents) directly on HTTP output?





[JAXB-1010] allow generate episode to use if-exists attribute Created: 22/May/12  Updated: 03/Apr/14

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: tdrury Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: emystein, Iaroslav Savytskyi, lexi and tdrury

 Description   

We forked the jaxb maven plugin a while back and I'm trying to replace it with the latest "open-source, off-the-shelf" version. The earlier maven plugin didn't generate episode files correctly (or at all?) so we wrote our own plugin to generate episodes. One nice attribute in episode files if the "if-exists" attribute as shown below:

<bindings if-exists="true" scd="~tns:Foo">
<class ref="com.acme.common.Foo"/>
</bindings>

This eliminates the need to re-import every schema when compiler later schemas with this episode file.



 Comments   
Comment by lexi [ 19/Jan/13 11:19 PM ]

I'm not quite sure, how is this related to the maven plugin for JAXB.

Comment by emystein [ 27/Mar/13 04:48 PM ]

tdrury could share your fork that generates episodes with if-exists attribute on bindings?
Thanks in advance,

Comment by tdrury [ 28/Mar/13 02:24 PM ]

I didn't fork the plugin. Instead, I wrote my own maven plugin that generates episode files from the package-info.java file that xjc creates.

Comment by lexi [ 03/Apr/14 07:50 PM ]

Hi Iaroslav,

here's an idea for bindings customization. Was filed in my maven-jaxb2-plugin project, but is clearly not in scope there.

Best wishes,
/Alexey





[JAXB-983] JAXB does not support meta class annotations Created: 14/Oct/13  Updated: 01/Apr/14

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Przemyslaw Bielicki Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: jaxb
Participants: Iaroslav Savytskyi and Przemyslaw Bielicki

 Description   

JAXB reads annotations directly from scanned classes by calling directly java.lang.Class.getAnnotation(Class<A>) This means that Java classes must be annotated directly by e.g. @XmlRootElement, @XmlType etc.

JAXB should read also meta annotations of scanned class annotations i.e. let's take the following example:

Bean.java
@XmlRootElement
@XmlType
// ... other annotations
@Retention(RUNTIME)
@Target(TYPE)
public @interface Bean {
}

and then a Java bean:

Input.java
@Bean
public class Input {

  BigInteger amount;
  Account account;
  // remainder omitted
}

In such case if you execute this:

Main.java
Input input = new Input();
input.setAmount(new BigInteger(1000));
// remainder omitted
JAXBContext.newInstance(Input.class).createMarshaller().marshal(input, System.out);

you will get an error:

Exception in thread "main" javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.SAXException2: unable to marshal type "Input" as an element 
because it is missing an @XmlRootElement annotation]

IMHO it's a bug. JAXB should support annotations annotated with javax.xml.bind annotations. I will send you a patch for class annotations but it should be also the case for fields and methods, I think.



 Comments   
Comment by Przemyslaw Bielicki [ 14/Oct/13 08:44 AM ]

patch sent to dev@jaxb.java.net

Comment by Przemyslaw Bielicki [ 01/Apr/14 09:45 AM ]

patch available on github: https://github.com/pbielicki/jaxb/commit/4bafc09fc6a2be203329e3e2423bf9143698828b





[JAXB-981] Customize default local name for XML element, type and property Created: 10/Oct/13  Updated: 01/Apr/14

Status: Reopened
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: Przemyslaw Bielicki Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: jaxb
Participants: Iaroslav Savytskyi, laune and Przemyslaw Bielicki

 Description   

The following class:

CalculatorInput.java
@XmlRootElement
public class CalculatorInput {

  BigDecimal leftOperand;
  BigDecimal rightOperand;
  Operation operation;

  // setters and getters omitted for brevity

will be serialized by JAXB to the following XML:

CalculatorInput.xml
<calculatorInput>
<operation>MULTIPLY</operation>
<leftOperand>150</leftOperand>
<rightOperand>7</rightOperand>
</calculatorInput>

It is desirable to change the default element, type and property naming convention by the user e.g. one would like to have one of the following outputs (without touching CalculatorInput.java):

CalculatorInput.xml
<CALCULATOR_INPUT>
<OPERATION>MULTIPLY</OPERATION>
<LEFT_OPERAND>150</LEFT_OPERAND>
<RIGHT_OPERAND>7</RIGHT_OPERAND>
</CALCULATOR_INPUT>

or

CalculatorInput.xml
<CalculatorInput>
<Operation>MULTIPLY</Operation>
<LeftOperand>150</LeftOperand>
<RightOperand>7</RightOperand>
</CalculatorInput>

At this moment JAXB does not allow to customize default behavior to obtain results above.

The same problem applies when you annotate your class as @XmlType.



 Comments   
Comment by Przemyslaw Bielicki [ 10/Oct/13 07:55 AM ]

sent patch with a solution proposal to dev@jaxb.java.net

Comment by Iaroslav Savytskyi [ 10/Oct/13 07:56 AM ]

It's possible to customize mapping names with "name" attribute of annotations.
e.g. @XmlRootElement (name="CALCULATOR_INPUT")
Fields can be annotated as @XmlElement(name="LeftOperand")

Comment by laune [ 10/Oct/13 08:01 AM ]

Do you have a proposal how to define these renaming actions in a way that is reasonably simple to handle at run time? Note that you say "without touching <the Java source file>". Also, note that this must work both ways, i.e., for unmarshalling, too.

A very simple XSLT would achieve such transformations easily - most certainly taking less time to write than what would be required in a Java source file context.

Comment by Przemyslaw Bielicki [ 10/Oct/13 08:02 AM ]

Yes I know this but it's not what is needed here.

What if one of my customers needs CALCULATOR_INPUT and another one CalculatorInput as root XML element? Should I maintain two different versions of class CalculatorInput.java with different annotations?

This is not a imaginary requirement - we have it in production.

It's not an acceptable solution.
Please take a look at my patch. I fixed it in an elegant way.

Cheers,
Przemyslaw

Comment by Przemyslaw Bielicki [ 10/Oct/13 08:03 AM ]

@Iaune - yes I have the fix

Comment by Przemyslaw Bielicki [ 10/Oct/13 08:06 AM ]

@Iaroslav - could you please reopen this issue. It's perfectly valid.

Thanks

Comment by Przemyslaw Bielicki [ 01/Apr/14 09:44 AM ]

patch available on github: https://github.com/pbielicki/jaxb/commit/25a20c8a88bdc7eea83f2ccefffc6347bd6abc34





[JAXB-980] Unable to set a generic factory method for @XmlType - factoryMethod / factoryClass Created: 04/Oct/13  Updated: 01/Apr/14

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: Przemyslaw Bielicki Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and Przemyslaw Bielicki

 Description   

JAXB implementation does not allow a generic factory method. Let's take a look at this simple example:

CalculatorInput.java
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "CalculatorInput")
@XmlType(factoryMethod = "getBean", factoryClass = BeanFactory.class)
@Named
public class CalculatorInput {
  
  @Inject
  Context someContext;
IocContainerObjectFactory .java
import javax.inject.Named;
import javax.inject.Singleton;

@Named
@Singleton
public class IocContainerObjectFactory {

  // bean factory init omitted 

  public static <T> T getBean(Class<T> clazz) {
    return beanFactory.getBean(clazz);
  }
}

Example provided above is impossible to implement in current JAXB. The problem here is that you either let JAXB invoke no-arg constructor of CalculatorInput class or explicit static factory method inside this class or in specific factory class. Note that you must have one factory method per class which is extremely bulky, not object-oriented, boilerplate, blah blah blah. Basically it's a mistake.
I know better than JXAB how to create my objects - I need JAXB only to fill these beans with parsed XML content.

Another argument is that JAXB in the current state completely ignores existence of Dependency Injection (which is a part of Java EE specification). In case JAXB creates my CalculatorInput, someContext attribute will be ignored (thus null) by DI container as it has absolutely no knowledge on this instance. The only correct way to make the injection work is to obtain the new instance from the DI bean / object factory - see IocContainerObjectFactory. OK, it is possible but only in such form (again, bulky, boilerplate, ugly):

IocContainerObjectFactory .java
import javax.inject.Named;
import javax.inject.Singleton;

@Named
@Singleton
public class IocContainerObjectFactory {

  // bean factory init omitted 

  public static CalculatorInput getCalculatorInput() {
    return beanFactory.getBean(CalculatorInput.class);
  }

  public static CurrencyConverterInput getCurrencyConverterInput() {
    return beanFactory.getBean(CurrencyConverterInput.class);
  }

  // etc.

}

Imagine what happens if you have more than couple of beans...

Note on JSR-222 specification

JavaDoc of javax.xml.bind.annotation.XmlType says:

XmlType.java
/**
 * Name of a no-arg factory method in the class specified in <tt>factoryClass</tt> factoryClass(). 
 * 
 */
String factoryMethod() default "";

But, the JSR-222 specification does not explicitly say that it must be a no-arg factory method.

Please correct me if I'm wrong.



 Comments   
Comment by Przemyslaw Bielicki [ 04/Oct/13 08:43 AM ]

how can I upload a patch file? I fixed this problem and I would like to submit my proposal

Comment by Przemyslaw Bielicki [ 04/Oct/13 09:16 AM ]

I sent my patch to dev@jaxb.java.net

Cheers,
Przemek

Comment by Przemyslaw Bielicki [ 01/Apr/14 09:43 AM ]

Patch available on GitHub: https://github.com/pbielicki/jaxb/commit/c70183967936ed3e3b0be46eb65694e95c4d583c





[JAXB-917] Add support for XML schema facets and documentation Created: 04/Sep/12  Updated: 01/Apr/14

Status: In Progress
Project: jaxb
Component/s: schemagen
Affects Version/s: 2.2.3
Fix Version/s: None

Type: New Feature Priority: Major
Reporter: yossico Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 17
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

all platforms; java se 7


File Attachments: Java Archive File jaxb-facets-0.3.jar     Java Archive File jaxb-facets-1.0.jar    
Tags: jaxb
Participants: blaise_doughan, Iaroslav Savytskyi, pellcorp, puce, schrepfler, sytzevk, tgeor, whummer and yossico

 Description   

While working closely with quite a few enterprise customers implementing ESBs/BPMs I realized the quality bar for xml schemas is constantly rising. It is no longer acceptable to have xml schema with no documentation and xsd facets.

One open source implementation supporting xsd facets can be found here: http://www.infosys.tuwien.ac.at/staff/hummer/tools/jaxb-facets.html but unfortunately it is not maintained as part of JAXB.

There are many good reasons to keep on using Java 1st approach for schema generation and it better not be neglected and supply such fundamental capabilities.
More relevant links:
http://jaxb.java.net/guide/Generating_Schema_that_you_want.html
http://java.net/projects/jaxb/lists/users/archive/2007-06/message/36



 Comments   
Comment by Iaroslav Savytskyi [ 05/Sep/12 07:44 AM ]

Hi, yossico,

To start working with your code we neen you to sign Oracle Contributor Agreement (OCA). Here are some links:

FAQ: http://www.oracle.com/technetwork/oca-faq-405384.pdf
OCA: http://glassfish.java.net/public/GovernancePolicy.html

Thanks a lot.

Comment by yossico [ 05/Sep/12 07:59 AM ]

Hi Iaroslav,

Just to make it clear, the code i have attached is not mine. It is an open source that is managed through this web site: http://www.infosys.tuwien.ac.at/staff/hummer/tools/jaxb-facets.html. Thus, if this code is planned to be used for this solution, it needs to comply with the license agreement published through that web site (contact: Mr. Waldemar Hummer; email: hummer@infosys.tuwien.ac.at).

Comment by yossico [ 09/Oct/12 07:42 PM ]

Hi,

I signed the form and sent it over a while ago.
To what Java release does Oracle plans to accomodate this enhancement?

Thanks,
Yossi C.

Comment by Iaroslav Savytskyi [ 08/Nov/12 04:57 PM ]

Hi, yossico,
I will look at this and hope if everything will be OK we will include it to JAXB 2.2.7 release.

Comment by whummer [ 09/Nov/12 12:34 PM ]

Version 1.0 of JAXB-Facets

Comment by whummer [ 09/Nov/12 12:34 PM ]

Hi,

there is a more recent, updated version 1.0 of JAXB-Facets available, which contains some minor bug fixes and API changes. I am attaching the most recent version.

EDIT: do we need to sign the agreement for each uploaded version..?

Thanks,
Waldemar H.

Comment by blaise_doughan [ 12/Dec/12 02:10 PM ]

Is JAXB-Facets compatible with Bean Validation (JSR-303)? If not changing it to be would help adoption and make it easier to include in a future version of the JAXB specification.

Comment by pellcorp [ 13/Dec/12 12:09 AM ]

it is not compatible and i would agree changing to use jsr 303 annotations would be a great idea. There is a new github repo for jaxb-facets and we are working on test coverage and refinements. i am using jsr 303 in gwt at work so there is definate synergy there. i am on leave until mid january but would be interested in seeing how easy the Facets and Min Max stuff could be refactored to use equivalent jsr 303 annotations.

only question to ponder is do we use the javax.validation annotations directly?

github is: https://github.com/whummer/jaxb-facets

Comment by pellcorp [ 13/Dec/12 01:38 PM ]

a very relevant forum post has already been made on this topic of jsr 303 compatibility which I was not aware of.

http://java.net/projects/jaxb/lists/dev/archive/2011-01/message/2

so compatibility might not be so easy because jsr 303 does not have the same level of validation as xsd and thus jaxb-facets.

Comment by whummer [ 13/Dec/12 01:47 PM ]

However, we do seek integration with JSR-303 in terms of the facets validation.

The @Facets/@MinOccurs/@MaxOccurs annotations are now annotated with @javax.validation.Constraint(validatedBy=...) and we will provide a custom validator implementation. This way, the Facets validation can be seamlessly integrated into the JSR-303 validation framework.

Comment by yossico [ 03/Feb/13 11:19 AM ]

Hello,

What is the estimated delivery time for this feature?
Is there a plan to incorporate this feature to the JAXB specification?

Thanks,
Yossi C.

Comment by puce [ 15/Feb/13 05:56 PM ]

+1 for adding this feature and making it compatible to JSR-303 resp. JSR-349 (Bean Validation 1.1)

Comment by schrepfler [ 24/Mar/13 03:13 AM ]

This would be a really great extension as it will fill a large hole on how we document services.
It would seem however the latest code is being developed here and not on the whummer repo?
https://github.com/pellcorp/jaxb-facets

Comment by tgeor [ 19/Jun/13 06:53 AM ]

In which version are you planning to include this feature? I think this extension is a must have in JAXB

Comment by schrepfler [ 19/Jun/13 07:49 AM ]

Also, would this only track schemagen or xjc as well?

Comment by whummer [ 21/Jun/13 12:10 PM ]

To avoid confusion, the repository we are working on is here:

https://github.com/whummer/jaxb-facets

We have just finished another round of refactoring, and in terms of features we believe that the code is ready for release. How shall we proceed..?

Comment by yossico [ 01/Aug/13 12:42 PM ]

Hello,

Any progress with this issue?
What is the target release for this enhancement?
When should we expect it?

Your reply to these questions will be greatly appreciated.

Thanks,
Yossi C.

Comment by Iaroslav Savytskyi [ 05/Aug/13 04:15 PM ]

I'm trying to contact the owner of jaxb-facets project. We need all projects' contributors to sign OCA. After that we'll be able to do something.

Comment by yossico [ 06/Nov/13 09:54 AM ]

Hello,

This is a gentle reminder

Do you know by now what is the target release for this enhancement? Release date?
Do you continually track bug-fixes/updates from jaxb-facets web site (https://github.com/whummer/jaxb-facets)?

Thanks,
Yossi C.

Comment by sytzevk [ 19/Jan/14 02:24 PM ]

I see that the Java-first approach is (going to be) covered, but what about wsdl-first ? Does the jaxb-facets project aim to support the jaxb java code generation annotated with facets ?

Comment by whummer [ 31/Jan/14 01:15 PM ]

We have added initial support for wsimport in the current release version (2.2.6-facets-1.1.0), which you can check out from github: https://github.com/whummer/jaxb-facets

@Iaroslav, is there any progress concerning the contributor agreements - when can we continue to merge this into the reference impl.? thanks

Comment by schrepfler [ 27/Mar/14 02:22 PM ]

Hi, any updates on progress or when can we expect to see this part of the official jaxb?

Comment by Iaroslav Savytskyi [ 31/Mar/14 01:59 PM ]

Hi,

We are working on the Bean Validation (JSR 303) support. I hope it will cover requirements of current request.

Comment by schrepfler [ 01/Apr/14 09:39 AM ]

Are you planning to release documentation and facet support at the same time? It might be good to decouple if facet+jsr303/349 will take longer to implement.





[JAXB-1009] JAXB spec should be updated to support new JDK8 Date/Time apis Created: 01/Apr/14  Updated: 01/Apr/14

Status: Open
Project: jaxb
Component/s: spec
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Critical
Reporter: Martin Grebac Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and Martin Grebac




[JAXB-793] Multiple element definition not read correctly Created: 06/Nov/10  Updated: 28/Mar/14

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.1
Fix Version/s: not determined

Type: Bug Priority: Major
Reporter: fhuonder Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 793
Tags: metro2_1-waived metro2_2-waived metro2_3-waived
Participants: daveboden, fhuonder, Iaroslav Savytskyi, kelvin-low and Pavel Bucek

 Description   

Hi all,

I have the following schema complex type:

<complexType name="PolicyType">
<complexContent>
<restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
<sequence>
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}Description" minOccurs="0"/>
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}PolicyDefaults" minOccurs="0"/>
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}CombinerParameters" minOccurs="0"/>
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}Target"/>
<choice maxOccurs="unbounded">
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}CombinerParameters" minOccurs="0"/>
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}RuleCombinerParameters" minOccurs="0"/>
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}VariableDefinition"/>
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}Rule"/>
</choice>
<element ref="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}Obligations" minOccurs="0"/>
</sequence>
<attribute name="PolicyId" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
<attribute name="Version" type="{urn:oasis:names:tc:xacml:2.0:policy:schema:os}VersionType" default="1.0" />
<attribute name="RuleCombiningAlgId" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
</restriction>
</complexContent>
</complexType>

The corresponding JAXB class looks like:

@XmlType(name = "PolicyType", propOrder = { "description", "policyDefaults", "combinerParameters", "target", "additionalInformation", "obligations" })
public class PolicyType implements Evaluatable, Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(name = "Description")
private String description;
@XmlElement(name = "PolicyDefaults")
private DefaultsType policyDefaults;
@XmlElement(name = "combinerParameters")
private CombinerParametersType combinerParameters;
@XmlElement(name = "Target", required = true)
private TargetType target;
@XmlElements({ @XmlElement(name = "Rule", type = RuleType.class), @XmlElement(name = "VariableDefinition", type = VariableDefinitionType.class), @XmlElement(name = "RuleCombinerParameters", type = RuleCombinerParametersType.class), @XmlElement(name = "CombinerParameters", type = CombinerParametersType.class) })
private List<Object> additionalInformation;
@XmlElement(name = "Obligations")
private ObligationsType obligations;
@XmlAttribute(name = "PolicyId", required = true)
@XmlSchemaType(name = "anyURI")
private String policyId;
@XmlAttribute(name = "Version")
private String version;
@XmlAttribute(name = "RuleCombiningAlgId", required = true)
@XmlJavaTypeAdapter(RuleCombiningAlgorithmJAXBTypeAdapter.class)
@XmlSchemaType(name = "anyURI")
private AbstractRuleCombiningAlgorithm ruleCombiningAlg;

...

The thing I want to talk about is the CombinerParameters element. This element is defined twice at different places.
Now when I unmarshal an XML that contains two CombinerParameters elements at the two places the unmarshalling is incorrect.
The second CombinerParameters element is saved into the CombinerParameters element and the first one disappears.
I think the unmarshalling saves both elements into this element and the second overrides the first.
I think the behavior should be that the first is saved into the CombinerParameters field and the second into the
additionalInformation (Choice).



 Comments   
Comment by Pavel Bucek [ 19/Nov/10 09:56 AM ]

thanks for reporting; too late for 2.2.2

metro2.1-waived

Comment by daveboden [ 18/Dec/12 02:25 PM ]

I'm seeing a very similar, if not identical, issue with the FPML 5.4 schema. Please note that I'm using the latest (at time of writing) version of jaxb-impl, 2.2.7-b41, both to compile the bindings and at runtime. Here's the relevant extract from fpml-doc-5.4.xsd :

<xsd:complexType name="TradeIdentifier">
  <xsd:annotation>
    <xsd:documentation xml:lang="en">
    A type defining a trade identifier issued
    by the indicated party.
    </xsd:documentation>
  </xsd:annotation>
  <xsd:sequence>
    <xsd:choice>
      <xsd:sequence>
        <xsd:element name="issuer" type="IssuerId"></xsd:element>
        <xsd:element name="tradeId" type="TradeId"></xsd:element>
      </xsd:sequence>
      <xsd:sequence>
        <xsd:group ref="PartyAndAccountReferences.model">
          <xsd:annotation>
            <xsd:documentation xml:lang="en">
            A pointer style reference to a party identifier and optionally
            an account identifier defined elsewhere in the document.
            The party referenced has allocated the trade identifier.
            </xsd:documentation>
          </xsd:annotation>
        </xsd:group>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="tradeId" type="TradeId"></xsd:element>
          <xsd:element name="versionedTradeId" type="VersionedTradeId">
            <xsd:annotation>
              <xsd:documentation xml:lang="en">
              A trade identifier accompanied by a version number.
              In regulatory reporting views, this should be avoided
              except for internal mnessaging.
              </xsd:documentation>
            </xsd:annotation>
          </xsd:element>
        </xsd:choice>
      </xsd:sequence>
    </xsd:choice>
  </xsd:sequence>
  <xsd:attribute name="id" type="xsd:ID" />
</xsd:complexType>

There are essentially two totally separate definitions of elements that have the same name. <tradeId/>. However, when JAXB parses the corresponding XML it treats all <tradeId/> values as they're the first definition. This results in multiple <tradeId/> values that are part of the second definition (that allows multiple instances of the element) being overwritten as the attribute. The JAXB parse loses the values of all but the last element in the incoming XML.

In this example, <partyTradeIdentifier> is of type TradeIdentifier (well, actually it's a subclass called PartyTradeIdentifier but that is not relevant at this stage):

<tradeReferenceInformation>
    <partyTradeIdentifier>
        <partyReference href="MSERV_BANK123"/>
        <tradeId tradeIdScheme="TradeRefNbr">1212H88885</tradeId>
        <tradeId tradeIdScheme="MatchID">MSE21212.026</tradeId>
        <tradeId tradeIdScheme="ClearerID">667789</tradeId>
    </partyTradeIdentifier>
    <partyTradeIdentifier>
        <issuer issuerIdScheme="http://www.fpml.org/coding-scheme/external/cftc/issuer-identifier">178921368077</issuer>
        <tradeId tradeIdScheme="http://www.fpml.org/coding-scheme/external/unique-transaction-identifier">AAB152121</tradeId>
    </partyTradeIdentifier>
</tradeReferenceInformation>

The result of the JAXB parse is two TradeIdentifier beans. The second one has the tradeId correctly filled in as "AAB152121". Unfortunately the first one doesn't have all 3 values in a list, it just retains the "667789" 3rd and final value as the tradeId. The object that represents the choice maxOccurs="unbounded", which is List<Object> getTradeIdOrVersionedTradeId contains NULL.

I'll work on a simplified test case.

Comment by daveboden [ 07/Jan/13 08:29 PM ]

By the time the Unmarshaller is using a SAX parser to look at the <tradeId/> element, the handler has a map keyed on XML tag Name (namespace + element name) to use:

StructureLoader.childElement(UnmarshallingContext$State, TagName) line: 248
ChildLoader child = childUnmarshallers.get(arg.uri,arg.local);

This only contains a single entry for <tradeId/>

The map is built up when the JAXB context is created here:

SingleElementLeafProperty.buildChildElementUnmarshallers line: 191
handlers.put(tagName, new ChildLoader(l, null));

This overwrites one tag name with another without warning. This line of code should probably check for the existence of the key in the map before overwriting it and at least log something at WARN level.

I don't have any ideas at the moment on how to make an improvement to rectify this issue. Because it's a SAX parser (rather than a more complex grammar parser) and everything is keyed just tag Name, it's not going to be a small change. I'll post my test case and workaround.

Comment by Iaroslav Savytskyi [ 08/Jan/13 10:05 AM ]

Nice, thanks a lot.

Comment by kelvin-low [ 28/Mar/14 05:35 AM ]

I having this issue as well. Daveboden, are you able to provide a workaround?





[JAXB-1008] Misleading xjc Error Message Created: 27/Mar/14  Updated: 27/Mar/14

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Trivial
Reporter: WizardOfZot Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and WizardOfZot

 Description   

Using xjc against a schema file that specifies an invalid version for the xmlns jaxb version results in the following error message:
[ERROR] JAXB version attribute must be "1.0"

However, other versions are applicable such as 2.0 and 2.1

Example:

Schema with the following root element declarations:
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.2"






[JAXB-1004] Specific enum member ignored and Enum class not generated Created: 06/Mar/14  Updated: 21/Mar/14  Resolved: 21/Mar/14

Status: Closed
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Michael Osipov Assignee: Iaroslav Savytskyi
Resolution: Cannot Reproduce Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and Michael Osipov

 Description   

Consider this XML snippet:

<xs:simpleType name="uom">
		<xs:restriction base="xs:string">
			<xs:enumeration value="kg" />
			<xs:enumeration value="m/s" />
			<xs:enumeration value="m³" />
			<xs:enumeration value="L" />
		</xs:restriction>
	</xs:simpleType>

XJC simple does not generate the Enum Uom. If you change to m3 it works.



 Comments   
Comment by Iaroslav Savytskyi [ 11/Mar/14 03:26 PM ]

Hi, Michael,

I've tried this on trunk, on jaxb 2.2.7 and besides it takes quite long I always have positive result:

Uom.java
XmlType(name = "uom", namespace = "")
@XmlEnum
public enum Uom { 
...
 @XmlEnumValue("m\u00b3")
 M("m\u00b3"),
...
}
Comment by Michael Osipov [ 21/Mar/14 10:44 AM ]

Thanks for the feedback. I tried several variations of it with XJC directly and through the Maven plugin and was not able to reproduce it anymore. Feel free to close as NOTABUG.





[JAXB-1007] NPE from marshalling an IDREF that point to a missing ID attribute value Created: 20/Mar/14  Updated: 20/Mar/14

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: tuomas_kiviaho Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and tuomas_kiviaho

 Description   

NPE is thrown prematurely in case of an id attribute being null instead of a more appropriate validation event (Object "..." is found in an IDREF property but this object doesnt have an ID.). In order to fix this see AttributeProperty.serializeAttributes method that deals with the null correctly.

It seems that other people have had to deal this problem before (http://stackoverflow.com/questions/10705532/in-jaxb-marshalling-how-to-identify-which-child-element-caused-jaxb-marshallin). I guess that pinpointing of the cause can be quite problematic with the current behavior.

  • * StackTrace * *
    AttributeProperty<BeanT>.getIdValue(BeanT) line: 128
    ClassBeanInfoImpl<BeanT>.getId(BeanT, XMLSerializer) line: 322
    TransducedAccessor$IDREFTransducedAccessorImpl<BeanT,TargetT>.print(BeanT) line: 290
    TransducedAccessor$IDREFTransducedAccessorImpl<BeanT,TargetT>(DefaultTransducedAccessor<T>).writeLeafElement(XMLSerializer, Name, T, String) line: 69
    SingleElementLeafProperty<BeanT>.serializeBody(BeanT, XMLSerializer, Object) line: 130
    ClassBeanInfoImpl<BeanT>.serializeBody(BeanT, XMLSerializer) line: 361
    XMLSerializer.childAsXsiType(Object, String, JaxBeanInfo, boolean) line: 696





[JAXB-598] Sorting of methods in generated ObjectFactory classes Created: 09/Feb/09  Updated: 18/Mar/14

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.1.9
Fix Version/s: not determined

Type: Improvement Priority: Major
Reporter: normann1974 Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 6
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 598
Tags:
Participants: ciscox83, fowlie, Iaroslav Savytskyi and normann1974

 Description   

When JAXB generated classes are under version control, it's more or less
impossible to see if a regeneration of the JAXB classes has introduced any
changes in the ObjectFactory class because the methods in this class are added
by XJC in random-like order and this leaves the file almost completely modified
according to the version control system. It would be nice if two invocations of
XJC would add the methods in the same order, e.g. by sorting them alphabetically.



 Comments   
Comment by fowlie [ 18/Mar/14 08:22 AM ]

This issue seems quite old, yet no fix for it. How about prioritizing it?

Me and my team would love to have this fixed! Our deployment tool detects changes with checksums, and to avoid having stub classes in source control, we generate them on the fly, thus everything gets deployed all the time, it's very annoying and time consuming.

Comment by ciscox83 [ 18/Mar/14 05:30 PM ]

Quoting fowlie.





[JAXB-1001] Cannot pass language for generated Javadoc Created: 28/Jan/14  Updated: 18/Mar/14

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: Michael Osipov Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi, Michael Osipov and puce

 Description   

Content of Javadoc depends on the locale of the developer machine. E.g., in my case it is de_DE but I need the language of the generated content to be in English. I cannot pass -Duser.language=en. Please add as switch to make this controlable.



 Comments   
Comment by Iaroslav Savytskyi [ 29/Jan/14 05:19 PM ]

I think the easiest way is to change user locale to English just before calling xjc. And if you need - you can switch it back afterwards.

Comment by Iaroslav Savytskyi [ 29/Jan/14 05:21 PM ]

If this solution is acceptable I'm going to close the issue.

Comment by Michael Osipov [ 29/Jan/14 09:03 PM ]

Actually, I can't. I do not use xjc directly but the JAXB Maven Plugin. I do not intend to modify Maven's environment just for one plugin.

Comment by puce [ 18/Mar/14 01:45 PM ]

Any workaround for this in a Jenkins started Maven build using the org.jvnet.jaxb2.maven2:maven-jaxb2-plugin Maven plugin?





[JAXB-514] passing episode file to xjc api creates incorrect Model Created: 11/Jun/08  Updated: 14/Mar/14

Status: In Progress
Project: jaxb
Component/s: xjc
Affects Version/s: 2.1.7
Fix Version/s: not determined

Type: Improvement Priority: Critical
Reporter: ramapulavarthi Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 20
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


File Attachments: Zip Archive jaxb_episode.zip     Text File jaxb_episode.zip     Text File jaxb_episode.zip    
Issuezilla Id: 514
Tags:
Participants: cedric.vidal, euxx, fribeiro, Iaroslav Savytskyi, jahutton, marcelcasado, Martin Grebac, Michael Osipov, Pavel Bucek, ramapulavarthi, rcardillo and RyanCarpenter

 Description   

Attached is the testcase which simulates the way wsimport invokes xjc.
Passing episode works when directly used with xjc ant task. But wsimport uses
xjc api.
This is required for https://jax-ws.dev.java.net/issues/show_bug.cgi?id=368



 Comments   
Comment by ramapulavarthi [ 11/Jun/08 07:15 PM ]

Created an attachment (id=254)
testcase

Comment by ramapulavarthi [ 11/Jun/08 07:25 PM ]

Created an attachment (id=255)
Updated testcase

Comment by ramapulavarthi [ 08/Jan/09 12:06 PM ]

Another bug is filed on jax-ws
(https://jax-ws.dev.java.net/issues/show_bug.cgi?id=690) on the same note.

Comment by Pavel Bucek [ 16/Jan/09 05:32 AM ]

I've tried xjc with episodes from command line and via com.sun.tools.xjc.api.XJC
and both ways are working fine.

My code:

SchemaCompiler sc = XJC.createSchemaCompiler();

InputSource file = new
InputSource("/Users/pavel/jaxb/bugs/514/tryout2/b.xsd");
InputSource episode = new
InputSource("/Users/pavel/jaxb/bugs/514/tryout2/a.episode");

sc.parseSchema(file);
sc.getOptions().addBindFile(episode);
// sc.getOptions().scanEpisodeFile(new
File("/Users/pavel/jaxb/bugs/514/tryout2/a.jar")); // works too

S2JJAXBModel model = sc.bind();

JCodeModel jcm = model.generateCode(null, null);
jcm.build(sc.getOptions().createCodeWriter());

It is working even with xsd and episode you've provided with testcase (after
fixed typos in file wrap.xsd (complesElement and AbstrcatType).

In uploaded testase you're checking for Hello class but it's already present in
episode file so xjc won't generate it. I'm not sure if I understood this
correctly so please reply if I'm missing something.

Comment by Pavel Bucek [ 04/Mar/09 05:05 AM ]

marking as incomplete

Comment by Pavel Bucek [ 19/Mar/09 07:09 AM ]

Closing as invalid. Feel free to reopen with additional info.

Comment by ramapulavarthi [ 20/Mar/09 05:31 PM ]

Reopening the issue.
Please see the testcase. As in the testcase, JAX-WS tries to get Element Mapping
from the model. Although the model has proper schema information,
model.get(QName) is not returning anything. I think there is some problem in
populating the JAXBModelImpl.byXmlName map.

Also, please use the newly attached testcase to reproduce the issue.

Comment by ramapulavarthi [ 20/Mar/09 05:32 PM ]

Created an attachment (id=301)
New testcase with the reopened issue.

Comment by Pavel Bucek [ 24/Mar/09 04:44 AM ]

Can you provide file common-targets.xml, please?

– removing incomplete keyword

– ant output:
$ ant
Buildfile: build.xml
/Users/pavel/jaxb/config/common-targets.xml could not be found

BUILD FAILED
java.io.FileNotFoundException: /Users/pavel/jaxb/config/common-targets.xml (No
such file or directory)

– build.xml:
$ cat ./build.xml | grep common-targets
<!ENTITY commonTargets SYSTEM "../../../../config/common-targets.xml">

Comment by ramapulavarthi [ 24/Mar/09 09:09 AM ]

The common-targets does not have much other than setting up the classpath for
xjc and defining xjc task.

Your earlier test case should suffice for reproducing the problem, just check
the model (model.get(QName)), if it can give info about the elements defined in
hello.xsd

Comment by fribeiro [ 14/Apr/09 05:31 PM ]

Any update yet?

Comment by Pavel Bucek [ 16/Apr/09 01:13 AM ]

We have a workaround.

After short brainstorming session with snajper we've discovered that the easiest
way to support this is do two models - one with episode file included and one
without it (so first will be used to generate java classes and second for
mapping check).

We are aware of performance loss in this case but this isn't used in runtime so
it shouldn't be a major issue.

Please, let us know if this is acceptable (at least for now).

Comment by euxx [ 12/May/09 09:07 AM ]

Is there an update on this?

This issue is very critical for us, we have a common schema and number of
extensions that should reuse the same binding files. So, without this fix the
wsimport can produce a conflicting code that fails at the runtime. Thanks.

Comment by fribeiro [ 08/Sep/09 07:45 PM ]

Any update yet?

Comment by Martin Grebac [ 11/Sep/09 01:50 AM ]

Pavle, did you contact Rama/Jitu about this one?

Comment by Martin Grebac [ 17/Sep/09 09:01 AM ]

Adding an evaluation here such that I don't forget again. Also setting target
milestone.

The reason why JAXB standalone testcase works and why wsimport fails is the very
basic definition of episode files - JAXB ignores types specified in episode
files in it's processing. It doesn't have enough info to create a model from
them. However, wsimport is requesting this information - it requests Mapping
instance from model.get(QName) call. That includes Type and Annotation info.

One possibility to fix this would be to make a place in episode files to provide
such info. Better solution I think is this:

When wsimport requests information for a qname which is not found in the model,
jaxb would look up the episode file, find a corresponding classname; it will
load the class from classpath, read the annotation/type info using reflection
and return it back to jax-ws in mapping instance.

There's a risk in this however: we don't know yet what other information jax-ws
would require from the model, so this fix could be just a beginning and could
uncover more hidden issues. I'll check with Jitu/Rama about what info is
required in the model. Pavel will look into this for 2.2 release.

Comment by Martin Grebac [ 27/Oct/09 08:25 AM ]

This is not really a bug in JAXB, it's an enhancement, so updating the issue. We'll target this one for 2.2.1
as it requires larger changes than we expected. We made several enhancements, but it requires more work
since JAX-WS requires a lot more information to be present from the classes.

Comment by fribeiro [ 02/Nov/09 07:54 PM ]

Thanks for the update.

Comment by fribeiro [ 25/Jan/10 05:41 AM ]

Any update yet?

Comment by fribeiro [ 04/Oct/10 12:59 PM ]

Any update yet?

Comment by marcelcasado [ 24/Nov/11 02:09 AM ]

Any update ? Which version will be this available? Is there a work around? Thanks

Comment by cedric.vidal [ 08/Jun/12 09:34 AM ]

I'm also interested for an update on this.

Comment by RyanCarpenter [ 06/Mar/13 08:55 PM ]

I also appear to be running into this issue and would appreciate an update, if one is available. Thanks

Comment by Iaroslav Savytskyi [ 07/Mar/13 01:13 PM ]

Hi,

To be honest now we have quite a lot of BUGs to be closed. But the light became visible in the end of the tunnel. So I hope I'll be able to start working with this in 1-2 months.

Iaroslav

Comment by rcardillo [ 19/Jul/13 02:35 PM ]

Some people (myself included) have been waiting years for this. Any update on where this is going? I mean, we cannot really use episode files with wsimport effectively without this fix.

Can you at least provide a list of known workarounds that should be considered? I've been finding it difficult to workaround because in a project that uses episode files to make XML binding libraries, it's also really easy to get something generated that fails at runtime (e.g., multiple ObjectFactories that support the same element cause JAXBContext issues at runtime).

Comment by Michael Osipov [ 25/Feb/14 09:34 PM ]

Any update on this? I wasted an entire day to figure out that this is actually a bug!

Comment by jahutton [ 14/Mar/14 02:36 PM ]

Any update? without this fixed it kind of makes jaxws generation useless.

Comment by Michael Osipov [ 14/Mar/14 11:00 PM ]

I second jahutton's statement. Without decoupling the model from the SEI, it is impossible to support separation of concerns. Iaroslav Savytskyi, an entire year has passed without any progress. Please act!





[JAXB-1006] Add @XmlSchemaType(name = "dateTime|date|time|...") annotation Created: 14/Mar/14  Updated: 14/Mar/14

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Michael Osipov Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and Michael Osipov

 Description   

XJC does not add @XmlSchemaType(name = "dateTime|date|time|...") annotation on a XMLGregorianCalendar. The result of this is that if JAX-WS uses these classes, the auto-generated schema has xs:anySimpleType instead of the correct type.






[JAXB-1005] Generation of classes with jaxb fails when an element is named "PRN" Created: 11/Mar/14  Updated: 11/Mar/14

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: francescato Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Eclipse Helios, Windows 7


Tags:
Participants: francescato and Iaroslav Savytskyi

 Description   

I am generating classes from a large xsd file. (Rightclick on pom in projectexplorer, run-as "maven generate sources") When I name an Element with "PRN" the generation process get stuck. It do not break and get also not to finished.
When I rename the Element to PRN2 the same code works.
Environment Helios, java 7, maven, maven-jaxb2 plugin 0.8.0 with basics and annotate 0.6.2. Jaxb version 2.2.7 (also tried 2.2.8 and 2.2.0 ...)
Cant explain such a strange behavior, where the name of an element makes the generation to be stuck.

Extraction from pom.xml
<build>
<plugins>
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.8.0</version>
<configuration>
<schemaDirectory>src/main/resources</schemaDirectory>
<bindingDirectory>src/main/resources</bindingDirectory>
<generatePackage>migration.xml</generatePackage>
<strict>true</strict>
<extension>true</extension>
<forceRegenerate>true</forceRegenerate>
<generateDirectory>src/main/java</generateDirectory>
<!-- <readOnly>true</readOnly> -->
<verbose>true</verbose>

<plugins>
<plugin>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics</artifactId>
<version>0.6.2</version>
</plugin>
<plugin>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics-annotate</artifactId>
<version>0.6.2</version>
</plugin>
</plugins>
<args>
<arg>-Xannotate</arg>
<!-- <arg>-XtoString</arg> -->
</args>
</configuration>
<executions>
<execution>
<id>generate-sources</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>

<!-- plugin to add the jars to the generated jar. -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>src/assemble/exe.xml</descriptor>
</descriptors>
<archive>
<manifestFile>src/main/java/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
</plugins>
</build>

The XSD fragment which do not work.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="PRN">
<xs:annotation>
<xs:documentation xml:lang="en">
ProductRelation
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:attribute name="A" use="required">
<xs:annotation>
<xs:documentation xml:lang="en">
ProductIdRef
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:IDREF">
<xs:minLength value="4"/>
<xs:maxLength value="14"/>
<xs:pattern value="(PDT|PDT-)([0-9])+"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="B" use="required">
<xs:annotation>
<xs:documentation xml:lang="en">
AmountValue
</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:long">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="2147483647"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>






[JAXB-1003]  Invalid pom: jaxb-xjc 2.1.16 has a wrong dependency to jaxb-core 2.1.16 Created: 06/Mar/14  Updated: 07/Mar/14

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.1.16
Fix Version/s: None

Type: Bug Priority: Major
Reporter: roos Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: jaxb-xjc pom dependency
Participants: Iaroslav Savytskyi and roos

 Description   

The pom states a dependency to jaxb-core 2.1.6 which does not exist for the 2.1.x versions.

This bug for 2.1.16 was already reported in a comment of JAXB-984, and one stated to fix it, but the bug is closed now (without a fix).
So nobody is currently able to use 2.1.17, unless they use a fixed private pom.

Please fix all the versions stated in JAXB-984, too.



 Comments   
Comment by roos [ 06/Mar/14 10:16 AM ]

Typos in the comment. 2.1.6 > 2.1.16, 2.1.17 > 2.1.16. Unable to edit the text, sorry.

Comment by Iaroslav Savytskyi [ 07/Mar/14 01:57 PM ]

Hi,

I have pushed jaxb-core 2.1.14. Can you use it as workaround?





[JAXB-937] Nested unmarshalling can lead to NullPointerException Created: 10/Jan/13  Updated: 26/Feb/14  Resolved: 31/Jul/13

Status: Resolved
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.4u2
Fix Version/s: 2.2.8

Type: Bug Priority: Major
Reporter: brands Assignee: Iaroslav Savytskyi
Resolution: Fixed Votes: 2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Java 7 Update 10 on Windows 7


Tags: threadLocal
Participants: anujshahwork, brands, Iaroslav Savytskyi, ratoo and schafdog

 Description   

The attached ZIP contains a Maven project with two test cases.
For this issue, the classes, resources and test case in package com.jaxbtest.java7.bug2 are relevant.

To reproduce:
1.) make sure your current test environment is Java 7 Update 10
For Maven 2.2.1 on Windows it means:
a) set the JAVA_HOME variable to your Java 7 Update 10 JDK installation directory.
b) prepend %JAVA_HOME%\bin to your Path.
2.) run the unit tests in the project
For Maven 2.2.1 it means:
a) execute "mvn test" in the project root directory
b) examine test result (look at ./target/surefire-reports/com.jaxbtest.java7.bug2.UnternehmenTestCase.txt)

It should fail with a NullPointerException.
Coordinator._getInstance() returns null at some point in the stacktrace, so the error reporting fails too.
You have to debug the test in an IDE to see the real cause. You can import the project into Eclipse (m2e required!) for that.

Some observations about the error cause:
Class Unternehmen is the XmlRootElement. It has a list of Branche-elements, which are handled by the BrancheXmlAdapter.
During unmarshall the adapter uses a BrancheConverter helper class. This class in turn loads a XML document via JAXB.
So we have a nested unmarshalling scenario in the same thread. When the nested umnmarshalling ends, Coordinator.resetThreadAffinity() is called. Later, when the second Branche is unmarshalled from the adapted list of Unternehmen, Coordinator._getInstance() returns null in
AdaptedLister#getAdapter()

com.jaxbtest.java7.bug2.UnternehmenTestCase is the entrypoint for the test.

I think it also fails for JAXB 2.2.6.
It works with Java 6 Update 35 for example.



 Comments   
Comment by brands [ 10/Jan/13 08:57 AM ]

How can I attach the ZIP file with the test???

Comment by brands [ 10/Jan/13 09:13 AM ]

Attachement is available here:
http://glassfish.10926.n7.nabble.com/attachment/87486/0/jaxb-testcases.zip

Comment by ratoo [ 10/Jan/13 09:52 AM ]

May be related to JAXB-844 fix

Comment by anujshahwork [ 05/Apr/13 09:04 PM ]

We've seen this problem as well. A possible fix that worked for us is to move the ThreadLocal removal logic from resetThreadAffinity() into the popCoordinator() method so that last leaver clears the table.

/**
     * Associates this {@link Coordinator} with the current thread.
     * Should be called at the very beginning of the episode.
     */
    protected final void setThreadAffinity() {
        table = activeTable.get();
        assert table!=null;
    }

    /**
     * Dis-associate this {@link Coordinator} with the current thread.
     * Sohuld be called at the end of the episode to avoid memory leak.
     */
    protected final void resetThreadAffinity() {
        // Don't remove the thread local activeTable here as we may be in a nested serialization situation
        if(debugTableNPE)
            guyWhoSetTheTableToNull = new Exception(); // remember that we set it to null 
        table = null;
    }

    /**
     * Called whenever an execution flow enters the realm of this {@link Coordinator}.
     */
    protected final void pushCoordinator() {
        old = table[0];
        table[0] = this;
    }

    /**
     * Called whenever an execution flow exits the realm of this {@link Coordinator}.
     */
    protected final void popCoordinator() {
        assert table[0]==this;
        table[0] = old;
        if (old == null) {
          // If the old Coordinator is null we must be the last one out of the stack.
          // So we should clear the ThreadLocal
          if (activeTable != null) {
            activeTable.remove();
          }
        }
        old = null; // avoid memory leak
    }
Comment by anujshahwork [ 07/May/13 07:52 PM ]

I have a simple one line fix and accompanying test in a patch. This has been attached to the forum.

http://glassfish.10926.n7.nabble.com/file/n87597/JAXB-937.patch

Comment by Iaroslav Savytskyi [ 31/Jul/13 01:15 PM ]

Fixed in JAXB 2.2.8

Comment by schafdog [ 26/Feb/14 03:18 PM ]

I am seeing a very similar crash, but as far as I can see there is no nested here. Implement this project

http://blog.bdoughan.com/2012/02/xmlanyelement-and-xmladapter.html

(a very simple @XmlAnyElement with a @XmlJavaTypeAdaptor using Java 7u51 jaxb-impl instead of the EclipseLink. The project works fine in Java 6 and Java 7u5. And if I override with jaxb-impl 2.2.4-1.

Or has the API change so the project is no longer valid code?

Secondly, I have checked out the code but I do not see any 2.2.8 tag? I will try with HEAD now to see if this fixes it.





[JAXB-992] Property "Value" is already defined in /com/sun/xml/xsom/impl/parser/datatypes.xsd[14,33] Created: 29/Nov/13  Updated: 26/Feb/14

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.1.13
Fix Version/s: None

Type: Bug Priority: Major
Reporter: martinspamer Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7 + Java 1.7.45 + Maven 3.11 + Eclipse Kepler


Tags:
Participants: anupamb82, Iaroslav Savytskyi and martinspamer

 Description   

Attempting to compile a schema exposes duplicate propertty in datatypes.xsd

[ERROR] jar:file:/C:/Users/MSpamer/.m2/repository/com/sun/xml/bind/jaxb-xjc/2.1.13/jaxb-xjc-2.1.13.jar!/com/sun/xml/xsom/impl/parser/datatypes.xsd[14,33]
com.sun.istack.SAXParseException2; systemId: jar:file:/C:/Users/MSpamer/.m2/repository/com/sun/xml/bind/jaxb-xjc/2.1.13/jaxb-xjc-2.1.13.jar!/com/sun/xml/xsom/impl/parser/datatypes.xsd; lineNumber: 14; columnNumber: 33; Property "Value" is already defined. Use <jaxb:property> to resolve this conflict.
at com.sun.tools.xjc.ErrorReceiver.error(ErrorReceiver.java:82)
at com.sun.tools.xjc.reader.ModelChecker.checkPropertyCollision(ModelChecker.java:108)
at com.sun.tools.xjc.reader.ModelChecker.check(ModelChecker.java:94)
at com.sun.tools.xjc.reader.ModelChecker.check(ModelChecker.java:67)
at com.sun.tools.xjc.reader.xmlschema.BGMBuilder._build(BGMBuilder.java:189)
at com.sun.tools.xjc.reader.xmlschema.BGMBuilder.build(BGMBuilder.java:116)
at com.sun.tools.xjc.ModelLoader.annotateXMLSchema(ModelLoader.java:415)
at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:167)
at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:113)
at com.sun.tools.xjc.Driver.run(Driver.java:313)
at org.codehaus.mojo.jaxb2.AbstractXjcMojo.execute(AbstractXjcMojo.java:327)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:106)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:317)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:152)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:555)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:214)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
at org.codehaus.classworlds.Launcher.main(Launcher.java:46)



 Comments   
Comment by Iaroslav Savytskyi [ 02/Dec/13 02:01 PM ]

Hi,

Please provide more info:

1) What exactly are you trying to do?
2) Why are you using JAXB 2.1.x?

Thanks.

Comment by martinspamer [ 09/Jan/14 01:22 PM ]

I'm writing an automation test suite for a system that has a unrigourously defined schema from a third party over which I have no control.

I was using http://mojo.codehaus.org/jaxb2-maven-plugin/ because I wanted to utilise its feature for creating test classes for the element object model. That plugin uses 2.1.13.

Comment by Iaroslav Savytskyi [ 09/Jan/14 04:52 PM ]

Can you please send me testcase to iaroslav.savytskyi at oracle.com so I will attach it here.

Thanks.

Hopefully we will update maven plugin for JAXB-RI soon.

Comment by anupamb82 [ 26/Feb/14 09:01 AM ]

I also faced the same issue when I tried to generate the class out of this xsd file.

ftp://ftp.ncbi.nlm.nih.gov/pubchem/data_spec/pubchem.xsd

I hope this will help to resolve the problem.

Regards
Anupam





[JAXB-936] problem with XMLMixed in a tag annotated XmlAnyElement Created: 21/Dec/12  Updated: 18/Feb/14

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.6
Fix Version/s: None

Type: Bug Priority: Major
Reporter: beynet Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 1
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: beynet, gastush and Iaroslav Savytskyi

 Description   

If two tags are separated only by spaces these spaces are lost.
Xml Example :
------------
<testAny> <h> <body>
<p>
Text content
<a href="http://www.google.com">link2</a> <a href="http://www.google.com">link3</a>
.
</p>
</body>
</h>
</testAny>

Java Jaxb class :
-------------
@XmlType(name="TestAnyType")
@XmlRootElement(name="testAny")
public class TestAny {
@XmlAnyElement(lax=false)
@XmlMixed
public List<Object> getContent() { return(content); }

private List<Object> content = new ArrayList<Object>();
}

Code to produce the problem :
--------------------------
public class TestAnyT {
@Test
public void marshal() throws JAXBException { JAXBContext context = JAXBContext.newInstance(TestAny.class); System.out.println(context); Marshaller marshaller = context.createMarshaller(); Unmarshaller unmarshaller = context.createUnmarshaller(); TestAny t = (TestAny)unmarshaller.unmarshal(new File("./src/test/java/org/beynet/t.xml")); System.out.println(t); marshaller.marshal(t, new StreamResult(System.out)); }
}
Resulting XML after marshaling :
---------------------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><testAny> <h><body><p>
Text content
<a href="http://www.google.com">link2</a><a href="http://www.google.com">link3</a>
.
</p>
</body>
</h>
</testAny>

The spaces between the two tags "<a" are lost ....



 Comments   
Comment by gastush [ 18/Feb/14 09:27 PM ]

The characters that are "lost" are the spaces but also the Line feed and tabs (all chars in the space class of characters).
This is causing any issue when using JAXB with XML fragment (using xsd:any) that are supposed to be in a cannonicalized form. (think about a WebService, using JAX-WS for which one of the operations takes an xsd:any that is in a cannonicalized form at that should be used to compute or verify a signature).
Adding any non-space chars between the tags brings back all the space characters in the marshalled XML.

If it can help, looking at the org.w3c.dom.Node produced when unmarshalling, one can see that the spaces that are lost are present in the previousSibling elements only.





[JAXB-924] bindingschema_2_0.xsd: globalBindings: extension binding declarations: wrong mulitplicity Created: 16/Oct/12  Updated: 13/Feb/14

Status: Open
Project: jaxb
Component/s: spec
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: puce Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 11
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: gzress, Iaroslav Savytskyi, Martin Grebac and puce

 Description   

The following JAXB bindings file creates the Adapter classes as expected, but Eclipse and XMLSpy say it's no valid:

<?xml version="1.0" encoding="UTF-8"?>
<jxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd" version="2.1">
<jxb:globalBindings>
<jxb:javaType name="java.util.Calendar" xmlType="xs:date" parseMethod="javax.xml.bind.DatatypeConverter.parseDate" printMethod="javax.xml.bind.DatatypeConverter.printDate" />
<jxb:javaType name="java.util.Calendar" xmlType="xs:dateTime" parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime" printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />
<jxb:javaType name="java.util.Calendar" xmlType="xs:time" parseMethod="javax.xml.bind.DatatypeConverter.parseTime" printMethod="javax.xml.bind.DatatypeConverter.printTime" />
</jxb:globalBindings>
</jxb:bindings>

The error is something like:

cvc-complex-type.2.4.b: The content of element 'jxb:globalBindings' is not complete. One of '{"http://java.sun.com/xml/ns/jaxb":javaType, "http://java.sun.com/xml/ns/jaxb":serializable, WC[##other:"http://java.sun.com/xml/ns/jaxb"]}' is expected.

I was pointed out that the multiplicity should be as follows:

<xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:documentation>allows extension binding declarations to be specified.</xs:documentation>
</xs:annotation>
</xs:any>



 Comments   
Comment by gzress [ 03/Jan/13 06:33 AM ]

Wouldn't it be a little faster to correct the XSD than to change this issue priority?

regards
Grzegorz Grzybek

Comment by Martin Grebac [ 03/Jan/13 08:01 AM ]

Well, not - the schema is defined in the JSR 222 spec, so this can only be addressed within MR.

Comment by gzress [ 03/Jan/13 08:22 AM ]

Well, right... And how to get the MR to be released?

Comment by puce [ 15/Oct/13 11:00 AM ]

Any news on this?

Comment by puce [ 13/Feb/14 11:58 AM ]

Will this be fixed in Java 8?

Comment by Iaroslav Savytskyi [ 13/Feb/14 12:47 PM ]

I'm not aware about the coming MR. So, unfortunately, no news and I don't think this would be fixed in JDK8.





[JAXB-926] CLONE -optionalProperty="primitive" does not work Created: 24/Oct/12  Updated: 12/Feb/14  Resolved: 12/Feb/14

Status: Resolved
Project: jaxb
Component/s: xjc
Affects Version/s: 2.1.7
Fix Version/s: 2.1.9

Type: Bug Priority: Major
Reporter: mdarwin Assignee: Iaroslav Savytskyi
Resolution: Fixed Votes: 1
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 510
Tags: xjc
Participants: Iaroslav Savytskyi, Martin Grebac and mdarwin

 Description   

My Xml file is like this

<?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://net.sf.webcommand/cmdmeta"
elementFormDefault="qualified" attributeFormDefault="unqualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://net.sf.webcommand/cmdmeta"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb" jxb:version="2.0">
<annotation>
<appinfo>
<jxb:globalBindings optionalProperty="primitive">
<jxb:serializable uid="1" />
</jxb:globalBindings>
</appinfo>
</annotation>

<complexType name="foo">
<sequence>
<element name="display" type="boolean" minOccurs="0">

</element>
</sequence>
</complexType>

</schema>

when I run the command, /xjc.sh -d src meta.xsd, the method signature for
display is always Boolean instead of primitive boolean type.

I tried JAXB-2.1.7, JAXB-2.0.5 and JAXB from java 6.
All of them gave me reference Boolean type instead of primitive boolean type.

thanks

-jason



 Comments   
Comment by mdarwin [ 24/Oct/12 08:04 AM ]

In the spec, it says the following:

optionalProperty controls how a JAXB property with a primitive base type that represents an optional non-nillable element/attribute is bound. If the attribute has the value "wrapper", then the base type of the JAXB property is the wrapper class for the primitive type. A user can indicate that this optional property is not set by calling the setter with “null” value. If the attribute’s value is "primitive", it binds as it did in JAXB 1.0. If the attribute’s value is “isSet”, it binds the optional property using the primitive base type and also the isSet/unset methods are generated for the optional property. The attribute’s default value is “wrapper”.

If you bind the above xml with jaxb1.0, you get generated objects with a method getDisplay() which returns boolean (primitive).

If you use jaxb 2.0 with optionalProperty set to "primitive" you should get exactly the same thing - that's what the spec says.

I see the point about what to do if minOccurs="0" - but again, the JAXB 1.0 code handles this just fine, by setting booleans to false by default.

I'm trying to migrate from JAXB 1.0 to JAXB 2, and I am at the point of giving up, because this bug makes it too hard for me to migrate my client code.

Comment by mdarwin [ 25/Oct/12 01:18 PM ]

see also http://stackoverflow.com/questions/13035975

Comment by Martin Grebac [ 30/Oct/12 02:50 PM ]

Agree - Yardo, let's try to address this.

Comment by Iaroslav Savytskyi [ 12/Feb/14 04:41 PM ]

Fixed in trunk.





[JAXB-927] optionalProperty="primitive" does not work Created: 27/Oct/12  Updated: 12/Feb/14  Resolved: 12/Feb/14

Status: Closed
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.6
Fix Version/s: 2.2.9

Type: Bug Priority: Major
Reporter: mdarwin Assignee: Martin Grebac
Resolution: Fixed Votes: 1
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Platform: All
OS: All


Tags: jaxb-xjc compile
Participants: archenroot, Iaroslav Savytskyi, Martin Grebac and mdarwin

 Description   

When an xsd defines an optional boolean field, if the optionalProperty attribute is set to "primitive", it should bind as it did in 1.0, according to the spec, but it doesn't.

For example, given the following xsd:

<xs:element name="usage-auth-rate-charge">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="service-id" type="xs:string"/>
            <xs:element name="pricepoint_custom_fields_required" type="xs:boolean" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

and specifying optionalProperty="primitive" in the binding xml, the generated class looks like this:

public class UsageAuthRateCharge {
........
public Boolean isPricepointCustomFieldsRequired() {
    return pricepointCustomFieldsRequired;
}

this method returns Boolean, not boolean as per the spec.

The problem is that although boxing will work, if the supplied xml doesn't contain a value for pricepoint_custom_fields_required, the class's Boolean field is null, instead of false. So a NullPointerException will be seen when doing something like this:

methodWhichTakesPrimitiveBooleanArg(myUsageAuthRateChargeInstance.isPricepointCustomFieldsRequired());

In the spec, it says the following:

optionalProperty controls how a JAXB property with a primitive base type that represents an optional non-nillable element/attribute is bound. If the attribute has the value "wrapper", then the base type of the JAXB property is the wrapper class for the primitive type. A user can indicate that this optional property is not set by calling the setter with "null" value. If the attribute's value is "primitive", it binds as it did in JAXB 1.0. If the attribute's value is "isSet", it binds the optional property using the primitive base type and also the isSet/unset methods are generated for the optional property. The attribute's default value is "wrapper".

If you bind the above xml with jaxb1.0, you get generated objects with a method getDisplay() which returns boolean (primitive).

If you use jaxb 2.0 with optionalProperty set to "primitive" you should get exactly the same thing - that's what the spec says.

In JAXB 1.0, if minOccurs="0", and the xsd contains no default value for the boolean, booleans are set to false by default.

NB This is a duplicate of 926 which was raised against an older version of the code. This bug affects 2.2.6.



 Comments   
Comment by archenroot [ 20/Nov/13 09:53 PM ]

I tried with 2.2.7 and 2.2.8 version and they are also affected.

So the expected result should be something like this in jaxb binding generated class?
public Boolean myBoolean() {
if (myBoolean== null){ return false; }
return myBoolean;
}

Or the isNull should be prevented inside of jaxb and in case of positive test (the attribute is not presented) it should default to false?

This issue is not only case of boolean type, but String as well, if you try to getString() attribute and it is also optional and not presented, you will fail the same way if you will try to any operation because it is also null.

Comment by mdarwin [ 06/Dec/13 09:42 AM ]

Hi archenroot,

Strictly speaking, to conform to the spec, the generated class should return boolean not Boolean (when the optionalProperty flag is set to primitive).

However, if the returned type is Boolean, that would work for me. We can rely on auto-unboxing, but it must never return a null (obviously).

It doesn't matter to me whether it's done inside jaxb or in the generated class. Just as long as the myBoolean method either returns boolean, or returns Boolean and guarantees that it will never be null.

Comment by Iaroslav Savytskyi [ 12/Feb/14 04:41 PM ]

Fixed in trunk.





[JAXB-999] Not well-formed XML output by Marshaller in conjunction with @XmlAnyAttribute Created: 26/Jan/14  Updated: 04/Feb/14

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: m4t Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Max OS X, JDK 1.7.0_51


Tags: marshaller well-formed xmlanyattribute
Participants: Iaroslav Savytskyi and m4t

 Description   

Summary

I encountered a situation where a javax.xml.bind.Marshaller produces not well-formed XML, despite throwing no exception nor raising a validation event. The problem arises when using @XmlAnyAttribute-Annotation in a special way.

Details

Consider the following scenario (imports omitted):

Test.java
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
public class Test {
	
	@XmlAttribute
	public String id;
	
	@XmlAnyAttribute
	public Map<QName,String> other;

}
test.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
    <xs:element name="test">
    	<xs:complexType>
    		<xs:anyAttribute processContents="skip"/>
    	</xs:complexType>
    </xs:element>
</xs:schema>
Main.java
public class Main {

	public static void main(String[] args) throws Exception {

		Test t = new Test();
		t.id = "5";
		t.other = new HashMap<QName, String>();
		t.other.put(new QName("id"), "10");

		JAXBContext jc = JAXBContext.newInstance(Test.class);
		Marshaller m = jc.createMarshaller();
		SchemaFactory sf = SchemaFactory
				.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		Schema schema = sf.newSchema(new File("test.xsd"));
		m.setSchema(schema);
		m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "test.xsd");
		m.setEventHandler(new ValidationEventHandler() {

			@Override
			public boolean handleEvent(ValidationEvent event) {
				System.out.println("Validaten event received.");
				return false;
			}
		});
		m.marshal(t, new File("test.xml"));

	}

}

The invocation of Main.main does the following:

  • No exception is raised.
  • The handleEvent-method is not called.
  • A file "test.xml" is written, in which the element "test" carries the attribute "id" twice. Once with value "5", and once with value "10". Hence, it is not well-formed XML.

Since the operation silently succeeds, a user expects a valid XML with respect to the XML schema. As far as I know, validity w.r.t. schema implies that it is also well-formed. Assuming no schema is used, a user would expect that the output is well-formed if no error or warning is given.

The ugly workaround is to add an additional check on top of the Marshal validation for well-formedness, as long as this shortcoming exists.

Side-notes

I am aware of the fact that this usage of the XmlAnyAttribute-map can be considered as an edge case. Nevertheless, the Marshaller should check for validity of the input. At the moment, the silent-fail-outcome is highly undesirable.

Proposals

Proposals in which direction a fix could go:

  1. A Marshaller raises an exception if the output would not be well-formed XML. The postcondition, that the output is always well-formed, should be included in the javadocs.
    1. In the special case where a regularly mapped attribute is again specified in the XmlAnyAttribute-map, this error is explained in the exception.
  2. If proposal 1 can not be implemented: When using a XML schema on a Marshaller, the validation succeeds only if the XML is also well-formed.

Thanks for looking into this!



 Comments   
Comment by m4t [ 04/Feb/14 09:23 PM ]

A situation where also not well-formed XML is produced, but doesn't build on attribute collision, is the following:

If you store an attribute with empty name into the QName-map. Replace

new QName("id")

with

new QName("")

in the above example. No exception is raised, the produced string is not XML (attribute with empty name). I guess also invalid characters for XML would not be intercepted.





[JAXB-1000] com.sun.xml.bind.v2.ClassFactory has memory leak Created: 28/Jan/14  Updated: 29/Jan/14

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.6, 2.2.7
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: herman.bovens Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Tomcat 7


Tags:
Participants: herman.bovens and Iaroslav Savytskyi

 Description   

This error is seen in tomcat 7 logs:

SEVERE: The web application [/secportal] created a ThreadLocal with key of type [com.sun.xml.bind.v2.ClassFactory$1] (value [com.sun.xml.bind.v2.ClassFactory$1@301013d6]) and a value of type [java.util.WeakHashMap]

This is caused by JAXB creating but never clearing a ThreadLocal of type ClassFactory.



 Comments   
Comment by herman.bovens [ 28/Jan/14 12:28 PM ]

Apparently there was JAXB-831 for an earlier version, but it seems it was never really resolved. I can't reopen that bug.
I don't know if it's possible at all to create a test case for it. If no thread pooling is done, this isn't really an issue, but it is in application servers like Tomcat.

Comment by Iaroslav Savytskyi [ 29/Jan/14 05:33 PM ]

You are absolutely right. Unfortunately JAXB doesn't have any chance to clean up caches. Simply because in API we don't have any 'finalization' process.

To avoid this bug Martin changed com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl signature and make is closeable. So in your code when you are done call close on your unmarshaller instance.

Thanks.





[JAXB-1002] "com.mypackage.A" is substituting "com.mypackage.BaseType", but "com.mypackage.A" is bound to an anonymous type. Created: 28/Jan/14  Updated: 28/Jan/14

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.4u2
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: MRalwasser Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows


Tags:
Participants: Iaroslav Savytskyi and MRalwasser

 Description   

I am facing an issue while marshalling a JAXB model tree to a xml file using JAXB.

Its classes has been created by the JDK's xjc.
The xml schema files seem to be valid according xjc (and other xml tools).
The creation of the class files completed without any errors.

However, I am unable to marshall them, the exception which I get is:

com.sun.istack.internal.SAXException2: "com.mypackage.A" is substituting "com.mypackage.BaseType", but "com.mypackage.A" is bound to an anonymous type.
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:237)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:652)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:143)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementNodeProperty.serializeItem(ArrayElementNodeProperty.java:54)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementProperty.serializeListBody(ArrayElementProperty.java:157)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:144)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:335)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:143)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:335)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:143)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:143)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:143)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl$1.serializeBody(ElementBeanInfoImpl.java:146)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl$1.serializeBody(ElementBeanInfoImpl.java:116)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeBody(ElementBeanInfoImpl.java:318)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeRoot(ElementBeanInfoImpl.java:325)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeRoot(ElementBeanInfoImpl.java:61)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayReferenceNodeProperty.serializeListBody(ArrayReferenceNodeProperty.java:103)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:144)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:143)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementNodeProperty.serializeItem(ArrayElementNodeProperty.java:54)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementProperty.serializeListBody(ArrayElementProperty.java:157)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:144)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl$1.serializeBody(ElementBeanInfoImpl.java:141)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl$1.serializeBody(ElementBeanInfoImpl.java:116)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeBody(ElementBeanInfoImpl.java:318)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeRoot(ElementBeanInfoImpl.java:325)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeRoot(ElementBeanInfoImpl.java:61)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:483)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:236)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:95)
(...)

I am asking whether

  • if this is a jaxb bug
  • I am doing something wrong
  • if the schema files are somewhat errornous which xjc does not detect

Important:
I cannot modify the XSD files - they are defined by federal authorities and according to several xml/xsd tools they seem to be correct.






[JAXB-998] running with option -fullversion fails Created: 22/Jan/14  Updated: 22/Jan/14

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: jkidd Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Mac Mavericks


Tags: cli command command-line
Participants: Iaroslav Savytskyi and jkidd

 Description   

jenss-mbp:bin jkv$ ./xjc.sh -fullversion
Exception in thread "main" java.lang.IllegalArgumentException: can't parse argument number: build.number
at java.text.MessageFormat.makeFormat(MessageFormat.java:1420)
at java.text.MessageFormat.applyPattern(MessageFormat.java:479)
at java.text.MessageFormat.<init>(MessageFormat.java:363)
at java.text.MessageFormat.format(MessageFormat.java:835)
at com.sun.tools.xjc.Messages.format(Messages.java:54)
at com.sun.tools.xjc.Driver.run(Driver.java:232)
at com.sun.tools.xjc.Driver.run(Driver.java:200)
at com.sun.tools.xjc.Driver._main(Driver.java:123)
at com.sun.tools.xjc.Driver.access$000(Driver.java:80)
at com.sun.tools.xjc.Driver$1.run(Driver.java:103)
Caused by: java.lang.NumberFormatException: For input string: "build.number"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at java.text.MessageFormat.makeFormat(MessageFormat.java:1418)
... 9 more






[JAXB-997] Provide a fluent interface on set methods Created: 09/Jan/14  Updated: 09/Jan/14  Resolved: 09/Jan/14

Status: Closed
Project: jaxb
Component/s: None
Affects Version/s: 2.2.8
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: martinspamer Assignee: Iaroslav Savytskyi
Resolution: Works as designed Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

All


Tags: codemodel fluent-interface improvement
Participants: Iaroslav Savytskyi and martinspamer

 Description   

Currently the code generated for setting the property of an Element is

/**

  • Sets the value of the name property.
  • @param value
  • allowed object is
  • {@link String }
  • */
    public void setName(String value) { this.name = value; }

If instead the following code was generated

public XmlElementName setName(String value) { this.name = value; return this; }

This would go a long way to providing a fluent interface for setting up the Object Model and lead to much more elegant production code for developers using jaxb.



 Comments   
Comment by Iaroslav Savytskyi [ 09/Jan/14 05:09 PM ]

I'm not sure it's possible.

According to specification [1] we have to follow JavaBeans-style.

What you can do is to write a JAXB plugin [2]. Which will make what you want.

1: https://jcp.org/aboutJava/communityprocess/mrel/jsr222/index2.html
2: https://jaxb.java.net/plugin.html





[JAXB-970] JAXB marshal if identation exceeds nested level 8 Created: 25/Jul/13  Updated: 09/Jan/14

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.1.10, 2.2.4u2
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: matejsp Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: 1 hour
Time Spent: Not Specified
Original Estimate: 1 hour
Environment:

JDK 1.6 and JDK 1.7


Tags:
Participants: Iaroslav Savytskyi, laune and matejsp

 Description   

When calling JAXB marshal with pretty print it outputs:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
<b>
<c>
<d>
<e>
<f>
<g>
<h>
<i>
<j/>
</i>
</h>
</g>
</f>
</e>
</d>
</c>
</b>
</a>

The problem is when reaching indentation level 8 it restarts indentation.

The problem is in the:
IndentingUTF8XmlOutput.java

buggy function:
private void printIndent() throws IOException { write('\n'); int i = depth%8; write( indent8.buf, 0, i*unitLen ); i>>=3; // really i /= 8; for( ; i>0; i-- ) indent8.write(this); }

You can see that variable i is using remainder of division with 8.
After that i>>3 is already the remainder.
i >>= 3 (i = i >> 3) should be instead ... i = depth >> 3;

Other implementations does not exhibit such behavior.



 Comments   
Comment by matejsp [ 24/Dec/13 09:51 AM ]

There is another issue in Encoding class.
indent8.write(this); does not work as it should.

code
Encoded e = new Encoded(indentStr);
indent8 = new Encoded();
indent8.ensureSize(e.len*8);
unitLen = e.len;
for( int i=0; i<8; i++ )
System.arraycopy(e.buf, 0, indent8.buf, unitLen*i, unitLen);
code

The problem is that Encoded.ensureSize does not change the field of encoded length.

Comment by Iaroslav Savytskyi [ 09/Jan/14 02:08 PM ]

I agree with you.. It's strange.
But I also see good thing and may be this code was written to do exactly this.

Imagine 100x elements depth. Is it good idea to scroll to see the middle element???

We will discuss this internally.

Thanks a lot for reporting.

Comment by laune [ 09/Jan/14 02:22 PM ]

Also, consider the potentially huge amount of white space.





[JAXB-996] Slow performance of Unmarshaller when reading xsd:any element Created: 24/Dec/13  Updated: 24/Dec/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: pcb Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7, standard JDK 1.7.0_04


Tags:
Participants: Iaroslav Savytskyi and pcb

 Description   

I had already reported this issue to Oracle, but I don't think it got attention (and maybe I was reporting it to the wrong people anyway). On the users@jaxb.java.net mailing list Iaroslav guided me here. So below is a copy/paste of my bug report. In short: unmarshalling xml files with a lot of 'any' elements takes an unacceptable long time in JDK 1.7u4.

Date Created: Thu Mar 28 08:28:09 MST 2013
Type: bug
Customer Name: Pieter Buzing
Customer Email: Buzing@...
SDN ID:
status: Waiting
Category: jaxb-xsd
Subcategory: runtime
Company: Riscure BV
release: 1.0.4
hardware: x64
OSversion: windows_7
priority: 3
Synopsis: Performance degradation between java 7u3 and 7u4 for xml
parsing of "xsd:any"
Description:
FULL PRODUCT VERSION :
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b22) Java HotSpot(TM)
64-Bit Server VM (build 23.0-b21, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows [Version 6.1.7601]

A DESCRIPTION OF THE PROBLEM :
We observe a performance degradation between java 7u3 and 7u4 with
regard to the xml parsing of an "xsd:any" element with JAXB2. Also
later java updates have the same poor performance.

Given:

  • an xsd schema which contains an "xsd:any" element and which is
    compiled with xjc (version 2.2.4)
  • an xml file that conforms to the above xsd schema and contains (a lot
    of) <xsd:any> elements
  • a java class that unmarshals the above xml file
  • a Windows 7 computer with both jdk 7u3 and a later update installed

When we run the java unmarshal code with jdk1.7.0_04\bin\java.exe (7u4)
we observe that the required time is at least twice the runtime needed
by jdk1.7.0_03\bin\java.exe (7u3).

REGRESSION. Last worked in version 1.0.4

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
1. Prepare an xsd file with an xs:any element (like in the comments in
the java code), compiling it with xjc.
2. Prepare a matching xml file that contains (a lot of) xs:any elements
(see also the comments in the java file).
3. Compile and run java code that unmarshals the xml data (like the
supplied example code).
4. Observe that running the code with jdk7u3 is at least twice as fast
compared to later updates.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
The expected behavior would be an equal runtime for both java 7u3 and
7u4.
ACTUAL -
We observed a performance difference between different java runtime
environments:

java version = 1.7.0_03
.file size = 1613 bytes, read took 36 ms

java version = 1.7.0_04
.file size = 1613 bytes, read took 75 ms

When we increase the size of the xml file (or read multiple xml files)
the relative performance difference grows. Also for later updates like
7u17 we see the same performance degradation compared to 7u3.

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import anyexample.Root;
import anyexample.Root.Anyproperties;

/**
This code demonstrates a performance bug in java 7u4. Steps to
replicate this bug:

1. Save and compile this xsd schema:
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema";>
<xs:element name='Root'>
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="1" maxOccurs="unbounded"
name="anyproperties">
<xs:complexType>
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded"
/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

The code assumes that the resulting class files are stored in a
directory called anyexample.

2. Store the following xml file as 'anyprops.xml':
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Root>
<anyproperties>
<Prop1>0</Prop1>
<Prop2>Inverse</Prop2>
<Prop3>bits</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>1</Prop1>
<Prop2>out</Prop2>
<Prop3>bits</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>3</Prop1>
<Prop2>bla</Prop2>
<Prop3>foo</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>4</Prop1>
<Prop2>bla</Prop2>
<Prop3>bar</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>5</Prop1>
<Prop2>bla</Prop2>
<Prop3>foo</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>6</Prop1>
<Prop2>bla</Prop2>
<Prop3>foo1</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>7</Prop1>
<Prop2>bla</Prop2>
<Prop3>foo2</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>8</Prop1>
<Prop2>bla</Prop2>
<Prop3>foo3</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>9</Prop1>
<Prop2>bla</Prop2>
<Prop3>foo4</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
<anyproperties>
<Prop1>10</Prop1>
<Prop2>bla</Prop2>
<Prop3>foo5</Prop3>
<Prop4>a</Prop4>
<Prop5>b</Prop5>
<Prop6>c</Prop6>
</anyproperties>
</Root>

3. Run the code below with both jdk7u3 and jdk7u4 (or later) and
observe a significant performance difference.
*/
public class AnyPropertiesTest {

private JAXBContext anyContext;
private Unmarshaller anyUnmarshaller;

public static final String PATH = "anyprops.xml";

public AnyPropertiesTest() {
System.out.println("java version = " +
System.getProperty("java.version"));
try {
if (anyContext == null) { anyContext = JAXBContext.newInstance(Root.class); anyUnmarshaller = anyContext.createUnmarshaller(); }
} catch (JAXBException e) { e.printStackTrace(); }
}

public void testAny() { long startTime = System.nanoTime(); File inputFile = new File(PATH); List<Anyproperties> propertiesList = getProperties(inputFile); long duration = (System.nanoTime() - startTime) / 1_000_000; String s = String.format("read %d properties in %d ms", propertiesList.size(), duration); System.out.println(s); }

private List<Anyproperties> getProperties(File path) {
List<Anyproperties> properties;

try { System.out.printf("file size = %d bytes, ", path.length()); properties = read(new FileInputStream(path)); } catch (JAXBException e) { System.out.println(String.format( "File '%s' could not be read by JAXB: might not be a valid XML file", path.getAbsolutePath())); properties = null; } catch (FileNotFoundException e) { // Impossible as path was obtained from listFiles String errorMessage = String.format("File '%s' obtained by File.listFiles() does not exist", path.getAbsolutePath()); throw new RuntimeException(errorMessage, e); }
return properties;
}

private synchronized List<Anyproperties> read(InputStream stream)
throws JAXBException { List<Anyproperties> templates = null; long startTime = System.nanoTime(); //It is the unmarshall method that takes a considerable amount of time on java 7u4, compared to 7u3 Root root = (Root) anyUnmarshaller.unmarshal(stream); long duration = (System.nanoTime() - startTime)/1_000_000; System.out.printf("read took %d ms\n", duration); templates = (List<Anyproperties>) root.getAnyproperties(); return templates; }

public static void main(String[] argv) { AnyPropertiesTest test = new AnyPropertiesTest(); test.testAny(); }
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
In order to deal with this issue we ship our product with java 7u3.
Upgrading to update 4 or later has a considerable performance impact
(we use large xml files).
The obvious solution is to avoid <xsd:any> elements, but this is not
always feasible.






[JAXB-963] JAXB xjc crashes while parsing trivial 8-line XSD file when -binding is used together with -catalog Created: 12/Jun/13  Updated: 20/Dec/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.4u2
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: m_perdikeas Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Ubuntu 12.04.2, JDK 1.7.0_21


Tags: jaxb-xjc xjc jaxb catalog binding
Participants: Iaroslav Savytskyi, m_perdikeas and markzimmngc

 Description   

Below is the absolute trivial, minimal example that demonstrates the problem.

Three schema files: A.xsd, B.xsd, C.xsd in the following import configuration:

  • C.xsd imports A.xsd and B.xsd
  • B.xsd imports A.xsd

So A.xsd is imported directly by C.xsd and again indirectly through B.xsd. The problem occurs when trying to run xjc (ver. 2.2.4) on C.xsd when both a catalog and a binding file is used (even an empty one).

---------- FILE A.xsd
<schema targetNamespace="foo://a"
xmlns="http://www.w3.org/2001/XMLSchema">
<simpleType name="year">
<restriction base="dateTime">
<pattern value="\d{4}"/>
</restriction>
</simpleType>
</schema>

---------- FILE B.xsd
<schema targetNamespace="foo://b"
xmlns="http://www.w3.org/2001/XMLSchema">
<import namespace="foo://a" schemaLocation="boo://a.xsd"/>
</schema>

---------- FILE C.xsd
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="foo://c">
<import namespace="foo://a" schemaLocation="A.xsd"/>
<import namespace="foo://b" schemaLocation="B.xsd"/>
</schema>

---------- FILE catalog.xml
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<system systemId="boo://a.xsd" uri="A.xsd"/>
</catalog>

---------- FILE binding.xjb
<bindings xmlns="http://java.sun.com/xml/ns/jaxb" version="2.1"/>

Given the above files, all placed in the same directory the below invocation succeeds:

xjc -d src -extension -catalog catalog.xml C.xsd

whereas the following invocation:

xjc -d src -extension -catalog catalog.xml C.xsd -b bindings.xjb

... fails with the bug-like message (pointing to some internal mess-up?):

parsing a schema...
[ERROR] 'year' is already defined
line 8 of file:/home/brutus/A.xsd

[ERROR] (related to above error) the first definition appears here
line 3 of file:/home/brutus/A.xsd

Failed to parse a schema.

All components of the above minimal reproduction are necessary to trigger the bug. If no binding file is used xjc parses correctly and generates code. If no catalog file is used xjc parses correctly and generates code. If both binding file an catalog are used xjc fails to parse. This is a blocking issue at least in my particular case as the XSD files are given and cannot be modified and I have to use both a catalog and a binding file (to get around other issues).



 Comments   
Comment by markzimmngc [ 20/Dec/13 05:39 PM ]

I am seeing this same issue with java version 1.7.0_45 and xjc 2.2.4-2 on RedHat.





[JAXB-995] Regression: Maven Plugin does not work with JDK 8 Created: 17/Dec/13  Updated: 17/Dec/13

Status: Open
Project: jaxb
Component/s: maven-plugin
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: puce Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

v2.2.8-b130911.1802
Java: 1.8.0-ea; Java HotSpot(TM) 64-Bit Server VM 25.0-b62
Runtime: Java(TM) SE Runtime Environment 1.8.0-ea-b120
System: Windows 7 version 6.1 running on amd64; Cp1252; de_CH (nb)


Tags:
Participants: Iaroslav Savytskyi and puce

 Description   

Running with JDK 8 EA b120, the maven plugin stops without any error message at:
"Parsing input schema(s)..."

No files get generated -> Blocker



 Comments   
Comment by puce [ 17/Dec/13 11:55 PM ]

Wrong component and I can't edit it.

I created a new issue: https://java.net/jira/browse/MAVEN_JAXB2_PLUGIN-83





[JAXB-994] Support for XML Schema 1.1 Created: 16/Dec/13  Updated: 16/Dec/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Major
Reporter: frocar Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 3
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: frocar and Iaroslav Savytskyi

 Description   

Support for XML Schema 1.1 would be awesome.
Especially things like assertions, conditional includes.






[JAXB-993] Proporder doesn't recogonize property if it is inherited Created: 10/Dec/13  Updated: 10/Dec/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: kavai Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Ubuntu, jdk1.6.0_45


Tags:
Participants: Iaroslav Savytskyi and kavai

 Description   

Whenever I inherit a property from a base-class, propOrder doesn't recognize it, and throws an exception:

Exception in thread "main" com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Property traceId appears in @XmlType.propOrder, but no such property exists.
at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:106)
...

Example to reproduce:
----------------------PropOrderDemo.java---------------------------------
public class PropOrderDemo
{
public static void main(String[] args) throws Exception

{ javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext.newInstance(FaultObject.class); javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller(); FaultObject exception = new FaultObject(13); marshaller.marshal(exception, System.out); }

}

----------------------FaultObject.java---------------------------------

@javax.xml.bind.annotation.XmlType(propOrder = { "traceId" })
@javax.xml.bind.annotation.XmlRootElement
@javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.PROPERTY)
public class FaultObject extends AbstractTraceableObject
{
private int traceId;

public FaultObject()
{
}

public FaultObject(int traceId)
{ this.traceId = traceId; }

@Override public int getTraceId()
{ return this.traceId; }

@Override public void setTraceId(int traceId)
{ this.traceId = traceId; } }
}

--------------------------AbstractTraceableObject.java--------------------------------------
public class AbstractTraceableObject
{
public int getTraceId()

{ return 0; }

public void setTraceId(int traceId)
{
}
}






[JAXB-991] Handle loading errors of XJC plugins gracefully to ignore dependencies from unnecessary plugins Created: 29/Nov/13  Updated: 29/Nov/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: hdelfs Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: hdelfs and Iaroslav Savytskyi

 Description   

When loading additional XJC plugins with the service discovery mechanism, java.util.ServiceLoader throws a ServiceConfigurationError (introduced in Java 6) if a plugin class cannot be loaded or instantiated. I suggest to output a warning in this case and continue the discovery process with further plugins.

Also consider the remark from the ServerceLoader's iterator() Javadoc description:

To write robust code it is only necessary to catch ServiceConfigurationError when using a service iterator.

In my case I wanted to use the ToString plugin from JAXB2 Basics, which is bundled with other plugins. Of these namely the Inheritance plugin requires the JavParser library as dependency. Currently I have to include the library in my classpath (though I don't use it) just to avoid the following Error:

java.util.ServiceConfigurationError: com.sun.tools.xjc.Plugin: Provider 
org.jvnet.jaxb2_commons.plugin.inheritance.InheritancePlugin could not be instantiated: 
java.lang.NoClassDefFoundError: japa/parser/ParseException
	at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:116)
	at org.apache.tools.ant.Task.perform(Task.java:348)
	at org.apache.tools.ant.Target.execute(Target.java:390)
	at org.apache.tools.ant.Target.performTasks(Target.java:411)
	at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
	at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
	at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
	at org.eclipse.ant.internal.launching.remote.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:32)
	at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
	at org.eclipse.ant.internal.launching.remote.InternalAntRunner.run(InternalAntRunner.java:423)
	at org.eclipse.ant.internal.launching.remote.InternalAntRunner.main(InternalAntRunner.java:137)
Caused by: java.util.ServiceConfigurationError: com.sun.tools.xjc.Plugin: Provider 
org.jvnet.jaxb2_commons.plugin.inheritance.InheritancePlugin could not be instantiated: 
java.lang.NoClassDefFoundError: japa/parser/ParseException
	at java.util.ServiceLoader.fail(ServiceLoader.java:207)
	at java.util.ServiceLoader.access$100(ServiceLoader.java:164)
	at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:353)
	at java.util.ServiceLoader$1.next(ServiceLoader.java:421)
	at com.sun.tools.xjc.Options.findServices(Options.java:957)
	at com.sun.tools.xjc.Options.getAllPlugins(Options.java:374)
	at com.sun.tools.xjc.Options.parseArgument(Options.java:688)
	at com.sun.tools.xjc.Options.parseArguments(Options.java:809)
	at com.sun.tools.xjc.XJC2Task._doXJC(XJC2Task.java:474)
	at com.sun.tools.xjc.XJC2Task.doXJC(XJC2Task.java:457)
	at com.sun.tools.xjc.XJC2Task.execute(XJC2Task.java:380)
	at com.sun.istack.tools.ProtectedTask.execute(ProtectedTask.java:103)
	at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
	... 10 more
Caused by: java.lang.NoClassDefFoundError: japa/parser/ParseException
	at org.jvnet.jaxb2_commons.plugin.inheritance.InheritancePlugin.<init>(InheritancePlugin.java:219)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
	at java.lang.Class.newInstance0(Class.java:355)
	at java.lang.Class.newInstance(Class.java:308)
	at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:345)
	... 25 more
Caused by: java.lang.ClassNotFoundException: japa.parser.ParseException
	at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
	... 33 more





[JAXB-990] xjc -fullversion does not work Created: 27/Nov/13  Updated: 28/Nov/13  Resolved: 28/Nov/13

Status: Closed
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: 2.2.8

Type: Bug Priority: Minor
Reporter: hdelfs Assignee: Iaroslav Savytskyi
Resolution: Fixed Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows, German locale


Tags:
Participants: hdelfs and Iaroslav Savytskyi

 Comments   
Comment by hdelfs [ 27/Nov/13 04:21 PM ]

Sorry, but the originally entered description got lost:

The command line option "-fullversion" for the XJC does not work but displays an exception. This is caused by the ${build.number} property used in the resource bundle definitions for Driver.FullVersion in (probably) all locales.

C:\Java\jaxb-ri-2.2.7\bin>xjc -fullversion
classLoader = java.net.URLClassLoader@118f375
SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@f84386
Exception in thread "main" java.lang.IllegalArgumentException: can't parse argument number build.number
        at java.text.MessageFormat.makeFormat(MessageFormat.java:1339)
        at java.text.MessageFormat.applyPattern(MessageFormat.java:458)
        at java.text.MessageFormat.<init>(MessageFormat.java:350)
        at java.text.MessageFormat.format(MessageFormat.java:811)
        at com.sun.tools.xjc.Messages.format(Messages.java:54)
        at com.sun.tools.xjc.Driver.run(Driver.java:232)
        at com.sun.tools.xjc.Driver.run(Driver.java:200)
        at com.sun.tools.xjc.Driver._main(Driver.java:123)
        at com.sun.tools.xjc.Driver.access$000(Driver.java:80)
        at com.sun.tools.xjc.Driver$1.run(Driver.java:103)

Also -version and -fullversion don't work with the xjc Ant task, which would be a nice enhancement.

Comment by Iaroslav Savytskyi [ 28/Nov/13 01:52 PM ]

Thank you for reporting.
I've checked in jaxb 2.2.8 - it's fixed.

Comment by Iaroslav Savytskyi [ 28/Nov/13 01:52 PM ]

Fixed

Comment by Iaroslav Savytskyi [ 28/Nov/13 01:54 PM ]

We have migrated JAXB project to maven. So ant tasks are not as prioritized as before.





[JAXB-989] Java's JAXB implementation does not handle underscores properly Created: 26/Nov/13  Updated: 26/Nov/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: prmatta Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: 2 days
Time Spent: Not Specified
Original Estimate: 2 days

Tags: jaxb jaxb-xjc jersey java
Participants: Iaroslav Savytskyi and prmatta

 Description   

The usecase to recreate the issue is to try and translate the following schema to java:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="Foo_Bar">
<xs:sequence>
<xs:element name="name" type="xs:string" minOccurs="0"/>
<xs:element name="choices" type="TypeMyEnum" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="TypeMyEnum">
<xs:restriction base="xs:string">
<xs:enumeration value="ALPHA_1_0_0"/>
<xs:enumeration value="BETA_2_0_0"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>

By default, xjc will create a file called FooBar.java and a file called TypeMyEnum.java. Notice how xjc "ate" the underscore in Foo_Bar. Also, by default, the internals of TypeMyEnum look like this:

ALPHA_1_0_0,
BETA_2_0_0;

To get the underscore back in Foo_Bar, one has to use a bindings file as follows:

<jxb:bindings version="1.0"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb">
<jxb:globalBindings underscoreBinding="asCharInWord"/>
</jxb:bindings>

Now, the code generates a Foo_Bar.java file as desired but horribly changes the internals of TypeMyEnum to look like:

@XmlEnumValue("ALPHA_1_0_0")
ALPHA__1_0__0("ALPHA_1_0_0"),

@XmlEnumValue("BETA_2_0_0")
BETA__2_0__0("BETA_2_0_0");
private final String value;

It seems every underscore in an enum value is changed to three underscores. This is the issue. This is easily reproducible and beyond me why xjc would do this.

There is no known way to get xjc to retain the underscore in the class name (i.e Foo_Bar.java) AND generate a sane enum file.






[JAXB-988] Add a new command line option to xjc for activating @XmlElementWrapper Created: 06/Nov/13  Updated: 06/Nov/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Improvement Priority: Trivial
Reporter: yossico Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

N/A


Tags: xjc optimization
Participants: Iaroslav Savytskyi and yossico

 Description   

Currently xjc creates a wrapper class as a container for a collection. This generates verbose code that is quite difficult to use.
The new CLI option will eliminate these wrapper classes and instead will make use of @XmlElementWrapper.
There are some implementations out there for doing this kind of optimization (e.g., https://github.com/dmak/jaxb-xew-plugin) but it seems much more natural for xjc to support it.






[JAXB-987] nillable elements with required attributes Created: 24/Oct/13  Updated: 24/Oct/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.6
Fix Version/s: None

Type: Bug Priority: Major
Reporter: dlatt Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: dlatt and Iaroslav Savytskyi

 Description   

Unfortunately I need to bring this issue up again since I'm again bitten by this bug (See JAXB-822, which I strongly suggest to re-open, but I'm not allowed to do so).

A nillable element with element content and required attributes cannot be processed using JAXB, since XJC doesn't create an JAXBElement wrapper.

It's occuring for example in the official German federal standard XJustiz set of XML schemas which we are obliged to use.

If this bug cannot be fixed, would you please care to explain a bit longer than the short comment by M. Grebac in JAXB-822 on 2011-Nov-22? As I wrote in the follow-up comment (which a developer might not have read as the issue was already closed then), that "solution" is not very helpful if one is forced to support a given schema.

Right now, our solution is to generate the code once every time there is an update on the schema and then, by hand, look for all instances where an JAXBElement wrapper is needed, modifying the generated code. This is a very frustrating task.

Please see also https://issues.apache.org/jira/browse/CXF-3732






[JAXB-986] Using marshaller on xjc generated classes causes Exception. Works in jdk7, not in jdk 8. Created: 24/Oct/13  Updated: 24/Oct/13

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.8
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: rne11 Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7
java version "1.8.0-ea"
Java(TM) SE Runtime Environment (build 1.8.0-ea-b109)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b51, mixed mode)


Tags: jaxb-xjc
Participants: Iaroslav Savytskyi and rne11

 Description   

Using marshaller on xjc generated classes causes java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

Works in jdk7, not in jdk 8.

Java file generated by xjc in jdk8 is different than what is produced
by xjc in jdk7.

Schema:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="intlist">
<xs:list itemType="xs:int"/>
</xs:simpleType>
<xs:complexType name="Person">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="scores" type="intlist"/>
</xs:sequence>
</xs:complexType>
<xs:element name="person" type="Person"/>
</xs:schema>

Difference in Person.java
in jdk8:
@XmlList
@XmlElement(type = Integer.class)
@XmlSchemaType(name = "anySimpleType")
protected List<Integer> scores;

in jdk 7:
@XmlList
@XmlElement(type = Integer.class)
protected List<Integer> scores;

REGRESSION : Additional Information
java version "1.8.0-ea"
Java(TM) SE Runtime Environment (build 1.8.0-ea-b109)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b51, mixed mode)

xjc 2.2.8-b20130806.1801

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Compile xsd to Java files:
$ xjc.exe -p jaxb -d src test.xsd

Compile test program and run.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Expected an XML file to be created with Person object.
ACTUAL -
Exception

ERROR MESSAGES/STACK TRACES THAT OCCUR :
java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.String

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
package jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

public class App {

public static void main( String[] args ) throws Exception {

File file = new File( "test-out.xml");
FileOutputStream fis = new FileOutputStream( file );
ObjectFactory of = new ObjectFactory();

Person person = of.createPerson();
person.setName( "Bob" );
List<Integer> values = person.getScores();
values.add( 1 );
values.add( 2 );

JAXBElement jaxbElement = of.createPerson( person );

JAXBContext ctx = JAXBContext.newInstance( "jaxb" );
try { Marshaller marshaller = ctx.createMarshaller(); // Dies here with: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String marshaller.marshal( jaxbElement, fis ); fis.close(); }
catch( JAXBException e ) { throw new RuntimeException( e ); }
}
}






[JAXB-978] UnmarshallerImpl has an ineffective finalize() method Created: 16/Sep/13  Updated: 24/Oct/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.4u2, 2.2.5, 2.2.6, 2.2.7
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: gadavis Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: gadavis, Iaroslav Savytskyi and rshekar

 Description   

During upgrading a web service we observed that a the Parallel new garbage collector was unable to achieve the previously seen thoughput when running with JAXB 2.2.5+

On investigation it seems the reason for this is the addition of the `finalize()` method on `UnmarshallerImpl`, this causes the object not to be collected but to be placed to to the finalizer queue. This is problematic for two reasons

  • it increases the contention on the finalizer queue
  • The last unmarshalled object (a large WS response object in our case) is retained until the finalizer invokes the `finalize()` method

In addition, the implementation of the `finalize()` method:

protected void finalize() throws Throwable {
        try {
            ClassFactory.cleanCache();
        } finally {
            super.finalize();
        }
    }

is broken because the `ClassFactory.cleanCache()` method needs to be called in the same thread as the original use of the `Unmarshaller`, but this won't be true as it will be called the Finalizer thread.

Will be posting a patch to remove the method to the dev mailing list.



 Comments   
Comment by Iaroslav Savytskyi [ 16/Sep/13 02:19 PM ]

Hi,

Thanks for reporting. I'll fix it.

Comment by rshekar [ 23/Oct/13 09:08 PM ]

Hi Iaroslav,

I am seeing a similar issue when using CXF client, 50% of the heap is java.lang.ref.Finalizer objects.

Can you please let me know if the fix planned for a release, and if so any ETA.

Thank you,
Raj.

Comment by Iaroslav Savytskyi [ 24/Oct/13 09:20 AM ]

The problem is that we are not able to determine when we have to clean our cache.

I think we will try to do something with this in 2.2.8... But unfortunately I'm not able to give any estimations when we will start working on this. This year???

Comment by gadavis [ 24/Oct/13 09:24 AM ]

how you clear the cache isn't really important to removing this finalise method. The finalise method does nothing to clear the cache and only messes with the garbage collector.





[JAXB-985] Different marshallization behaviour with OutputStream and Writer Created: 18/Oct/13  Updated: 21/Oct/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: glam Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: glam and Iaroslav Savytskyi

 Description   

We discovered a difference in the behaviour of the marshaller when using a Writer and when using an OutputStream.

In our case, we needed to marshall (formatted):

<foo>text<bar />text<bar>baz</bar></foo>

This worked when using an OutputStream, but new lines were inserted when using a Writer.

On investigation, I noticed that in com.sun.xml.bind.v2.runtime.MarshallerImpl has two distinct methods called createWriter(..) - one taking a Writer, and one taking an OutputStream.
The version taking an OutputStream is doing something special in case the encoding is UTF-8 (Why??). The difference is in the usage of IndentingUTF8XmlOutput, which correctly implements the desired functionality - whenever there's text content before the element, no new line+indentation is appended.

However, OutputStream+UTF-8 is the only case *UTF8XmlOutput classes are used, otherwise they aren't. The indentation behaviour might be just one example of behaviour difference, so I would suggest to make the behaviour consistent (i.e. - work for both OutputStream and Writer implementations, and preferably for all encodings)

And while at it, in that class there is one check if (encoding.equals("UTF-8")) {..} and one if (encoding.startsWith("UTF")) {..}. This is pretty bad, as it doesn't work with lower-case utf-8 or without a dash, and also would yield different results for these combinations - for UTF8 one if-clause will work, the other won't. If different behaviour based on encoding is really needed (I would say it shouldn't be), then please use normalization/canonicalization of the string - via Charset.forName(..) for example.



 Comments   
Comment by Iaroslav Savytskyi [ 21/Oct/13 08:28 AM ]

I know about the difference. But why 'new lines' is the case?

Comment by glam [ 21/Oct/13 08:38 AM ]

Well, in our case we needed not to have new lines. The behaviour implemented by IndendtingUTF8XmlOutput, and not implemented elsewhere.

For example, we have a unit-test that fails because of that - we process the document multiple times, sometimes by writers, sometimes by output streams, and the outputs don't match.





[JAXB-172] More Schema Annotations/Documentation to Javadoc Created: 06/Jun/06  Updated: 20/Oct/13

Status: Reopened
Project: jaxb
Component/s: xjc
Affects Version/s: 2.0 FCS
Fix Version/s: not determined

Type: Improvement Priority: Critical
Reporter: vorburger Assignee: Martin Grebac
Resolution: Unresolved Votes: 34
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All
URL: https://jaxb.dev.java.net/servlets/ReadMsg?list=users&msgNo=5469


File Attachments: XML File test.xsd    
Issue Links:
Duplicate
is duplicated by JAXB-839 More Schema Annotations/Documentation... Resolved
Issuezilla Id: 172
Tags:
Participants: Aleksander Adamowski, dkulp, kohsuke, kpsdevi, marcelstoer, Martin Grebac, os111, skells and vorburger

 Description   

As discussed on the "Schema Annotations/Documentation to Javadoc" thread on
users@jaxb.dev.java.net (see
https://jaxb.dev.java.net/servlets/ReadMsg?list=users&msgNo=5469) :

>> If you find cases where it doesn't work as you expected,
>
> . not the same complexType's sequence/element* documentation (which
> I'd think you'd expect on the respective getters/setters, instead of
> that pretty useless "Gets the value of the ... property."), nor a
> simpleType's annotation/documentation that turns into a @XmlEnum
> public enum, where one would expect both JavaDoc of the class as well
> as the individual enum values, from the
> simpleType/restriction/enumeration/annotation/documentation.
> (Additionally maybe putting schema/annotation/documentation into
> package-info.java as JavaDoc; although not sure how to deal with one
> namespace schema in several .xsd... not sure how that looks in XSOM by
> the time you process this?)

Please let me know if you need more details, schemas or code - hoping above is
clear.

When you do commit code for this, I'd would be happy to try a nightly build and
provide feedback; please add a comment to this Bugzilla and we'll give the next
build a shot. Thanks!



 Comments   
Comment by kohsuke [ 16/Jun/06 04:55 PM ]

Created an attachment (id=105)
Schema I used to test the problem.

Comment by vorburger [ 21/Jul/06 04:11 AM ]

FYI: http://jira.codehaus.org/browse/XFIRE-507

Comment by kohsuke [ 24/Sep/07 10:26 AM ]

Also in this category is javadoc for enumeration values.

Comment by kohsuke [ 06/Feb/08 08:18 AM ]
      • Issue 431 has been marked as a duplicate of this issue. ***
Comment by kohsuke [ 06/Feb/08 08:19 AM ]

issue #431 that was marked as a duplicate for this had 25 votes on its own, so
this appears to be a highly requested feature.

Comment by Aleksander Adamowski [ 22/Oct/09 04:39 AM ]

CCing myself (Bugzilla doesn't allow without a comment).

Comment by dkulp [ 22/Oct/09 06:13 AM ]

This is also the blocker for a CXF issue:

https://issues.apache.org/jira/browse/CXF-2486

Comment by skells [ 26/Oct/09 06:06 AM ]

I have a plugin that adds documentation to the getters, setters and the fields,
that works withthe placement that xmlspy used for the documentation. I would
not say that it is complete, but it works OK for the cases that we use.

Theer are some problems with it mostly related to the API the generate the
javadoc, and I would not say that the code is clean ....

I can share the code if anyone is interested in taking it forward

Comment by dkulp [ 26/Oct/09 08:29 AM ]

If you'd like to donate the code to CXF, we could certainly use it. CXF
already has a couple plugins to workaround XJC issues.

Just log a JIRA at:
https://issues.apache.org/jira/browse/CXF
and attach the code.

Comment by dkulp [ 11/Feb/10 10:04 AM ]

skells,

In CXF, we've recently setup a subproject to house additional XJC plugins
that the community finds useful. We'd love to have your contribution if the
offer still stands.

Comment by kpsdevi [ 11/May/11 02:01 PM ]

The schema is provided by the service provider and they have defined integer enumeration values with documentation but without names as given below.
<xsd:simpleType name="XYZCodeSimpleType">
<xsd:annotation>
<xsd:documentation>A data type for an enumeration of XYZ Codes.</xsd:documentation>
</xsd:annotation>
<xsd:restriction base="xsd:token">
<xsd:enumeration value="0">
<xsd:annotation>
<xsd:documentation>Undefined</xsd:documentation>
</xsd:annotation>
</xsd:enumeration>
<xsd:enumeration value="1">
<xsd:annotation>
<xsd:documentation>Left</xsd:documentation>
</xsd:annotation>
</xsd:enumeration>
<xsd:enumeration value="2">
<xsd:annotation>
<xsd:documentation>Right</xsd:documentation>
</xsd:annotation>
</xsd:enumeration>
</xsd:restriction>
</xsd:simpleType>

1) JAXB 2 has not generated classes for those enum types. So I added global bindings as given below

<jaxb:globalBindings typesafeEnumMemberName="generateName">

Then I was able to generate classes as given below with prefix "VALUE_" in the name, which was confusing as my enum values start with 0.

public enum XYZCodeSimpleType {

/**

  • Undefined
  • */
    @XmlEnumValue("0")
    VALUE_1("0"),

/**

  • Left
  • */
    @XmlEnumValue("1")
    VALUE_2("1"),

/**

  • Right
  • */
    @XmlEnumValue("2")
    VALUE_3("2");

2) So I have used external bindings to define name as given below.

<jaxb:bindings node="//xsd:simpleType[@name='XYZSimpleType']">
<jaxb:typesafeEnumClass>
<jaxb:typesafeEnumMember value="0" name="UNDEFINED" />
<jaxb:typesafeEnumMember value="1" name="LEFT" />
<jaxb:typesafeEnumMember value="2" name="RIGHT" />
</jaxb:typesafeEnumClass>
</jaxb:bindings>

With this external binding I was able to generate classes with names as given below but I lost the documentation which is there in the schema. Because of that I need to duplicate documentation as well in jaxb bindings which I don't want to.

public enum XYZCodeSimpleType {

@XmlEnumValue("0")
UNDEFINED("0"),
@XmlEnumValue("1")
LEFT("1"),
@XmlEnumValue("2")
RIGHT("2");

3) I looked at JAXB 2.2.3 source code and figured out the cause of this issue. Issue is in the method "buildCEnumConstants" of "com.sun.tools.xjc.reader.xmlschema.SimpleTypeBuilder". The documentation from schema is getting overwritten even when the javadoc is not specified in the bindings and getting nullified if there is no value in the bindings.

if( mem!=null ) { name = mem.name; mdoc = mem.javadoc; }

So the above code should be modified as given below

if( mem!=null ) {
name = mem.name;
if (mem.javadoc!=null){ //Fix mdoc = mem.javadoc; }
}

I request you to fix this issue and release the update of JAXB2.2.3 as soon as possible.

Comment by Martin Grebac [ 30/May/11 09:54 AM ]

Unfortunately have to close this one as incomplete because the original thread wast lost and I'm not able to grasp the roots of the bug here. Recently I fixed one javadoc issue with enums thanks to a specific submission, but other than that I think I need more info on what is requested here. Feel free to reopen if you have that. Thanks.

Comment by os111 [ 31/May/11 01:40 PM ]

Not sure why this was closed?

As I understood it the original intent was to include documentations from the XSD in the Javadoc of autogenerated code.

For example the following from schema snippet

<attribute name="documentedAttribute" type="string" use="optional">
<annotation>
<documentation>This attribute can be either 1, 2, or 3.</documentation>
</annotation>
</attribute>

Generates the following javadoc:

/**

  • Gets the value of the documentedAttribute property.
  • @return
  • possible object is
  • {@link String }
  • */

The javadoc should also include the schema's documentation.

Comment by vorburger [ 01/Jun/11 01:47 AM ]

JAXB-839 (new) created to avoid this being swiped under the carpet.

Comment by Martin Grebac [ 01/Jun/11 02:37 AM ]

Understood, thanks for the clarifications here.

Comment by marcelstoer [ 20/Oct/13 10:13 PM ]

Just found here thanks to a really helpful SO answer.





[JAXB-984] Invalid pom: jaxb-xjc 2.1.x has a wrong dependency to jaxb-core 2.1.x Created: 15/Oct/13  Updated: 16/Oct/13  Resolved: 16/Oct/13

Status: Closed
Project: jaxb
Component/s: xjc
Affects Version/s: 2.1.14, 2.1.15, 2.1.16
Fix Version/s: 2.1.14

Type: Bug Priority: Major
Reporter: Dennis Kieselhorst Assignee: Iaroslav Savytskyi
Resolution: Fixed Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: maven pom jaxb-xjc
Participants: Dennis Kieselhorst and Iaroslav Savytskyi

 Description   

The jaxb-xjc pom was changed for release 2.1.14 and now refers to jaxb-core, which is only available for JAXB 2.2. I think the correct dependency is jaxb-impl as in the pom of release 2.1.13.



 Comments   
Comment by Dennis Kieselhorst [ 15/Oct/13 08:55 AM ]

Same error is in the jaxb-impl pom.

Comment by Iaroslav Savytskyi [ 16/Oct/13 07:19 AM ]

Thanks for reporting.

It was bad copy/paste from trunk.

Comment by Iaroslav Savytskyi [ 16/Oct/13 03:44 PM ]

I've released fake jaxb-core 2.1.14 artifact. Which has dependency to jaxb-api 2.1.

Comment by Dennis Kieselhorst [ 16/Oct/13 03:56 PM ]

What about 2.1.15 and 2.1.16?

Comment by Iaroslav Savytskyi [ 16/Oct/13 06:46 PM ]

I think we will fix this in 2.17. Or if it will be critical - will do the same fix as for 2.14

Comment by Iaroslav Savytskyi [ 16/Oct/13 06:48 PM ]

I meant 2.1.17 and 2.1.14 respectively.





[JAXB-546] Custom IDResolver gets wrong target type with IDREF collections Created: 02/Sep/08  Updated: 16/Oct/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.1.7
Fix Version/s: not determined

Type: Bug Priority: Minor
Reporter: uryssel Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 7
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


File Attachments: Java Source File Reflect.java    
Issuezilla Id: 546
Tags: 2_2_8
Participants: Iaroslav Savytskyi, ktcorby, larsrc, Pavel Bucek, realsonic3 and uryssel

 Description   

The issue is described in the forum:
http://forums.java.net/jive/thread.jspa?threadID=45481&tstart=120

When using IDREFed collections:

@XmlIDREF
Set<Y> ySet;

the resolve() method of a custom IDResolver gets Object.class as targetType,
but it should be Y.class. This results on wrong ID resolving.

If I use an empty derived class instead:

class YSet extends HashSet<Y> {}
...
@XmlIDREF
YSet ySet;

then I get the right targetType in the resolve() method.



 Comments   
Comment by Pavel Bucek [ 04/Mar/09 12:58 AM ]

Would you please provide the schema file and/or reproducible testcase? Thanks in
advance.

Comment by Pavel Bucek [ 06/Mar/09 12:55 AM ]

I agree with Wolfgang - see attached mail:

(workaround available and this is not part of jsr222 -> adjusting priority to P4)

================================================
The reason resolve() is called with Object.class for the target type when
a field of some parameterized type is annotated with @XmlIDREF is
simply because that's the way Java works. At runtime, Set<Foo> is
erased to Set<? extends Object> or Set<?>. See this simple test
program and its output:

mport java.util.*;
import java.lang.reflect.*;
public class Reflect {
public List<String> sList;
public ArrayList<String> sArrayList;
private static void dr( String fname ) throws Exception {
Class reflectClass = Reflect.class;
Field sListField = reflectClass.getField( fname );
System.out.println( sListField.toString() );
Class sListClass = sListField.getType();
System.out.println( sListClass.toString() );
if( sListClass instanceof GenericDeclaration ){ TypeVariable<?>[] typeVars = sListClass.getTypeParameters(); System.out.println( "generic " + typeVars.length + " parameter" ); Type[] types = typeVars[0].getBounds(); System.out.println( "bounds " + types.length + ": " + types[0].toString() ); System.out.println( "name " + typeVars[0].getName() ); }
}
public static void main( String[] args ) throws Exception { dr( "sList" ); dr( "sArrayList" ); }
}
=========================================
public java.util.List Reflect.sList
interface java.util.List
generic 1 parameter
bounds 1: class java.lang.Object
name E
public java.util.ArrayList Reflect.sArrayList
class java.util.ArrayList
generic 1 parameter
bounds 1: class java.lang.Object
name E
==========================================

The code in com/sun/xml/bind/v2/runtime/reflect/Lister.java,
latest release, around line 140 seems to indicate that the
declared parameter type is available, but perhaps I've
not understood it in full.

The ID Resolver is an extension of Sun's implementation.
The official JAXB documentation doesn't contain any hint for
this; as far as I know, Kohsuke's blog is the only place where this
feature is published.

The original reporter has found a reasonable workaround by
declaring a dedicated wrapper type for the parameterized
container class, so that ID resultion into separate namespaces
is applicable for IDREFs in containers as well.

================================================

Comment by Pavel Bucek [ 06/Mar/09 01:00 AM ]

I forgot change priority...

Comment by ktcorby [ 06/Mar/09 06:28 AM ]

I think it would be much more convenient if there was an additional parameter to
the annotation, like @IDRef(targetType=String.class) or possibly an additional
annotation (@IDRefType(String.class)), so that the resolver could map to the
proper type at runtime.

I realize this may not be a possible short-term solution, but I wanted to
mention it.

Comment by larsrc [ 07/Aug/09 02:49 AM ]

Created an attachment (id=322)
Update example source showing the old example plus a part that shows that getGenericType can find the right type.

Comment by larsrc [ 07/Aug/09 02:50 AM ]

Using getGenericType() instead of getType() allows you to find the actual type.
With getType(), you're affected by erasure.

Comment by realsonic3 [ 05/Sep/12 08:28 AM ]

Hello. Can you please tell can this issue be fixed? Thanks.

Comment by Iaroslav Savytskyi [ 11/Sep/12 07:55 AM ]

Hi,realsonic3,

As I see with "getGenericType" is looks optimistic. So we will try to add it to 2.2.7.

Comment by realsonic3 [ 26/Sep/12 02:12 PM ]

Sorry, but in which java version will be JAXB 2.2.7? Thanks a lot.

Comment by Iaroslav Savytskyi [ 26/Sep/12 04:53 PM ]

It's no need to wait for JDK integration. You can use JAXB as standalone application.

Comment by realsonic3 [ 12/Nov/12 12:22 PM ]

Can you please fill "Fix Version/s:" field?

Comment by realsonic3 [ 20/Jun/13 08:27 PM ]

Hello. Can you please update when this issue will be fixed? Thanks.

Comment by Iaroslav Savytskyi [ 21/Jun/13 08:52 AM ]

Hi,

I hope I'll be able to fix it in 2.2.8

Comment by realsonic3 [ 10/Sep/13 01:06 PM ]

Let me please update you. This bug causes a problem that two or more objects with same ID but different types are unmarshalled as one type.

Comment by realsonic3 [ 15/Oct/13 10:57 AM ]

Any chances it will be fixed in 2.2.8?

Comment by Iaroslav Savytskyi [ 16/Oct/13 07:23 AM ]

We are quite busy with maintenance now. So I can't promise.





[JAXB-982] XMLAnyElement wmissing lax=true with xjc simple Created: 11/Oct/13  Updated: 11/Oct/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: dcarniel Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows machine, xjc triggered via jaxws-maven-plugin version 2.3


Tags: jaxb-xjc
Participants: dcarniel and Iaroslav Savytskyi

 Description   

When generating code from a wsdl that contains an xs:any tag with processContents="lax" and the xjc "simple" option (set via "<xjc:simple/>" in the jaxb custom binding XML), the generated code has a @XMLAnyElement tag without the ( lax = true ) property.

If the processContents is set to "skip" or if the "simple" option is not set the tag is generated with the attribute.

As the xsd is not one I master (it is the ws-trust XSD), I cannot permanently change it.






[JAXB-758] Wrong behaviour with xsd:any and a payload with default namespace Created: 19/May/10  Updated: 18/Sep/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2
Fix Version/s: not determined

Type: Improvement Priority: Major
Reporter: cistox Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 5
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 758
Tags:
Participants: bshrom, cistox, cistox, fontana.damiano, Iaroslav Savytskyi, Martin Grebac and Pavel Bucek

 Description   

Hello,
I am working with Metro 2.1 nightly, JAXB 2.2 and WS-Transfer.
WS-Transfer elements like Put, Create, ... are providing an xsd:any content
where I need to add the original payload to be transferred.
Actually JAXB is erroneously modifying the namespace of a payload with default
namespace.

xsd:Any allows almost any content and expecially using skip processing such
content must be ignored.
There is no reason to add the outer namespace (e.g. the namespace of a
ws-transfer "Put" element) to the inner payload.

Payload's integrity is required to be preserved as it could represent an Invoice
with an incorporated digital signature.
This means the receiver must be able to validate the signature against the
payload content (and this is not possible if the payload is modified on-the-road).
The transport should not change the payload at all...

Actually I noted that JAXB has a strange behaviour with either "lax" and "skip"
processing of the xsd:any if the payload has a default namespace declared into
its root (xmlns="...").

Example using LAX or SKIP processing
----------------------------------------------------
Generated by JAXB:

<ns4:Put xmlns:ns4="[WS-Transfer NS]">
<Invoice xmlns="" xmlns:ns4="[WS-Transfer NS]" xmlns="[original default NS]" />
</ns4:Put>

This is how it should be with the original payload:

<ns4:Put xmlns:ns4="[WS-Transfer NS]">
<Invoice xmlns="[original default NS]"/>
</ns4:Put>

I believe that xsd:Any "skip" processing should completely ignore the xml
content and thus the way namespaces are declared in the payload should be
untouched...

The same is for "lax" processing if the payload is not using elements from
declared namespaces in the context (as it is usually for a business payload).

Example using <jaxb:dom/> xs:annotation
----------------------------------------------------
I made this exercise to avoid a dependancy between Put and its xs:any content.
I dreamed to see the payload untouched after this change but I was wrong.

<xs:element name="Put">
<xs:complexType>
<xs:sequence>
<xs:any minOccurs="1" maxOccurs="unbounded" namespace="##other"
processContents="skip">
<xs:annotation><xs:appinfo>
<jaxb:dom/>
</xs:appinfo></xs:annotation>
</xs:any>
</xs:sequence>
<xs:anyAttribute namespace="##other" processContents="lax" />
</xs:complexType>
</xs:element>

Generated by JAXB:

<ns4:Put xmlns:ns4="[WS-Transfer NS]">
<Invoice:Invoice xmlns:Invoice="[original default NS]" xmlns:ns4="[WS-Transfer
NS]" xmlns="[original default NS]" />
</ns4:Put>

NOTE: The behaviour is changed a few here, but the namespace "xmlns:Invoice" is
really undesired and not useful at all.

This is how the Put should be with the original payload:

<ns4:Put xmlns:ns4="[WS-Transfer NS]">
<Invoice xmlns="[original default NS]"/>
</ns4:Put>

Payloads with a default namespace are a common case, I really hope this is not a
real limit of JAXB.

Please can you suggest a workaround ?

Thank you in advance for any help

Best regards

Roberto Cisternino



 Comments   
Comment by cistox [ 19/May/10 01:19 AM ]

The following thread and issue are related:

Namespace error when marshalling DOM element with attributes using JAXB 2.1
http://forums.java.net/jive/thread.jspa?threadID=55699&tstart=0

Issue
https://jaxb.dev.java.net/issues/show_bug.cgi?id=585

Comment by Pavel Bucek [ 19/May/10 01:26 AM ]

adjusting priority (P1 is showstopper)

we know about this but its very hard to fix anything regarding namespaces (because of our thorough test
suites and regressions from dependent products). additionally, this is not "wrong", its valid xml.
Namespaces are there because of unpredictability of xsd:any content.

Comment by Martin Grebac [ 06/Oct/10 01:49 AM ]

updating

Comment by bshrom [ 17/May/12 10:47 PM ]

While this is a valid xml, this bug causes XML signature failure and eventually interoperability problem in Metro.
Metro/WSIT uses JAXB under the hood and when security tokens are included, located under xsd:any, they are modified before they go on the wire.
See related bug: http://java.net/jira/browse/METRO-16
The same problem is with OnBehalfOf when SAML Assertion token is used, which breaks WS-Trust interoperability between Metro and .NET.
MS .NET uses xmlns="[original default NS]" constructs all the time resulting in modified XML and signature failure.

This bug should've never been classified as Improvement.

Comment by cistox [ 31/May/12 04:54 PM ]

It is incredible the JAXB 758 bug is still there. The way xsd:Any is handled is wrong. There is no reason to add namespaces from the outer envelope (e.g. WS-Transfer scaffolding) on the xsd:Any content.

Primary European projects are suffering of these bugs, it is very bad that such fixes are not applied due to dependancies from other bugged projects...
I am curious to know one of these projects that is relying on such JAXB bugs for its functions. It's a crazy situation.

XML is a nice thing but it's happen is going to be used on real business scenarios... thus digital signatures and other most serious dependancies have to be supported...

Comment by cistox [ 17/May/13 08:20 AM ]

Dear all,
major European projects like PEPPOL are going to fail using the actual Metro stack due to such JAXB issues.
All the project is moving to AS2 due to the interop issues with .NET.

I am really curious why JAXB cannot be fixed about the xsd:Any behaviour... I do not think other software can take any benefit from such wrong behaviour.

Comment by cistox [ 29/May/13 07:44 PM ]

HOW TO SOLVE THIS ISSUE:

The actual way the xsd:Any is handled by JAXB is not conformant to W3C XML Schema.

My proposal is to introduce a switch to let the developer to use JAXB in a conformant way and another to play the actual version (let's give it a name to justify its existance...)

With this basic switch the actual dependancies will be safe, but those interested into a conformat behaviour of xsd:Any will be really happy.

At this stage WS-Transfer and SAML have been identified as suffering from this bug when implemented using JAXB, but I am pretty sure this bug is the cause of several other issues. For instance the digital signature applied to a payload could be compromised by the addition of unwanted namespaces.

Hope this helps.

Comment by fontana.damiano [ 18/Sep/13 09:04 AM ]

we are experimenting the same issue described above.
We hope that it will be fixed as soon as possible, in order to successufully use JAXB in enterprise B2B solutions to exchange document of any type in XML format





[JAXB-518] When XMLSchema is generated from Java with schemagen command, information on nillable of Java is not correctly reflected in XMLSchema. Created: 24/Jun/08  Updated: 17/Sep/13  Resolved: 18/Sep/09

Status: Resolved
Project: jaxb
Component/s: schemagen
Affects Version/s: 2.1.6
Fix Version/s: 2.1.13

Type: Bug Priority: Major
Reporter: taniguti Assignee: Martin Grebac
Resolution: Won't Fix Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 518
Tags:
Participants: gfuser9999, Martin Grebac, taniguti and zhaohuifeng

 Description   

When nillable is not specified for @XMLElement of Java, nillable ="true" is
specified for XMLSchema generated with the schemagen command.

Accoding to javadoc of javax.xml.bind.annotation.XmlElement.nillable, its
default value is false.

Moreover, when XMLSchema is the following, nillable is not actually specified
for @XmlElement of the Java generated from the XMLSchema by xjc command.
・When you specify nillable ="false" for element of XMLSchema, or
・When you do not specify nillable for element of XMLSchema.

Therefore, when Java is generated from XMLSchema of the above-mentioned
condition, and XMLSchema is generated from that Java, the nillable attribute
information of XMLSchema is different from former XMLSchema.

(example)
----------------formar SCHEMA------------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" targetNamespace="http://servlet_endpoint/"
xmlns:tns="http://servlet_endpoint/" xmlns:ns1="http://jaxb.dev.java.net/array"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:import namespace="http://jaxb.dev.java.net/array"
schemaLocation="MultiTypeArrayService_schema2.xsd"/>

<xs:element name="paramInInteger" type="tns:paramInInteger"/>

<xs:element name="paramInIntegerResponse" type="tns:paramInIntegerResponse"/>

<xs:complexType name="paramInInteger">
<xs:sequence>
<xs:element name="arg0" type="ns1:intArray" minOccurs="0"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="paramInIntegerResponse">
<xs:sequence>
<xs:element name="return" type="xs:int"/>
</xs:sequence>
</xs:complexType>

</xs:schema>

----------------generated Java------------------
servlet_endpoint/ParamInInteger.java

package servlet_endpoint;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import net.java.dev.jaxb.array.IntArray;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "paramInInteger", propOrder = {
"arg0"
})
public class ParamInInteger {

protected List<IntArray> arg0;

public List<IntArray> getArg0() {
if (arg0 == null) { arg0 = new ArrayList<IntArray>(); }
return this.arg0;
}

}
----------------generated SCHEMA------------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" targetNamespace="http://servlet_endpoint/"
xmlns:tns="http://servlet_endpoint/" xmlns:ns1="http://jaxb.dev.java.net/array"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:import namespace="http://jaxb.dev.java.net/array"
schemaLocation="MultiTypeArraySchema2.xsd"/>

<xs:element name="paramInInteger" nillable="true" type="tns:paramInInteger"/>

<xs:element name="paramInIntegerResponse" nillable="true"
type="tns:paramInIntegerResponse"/>

<xs:complexType name="paramInIntegerResponse">
<xs:sequence>
<xs:element name="return" type="xs:int"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="paramInInteger">
<xs:sequence>
<xs:element name="arg0" type="ns1:intArray" nillable="true" minOccurs="0"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
------------------------------------------

How about you though it thinks this to be an acute problem?



 Comments   
Comment by zhaohuifeng [ 29/May/09 05:14 PM ]

I'm seeing the same issue with javax.xml.bind.JAXBContext.generateSchema
(SchemaOutputResolver). With the nillable is set to true, the generated WSDL is
not qualified as doc-lit-wrapper style per JAX-WS spec.

Comment by Martin Grebac [ 17/Sep/09 04:57 AM ]

I do have a fix in trunk, that's easy to fix in JAXB. However, this should most
certainly break JAX-WS compatibility tests - since JAX-WS uses schemagen with
their web services from Java. So I need to contact JAX-WS guys on how to proceed
here. Might happen we will not be allowed to fix this. Stay tuned.

Comment by Martin Grebac [ 17/Sep/09 05:03 AM ]

Forgot to reassign to myself.

Comment by Martin Grebac [ 18/Sep/09 01:34 AM ]

Unfortunately this would break backward compatibility for both JAXB and JAX-WS,
so marking as wontfix. You can easily workaround it by specifying XmlElement
annotation on the collection property, with or without including the nillability
attribute.

Comment by gfuser9999 [ 17/Sep/13 06:42 AM ]

How do this workaround work for parameter

void test1Darray(@XmlElement(nillable=false) int[]array) {
}

It seems that the generated XSD always have nillable true
and then later code using these XSD will not generate
the right stuff. So what's the workaround for these.





[JAXB-918] Wrong element name serialized. Created: 05/Sep/12  Updated: 16/Sep/13

Status: In Progress
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.5
Fix Version/s: None

Type: Bug Priority: Major
Reporter: ratoo Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

JDK6u35, JDK7u7 Win7 64


File Attachments: Zip Archive jaxb918.zip    
Tags:
Participants: Iaroslav Savytskyi and ratoo

 Description   

There is a bug in com.sun.xml.bind.v2.runtime.output.NamespaceContextImpl

NamespaceContextImpl reuses NamespaceContextImpl.Element objects to generate prefixes.
NamespaceContextImpl.Element.setTagName(Name tagName, Object outerPeer) doesn't clean up NamespaceContextImpl.Element.elementLocalName
When the element is reused in
NamespaceContextImpl.declareNsUri(String uri, String preferedPrefix, boolean requirePrefix) {
...
if (current.elementLocalName!=null) { // CHANGES A NAME TO THOSE LEFT FROM AN OTHER NODE!!! current.setTagName(size, current.elementLocalName, current.getOuterPeer()); }
...
}

Solution is to clean elementLocalName in

public void setTagName( Name tagName, Object outerPeer ) { assert tagName!=null; this.elementName = tagName; this.elementLocalName = null; // + this.outerPeer = outerPeer; }



 Comments   
Comment by Iaroslav Savytskyi [ 24/Jan/13 04:09 PM ]

Hi,

thank you for reporting. Can you please provide small test case how can I reproduce the problem.

Thanks.

Comment by ratoo [ 24/Jan/13 04:46 PM ]

Unfortunately I can't .
Things works to me now and I did too much changes to figure out what was wrong.

I had an adapter with a DOM Element returned.
Somehow JAXB is parsing this element tree using localNames.
IMHO it's obvious that either elementName or elementLocalName must be null.

Cheers,

D.

Comment by ratoo [ 17/May/13 02:14 PM ]

Hello,

I got the bug again and finally figured out what exactly happens.
I have a QName attribute.
When the default namespace is defined (i.e. xmlns="www.example.com") and
my QName attribute has no namespace,
NamespaceContextImpl tries to rearrange:

> 188 // first, if the previous URI assigned to "" is
> 189 // a "known URI", remember what we've reallocated
> 190 // so that we can fix it when this context pops.
...
> 202 if (current.elementLocalName!=null) { > 203 current.setTagName(size, current.elementLocalName, current.getOuterPeer()); > 204 }

here it changes the tag name (current).
setTagName has a bug - doesn't clean elementLocalName (as seen above).

P.S. can't find a way to submit jUnit test code.
https://java.net/projects/jaxb/lists/users/archive/2013-05/message/7





[JAXB-979] ClassFactory constructor cache could be more efficient Created: 16/Sep/13  Updated: 16/Sep/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: not determined
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: gadavis Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: gadavis and Iaroslav Savytskyi

 Description   

ClassFactory currently uses a ThreadLocal Map<Class,Constructor> in order to cache the default constructor lookups used in unmarshalling.

issues:

  • The Cache is only valid with the current thread, thus each thread (possibly hundreds in an app server) has to populate it's own cache
  • Use of ThreadLocal's within an application server can lead to ClassLoader leaks, as each Thread can retain a reference to a ThreadLocal even though it is unreachable

The common solution to the ThreadLocal issue is to call ClassFactory.clearCache() in a Servlet filter or similar which removes the ThreadLocal map.

I propose (see mailing list for patch) that the cache can be implemented using a non locking copy on write algorithm that would will be the same or very close performance with a much reduced memory overhead (once populated) and better hit ratio.






[JAXB-977] XMLCatalog not used from xjc/xjctask when strict validation is enabled (JAXB-616 not actually fixed) Created: 27/Aug/13  Updated: 27/Aug/13

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: christopherincanada Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: christopherincanada and Iaroslav Savytskyi

 Description   

When using XJC from ANT and providing an XML Catalog and using strict schema validation, the XML Catalog is ignored. This was originally reported in JAXB-616 (and again in JAXB-795) and was supposed to have been fixed in 2.2.5. However, the fix does not solve the problem. Specifically, the fix was made in class:

com.sun.tools.xjc.reader.xmlschema.parser.SchemaConstraintChecker

Notice the commented out line though... which means the EntityResolver isn't actually used:

private static Source[] [More ...] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException {
SAXSource[] sources = new SAXSource[schemas.length];
for (int i = 0; i < schemas.length; i++) { sources[i] = new SAXSource(schemas[i]); // sources[i].getXMLReader().setEntityResolver(entityResolver); }
return sources;
}

I'm not an expert with respect to JAXB, but after examining some other code I modified it as follows, recompiled, and this does resolve the problem (at least for me):

private static Source[] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException {
SAXSource[] sources = new SAXSource[schemas.length];
for (int i = 0; i < schemas.length; i++) {
sources[i] = new SAXSource(schemas[i]);
if (entityResolver != null)
{
XMLReader reader = sources[i].getXMLReader();
if (reader == null)
{
SAXParserFactory spFactory = SAXParserFactory.newInstance();
spFactory.setNamespaceAware(true);
try

{ reader = spFactory.newSAXParser().getXMLReader(); }

catch (ParserConfigurationException ex)

{ throw new SAXException(ex); }

}
reader.setEntityResolver(entityResolver);
sources[i].setXMLReader(reader);
}
}
return sources;
}



 Comments   
Comment by christopherincanada [ 27/Aug/13 09:32 PM ]

Here is an improved version of the fix that is more efficient:

private static Source[] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException
{
SAXSource[] sources = new SAXSource[schemas.length];
for (int i = 0; i < schemas.length; i++)
{
XMLReader reader = null;
if (entityResolver != null)
{
try

{ reader = getSAXParserFactory().newSAXParser().getXMLReader(); }

catch (ParserConfigurationException ex)

{ throw new SAXException(ex); }

reader.setEntityResolver(entityResolver);
}
sources[i] = new SAXSource(reader, schemas[i]);
}
return sources;
}

private static SAXParserFactory spFactory;

private static SAXParserFactory getSAXParserFactory()
{
if (spFactory == null)

{ spFactory = SAXParserFactory.newInstance(); spFactory.setNamespaceAware(true); }

return spFactory;
}





[JAXB-976] XJC generated field name is not consistent with getter/setter method names Created: 23/Aug/13  Updated: 23/Aug/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: burper Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: xjc wrong property naming
Participants: burper and Iaroslav Savytskyi

 Description   

When an attribute name contains an underscore character, the name of the generated field doesn't match the getter/setter method names.

E.g.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="http://www.foo.com/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="tag">
        <xs:complexType>
            <xs:attribute name="a_b_c" type="xs:string"/>
        </xs:complexType>
    </xs:element>
</xs:schema>

generates:

@XmlAttribute(name = "a_b_c")
protected String abc;

public String getABC() {
    return abc;
}

It would be better if the field is named ABC or aBC, accordingly to the accessor method names.

This gives some trouble when I want to know at runtime the property name binded to an xml attribute. I would usually look up for the XmlAttribute annotation and take the related field name, but with this mismatch I ended up replicating the naming behaviour of xjc in my own code

Thank you






[JAXB-975] Example wrong on http://jaxb.java.net/tutorial/section_3_1-Unmarshalling-and-Using-the-Data.html#Unmarshalling Created: 20/Aug/13  Updated: 20/Aug/13

Status: Open
Project: jaxb
Component/s: docs
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: blaise_doughan Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Online examples


Tags:
Participants: blaise_doughan and Iaroslav Savytskyi

 Description   

The example code on the following page are incorrect:

It should be something like:

public <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException { JAXBContext jc = JAXBContext.newInstance( docClass ); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<T> doc = (JAXBElement<T>)u.unmarshal( inputStream ); return doc.getValue(); }

Another issue with this example is that it doesn't demonstrate caching the JAXBContext (which is thread safe). If the intent is not to show reusing the JAXBContext, then the example could be further simplified to be:

public <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException { return JAXB.unmarshal(inputStream, docClass); }



 Comments   
Comment by blaise_doughan [ 20/Aug/13 06:03 PM ]

There also appears to be some confusion as to what gets returned from the Unmarshal call. The code makes it appear as though it is always JAXBElement, when in reality it is only JAXBElement when the root element is mapped with @XmlElementDecl. Perhaps the code should be:

public <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException { JAXBContext jc = JAXBContext.newInstance( docClass ); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<T> doc = u.unmarshal( new StreamSource(inputStream) docClass ); return doc.getValue(); }





[JAXB-579] Add the ability to exclude namespaces from code generation Created: 11/Dec/08  Updated: 15/Aug/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2
Fix Version/s: not determined

Type: Improvement Priority: Major
Reporter: kitfox Assignee: jaxb-issues
Resolution: Unresolved Votes: 1
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 579
Tags:
Participants: jaxb-issues, kitfox and tastle

 Description   

I'm writing a complex program that splits its work into multiple projects. Each
project produces a jar, some of which depend on classes supplied by other jars.
Let's call these projects A, B and C, where A and B use classes defined in C.

Now C defines a schema core.xsd. B defines a schema beta.xsd which imports
core.xsd. And A defines alpha.xsd which also imports core.xsd. Each of these
schemas have different namespaces.

I'd like to generate JAXB code for each of these projects, but am running into
the problem that all three projects generate their own copy of the classes
described by core.xsd. I can't generate all the JAXB in only one project, since
all projects need access to the produced code. I also can't create a special
project that contains only JAXB code since I may not have access to all projects
at compile time (I'm designing a plugin architecture, so A will not necessarily
even exist at the time the core classes are compiled and distributed).

Ideally I would be able to generate core.xsd classes and compile them into
C.jar. When JAXB classes are generated for B.jar and A.jar, they would realize
that these classes already exist in another project and not create duplicates.

This could be done by adding a binding that lets me suppress generation of
classes for specified namespaces. I could set this binding when running xjc on
my A and B projects.

You could also likely implement this by allowing the user to specify per
namespace which directory (not just package name) binding code is generated to.
Then the compiler could check to see if the generated code already exists.



 Comments   
Comment by tastle [ 15/Aug/13 05:52 PM ]

I believe this is the same problem faced in the OGC JAXB Schemas project also hosted here at java.net. After XJC runs, the unnecessary generated sources (normally matches the episode files fed into it) are being deleted by a Maven Ant Plugin. This is a undesirable work around.

Now I'm running into this same case with another project.





[JAXB-974] Schema generation fails when result path contains space Created: 11/Aug/13  Updated: 11/Aug/13

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: sentinel_atteo Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and sentinel_atteo

 Description   

Given the 'filename' variable contains path with space character, the following code:

context = JAXBContext.newInstance(klasses);
context.generateSchema(new SchemaOutputResolver() {
@Override
public Result createOutput(String namespaceUri, String suggestedFileName)
throws IOException { return new StreamResult(filename); }
});

results in the following exception:

java.io.IOException: java.io.FileNotFoundException: /var/lib/jenkins/jobs/Moonshine%20REVIEW/workspace/atomikos/target/test-home/config/schema.xsd (No such file or directory)
at com.sun.xml.bind.v2.schemagen.XmlSchemaGenerator$Namespace.writeTo(XmlSchemaGenerator.java:729)
at com.sun.xml.bind.v2.schemagen.XmlSchemaGenerator$Namespace.access$800(XmlSchemaGenerator.java:505)
at com.sun.xml.bind.v2.schemagen.XmlSchemaGenerator.write(XmlSchemaGenerator.java:487)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.generateSchema(JAXBContextImpl.java:832)
at org.atteo.evo.config.Configuration.generateSchema(Configuration.java:222)
at org.atteo.moonshine.services.Services.generateTemplateConfigurationFile(Services.java:250)
at org.atteo.moonshine.services.Services.setup(Services.java:277)
at org.atteo.moonshine.MoonshineImplementation.start(MoonshineImplementation.java:206)
at org.atteo.moonshine.tests.MoonshineRule$1.evaluate(MoonshineRule.java:136)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
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.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray2(ReflectionUtils.java:208)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:158)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:86)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:95)



 Comments   
Comment by sentinel_atteo [ 11/Aug/13 01:51 PM ]

As you can see the space character is somehow converted to %20.

Comment by sentinel_atteo [ 11/Aug/13 02:01 PM ]

I think the problem is somewhere in the convertURL method of the StreamSerializer class where some weird magic is going on while extracting path to file from URL.

See:
https://java.net/projects/jaxb/sources/version2/content/trunk/txw2/runtime/src/main/java/com/sun/xml/txw2/output/StreamSerializer.java?rev=4179





[JAXB-973] generated code should be compilable with '-Xdoclint:all' Created: 07/Aug/13  Updated: 07/Aug/13

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Lukas Jungmann Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

jdk8


Tags:
Participants: Iaroslav Savytskyi and Lukas Jungmann

 Description   

-have a schema
-run xjc on it to generate jaxb sources
-run javac -Xdoclint:all on the generated code

=> error(s) appear(s), ie: "error: bad use of '>'"






[JAXB-972] XJC simple mode: pluralisation not suitable for other languages (than english) Created: 06/Aug/13  Updated: 06/Aug/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: starfury Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows, Java6
(Eclipse, XJC ant task)


Tags: simple
Participants: Iaroslav Savytskyi and starfury

 Description   

When using "xjc:simple" is used when generating Java classes from a XSD file, the field names of collections in the generated classes are pluralised.

This might be convenient if the element names in the given XSD are in the english language, but it produces quite strange names in other languages than english.

So it might be very helpful if the pluralisation could be turned off when using "xjc:simple".

Thanks.






[JAXB-968] Schema validation fails breaks for infinispan 2.4 default schema Created: 20/Jul/13  Updated: 04/Aug/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.5
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: jamesmcintosh Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

JDK 7, OSX


File Attachments: File infinispan-test.tgz    
Tags:
Participants: Iaroslav Savytskyi and jamesmcintosh

 Description   

In version 2.2.4 and below the validation worked, in 2.2.5 it stopped working.
I see that there was a change to how <any> is handled see JAXB-869, maybe this the reason it broke as it is the abstractCacheStoreConfig complex type which is failing validation.

javax.xml.bind.UnmarshalException: unexpected element (uri:"urn:infinispan:config:4.2", local:"properties"). Expected elements are <{urn:infinispan:config:4.2}typedProperties>,<{urn:infinispan:config:4.2}singletonStore>,<{urn:infinispan:config:4.2}async>
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:662)
	at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:258)
	at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:253)
	at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:120)
	at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.childElement(Loader.java:105)
	at com.sun.xml.bind.v2.runtime.unmarshaller.StructureLoader.childElement(StructureLoader.java:262)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:498)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:480)
	at com.sun.xml.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(ValidatingUnmarshaller.java:102)
	at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:150)
	at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:551)
	at org.infinispan.config.parsing.NamespaceFilter.startElement(NamespaceFilter.java:29)
	at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
	at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
	at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
	at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
	at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
	at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
	at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
	at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
	at org.xml.sax.helpers.XMLFilterImpl.parse(XMLFilterImpl.java:357)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:218)
	at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:190)
	at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:140)
	at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:123)

This config xml file is from the hibernate-infinispan v3.6.10.Final

infinispan-config-4.2.xml
<?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:infinispan:config:4.2">
   <global>
      <transport transportClass = "org.infinispan.remoting.transport.jgroups.JGroupsTransport" 
            clusterName="infinispan-hibernate-cluster" distributedSyncTimeout="50000">
         <!-- Note that the JGroups transport uses sensible defaults if no configuration property is defined. -->
         <properties>
            <!-- TODO: Change to udp.xml once streaming transfer requirement has been removed.  -->
            <property name="configurationFile" value="flush-udp.xml"/>
         </properties>
         <!-- See the JGroupsTransport javadocs for more flags -->
      </transport>
   </global>

   <default>
      <!-- Used to register JMX statistics in any available MBean server -->
      <jmxStatistics enabled="false"/>
   </default>

   <!-- Default configuration is appropriate for entity/collection caching. -->
   <namedCache name="entity">
      <clustering mode="invalidation">
         <stateRetrieval fetchInMemoryState="false" timeout="20000"/>
         <sync replTimeout="20000"/>
      </clustering>
      <locking isolationLevel="READ_COMMITTED" concurrencyLevel="1000"
               lockAcquisitionTimeout="15000" useLockStriping="false" />
      <!-- Eviction configuration.  WakeupInterval defines how often the eviction thread runs, in milliseconds.  
           0 means the eviction thread will never run.  A separate executor is used for eviction in each cache. -->
      <eviction wakeUpInterval="5000" maxEntries="10000" strategy="LRU"/>
      <expiration maxIdle="100000"/>
      <lazyDeserialization enabled="true"/>
   </namedCache>
   
   <!-- Default configuration is appropriate for entity/collection caching. -->
   <namedCache name="entity-repeatable">
      <clustering mode="invalidation">
         <stateRetrieval fetchInMemoryState="false" timeout="20000"/>
         <sync replTimeout="20000"/>
      </clustering>
      <!-- Note: REPEATABLE_READ is only useful if the application evicts/clears entities 
        from the Hibernate Session and then expects to repeatably re-read them in 
        the same transaction. Otherwise, the Session's internal cache provides a 
        repeatable-read semantic. Before choosing this config, carefully read the docs
        and make sure you really need REPEATABLE_READ.
       -->
      <locking isolationLevel="REPEATABLE_READ" concurrencyLevel="1000"
               lockAcquisitionTimeout="15000" useLockStriping="false"/>
      <!-- Eviction configuration.  WakeupInterval defines how often the eviction thread runs, in milliseconds.  
           0 means the eviction thread will never run.  A separate executor is used for eviction in each cache. -->
      <eviction wakeUpInterval="5000" maxEntries="10000" strategy="LRU"/>
      <expiration maxIdle="100000"/>
      <lazyDeserialization enabled="true"/>
   </namedCache>
   
   <!-- An alternative configuration for entity/collection caching that uses replication instead of invalidation -->
   <namedCache name="replicated-entity">
      <clustering mode="replication">
         <stateRetrieval fetchInMemoryState="false" timeout="20000"/>
         <sync replTimeout="20000"/>
      </clustering>
      <locking isolationLevel="READ_COMMITTED" concurrencyLevel="1000"
               lockAcquisitionTimeout="15000" useLockStriping="false"/>
      <!-- Eviction configuration.  WakeupInterval defines how often the eviction thread runs, in milliseconds.  
           0 means the eviction thread will never run.  A separate executor is used for eviction in each cache. -->
      <eviction wakeUpInterval="5000" maxEntries="10000" strategy="LRU"/>
      <expiration maxIdle="100000"/>
      <lazyDeserialization enabled="true"/>
   </namedCache>
   
   
   <!-- A config appropriate for query caching. Does not replicate queries. -->
   <namedCache name="local-query">
      <locking isolationLevel="READ_COMMITTED" concurrencyLevel="1000"
               lockAcquisitionTimeout="15000" useLockStriping="false"/>
      <!--Eviction configuration.  WakeupInterval defines how often the eviction thread runs, in milliseconds.  0 means
         the eviction thread will never run.  A separate executor is used for eviction in each cache. -->
      <eviction wakeUpInterval="5000" maxEntries="10000" strategy="LRU"/>
      <expiration maxIdle="100000"/>
   </namedCache>

   <!-- A query cache that replicates queries. Replication is asynchronous. -->
   <namedCache name="replicated-query">
      <clustering mode="replication">
         <async/>
      </clustering>
      <locking isolationLevel="READ_COMMITTED" concurrencyLevel="1000"
               lockAcquisitionTimeout="15000" useLockStriping="false"/>
      <!--Eviction configuration.  WakeupInterval defines how often the eviction thread runs, in milliseconds.  0 means
         the eviction thread will never run.  A separate executor is used for eviction in each cache. -->
      <eviction wakeUpInterval="5000" maxEntries="10000" strategy="LRU"/>
      <expiration maxIdle="100000"/>
      <!-- State transfer forces all replication calls to be synchronous,
           so for calls to remain async, use a cluster cache loader instead -->
      <loaders passivation="false" shared="false" preload="false">
         <loader class="org.infinispan.loaders.cluster.ClusterCacheLoader" fetchPersistentState="false"
                 ignoreModifications="false" purgeOnStartup="false">
            <properties>
               <property name="remoteCallTimeout" value="20000"/>
            </properties>
         </loader>
      </loaders>
   </namedCache>

   <!-- Optimized for timestamp caching. A clustered timestamp cache
        is required if query caching is used, even if the query cache
        itself is configured with CacheMode=LOCAL. -->
   <namedCache name="timestamps">
      <clustering mode="replication">
         <async/>
      </clustering>
      <locking isolationLevel="READ_COMMITTED" concurrencyLevel="1000"
               lockAcquisitionTimeout="15000" useLockStriping="false"/>
      <lazyDeserialization enabled="true"/>
      <!--  Don't ever evict modification timestamps -->
      <eviction wakeUpInterval="0" strategy="NONE"/>
      <!-- State transfer forces all replication calls to be synchronous,
           so for calls to remain async, use a cluster cache loader instead -->
      <loaders passivation="false" shared="false" preload="false">
         <loader class="org.infinispan.loaders.cluster.ClusterCacheLoader" fetchPersistentState="false"
                 ignoreModifications="false" purgeOnStartup="false">
            <properties>
               <property name="remoteCallTimeout" value="20000"/>
            </properties>
         </loader>
      </loaders>
   </namedCache>

</infinispan>

The schema to validate against

infinispan-schema-4.2.xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" targetNamespace="urn:infinispan:config:4.2" xmlns:tns="urn:infinispan:config:4.2" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="infinispan" type="tns:infinispanConfiguration"/>

  <xs:complexType name="infinispanConfiguration">
    <xs:sequence>
      <xs:element name="global" type="tns:globalConfiguration" minOccurs="0"/>
      <xs:element name="default" type="tns:configuration" minOccurs="0"/>
      <xs:element name="namedCache" type="tns:configuration" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="globalConfiguration">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBean">
        <xs:all>
          <xs:element name="asyncListenerExecutor" type="tns:executorFactoryType" minOccurs="0"/>
          <xs:element name="asyncTransportExecutor" type="tns:executorFactoryType" minOccurs="0"/>
          <xs:element name="evictionScheduledExecutor" type="tns:scheduledExecutorFactoryType" minOccurs="0"/>
          <xs:element name="replicationQueueScheduledExecutor" type="tns:scheduledExecutorFactoryType" minOccurs="0"/>
          <xs:element name="globalJmxStatistics" type="tns:globalJmxStatisticsType" minOccurs="0"/>
          <xs:element name="transport" type="tns:transportType" minOccurs="0"/>
          <xs:element name="serialization" type="tns:serializationType" minOccurs="0"/>
          <xs:element name="shutdown" type="tns:shutdownType" minOccurs="0"/>
        </xs:all>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="abstractConfigurationBean" abstract="true">
    <xs:sequence/>
  </xs:complexType>

  <xs:complexType name="executorFactoryType">
    <xs:complexContent>
      <xs:extension base="tns:factoryClassWithPropertiesType">
        <xs:sequence/>
        <xs:attribute name="factory" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="factoryClassWithPropertiesType" abstract="true">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBeanWithGCR">
        <xs:sequence>
          <xs:element name="properties" type="tns:propertiesType" minOccurs="0"/>
        </xs:sequence>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="abstractConfigurationBeanWithGCR" abstract="true">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBean">
        <xs:sequence/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="propertiesType">
    <xs:sequence>
      <xs:element name="property" type="tns:property" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="property">
    <xs:sequence/>
    <xs:attribute name="name" type="xs:string"/>
    <xs:attribute name="value" type="xs:string"/>
  </xs:complexType>

  <xs:complexType name="scheduledExecutorFactoryType">
    <xs:complexContent>
      <xs:extension base="tns:factoryClassWithPropertiesType">
        <xs:sequence/>
        <xs:attribute name="factory" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="globalJmxStatisticsType">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBeanWithGCR">
        <xs:sequence>
          <xs:element name="properties" type="tns:propertiesType" minOccurs="0"/>
        </xs:sequence>
        <xs:attribute name="allowDuplicateDomains" type="xs:boolean"/>
        <xs:attribute name="cacheManagerName" type="xs:string"/>
        <xs:attribute name="enabled" type="xs:boolean"/>
        <xs:attribute name="jmxDomain" type="xs:string"/>
        <xs:attribute name="mBeanServerLookup" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="transportType">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBeanWithGCR">
        <xs:sequence>
          <xs:element name="properties" type="tns:propertiesType" minOccurs="0"/>
        </xs:sequence>
        <xs:attribute name="clusterName" type="xs:string"/>
        <xs:attribute name="distributedSyncTimeout" type="xs:long"/>
        <xs:attribute name="machineId" type="xs:string"/>
        <xs:attribute name="nodeName" type="xs:string"/>
        <xs:attribute name="rackId" type="xs:string"/>
        <xs:attribute name="siteId" type="xs:string"/>
        <xs:attribute name="strictPeerToPeer" type="xs:boolean"/>
        <xs:attribute name="transportClass" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="serializationType">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBeanWithGCR">
        <xs:sequence/>
        <xs:attribute name="marshallerClass" type="xs:string"/>
        <xs:attribute name="version" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="shutdownType">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBeanWithGCR">
        <xs:sequence/>
        <xs:attribute name="hookBehavior" type="tns:shutdownHookBehavior"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="configuration">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:all>
          <xs:element name="locking" type="tns:lockingType" minOccurs="0"/>
          <xs:element name="loaders" type="tns:cacheLoaderManagerConfig" minOccurs="0"/>
          <xs:element name="transaction" type="tns:transactionType" minOccurs="0"/>
          <xs:element name="customInterceptors" type="tns:customInterceptorsType" minOccurs="0"/>
          <xs:element name="eviction" type="tns:evictionType" minOccurs="0"/>
          <xs:element name="expiration" type="tns:expirationType" minOccurs="0"/>
          <xs:element name="unsafe" type="tns:unsafeType" minOccurs="0"/>
          <xs:element name="clustering" type="tns:clusteringType" minOccurs="0"/>
          <xs:element name="jmxStatistics" type="tns:jmxStatistics" minOccurs="0"/>
          <xs:element name="lazyDeserialization" type="tns:lazyDeserialization" minOccurs="0"/>
          <xs:element name="invocationBatching" type="tns:invocationBatching" minOccurs="0"/>
          <xs:element name="deadlockDetection" type="tns:deadlockDetectionType" minOccurs="0"/>
          <xs:element name="indexing" type="tns:queryConfigurationBean" minOccurs="0"/>
        </xs:all>
        <xs:attribute name="name" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="abstractNamedCacheConfigurationBean" abstract="true">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBean">
        <xs:sequence/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="lockingType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="concurrencyLevel" type="xs:int"/>
        <xs:attribute name="isolationLevel" type="tns:isolationLevel"/>
        <xs:attribute name="lockAcquisitionTimeout" type="xs:long"/>
        <xs:attribute name="useLockStriping" type="xs:boolean"/>
        <xs:attribute name="writeSkewCheck" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="cacheLoaderManagerConfig">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence>
          <xs:element name="loader" type="tns:abstractCacheStoreConfig" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
        <xs:attribute name="passivation" type="xs:boolean"/>
        <xs:attribute name="preload" type="xs:boolean"/>
        <xs:attribute name="shared" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="abstractCacheStoreConfig">
    <xs:complexContent>
      <xs:extension base="tns:abstractCacheLoaderConfig">
        <xs:all>
          <xs:element name="async" type="tns:asyncStoreConfig" minOccurs="0"/>
          <xs:element name="singletonStore" type="tns:singletonStoreConfig" minOccurs="0"/>
          <xs:element name="properties" type="tns:propertiesType" minOccurs="0"/>
        </xs:all>
        <xs:attribute name="fetchPersistentState" type="xs:boolean"/>
        <xs:attribute name="ignoreModifications" type="xs:boolean"/>
        <xs:attribute name="purgeOnStartup" type="xs:boolean"/>
        <xs:attribute name="purgeSynchronously" type="xs:boolean"/>
        <xs:attribute name="purgerThreads" type="xs:int"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="abstractCacheLoaderConfig">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="class" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="asyncStoreConfig">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="enabled" type="xs:boolean"/>
        <xs:attribute name="flushLockTimeout" type="xs:long"/>
        <xs:attribute name="shutdownTimeout" type="xs:long"/>
        <xs:attribute name="threadPoolSize" type="xs:int"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="singletonStoreConfig">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="pushStateTimeout" type="xs:long"/>
        <xs:attribute name="pushStateWhenCoordinator" type="xs:boolean"/>
        <xs:attribute name="enabled" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="transactionType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="cacheStopTimeout" type="xs:int"/>
        <xs:attribute name="eagerLockSingleNode" type="xs:boolean"/>
        <xs:attribute name="syncCommitPhase" type="xs:boolean"/>
        <xs:attribute name="syncRollbackPhase" type="xs:boolean"/>
        <xs:attribute name="transactionManagerLookupClass" type="xs:string"/>
        <xs:attribute name="useEagerLocking" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="customInterceptorsType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence>
          <xs:element name="interceptor" type="tns:interceptor" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="interceptor">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence>
          <xs:element name="properties" type="tns:propertiesType" minOccurs="0"/>
        </xs:sequence>
        <xs:attribute name="index" type="xs:int"/>
        <xs:attribute name="after" type="xs:string"/>
        <xs:attribute name="before" type="xs:string"/>
        <xs:attribute name="position" type="tns:position"/>
        <xs:attribute name="class" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="evictionType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="maxEntries" type="xs:int"/>
        <xs:attribute name="strategy" type="tns:evictionStrategy"/>
        <xs:attribute name="threadPolicy" type="tns:evictionThreadPolicy"/>
        <xs:attribute name="wakeUpInterval" type="xs:long"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="expirationType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="lifespan" type="xs:long"/>
        <xs:attribute name="maxIdle" type="xs:long"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="unsafeType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="unreliableReturnValues" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="clusteringType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:all>
          <xs:element name="sync" type="tns:syncType" minOccurs="0"/>
          <xs:element name="stateRetrieval" type="tns:stateRetrievalType" minOccurs="0"/>
          <xs:element name="l1" type="tns:l1Type" minOccurs="0"/>
          <xs:element name="async" type="tns:asyncType" minOccurs="0"/>
          <xs:element name="hash" type="tns:hashType" minOccurs="0"/>
        </xs:all>
        <xs:attribute name="mode" type="xs:string"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="syncType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="replTimeout" type="xs:long"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="stateRetrievalType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="alwaysProvideInMemoryState" type="xs:boolean"/>
        <xs:attribute name="fetchInMemoryState" type="xs:boolean"/>
        <xs:attribute name="initialRetryWaitTime" type="xs:long"/>
        <xs:attribute name="logFlushTimeout" type="xs:long"/>
        <xs:attribute name="maxNonProgressingLogWrites" type="xs:int"/>
        <xs:attribute name="numRetries" type="xs:int"/>
        <xs:attribute name="retryWaitTimeIncreaseFactor" type="xs:int"/>
        <xs:attribute name="timeout" type="xs:long"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="l1Type">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="enabled" type="xs:boolean"/>
        <xs:attribute name="lifespan" type="xs:long"/>
        <xs:attribute name="onRehash" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="asyncType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="asyncMarshalling" type="xs:boolean"/>
        <xs:attribute name="replQueueClass" type="xs:string"/>
        <xs:attribute name="replQueueInterval" type="xs:long"/>
        <xs:attribute name="replQueueMaxElements" type="xs:int"/>
        <xs:attribute name="useReplQueue" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="hashType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="class" type="xs:string"/>
        <xs:attribute name="hashFunctionClass" type="xs:string"/>
        <xs:attribute name="numOwners" type="xs:int"/>
        <xs:attribute name="rehashEnabled" type="xs:boolean"/>
        <xs:attribute name="rehashRpcTimeout" type="xs:long"/>
        <xs:attribute name="rehashWait" type="xs:long"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="jmxStatistics">
    <xs:complexContent>
      <xs:extension base="tns:booleanAttributeType">
        <xs:sequence/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="booleanAttributeType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="enabled" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="lazyDeserialization">
    <xs:complexContent>
      <xs:extension base="tns:booleanAttributeType">
        <xs:sequence/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="invocationBatching">
    <xs:complexContent>
      <xs:extension base="tns:booleanAttributeType">
        <xs:sequence/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="deadlockDetectionType">
    <xs:complexContent>
      <xs:extension base="tns:abstractNamedCacheConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="enabled" type="xs:boolean"/>
        <xs:attribute name="spinDuration" type="xs:long"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="queryConfigurationBean">
    <xs:complexContent>
      <xs:extension base="tns:abstractConfigurationBean">
        <xs:sequence/>
        <xs:attribute name="enabled" type="xs:boolean"/>
        <xs:attribute name="indexLocalOnly" type="xs:boolean"/>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:simpleType name="shutdownHookBehavior">
    <xs:restriction base="xs:string">
      <xs:enumeration value="DEFAULT"/>
      <xs:enumeration value="REGISTER"/>
      <xs:enumeration value="DONT_REGISTER"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="isolationLevel">
    <xs:restriction base="xs:string">
      <xs:enumeration value="NONE"/>
      <xs:enumeration value="SERIALIZABLE"/>
      <xs:enumeration value="REPEATABLE_READ"/>
      <xs:enumeration value="READ_COMMITTED"/>
      <xs:enumeration value="READ_UNCOMMITTED"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="position">
    <xs:restriction base="xs:string">
      <xs:enumeration value="FIRST"/>
      <xs:enumeration value="LAST"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="evictionStrategy">
    <xs:restriction base="xs:string">
      <xs:enumeration value="NONE"/>
      <xs:enumeration value="UNORDERED"/>
      <xs:enumeration value="FIFO"/>
      <xs:enumeration value="LRU"/>
      <xs:enumeration value="LIRS"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="evictionThreadPolicy">
    <xs:restriction base="xs:string">
      <xs:enumeration value="PIGGYBACK"/>
      <xs:enumeration value="DEFAULT"/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

Here is a simplified JUnit version of the code to test

InfinispanConfigurationTest.java
package test.infinispan;

import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;

import org.infinispan.config.InfinispanConfiguration;
import org.infinispan.config.JAXBUnmarshallable;
import org.infinispan.config.parsing.NamespaceFilter;
import org.infinispan.util.FileLookup;
import org.junit.Ignore;
import org.junit.Test;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;


public class InfinispanConfigurationTest {

	@Test
	public void testFull42() throws SAXException, JAXBException {
		testFull("infinispan-config-4.2.xml", "infinispan-config-4.2.xsd");
	}
	
	@Ignore
	private void testFull(String xml, String xsd) throws SAXException, JAXBException {
		FileLookup fileLookup = new FileLookup();
		InputStream config = fileLookup.lookupFile(xml);
		InputStream schema = InfinispanConfiguration.findSchemaInputStream(xsd);
		JAXBContext jc = JAXBContext.newInstance(InfinispanConfiguration.class);
		Unmarshaller u = jc.createUnmarshaller();
		NamespaceFilter nf = new NamespaceFilter();
		XMLReader reader = XMLReaderFactory.createXMLReader();
		nf.setParent(reader);

		SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
		u.setSchema(factory.newSchema(new StreamSource(schema)));
		u.setEventHandler(new ValidationEventHandler() {
			@Override
			public boolean handleEvent(ValidationEvent event) {
				int severity = event.getSeverity();
				return (severity != ValidationEvent.FATAL_ERROR && severity != ValidationEvent.ERROR);
			}
		});

		SAXSource source = new SAXSource(nf, new InputSource(config));
		u.setListener(new Unmarshaller.Listener() {
			@Override
			public void beforeUnmarshal(Object target, Object parent) {
				if (target instanceof JAXBUnmarshallable) {
					// notify the bean that it is about to be unmarshalled
					((JAXBUnmarshallable) target).willUnmarshall(parent);
				}
			}
		});

		InfinispanConfiguration ic = (InfinispanConfiguration) u.unmarshal(source);
		ic.accept(null);
	}

}

And maven dependencies of the versions I tested with.

maven dependencies
<dependency>
	<groupId>javax.xml.bind</groupId>
	<artifactId>jaxb-api</artifactId>
	<version>2.2</version>
</dependency>
<dependency>
	<groupId>com.sun.xml.bind</groupId>
	<artifactId>jaxb-impl</artifactId>
	<version>2.2.5</version>
<!--
	<version>2.2.4</version>
-->
</dependency>
<dependency>
	<groupId>xerces</groupId>
	<artifactId>xercesImpl</artifactId>
	<version>2.11.0</version>
</dependency>
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-infinispan</artifactId>
	<version>3.6.10.Final</version>
	<exclusions>
		<exclusion>
			<groupId>org.infinispan</groupId>
			<artifactId>infinispan-parent</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>org.infinispan</groupId>
	<artifactId>infinispan-core</artifactId>
	<version>4.2.1.FINAL</version>
	<exclusions>
		<exclusion>
			<groupId>org.jboss.javaee</groupId>
			<artifactId>jboss-transaction-api</artifactId>
		</exclusion>
	</exclusions>
</dependency>


 Comments   
Comment by Iaroslav Savytskyi [ 22/Jul/13 07:13 AM ]

Hi,

Thank you for reporting. Is this problem reproducible with the latest 2.2.7 release or 2.2.8-bxx?


Iaroslav

Comment by jamesmcintosh [ 27/Jul/13 11:50 AM ]

Yes, it fails on 2.2.7 and 2.2.8-b1

Comment by jamesmcintosh [ 27/Jul/13 11:51 AM ]

I also have a maven project with a unit test but I can't see how to attach a file to this ticket.





[JAXB-643] Cannot use gMonth on jdk/jre 6 Created: 20/May/09  Updated: 29/Jul/13  Resolved: 29/Jul/13

Status: Resolved
Project: jaxb
Component/s: runtime
Affects Version/s: 2.1.11
Fix Version/s: 2.2.8

Type: Bug Priority: Major
Reporter: kasaihiroyoshi Assignee: Iaroslav Savytskyi
Resolution: Fixed Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


File Attachments: Text File JAXB643_RuntimeBuildinLeafInfoImpl.2.patch     Text File JAXB643_RuntimeBuildinLeafInfoImpl.patch    
Issuezilla Id: 643
Tags: gMonth xmlGregorianCalendar
Participants: Iaroslav Savytskyi, kasaihiroyoshi and Martin Grebac

 Description   

Sun's DatatypeFactory#newXMLGregorianCalendar(String) and XMLGregorianCalendar
which was buldled in jdk/jre6 lost backward compatibility in xsd:gMonth.

JAXP said it as by-design, but in practice use, old format WAS LEGAL in several
years, and many implimentations use old format now and for a while.

So, Apache's xerces kept compatibility in the change (http://
fisheye5.cenqua.com/browse/jaxp-sources/xml-xerces/java/src/com/sun/org/apache/
xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java?r1=1.4&r2=1.5)

This is critical especially in webservices, and JAXB is used in JAX-WS.
I hope JAXB to take a practical way.



 Comments   
Comment by kasaihiroyoshi [ 20/May/09 09:54 PM ]

Created an attachment (id=308)
fix in roughly same way to apache's xerces does.

Comment by kasaihiroyoshi [ 20/May/09 11:30 PM ]

JAXB prints gMonth in old style like "-12-+09:00" on JDK/JRE 6.
But it cannot parse the "-12-+09:00" even though the text is printed by
itsself !

On JDK/JRE6, JAXB requires new style gMonth string in read,
but it print gMonth string in old style.

Attached patch lets it allow both of old and new style gMonth string in read.

Comment by kasaihiroyoshi [ 21/May/09 04:21 AM ]

Created an attachment (id=309)
quick dirty switcher of printing format of gMonth. Defaulting old style as of now.

Comment by Martin Grebac [ 29/Jul/13 01:16 PM ]

Yardo, I think you just fixed this one - didn't you? If so, please update the status ...

Comment by Iaroslav Savytskyi [ 29/Jul/13 01:44 PM ]

The issue is fixed in 2.2.8.

For backwards compatibility Matrin introduced system property: "jaxb.ri.useOldGmonthMapping". If it's set - we will use old format "-MM-" to parse gMonth. I'm not sure if xerces has some property to work with old format.





[JAXB-395] XJC does not support compiler properties and features Created: 31/Jul/07  Updated: 29/Jul/13  Resolved: 29/Jul/13

Status: Resolved
Project: jaxb
Component/s: xjc
Affects Version/s: 2.1.4
Fix Version/s: 2.2.8

Type: Improvement Priority: Major
Reporter: ewrdk Assignee: Martin Grebac
Resolution: Won't Fix Votes: 2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 395
Tags: as91-na
Participants: ewrdk, kohsuke, Martin Grebac, mmuller and Pavel Bucek

 Description   

XJC generates code based on an underlying implementation of
javax.xml.validation.SchemaFactory (the schema compiler). This class has the
methods setProperty and setFeature. Neither of these can be accessed via XJC.

This means that certain schemas cannot be compiled f.ex. this:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
xmlns:tns="http://example.org/"
xmlns:dkcc2005="http://rep.oio.dk/ebxml/xml/schemas/dkcc/2005/03/15/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://example.org/">

<xsd:import namespace="http://rep.oio.dk/ebxml/xml/schemas/dkcc/2005/03/15/"
schemaLocation="http://rep.oio.dk/ebxml/xml/schemas/dkcc/2005/03/15/DKCC_StreetName.xsd"/>
<xsd:import namespace="http://rep.oio.dk/ebxml/xml/schemas/dkcc/2005/03/15/"
schemaLocation="http://rep.oio.dk/ebxml/xml/schemas/dkcc/2005/03/15/DKCC_PostCodeIdentifier.xsd"/>

<xsd:complexType name="MyComplexType">
<xsd:sequence>
<xsd:element minOccurs="0" ref="dkcc2005:StreetName"/>
<xsd:element minOccurs="0" ref="dkcc2005:PostCodeIdentifier"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>

The problem here is that there are multiple imports to the same namespace which
will generate the error:

src-resolve: Cannot resolve the name 'dkcc2005:PostCodeIdentifier' to a
'element declaration' component.

Using Xerces this can solved by setting the feature
'http://apache.org/xml/features/honour-all-schemaLocations' to true. Hence XJC
needs to support setting features.

PS: The above feature
'http://apache.org/xml/features/honour-all-schemaLocations' is only available
from Xerces 2.7.0. Current releases of Java 5.0 and 6.0 has a Xerces 2.6.2
built-in. Hence one has to use a newer Xerces library in order for this to work,
ie. copying xml-apis.jar and xercesImpl.jar to <jdk-home>/jre/lib/endorsed and
creating a jaxp.properties file in <jdk-home>/jre containing the line
javax.xml.validation.SchemaFactory\:http\://www.w3.org/2001/XMLSchema=org.apache.xerces.jaxp.validation.XMLSchemaFactory



 Comments   
Comment by kohsuke [ 01/Aug/07 05:52 PM ]

Added as91-na

Comment by Pavel Bucek [ 21/Jan/09 02:37 AM ]

Not a bug, it's a missing feature.

Marking as enhancement.

Comment by mmuller [ 05/Jul/11 12:24 PM ]

FYI, there seems to be a workaround to the error that is mentionned (src-resolve: Cannot resolve the name…): disabling schema validation by passing -nv to xjc. Java classes will still be correctly generated.

Comment by Martin Grebac [ 29/Jul/13 01:20 PM ]

Since there's a -nv switch, passing complicated jaxp properties from jaxb tools would be cumbersome, and there's a jaxp way to specify values of properties jdk wide, I don't think this is really critical to be supported.





[JAXB-971] Regression: annotation @XmlJavaTypeAdapters on package is ignored since JAXB v2.2.4-1 Created: 26/Jul/13  Updated: 29/Jul/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.5, 2.2.6, 2.2.7
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: donatasc Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7 x64; JDK 1.6 and JDK 1.7


Tags:
Participants: donatasc and Iaroslav Savytskyi

 Description   

JAXB v2.2.4-1 was the last version that takes into account @XmlJavaTypeAdapters annotation (applied on package). All later JAXB versions ignore this annotation - supplied XmlAdapters are not being used.

Attached is an Ant project, adapted from JAXB sample "j2s-xmlAdapter".
Original sample code (working OK in all JAXB versions) had:

@XmlRootElement
@XmlType(name="KitchenWorldBasketType")
public class KitchenWorldBasket {
    @XmlJavaTypeAdapter(AdapterPurchaseListToHashMap.class)
    HashMap basket = new HashMap();
    ...

and

public class Main {
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(KitchenWorldBasket.class);
        ...

The attached project has these modifications:

@XmlRootElement
@XmlType(name="KitchenWorldBasketType")
public class KitchenWorldBasket {
    //@XmlJavaTypeAdapter(AdapterPurchaseListToHashMap.class)
    @XmlElement(type = PurchaseList.class)
    public LinkedHashMap basket = new LinkedHashMap();
    ...

and

@XmlJavaTypeAdapters({
        @XmlJavaTypeAdapter(value = AdapterPurchaseListToHashMap.class, type = LinkedHashMap.class)
})
package shoppingCart;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
import java.util.LinkedHashMap;

and

public class Main {
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(KitchenWorldBasket.class.getPackage().getName());
        ...

Running the attached project with JAXB v2.2.4-1 gives:

run:
     [echo] Running the sample application...
     [java] KitchenWorldBasket:
     [java] key: 9027   value: glasstop stove in black
     [java] key: 10424  value: backsplash kit in black
     [java] key: 288    value: wooden spoon
     [java] key: 289    value: salt and pepper shakers in yellow
     [java]
     [java] <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     [java] <kitchenWorldBasket>
     [java]     <basket>
     [java]         <item key="9027">glasstop stove in black</item>
     [java]         <item key="10424">backsplash kit in black</item>
     [java]         <item key="288">wooden spoon</item>
     [java]         <item key="289">salt and pepper shakers in yellow</item>
     [java]     </basket>
     [java] </kitchenWorldBasket>

BUILD SUCCESSFUL

Running with JAXB v2.2.5, v2.2.6 and v2.2.7:

run:
     [echo] Running the sample application...
     [java] KitchenWorldBasket:
     [java]
     [java] <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     [java] <kitchenWorldBasket>
     [java]     <basket/>
     [java] </kitchenWorldBasket>

BUILD SUCCESSFUL

There is no difference, whether namespaces are being used or not. I stumbled on this bug working with WebServices and JAX-WS/JAXB bindings (where namespaces are being used).

Additionally, annotation @XmlJavaTypeAdapter is being ignored on classes too (though I do not have a sample test case).

It seems, that @XmlJavaTypeAdapter is being taken into account only when it is applied on class fields.



 Comments   
Comment by donatasc [ 26/Jul/13 08:19 AM ]

Sample project can be downloaded from:
http://www.mif.vu.lt/~donatas/private/j2s-xmlAdapter-onPackage.zip

Comment by Iaroslav Savytskyi [ 29/Jul/13 12:58 PM ]

Hi,

Thanks a lot for reporting.

May be this problem occurred because of APT rewrite in 2.2.5. I have to check.





[JAXB-962] JAXBContext.newInstance fails when one schema uses a reference to another with: The element name ... has more than one mapping. Created: 31/May/13  Updated: 25/Jul/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.4u2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: m_perdikeas Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 1
Σ Remaining Estimate: Not Specified Remaining Estimate: Not Specified
Σ Time Spent: Not Specified Time Spent: Not Specified
Σ Original Estimate: Not Specified Original Estimate: Not Specified
Environment:

Oracle JDK 1.7.0_21, Ubuntu 12.04.2 LTS


Sub-Tasks:
Key
Summary
Type
Status
Assignee
JAXB-969 JAXBContext.newInstance fails when on... Sub-task Closed Iaroslav Savytskyi  
Tags:
Participants: Iaroslav Savytskyi, m_perdikeas and Phoenix_the_II

 Description   

I have two XSD files, one referencing an element of another. I am compiling the two schemas separately using episodes and then try to instantiate a JAXBContext in order to unmarshall an XML file and I get the following exception:

Caused by: javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not
be instantiated: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts
of IllegalAnnotationExceptions
[java] The element name {http://www.example.org/A}someType has more than one mapping.

Below is the smallest possible specimen that demonstrates this issue:

      • file A.xsd ***

<?xml version="1.0" encoding="UTF-8"?>
<schema elementFormDefault="qualified"
xmlns ="http://www.w3.org/2001/XMLSchema"
targetNamespace ="http://www.example.org/A">

<element name="someType" type="string"></element>
</schema>

      • file B.xsd ***

<?xml version="1.0" encoding="UTF-8"?>
<schema elementFormDefault="qualified"
xmlns ="http://www.w3.org/2001/XMLSchema"
xmlns:a ="http://www.example.org/A"
xmlns:b ="http://www.example.org/B"
targetNamespace="http://www.example.org/B"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<import namespace="http://www.example.org/A" schemaLocation="A.xsd"/>

<element name="root" type="b:RootType"></element>
<complexType name="RootType">
<sequence>
<element ref="a:someType"/>
</sequence>
</complexType>
</schema>

      • file b.xml ***

<?xml version="1.0" encoding="UTF-8"?>
<b:root xmlns:a="http://www.example.org/A"
xmlns:b="http://www.example.org/B"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.org/A A.xsd
http://www.example.org/B B.xsd">
<a:someType>foo</a:someType>
</b:root>

      • excrepts from build.file that show XMLSchema compilation ***

<property name="a.schema" value="A.xsd"/>
<property name="a.schema.file" value="${basedir}/${a.schema}"/>
<property name="a.schema.package" value="example.a"/>
<property name="a.dir" value="${src.dir}/example/a"/>
<property name="a.schema.episode" value="${a.schema.package}.episode"/>

<property name="b.schema" value="B.xsd"/>
<property name="b.schema.file" value="${basedir}/${b.schema}"/>
<property name="b.schema.package" value="example.b"/>
<property name="b.dir" value="${src.dir}/example/b"/>

<target name="jaxb-generate-a">
<mkdir dir="${a.dir}"/>
<xjc schema="${a.schema.file}" destdir="${src.dir}" package="${a.schema.package}" extension="true">
<arg value="-npa"/>
<arg value="-episode"/>
<arg value="${a.schema.episode}"/>
<depends dir="${basedir}">
<include name="${a.schema}"/>
</depends>
<produces dir="${a.dir}">
<include name="*.java"/>
</produces>
</xjc>
</target>

<target name="jaxb-generate-b" depends="jaxb-generate-a">
<mkdir dir="${b.dir}"/>
<xjc schema="${b.schema.file}" destdir="${src.dir}" package="${b.schema.package}" extension="true">
<arg value="-npa"/>
<arg value="-b"/>
<arg value="${a.schema.episode}"/>
<depends dir="${basedir}">
<include name="${b.schema}"/>
</depends>
<produces dir="${b.dir}">
<include name="*.java"/>
</produces>
</xjc>
</target>

      • Java code ***

import java.io.*;
import java.util.List;
import java.math.BigDecimal;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;

import example.a.*;
import example.b.*;

public class FooMain {

public static void main (String args[]) throws JAXBException, FileNotFoundException { JAXBContext jc = JAXBContext.newInstance( "example.a:example.b" ); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<RootType> element = (JAXBElement<RootType>)u.unmarshal( new FileInputStream( "b.xml" ) ); }
}

      • exception trace ***
        [java] javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
        [java] The element name {http://www.example.org/A}someType has more than one mapping.
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.b.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.b.ObjectFactory
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.a.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.a.ObjectFactory
        [java]
        [java] - with linked exception:
        [java] [com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
        [java] The element name {http://www.example.org/A}someType has more than one mapping.
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.b.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.b.ObjectFactory
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.a.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.a.ObjectFactory
        [java] ]
        [java] at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:194)
        [java] at org.apache.tools.ant.taskdefs.Java.run(Java.java:771)
        [java] at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:221)
        [java] at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:135)
        [java] at org.apache.tools.ant.taskdefs.Java.execute(Java.java:108)
        [java] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
        [java] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
        [java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        [java] at java.lang.reflect.Method.invoke(Method.java:601)
        [java] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
        [java] at org.apache.tools.ant.Task.perform(Task.java:348)
        [java] at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68)
        [java] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
        [java] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
        [java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        [java] at java.lang.reflect.Method.invoke(Method.java:601)
        [java] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
        [java] at org.apache.tools.ant.Task.perform(Task.java:348)
        [java] at org.apache.tools.ant.taskdefs.MacroInstance.execute(MacroInstance.java:398)
        [java] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
        [java] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
        [java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        [java] at java.lang.reflect.Method.invoke(Method.java:601)
        [java] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
        [java] at org.apache.tools.ant.Task.perform(Task.java:348)
        [java] at org.apache.tools.ant.Target.execute(Target.java:390)
        [java] at org.apache.tools.ant.Target.performTasks(Target.java:411)
        [java] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
        [java] at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
        [java] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
        [java] at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
        [java] at org.apache.tools.ant.Main.runBuild(Main.java:809)
        [java] at org.apache.tools.ant.Main.startAnt(Main.java:217)
        [java] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
        [java] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
        [java] Caused by: javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
        [java] The element name {http://www.example.org/A}someType has more than one mapping.
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.b.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.b.ObjectFactory
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.a.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.a.ObjectFactory
        [java]
        [java] - with linked exception:
        [java] [com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
        [java] The element name {http://www.example.org/A}someType has more than one mapping.
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.b.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.b.ObjectFactory
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.a.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.a.ObjectFactory
        [java] ]
        [java] at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:146)
        [java] at javax.xml.bind.ContextFinder.find(ContextFinder.java:334)
        [java] at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:431)
        [java] at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:394)
        [java] at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:298)
        [java] at FooMain.main(FooMain.java:20)
        [java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        [java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        [java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        [java] at java.lang.reflect.Method.invoke(Method.java:601)
        [java] at org.apache.tools.ant.taskdefs.ExecuteJava.run(ExecuteJava.java:217)
        [java] at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:152)
        [java] ... 34 more
        [java] Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
        [java] The element name {http://www.example.org/A}someType has more than one mapping.
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.b.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.b.ObjectFactory
        [java] this problem is related to the following location:
        [java] at public javax.xml.bind.JAXBElement example.a.ObjectFactory.createSomeType(java.lang.String)
        [java] at example.a.ObjectFactory
        [java]
        [java] at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:106)
        [java] at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:471)
        [java] at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:303)
        [java] at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:142)
        [java] at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1174)
        [java] at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:162)
        [java] at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:286)
        [java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        [java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        [java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        [java] at java.lang.reflect.Method.invoke(Method.java:601)
        [java] at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:172)
        [java] at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:132)
        [java] ... 45 more
        [java] Java Result: -1


 Comments   
Comment by Phoenix_the_II [ 23/Jul/13 12:58 PM ]

I'm having the same problem. Did you manage to work around this problem or?

Comment by Iaroslav Savytskyi [ 23/Jul/13 02:05 PM ]

Hi,

I've tried to reproduce the issue. The only difference I've made is that I've generated classes with xjc from command line.

xjc a.xsd b.xsd

and with a fresh JAXB I have no error.

Can you please try to test the issue with JAXB 2.2.8-b01 (it's available on maven).

Thanks.


Iaroslav

Comment by Phoenix_the_II [ 23/Jul/13 03:05 PM ]

Same error shall I provide a complete zip file with a test case inside of it? And a download link?

Will use original XSD's of third parties, they are opensource anyways so

Comment by Phoenix_the_II [ 25/Jul/13 09:16 AM ]

Ok here's the test case:

https://dl.dropboxusercontent.com/u/3828392/jaxb-962.zip

Just run the com.jaxb.Main class and you'll see the errors popup.

Inside com.jaxb.schema.iisse is a build.sh this is used to compile the jaxb classes. Note that we both use episodes instead of a 1-liner xjc.





JAXBContext.newInstance fails when one schema uses a reference to another with: The element name ... has more than one mapping. (JAXB-962)

[JAXB-969] JAXBContext.newInstance fails when one schema uses a reference to another with: The element name ... has more than one mapping. Created: 23/Jul/13  Updated: 23/Jul/13  Resolved: 23/Jul/13

Status: Closed
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Sub-task Priority: Blocker
Reporter: Phoenix_the_II Assignee: Iaroslav Savytskyi
Resolution: Duplicate Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

JDK1.7u25 on Ubuntu 13.04


Tags:
Participants: Iaroslav Savytskyi and Phoenix_the_II

 Description   

Having the same problem, different version



 Comments   
Comment by Phoenix_the_II [ 23/Jul/13 01:05 PM ]

Due to the nature of this problem I cannot reuse XSD to extend and reuse already existing object. Preventing me from making a further implementation of our code.

Changing XSD is not an option since they are 3rd party and industry standards.

Comment by Iaroslav Savytskyi [ 23/Jul/13 02:41 PM ]

JDK 1.7u25 and JDK 1.7u21 contain the same JAXB version.





[JAXB-956] JAXBContext generateSchema() method generates invalid schema when @XmlElements is used Created: 25/Apr/13  Updated: 18/Jul/13

Status: Open
Project: jaxb
Component/s: schemagen
Affects Version/s: 2.2.6
Fix Version/s: None

Type: Bug Priority: Major
Reporter: seanmills Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi and seanmills

 Description   

Schema generation produces invalid schema when classes contain @XmlElements annotations.



 Comments   
Comment by seanmills [ 25/Apr/13 09:09 PM ]

I have a sample maven application, however I don't see an option to attach files to this ticket.

Comment by Iaroslav Savytskyi [ 26/Apr/13 10:25 AM ]

Hi,

can you upload your app to any file exchange server and put here the link (e.g. dropbox, google drive, etc)? We disabled attachments here because people started to attach viruses.

Thanks a lot. I'll look at your problem when will have test case.


Iaroslav

Comment by seanmills [ 26/Apr/13 02:37 PM ]

Here is a maven project that you can run to demonstrate the issue. Executing "mvn clean install" will run the test case and it should complete successfully the first run since it is configured to use com.sun.xml.bind:jaxb-impl:2.2.3.

https://docs.google.com/file/d/0B1Dj_J0_vXZaaGNwaXA0NUstUHc/edit?usp=sharing

Now change the com.sun.xml.bind:jaxb-impl artifact from version 2.2.3 to 2.2.6 in the pom.xml and rerun. I tried version 2.2.7 and it fails in the same way. The issue appears to be a missing namespace issue.

Comment by seanmills [ 17/Jul/13 03:46 PM ]

This issue appears fixed in 2.2.8-b01. Any gut feel on when 2.2.8 will be officially released?

Comment by Iaroslav Savytskyi [ 18/Jul/13 08:46 AM ]

Hi,

According to my info we are planning to release it at October-November.

But you can use 2.2.8-bXX for the time being. It's our official development releases integrated into metro, GF, etc.


Iaroslav





[JAXB-430] JAXB Validation Without Schema Created: 15/Oct/07  Updated: 16/Jul/13

Status: Open
Project: jaxb
Component/s: spec
Affects Version/s: 2.1.5
Fix Version/s: not determined

Type: Improvement Priority: Major
Reporter: shelleyb Assignee: Martin Grebac
Resolution: Unresolved Votes: 14
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 430
Tags:
Participants: areami, cruelfate, Iaroslav Savytskyi, lennartj, Martin Grebac, ovy9086, pastafarian, roos, shelleyb and tuukkamustonen

 Description   

Enhance JAXB to allow validation based on annotations, without requiring a schema.

One of the benefits of JAXB 2 is that a schema is not required; annotating Java
classes alone allows for XML serialization/deserialization. With the deprecation
of the Unmarshaller.setValidating() in favor of the unmarshaller.setSchema()
method, however, validation is only available when an XSD is present. Ideally,
validation can occur during unarshalling (or marshalling) without a physical
schema file.



 Comments   
Comment by tuukkamustonen [ 07/Feb/11 12:28 AM ]

It's now year 2011 and this ticket was created roughly 2,5 years ago. No comments here, but seems like it has been discussed "many times". See at least http://stackoverflow.com/questions/3844701/jaxb-validation-of-xml-during-unmarshalling and http://old.nabble.com/Using-JAXB2-Commons-with-the-jaxws-maven-plugin--td29108017.html

Despite of this feature being (maybe) not implemented, updating the ticket with the current status of consideration wouldn't be a bad thing?

Comment by pastafarian [ 27/Jun/11 05:17 PM ]

+1 on the need for better annotation-based validation. Every time we make a change to our data objects, we (re)generate our XSDs from code and share them with other projects / clients.

Without better XML schema validation options, we might as well be using JSON

Comment by lennartj [ 04/Nov/11 07:57 AM ]

This is a rather important issue, since everyone using annotated POJOs - rather than XML schema - as the model source at present need to create their own custom validation for generated objects due to the lack of validation facilities for this scenario within JAXB.

Validation of JAXB structures should really be part of the JAXB family of tasks; otherwise we condemn project to using XSDs (as opposed to POJOs) as the data model source. POJO entities should also be first-class citizens, without the need to generate intermediary XML Schemas simply to enable some kind of validation).

... which implies we need to provide validation facilities without XML Schema.

Comment by cruelfate [ 13/Jan/12 07:44 AM ]

Indeed. I'm not looking for much .. heck I'd take something that only regarded XmlElement(required=true) so I wouldn't have to resort to this horror show:

Use Case

import javax.xml.bind.annotation.XmlElement;
import JaxbValidator.ValidationException;
import org.testng.annotations.Test;

public class JaxbValidatorTest {

    static class Llama {
        @XmlElement(required = false)
        private final String no;

        @XmlElement(required = true)
        private final String yes;

        public Llama(String no, String yes) {
            super();
            this.no = no;
            this.yes = yes;
        }
    }
    @Test
    public void validateRequired() {
        try {
            Llama o = new Llama("a", "b");
            // THE MAIN EVENT - see if 'required' is honored
            JaxbValidator.validateRequired(o, Llama.class);
        } catch (ValidationException e) {
            assert false : "Should not have thrown validation exception.";
        }
        try {
            Llama o = new Llama(null, null);
            // Again - see if 'required' is honored
            JaxbValidator.validateRequired(o, Llama.class);
            assert false : "Should have thrown validation exception for 'yes'";
        } catch (ValidationException e) {
            assert e.getMessage() != null: "Expected validation message, got null." ;
        }
    }
}

Implementation

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.xml.bind.annotation.XmlElement;
import org.apache.log4j.Logger;

/**
 * oh so minimal consideration of JAXB annotation
 */
public class JaxbValidator {

    private static final Logger LOG = Logger.getLogger(JaxbValidator.class);

    public static class ValidationException extends Exception {
        public ValidationException(String message, Throwable cause) {
            super(message, cause);
        }
        public ValidationException(String message) {
            super(message);
        }
    }

    /**
     * Enforce 'required' attibute.
     *
     * Requires either no security manager is used or the default security manager is employed. 
     * @see {@link Field#setAccessible(boolean)}.
     */
    public static <T> void validateRequired(T target, Class<T> targetClass)
        throws ValidationException {
        StringBuilder errors = new StringBuilder();
        Field[] fields = targetClass.getDeclaredFields();
        for (Field field : fields) {
            XmlElement annotation = field.getAnnotation(XmlElement.class);
            if (annotation != null && annotation.required()) {
                try {
                    field.setAccessible(true);
                    if (field.get(target) == null) {
                        if (errors.length() != 0) {
                            errors.append(" ");
                        }
                        String message = String.format("%s: required field '%s' is null.",
                                                       targetClass.getSimpleName(),
                                                       field.getName());
                        LOG.error(message);
                        errors.append(message);
                    }
                } catch (IllegalArgumentException e) {
                    LOG.error(field.getName(), e);
                } catch (IllegalAccessException e) {
                    LOG.error(field.getName(), e);
                }
            }
        }
        if (errors.length() != 0) {
            throw new ValidationException(errors.toString());
        }
    }

And yes ... it doesn't do deep inspection. I wasn't sure if JAXB handles cyclic graphs, so I didn't attempt recursion without knowing if I needed to detect loops.

Comment by roos [ 30/Oct/12 01:17 PM ]

Its 10/2012 now and still nothing.

Comment by ovy9086 [ 16/Jul/13 01:50 PM ]

now it's 2013... and still no updates on this. I just started with JAXB and in the first day I needed this and... BUMMER. Not available...

Comment by areami [ 16/Jul/13 01:54 PM ]

please have a look at https://github.com/whummer/jaxb-facets; they may have implemented this there

Comment by Iaroslav Savytskyi [ 16/Jul/13 01:59 PM ]

May be MOXy JAXB implementation can help.

http://www.eclipse.org/eclipselink/moxy.php

Comment by lennartj [ 16/Jul/13 10:56 PM ]

Actually, being able to validate XSDs generated from annotated POJOs in a simple
and useable form is still very important for JAXB. It is puzzling that this is not a
trivial operation in the year 2013.

My workaround has been the implementation in

<dependency>
    <groupId>se.jguru.nazgul.core.xmlbinding.spi.jaxb</groupId>
    <artifactId>nazgul-core-xmlbinding-spi-jaxb</artifactId>
    <version>1.5.0</version>
</dependency>

It generates schema from annotated POJOs and performs validation during marshalling and unmarshalling.





[JAXB-791] Support java.util.Map and it's subtypes, as it's in the spec Created: 04/Nov/10  Updated: 15/Jul/13

Status: Reopened
Project: jaxb
Component/s: spec
Affects Version/s: 2.1
Fix Version/s: not determined

Type: Improvement Priority: Minor
Reporter: rdohna Assignee: Martin Grebac
Resolution: Unresolved Votes: 1
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


File Attachments: Java Source File TestJaxbMap.java    
Issuezilla Id: 791
Tags:
Participants: Iaroslav Savytskyi, Martin Grebac, Pavel Bucek and rdohna

 Description   

Section 8.5.4 of the JAXB spec states that java.util.Map (and its subtypes) must
be supported. The RI does not, does it?

I didn't find any issues with "Map" in the Summary.

I'm not shure about the exact version... the one shipped with OpenJDK-6.



 Comments   
Comment by Pavel Bucek [ 19/Nov/10 09:52 AM ]

what do you mean its not supported? Have you encountered any issue with Map
marshalling/unmarshalling? Do you have a testcase?

We do have PASSING roundtrip tests which are using Maps..

Comment by rdohna [ 17/Mar/11 09:31 AM ]

I just wrote a test case that runs with Eclipse-Link MOXy, but fails
with the Reference Implementation. Please find it attached.

@Pavel: Could you pleas take another look? Thanks!

Comment by Martin Grebac [ 30/Mar/11 07:39 AM ]

One shall use XmlElementWrapper to map Map. Moving this to a spec category, as it seems neither TCK nor the spec assure compatibility of implementations. This shall be clarified in the spec itself and TCK shall enforce correct mapping.

Comment by Martin Grebac [ 30/Mar/11 07:40 AM ]

reopening

Comment by rdohna [ 30/Mar/11 08:09 AM ]

It would be sad to remove this from the spec. Using an XmlElementWrapper is a solution, sure... but just not having to care about it, would be much nicer, wouldn't it? And as MOXy proves, this is quite possible! I think the people writing the spec thought just like that, and implementation problems should generally not influence the spec, should they?

Comment by Martin Grebac [ 30/Mar/11 08:14 AM ]

I'm not saying we'll remove it from the spec. But spec shall make sure the implementations are compatible, so it shall be clear how to map a Map. I'll provide the fix in RI to allow XmlElement mapping but will leave this issue open in spec to make sure we think about it in next spec revisions.

Comment by Martin Grebac [ 12/Apr/11 01:59 AM ]

The RI has been fixed, thus changing this to spec enhancement.

Comment by Iaroslav Savytskyi [ 15/Jul/13 04:15 PM ]

RI fix should be improved to use XmlElement annotation values. (e.g. name)





[JAXB-922] JAXB samples fail Created: 04/Oct/12  Updated: 09/Jul/13  Resolved: 21/Dec/12

Status: Resolved
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: 2.2.7

Type: Bug Priority: Major
Reporter: Iaroslav Savytskyi Assignee: Iaroslav Savytskyi
Resolution: Fixed Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

File Attachments: Text File xjc_classloading.patch    
Tags: xjc
Participants: Arul Dhesiaseelan and Iaroslav Savytskyi

 Description   

Because of xjc split some samples began to fail.
e.g. inline-customize fails with:
[com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
com.sun.xml.bind.api.impl.NameConverter is an interface, and JAXB can't handle interfaces.

There are several problems:

  • jaxb-impl.jar should be on classpath.
    -jaxb-impl.jar is now loaded by different classloader. Which is in parents of JAXB masking classloader.


 Comments   
Comment by Iaroslav Savytskyi [ 04/Oct/12 09:42 AM ]

Temporary patch.

Still open issue with passing jaxb-impl.jar to

java -jar jaxb-xjc.jar

Comment by Iaroslav Savytskyi [ 21/Dec/12 10:52 AM ]

Unit tests are still required.

Comment by Iaroslav Savytskyi [ 21/Dec/12 10:54 AM ]

Fixed bugs with contextClassLoader in AntClassLoader and in XJCFacade.

Comment by Arul Dhesiaseelan [ 03/Jul/13 10:44 PM ]

I am still seeing this issue in 2.2.7 using JDK 6 and JDK 7.

classLoader = java.net.URLClassLoader@24a37368
SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7@48e29820
Exception in thread "main" java.lang.AssertionError: javax.xml.bind.JAXBException
 - with linked exception:
[com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
com.sun.xml.bind.api.impl.NameConverter is an interface, and JAXB can't handle interfaces.
	this problem is related to the following location:
		at com.sun.xml.bind.api.impl.NameConverter
		at public com.sun.xml.bind.api.impl.NameConverter com.sun.tools.xjc.reader.xmlschema.bindinfo.BIGlobalBinding.nameConverter
		at com.sun.tools.xjc.reader.xmlschema.bindinfo.BIGlobalBinding
com.sun.xml.bind.api.impl.NameConverter does not have a no-arg default constructor.
	this problem is related to the following location:
		at com.sun.xml.bind.api.impl.NameConverter
		at public com.sun.xml.bind.api.impl.NameConverter com.sun.tools.xjc.reader.xmlschema.bindinfo.BIGlobalBinding.nameConverter
		at com.sun.tools.xjc.reader.xmlschema.bindinfo.BIGlobalBinding
]
	at com.sun.tools.xjc.reader.xmlschema.bindinfo.BindInfo.getCustomizationContext(BindInfo.java:356)
	at com.sun.tools.xjc.reader.xmlschema.bindinfo.BindInfo.getCustomizationUnmarshaller(BindInfo.java:362)
	at com.sun.tools.xjc.reader.xmlschema.bindinfo.AnnotationParserFactoryImpl$1.<init>(AnnotationParserFactoryImpl.java:85)
	at com.sun.tools.xjc.reader.xmlschema.bindinfo.AnnotationParserFactoryImpl.create(AnnotationParserFactoryImpl.java:84)
	at com.sun.xml.xsom.impl.parser.NGCCRuntimeEx.createAnnotationParser(NGCCRuntimeEx.java:365)
	at com.sun.xml.xsom.impl.parser.state.annotation.action0(annotation.java:88)
	at com.sun.xml.xsom.impl.parser.state.annotation.enterElement(annotation.java:113)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:417)
	at com.sun.xml.xsom.impl.parser.state.NGCCHandler.spawnChildFromEnterElement(NGCCHandler.java:113)
	at com.sun.xml.xsom.impl.parser.state.Schema.enterElement(Schema.java:353)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:417)
	at com.sun.xml.xsom.impl.parser.state.NGCCHandler.revertToParentFromEnterElement(NGCCHandler.java:150)
	at com.sun.xml.xsom.impl.parser.state.foreignAttributes.enterElement(foreignAttributes.java:90)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:417)
	at com.sun.xml.xsom.impl.parser.state.NGCCHandler.spawnChildFromEnterElement(NGCCHandler.java:113)
	at com.sun.xml.xsom.impl.parser.state.Schema.enterElement(Schema.java:228)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:417)
	at com.sun.xml.xsom.impl.parser.state.Schema.enterElement(Schema.java:345)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:417)
	at com.sun.xml.xsom.impl.parser.state.Schema.enterElement(Schema.java:333)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:417)
	at com.sun.xml.xsom.impl.parser.state.Schema.enterElement(Schema.java:427)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:417)
	at com.sun.xml.xsom.impl.parser.state.Schema.enterElement(Schema.java:477)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.sendEnterElement(NGCCRuntime.java:417)
	at com.sun.xml.xsom.impl.parser.state.Schema.enterElement(Schema.java:317)
	at com.sun.xml.xsom.impl.parser.state.NGCCRuntime.startElement(NGCCRuntime.java:258)
	at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:527)
	at com.sun.tools.xjc.util.SubtreeCutter.startElement(SubtreeCutter.java:108)
	at com.sun.tools.xjc.reader.ExtensionBindingChecker.startElement(ExtensionBindingChecker.java:150)
	at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:527)
	at com.sun.tools.xjc.reader.xmlschema.parser.IncorrectNamespaceURIChecker.startElement(IncorrectNamespaceURIChecker.java:128)
	at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:527)
	at com.sun.tools.xjc.reader.xmlschema.parser.CustomizationContextChecker.startElement(CustomizationContextChecker.java:193)
	at org.xml.sax.helpers.XMLFilterImpl.startElement(XMLFilterImpl.java:527)
	at com.sun.tools.xjc.reader.internalizer.DOMForestScanner$LocationResolver.startElement(DOMForestScanner.java:147)
	at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:244)
	at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:281)
	at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:250)
	at com.sun.xml.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:127)
	at com.sun.tools.xjc.reader.internalizer.DOMForestScanner.scan(DOMForestScanner.java:92)
	at com.sun.tools.xjc.reader.internalizer.DOMForestScanner.scan(DOMForestScanner.java:100)
	at com.sun.tools.xjc.reader.internalizer.DOMForestParser.parse(DOMForestParser.java:104)
	at com.sun.tools.xjc.ModelLoader$XMLSchemaParser.parse(ModelLoader.java:269)
	at com.sun.xml.xsom.impl.parser.NGCCRuntimeEx.parseEntity(NGCCRuntimeEx.java:347)
	at com.sun.xml.xsom.impl.parser.ParserContext.parse(ParserContext.java:128)
	at com.sun.xml.xsom.parser.XSOMParser.parse(XSOMParser.java:168)
	at com.sun.xml.xsom.parser.XSOMParser.parse(XSOMParser.java:157)
	at com.sun.tools.xjc.ModelLoader.createXSOM(ModelLoader.java:534)
	at com.sun.tools.xjc.ModelLoader.loadXMLSchema(ModelLoader.java:378)
	at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:174)
	at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:119)
	at com.sun.tools.xjc.Driver.run(Driver.java:333)
	at com.sun.tools.xjc.Driver.run(Driver.java:200)
	at com.sun.tools.xjc.Driver._main(Driver.java:123)
	at com.sun.tools.xjc.Driver.access$000(Driver.java:80)
	at com.sun.tools.xjc.Driver$1.run(Driver.java:103)
Comment by Iaroslav Savytskyi [ 04/Jul/13 11:11 AM ]

Hi,

Thank you for reporting.

What example is failing and how do you run it?


Iaroslav

Comment by Arul Dhesiaseelan [ 04/Jul/13 09:28 PM ]

This happens only when I pass bindings file as an argument to xjc. Here is how I run the command:

bin/xjc.sh samples/create-marshal/po.xsd -b bindings.xml -d src

Here is how my bindings.xml look like:

<bindings xmlns="http://java.sun.com/xml/ns/jaxb" version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <globalBindings>
    <javaType name="java.util.Date" xmlType="xs:date"
              parseMethod="jaxb.adapters.DateAdapter.parseDate"
              printMethod="jaxb.adapters.DateAdapter.printDate"
        />
    <javaType name="java.util.Date" xmlType="xs:dateTime"
              parseMethod="jaxb.adapters.DateTimeAdapter.parseDateTime"
              printMethod="jaxb.adapters.DateTimeAdapter.printDateTime"
        />
  </globalBindings>
</bindings>

The same command runs without any problems in jaxb-ri-2.2.6.

Comment by Iaroslav Savytskyi [ 08/Jul/13 02:16 PM ]

I see...

The problem is that by default jaxb-xjc.jar is not depending on jaxb-impl.jar anymore.

That's why you have specify that you are going to use jaxb-impl.jar as jaxb implementation. In other case jaxb is not able to find anything else than jaxb in jdk. We have changed this behavior in 2.2.8.

For 2.2.7 you should do the trick:

bin/xjc.sh -cp lib/jaxb-impl.jar samples/create-marshal/po.xsd -b binding.xml -d src

I've written about this in comments for 2.2.7 release. https://jaxb.java.net/nonav/2.2.7/docs/release-documentation.html#jaxb-2-0-release-notes As I see this is not enough. I'll fix this.

Once again thanks for reporting.


Iaroslav

Comment by Arul Dhesiaseelan [ 09/Jul/13 01:50 AM ]

Awesome, that fixed it. Thanks!





[JAXB-484] JAXB sometimes can't apply a customisation in multiple compilation scenario. Created: 15/Feb/08  Updated: 04/Jul/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.1.6
Fix Version/s: not determined

Type: Bug Priority: Minor
Reporter: nzlemming Assignee: jaxb-issues
Resolution: Unresolved Votes: 2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: Mac OS X
Platform: Macintosh


File Attachments: File testcase.tgz    
Issuezilla Id: 484
Tags:
Participants: aledibe, Iaroslav Savytskyi, jaxb-issues, nzlemming and pbober

 Description   

We have a large project where the data layer is almost totally based on JAXB. We
have multiple levels of schemas, and use xs:import and extensions heavily.
Occasionally we have a problem where JAXB will refuse to run, saying that it
cannot honour a customisation, usually from a base schema when compiling a
sub-schema.

I finally managed to isolate a test case, see the files in the attached tar. The
problem is the javaType customisation on core:ID (in core.xsd).

To reproduce:

xjc.sh core.xsd -d output -p generated.core.com.mycorp.model.common.datatypes

This compiles just the base schema, and works correctly.

xjc.sh core.xsd card.xsd -extension -b core.episode -d output -p
generated.card.com.mycorp.model.common.datatypes

This demonstrates the base file being imported with the corresponding episode.
This also works.

xjc.sh core.xsd iso8583.xsd testcase.xsd -extension -b core.episode -b
iso8583.episode -d output -p generated.testcase.com.mycorp.model.common.datatypes

This case should be identical to the above, but breaks with the error below:

[ERROR] compiler was unable to honor this javaType customization. It is attached
to a wrong place, or its inconsistent with other bindings.
line 66 of file:/Users/colin/dev/platform/common/testcase/core.xsd

[ERROR] (the above customization is attached to the following location in the
schema)
line 61 of file:/Users/colin/dev/platform/common/testcase/core.xsd

This is a very urgent issue for us, any workaround until a fix is available
would be greatly appreciated.



 Comments   
Comment by nzlemming [ 15/Feb/08 10:46 AM ]

Created an attachment (id=243)
Test case files.

Comment by pbober [ 06/Oct/12 12:00 AM ]

I've run across this issue in 2.2.6 and 2.2.7-b41. It's four years old so I am surprised there is nobody else reporting it. Are there plans to fix it?

Comment by aledibe [ 04/Jul/13 10:46 AM ]

I'm having the same problem with the latest 2.2.7 version. Dis anybody found a fix/workaround?

Comment by Iaroslav Savytskyi [ 04/Jul/13 11:05 AM ]

Hi,

The issue is really old. And because nobody else reporting it I assumed that it's fixed.
I'll take a look at it.


Iaroslav





[JAXB-967] Support XSD Conditional Inclusion Versioning Created: 28/Jun/13  Updated: 28/Jun/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.8
Fix Version/s: None

Type: New Feature Priority: Major
Reporter: jorgew93 Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: patch
Participants: Iaroslav Savytskyi and jorgew93

 Description   

We've been integrating with XSD 1.1 schemas quite a bit now, unfortunately JAX-B only supports XSD 1.0 and I presume that it may be a long while before JAX-B supports XSD 1.1.

To remedy that sort of situation the XSD 1.1 specification introduces a new feature known as Conditional Inclusion. With conditional inclusion, we add attributes to our schema documents that allows us to create a single schema that can be processed by both XSD 1.0 and XSD 1.1 processors.

Here's an example:

  <simpleType name="UTCDateTime">
        <restriction base="xsd:dateTime" vc:typeUnavailable="xsd:dateTimeStamp"/>
        <restriction base="xsd:dateTimeStamp" vc:typeAvailable="xsd:dateTimeStamp">
            <assertion
                test="ends-with(string($value),'Z') or ends-with(string($value),'+00:00') or ends-with(string($value),'-00:00')"/>
        </restriction>
    </simpleType>

Notice in the example above the simpleType has two restriction elements. An XSD processor that offers support for the xsd:dateTimeStamp type should use the second restriction element and a processor that does not support that type should use the first. Which element to use is determined by the vc:typeAvailable and vc:typeUnavailable attributes.

The process for performing conditional inclusion is described in detail here:

http://www.w3.org/TR/xmlschema11-1/#cip

The idea is that Conditional Inclusion should be retrofitted into existing XML Schema processors. We have been running our schemes through an XSLT before processing them with JAX-B, but this is getting tedious and error prone, especially when as we start sharing our schemas with others.

We've implemented a simple patch that adds support for conditional inclusion and the ask is that you incorporate this (or something like it) with future versions of xjc.



 Comments   
Comment by jorgew93 [ 28/Jun/13 11:53 PM ]

Was hoping to attach patch to this issue. Should I submit to dev list?





[JAXB-964] JAXB unmarshalling failing when whitespace is present around token enumerations Created: 14/Jun/13  Updated: 24/Jun/13  Resolved: 17/Jun/13

Status: Closed
Project: jaxb
Component/s: runtime, xjc
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Major
Reporter: m_perdikeas Assignee: Iaroslav Savytskyi
Resolution: Won't Fix Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

JDK 1.7.0_21, Ubuntu 12.04.2


Tags:
Participants: Iaroslav Savytskyi, laune and m_perdikeas

 Description   

SO post on the subject: http://stackoverflow.com/questions/17114304/jaxb-unmarshalling-not-tolerating-whitespace-around-token-enumerations

Here's the code that demonstrates the issue, for completeness purposes:

A.xsd

<xs:schema targetNamespace="foo://a"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="foo://a">

<xs:element name="type" type="Type"/>

<xs:simpleType name="Type">
<xs:restriction base="xs:token">
<xs:enumeration value="Archive"/>
<xs:enumeration value="Organisation"/>
</xs:restriction>
</xs:simpleType>

</xs:schema>

a.xml

<a:type xmlns:a="foo://a" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="foo://a A.xsd"
>Organisation </a:type>

(notice the space after the 'Organisation')

unmarshalling code that fails

import java.io.*;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import javax.xml.validation.Validator;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;

import a.*;

public class FooMain {

public static void main(String args[]) throws Exception {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
JAXBContext payloadContext = JAXBContext.newInstance("a");
Unmarshaller unmarshaller = payloadContext.createUnmarshaller();
unmarshaller.setSchema(schemaFactory.newSchema(new Source[]{new StreamSource(new FileInputStream(new File("A.xsd")))}));
unmarshaller.setAdapter(new StringTrimAdapter());
JAXBElement<?> oUnmarshalled = (JAXBElement<?>) unmarshaller.unmarshal(new File("a.xml"));
Object o = oUnmarshalled.getValue();
System.out.println("o==null? "+(o==null?"YES":"NO"));
System.out.println("the type of object is: "+o.getClass().getName()); // NPE here
}
}



 Comments   
Comment by laune [ 15/Jun/13 04:58 AM ]

From XML Schema Part 2: Datatypes Second Edition, section 3.3.2, token:

[Definition:] token represents tokenized strings. The ·value space· of token is the set of strings that do not contain the carriage return (#xD), line feed (#xA) nor tab (#x9) characters, that have no leading or trailing spaces (#x20) and that have no internal sequences of two or more spaces. The ·lexical space· of token is the set of strings that do not contain the carriage return (#xD), line feed (#xA) nor tab (#x9) characters, that have no leading or trailing spaces (#x20) and that have no internal sequences of two or more spaces.

Comment by m_perdikeas [ 15/Jun/13 11:15 AM ]

@laune: if I read you right, JAXB RI should then complain during validation. The current behavior is that it stays silent at validation and returns null when trying to get the token.

Comment by Iaroslav Savytskyi [ 17/Jun/13 09:09 AM ]

Hi,

This is probably not a JAXB bug. JAXB relies on JAXP XML validation.

What we can do - we can try to file an issue for JAXP and will see. Do you want me to do this OR you will do it by yourself?

Thank you for reporting.


Iaroslav.

Comment by m_perdikeas [ 17/Jun/13 11:12 AM ]

@Iaroslav

I wouldn't want to post the exact same code sample on JAXP bug tracker as it uses JAXB unmarshalling.

I would rather you did it since you may be able to narrow it down further to only JAXP code to make it crystal clear the ball is on their side.

Comment by m_perdikeas [ 24/Jun/13 08:28 PM ]

OK, so I reported it to JAXP as: https://java.net/jira/browse/JAXP-78





[JAXB-966] unable to honor this schemaBinding customization (MINIMAL and DIFFERENT behavior of command-line xjc from Ant task xjc) Created: 24/Jun/13  Updated: 24/Jun/13

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: m_perdikeas Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

JDK 1.7.0_21 * JAXB 2.2.7 * Ubuntu 12.04.2


Tags: jaxb jaxb-xjc
Participants: Iaroslav Savytskyi and m_perdikeas

 Description   

Note: this is related to https://java.net/jira/browse/JAXB-965 but IS not identical. See below.

It is different in two respects: (1) it showcases the same kind of bug but in an absolutely minimal setting (with only three, extra-short, xsd files) (2) it demonstrates that in this particular setting, the Ant xjc task fails but the command-line invocation of xjc succeeds which is unsettling but may provide a hint as to the location of this bug.

Here we have three minimal xsd files where invoking the Ant xjc tasks with episodic compilation fails with "unable to honor this schemaBinding" whereas invoking the xjc tool from the command line succeeds. You can view the failure with:

git clone https://github.com/mperdikeas/unable_to_honor-narrowdown.git && cd unable_to_honor-narrowdown && ant

whereas the invocation of the invoke-xjc-2.2.7 succeeds.

Relevant SO post link: http://stackoverflow.com/questions/17274109/jaxb-compiler-was-unable-to-honor-this-schemabinding-customization






[JAXB-965] compiler was unable to honor this schemaBinding customization (in episodic compilation) Created: 24/Jun/13  Updated: 24/Jun/13

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.7
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: m_perdikeas Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

JDK 1.7.0_21 Ubuntu 12.04.2 JAXB 2.2.7


Tags: jaxb jaxb-xjc
Participants: Iaroslav Savytskyi and m_perdikeas

 Description   

When generating Java source files from a bunch of schemas importing one another (and therefore using episodic compilation to avoid having the same classes generated twice), and using some rather complex XSD files (which however I cannot edit since they are industry standard), I get "compiler was unable to honor this schemaBinding customization" failures in random locations. I've created a github repo that captures the case. You can view the "bug" by doing:

git clone https://github.com/mperdikeas/unable_to_honor.git && cd unable_to_honor && ant

Not only will you see the "compiler was unable to honor this schemaBinding" messages, but moreover on successive invocations of "ant clean && ant" you will see the exact line complained about being different (but always the last line in the binding file which to me suggest some parsing bug). I posted on SO on that one as well here:

http://stackoverflow.com/questions/17265960/jaxb-xjc-episodic-compilation-failing-in-random-way-compiler-was-unable-to-ho






[JAXB-923] Unmarshalled content interchange between two threads Created: 15/Oct/12  Updated: 21/Jun/13  Resolved: 09/Jan/13

Status: Closed
Project: jaxb
Component/s: None
Affects Version/s: 2.1.13
Fix Version/s: 2.2.3

Type: Bug Priority: Major
Reporter: csupi Assignee: Iaroslav Savytskyi
Resolution: Fixed Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Java 64-Bit Server 1.6.0_31
Ubuntu 12.04 64-Bit


File Attachments: Java Source File ConcurrentIT.java    
Tags: jaxp multi-threding
Participants: csupi, Iaroslav Savytskyi and Martin Grebac

 Description   

I have many threads which are unmarshall xmls to objects. There is a map and some other fields in this class.

I realized that there are some cases where the content in the map is changed.

I created a simple unit test. Put a String into the map and into a field where the map is. Create 15 threads to marshall and unmarshall my object 1000 times.
After the test execution I realized that about in the 2% of the calls, the String in the map differs from the value in the field.

I add my test case.

There are some interesting things:

final Unmarshaller[] marshaller = new Unmarshaller[NUMBER_OF_CLIENTS];
        final JAXBContext jaxbContext = JAXBContext.newInstance(Event.class);
        for (int i = 0; i < NUMBER_OF_CLIENTS; i++) {
            marshaller[i] = jaxbContext.createUnmarshaller();
        }

Here I create unmarshallers for all threads. But if I create new JAXBContext instance for each threads, the test passed, no errors.

//        @XmlJavaTypeAdapter(MyAdapter.class)
        public final HashMap<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Object put(final String key, final Object value) {
                if ("expected".equals(key) && !value.equals(Event.this.expected)) {
                    System.out.println(Event.this.expected + "  " + value);
                }
                return super.put(key, value);
            }
        };

Here if I uncomment the @XmlJavaTypeAdapter annotation, the test passed, no errors.



 Comments   
Comment by Martin Grebac [ 19/Oct/12 12:52 PM ]

Hi, thanks for submission, however not able to reproduce - is this JDK/OS specific? Would you please verify with latest 2.2.x version as well? Thanks.

Comment by csupi [ 24/Oct/12 08:30 AM ]

2.2.x is not an option for me because of the cxf version.

Anyway the test does not fail, but prints messages to the system out.

Comment by csupi [ 24/Oct/12 08:53 AM ]

I tested it with previous versions of 2.1.x:

2.1.11: passed
2.1.12: failed

Comment by csupi [ 29/Oct/12 07:38 PM ]

Do you have any news about this issue? Could you reproduce this?

Comment by Iaroslav Savytskyi [ 30/Oct/12 01:38 PM ]

Hi,

As I know, we don't have maintenance release for 2.1.x in plan.

Comment by Martin Grebac [ 08/Jan/13 12:51 PM ]

Isn't this http://java.net/jira/browse/JAXB-596 ? Which is already fixed in 2.2.x codebase?

Comment by Iaroslav Savytskyi [ 09/Jan/13 03:01 PM ]

Was fixed with 3372 revision.

Comment by Iaroslav Savytskyi [ 09/Jan/13 03:09 PM ]

I'm not sure about the fix version. But fix revision was committed 17.10.2010.
It could be included into next 2.1.x release (if any would be).

Comment by csupi [ 21/Jun/13 01:54 PM ]

Hi,

I found a bugfix in the release 2.1.14, which looks alike this one:
Bug 16016894: webservice de-marshalling is corrupting hashMap parameters

I can not find any detailed information about that bugfix. Is that a fix for this issue also?





[JAXB-392] Extensible xsd schema generation Created: 29/Jul/07  Updated: 21/Jun/13

Status: Open
Project: jaxb
Component/s: schemagen
Affects Version/s: 2.1.4
Fix Version/s: not determined

Type: New Feature Priority: Major
Reporter: slonopotamus Assignee: Martin Grebac
Resolution: Unresolved Votes: 1
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Operating System: All
Platform: All


Issuezilla Id: 392
Tags:
Participants: Martin Grebac, slonopotamus and whummer

 Description   

Allow making extensions to xsd schema generation (same as
WSDLGeneratorExtension in jaxws-ri).

I have an extension to jaxws-ri that writes wsdl:documentation to generated
wsdl using custom annotations on webservice methods but cannot do the same for
jaxb generated xsd.



 Comments   
Comment by whummer [ 21/Jun/13 12:27 PM ]

You might be interested in the JAXB-Facets extension, which allows you to specify XSD annotations, documentations, and facets:
https://github.com/whummer/jaxb-facets

Also see JIRA page here:
https://java.net/jira/browse/JAXB-917





[JAXB-942] Catalog with PUBLIC definition fails when using an episode Created: 21/Jan/13  Updated: 19/Jun/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.6
Fix Version/s: None

Type: Bug Priority: Major
Reporter: lexi Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 2
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Iaroslav Savytskyi, lexi and phax

 Description   

This issue is a result of analysis for MAVEN_JAXB2_PLUGIN-53.

The problem is that using a catalog with PUBLIC definition fails when episode is used as well.

I have a schema b.xsd which imports a schema a.xsd:

<xsd:import namespace="http://maven-jaxb2-plugin/samples/episode/a" schemaLocation="a.xsd"/>

The schema a.xsd is, however placed in a/a.xsd. This can be handled with the following catalog entry:

PUBLIC "http://maven-jaxb2-plugin/samples/episode/a" "a/a.xsd"

This works fine:

xjc -catalog catalog.cat b.xsd

Now assume we also have an episode JAR:

a.jar!/META-INF/sun-jaxb.episode
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bindings version="2.1" xmlns="http://java.sun.com/xml/ns/jaxb">
  <bindings scd="x-schema::tns" xmlns:tns="http://maven-jaxb2-plugin/samples/episode/a">
    <schemaBindings map="false">
      <package name="maven_jaxb2_plugin.samples.episode.a"/>
    </schemaBindings>
    <bindings scd="~tns:AType">
      <class ref="maven_jaxb2_plugin.samples.episode.a.AType"/>
    </bindings>
    <bindings scd="~tns:A1Type">
      <class ref="maven_jaxb2_plugin.samples.episode.a.A1Type"/>
    </bindings>
    <bindings scd="~tns:A2EnumType">
      <typesafeEnumClass ref="maven_jaxb2_plugin.samples.episode.a.A2EnumType"/>
    </bindings>
  </bindings>
</bindings>

Now this fails:

xjc -extension -catalog catalog.cat b.xsd a.jar

The catalog does not work:

xjc -extension -catalog catalog.cat b.xsd a.jar
parsing a schema...
[ERROR] ...\test\a.xsd (Das System kann die angegebene Datei nicht finden) (eng. Could not find the file)
unknown location

Failed to parse a schema.

I can provide a minimal test project which reproduces this. Attachments do not work. Via mail? (Please ping me: valikov at gmx.net)



 Comments   
Comment by lexi [ 21/Jan/13 11:42 PM ]

I did some debugging and found out that in case no binding files are used, model loading opts to "speculative mode"

I traced it down to the DOMForest which calls the entity resolver with null publicId (whereas it is not null - the namespace is provided):

DOMForest.java
public Document parse( String systemId, boolean root ) throws SAXException, IOException {

        systemId = Options.normalizeSystemId(systemId);

        if( core.containsKey(systemId) )
            // this document has already been parsed. Just ignore.
            return core.get(systemId);
        
        InputSource is=null;
        
        // allow entity resolver to find the actual byte stream.
        if( entityResolver!=null )

// HERE:
            is = entityResolver.resolveEntity(null,systemId);
        if( is==null )
            is = new InputSource(systemId);
        
        // but we still use the original system Id as the key.
        return parse( systemId, is, root );
    }

If no episodes are provided, then no binding files are defined and ModelLoader opts to the "speculative" mode:

ModelLoader.java
public XSSchemaSet loadXMLSchema() throws SAXException {

        if( opt.strictCheck && !SchemaConstraintChecker.check(opt.getGrammars(),errorReceiver,opt.entityResolver, opt.disableXmlSecurity)) {
            // schema error. error should have been reported
            return null;
        }

        if(opt.getBindFiles().length==0) {
            // no external binding. try the speculative no DOMForest execution,
            // which is faster if the speculation succeeds.
            try {
                return createXSOMSpeculative();
            } catch( SpeculationFailure _ ) {
                // failed. go the slow way
            }
        }

        // the default slower way is to parse everything into DOM first.
        // so that we can take external annotations into account.
        DOMForest forest = buildDOMForest( new XMLSchemaInternalizationLogic() );
        return createXSOM(forest, scdBasedBindingSet);
    }

It seems to be something wrong with the DOMForest. It should not ignore the publicId.

Comment by phax [ 19/Jun/13 01:45 PM ]

I'm having the same problem in 2.2.7.
I was tracing it down to AbstractReferenceFinderImpl.startElement

The call to abstract method "findExternalResource" only returns the specified XSD path but totally ignores the publicID of the item (if present). The implementation to this method is in com.sun.tools.xjc.reader.xmlschema.parser.XMLSchemaInternalizationLogic$ReferenceFinder

And afterwards it seems to me, that the resolution of the artifact does not consider a catalog!
-> In my case this leads to the problem that the catalog file must contain an absolute path instead of a relative path!





[JAXB-961] xjc silenting ignores generating Enums when a numeric value is introduced Created: 22/May/13  Updated: 22/May/13

Status: Open
Project: jaxb
Component/s: None
Affects Version/s: 2.2.4u2
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: ericpeters Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 1
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: ericpeters, Iaroslav Savytskyi and laune

 Description   

I had an original XSD that was created that had a Enum created and I was using it.

With an updated XSD I was given, I updated the jar files with xjc only to find out the Enum was no longer being created. Even with the -verbose flag there was no indication of what the problem was.

After lots of beating my head against the wall, I finally found: typesafeEnumMemberName="generateError" and that helped isolate what the problem was.

The default xjc really should have some type of warning/info message - especially when -verbose is specified.



 Comments   
Comment by laune [ 22/May/13 07:27 PM ]

An example of the input XSD that was expected to result in an enum and didn't sure would help...

Comment by ericpeters [ 22/May/13 07:51 PM ]

@Iaune:

The orginal XSD looked something like:

<xs:simpleType name="AssetType">
		<xs:annotation>
			<xs:documentation>...
			</xs:documentation>
		</xs:annotation>
		<xs:restriction base="xs:string">
			<xs:length value="3"/>
			<xs:enumeration value="APG"/>
			<xs:enumeration value="AUD"/>
			<xs:enumeration value="BRO"/>
...
		</xs:restriction>
	</xs:simpleType>

XJC generated an enum like

@XmlType(name = "AssetType")
@XmlEnum
public enum AssetType {

    APG("APG"),
    AUD("AUD"),
....

The updated XSD had:

<xs:simpleType name="AssetType">
		<xs:annotation>
			<xs:documentation>...
			</xs:documentation>
		</xs:annotation>
		<xs:restriction base="xs:string">
			<xs:length value="3"/>
			<xs:enumeration value="360"/>
			<xs:enumeration value="APG"/>
			<xs:enumeration value="AUD"/>
			<xs:enumeration value="BRO"/>
		</xs:restriction>
	</xs:simpleType>

After running xjc on the updated XSD, my client code was broken, since the Enum didn't exist. Ultimately it was the numeric value 360 that isn't valid for an enum variable name that was the culprit. However, even with -verbose settings it was not clear, since there was no warning/info message/etc, that xjc found an invalid enum value and was simply skipping the generation of the Enum and getting/setting Strings directly instead in the generated class.

The work around I finally found was to add into the bindings:

<!-- AssetType Numeric Enum Values -->
        <jaxb:bindings node="//xsd:simpleType[@name='AssetType']/xsd:restriction/xsd:enumeration[@value='360']">
            <jaxb:typesafeEnumMember name="ThreeSixty"/>
        </jaxb:bindings>

It was very frustrating determining why XJC wasn't generating the same classes that it had generated before.





[JAXB-960] JAXB generates invalid XML (includes characters illegal in XML 1.0) Created: 13/May/13  Updated: 14/May/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.6
Fix Version/s: None

Type: Bug Priority: Major
Reporter: gredler Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: gredler, Iaroslav Savytskyi and Martin Grebac

 Description   

As per the XML spec [1], the following characters are legal in XML 1.0:

#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

However, JAXB allows other, illegal characters in input strings (e.g. bell character 0x0007, or vertical tab 0x000B), and marshals them into output XML without any errors or warnings.

I know the solution is not to escape them, since they are illegal regardless of whether they are escaped or not (see JAXB-226), but the fact that JAXB generates invalid (and unparseable) XML without any sort of error or warning seems wrong to me.

There are a number of workarounds out in the wild [2, 3] that rely on replacing the illegal characters with legal characters (e.g. space 0x0020, or replacement character 0xFFFD). Another option would be to eat the illegal characters and just not write them to the output.

Regardless of the approach, I think it would be a good idea to at least provide an out-of-the-box way for users to ensure the correctness of JAXB-generated XML. Some options:

  • Add another property that can be used via Marshaller.setProperty(String, Object) to replace invalid characters with another character ("com.sun.xml.bind.illegalCharacterReplacement"?)
  • Add another property that can be used via Marshaller.setProperty(String, Object) to eat invalid characters ("com.sun.xml.bind.omitIllegalCharacters"?)
  • Enhance the out-of-the-box CharacterEscapeHandler classes to allow for this sort of replacement / omission.
  • Something else?

[1] http://www.w3.org/TR/REC-xml/#NT-Char
[2] http://blog.lesc.se/2009/03/escape-illegal-characters-with-jaxb-xml.html
[3] http://camel.apache.org/jaxb.html#JAXB-IgnoringtheNonXMLCharacter



 Comments   
Comment by Martin Grebac [ 14/May/13 11:26 AM ]

Yardo, correct me if I'm wrong but we use JAXP for validating what we read/write. Thus, if valid, I think the issue should be filed against JAXP instead?





[JAXB-959] The default UTF CharacterEscapeHandler (MinimumEscapeHandler) eats carriage returns Created: 13/May/13  Updated: 13/May/13

Status: Open
Project: jaxb
Component/s: runtime
Affects Version/s: 2.2.6
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: gredler Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: gredler and Iaroslav Savytskyi

 Description   

For some reason the default UTF CharacterEscapeHandler (MinimumEscapeHandler) eats carriage returns ("\r"), i.e. it doesn't write them to the output. NioEscapeHandler, an alternate CharacterEscapeHandler included in JAXB, doesn't ignore them. Here's the relevant code:

public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
        // avoid calling the Writerwrite method too much by assuming
        // that the escaping occurs rarely.
        // profiling revealed that this is faster than the naive code.
        int limit = start+length;
        for (int i = start; i < limit; i++) {
            char c = ch[i];
                if(c == '&' || c == '<' || c == '>' || c == '\r' || (c == '\"' && isAttVal) ) {
                if(i!=start)
                    out.write(ch,start,i-start);
                start = i+1;
                switch (ch[i]) {
                    case '&':
                        out.write("&amp;");
                        break;
                    case '<':
                        out.write("&lt;");
                        break;
                    case '>':
                        out.write("&gt;");
                        break;
                    case '\"':
                        out.write("&quot;");
                        break;
                }
            }
        }
        
        if( start!=limit )
            out.write(ch,start,limit-start);
    }


 Comments   
Comment by gredler [ 13/May/13 03:35 PM ]

Possibly relevant past issue (though I can't find a record in SVN of how it was addressed in the code): JAXB-449





[JAXB-958] XJC extension creates JDefinedClass for JVM-wide class Created: 13/May/13  Updated: 13/May/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.4u1
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: Dmitry Katsubo Assignee: Iaroslav Savytskyi
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags:
Participants: Dmitry Katsubo and Iaroslav Savytskyi

 Description   

When following customization is enabled:

<jaxb:globalBindings generateValueClass="false">
	<xjc:superInterface name="java.lang.Cloneable" />
</jaxb:globalBindings>

XJC generates JDefinedClass for super interface java.lang.Cloneable. However by contract JDefinedClass objects should be created for generated classes.

Expected: java.lang.Cloneable should be a JClass created by JCodeModel.ref(Class) or JDirectClass created by JCodeModel.directClass(String).

The confusion is generally caused by the use of JDefinedClass.hide(). This effect and should be better implemented by making a common class of JDefinedClass and JDirectClass. Then JDefinedClass is always generated class, while JDirectClass is always hidden.

The same should be applied to super class:

<jaxb:globalBindings>
	<xjc:superClass name="com.mycompany.CommonBean" />
</jaxb:globalBindings>

Problematic code: BIGlobalBinding.getSuperClass(), BIGlobalBinding.getSuperInterface().






[JAXB-878] Model improvements for JAnnotationValue implementations Created: 07/Feb/12  Updated: 08/May/13

Status: Open
Project: jaxb
Component/s: xjc
Affects Version/s: 2.2.5
Fix Version/s: None

</
Type: Improvement Priority: Major
Reporter: Dmitry Katsubo Assignee: Martin Grebac
Resolution: Unresolved Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified