Skip to content

jaxb underscores in schema element names - #713

Merged
gunnarmorling merged 1 commit into
mapstruct:masterfrom
grandmasterpixel:jaxb-underscores
Jan 19, 2016
Merged

gunnarmorling merged 1 commit into
mapstruct:masterfrom
grandmasterpixel:jaxb-underscores

Conversation

@grandmasterpixel

Copy link
Copy Markdown
Contributor

Hi,
since I have only been working with jaxb, xml schemas and soap for about 2 weeks there is a lot I still don't know about the problem I "solved" in this PR.

I have a wsdl of a third party soap service. Some of the elements have names using underscores instead of camel case like this:

<element name="planet_name" type="string"/>

which is perfectly ok.

When generating code from that wsdl with the "cxf-codegen-plugin" I get Code mit mostly "javaified" names (camel case with no underscores)
In the "ObjectFactory" the factory methods have @XmlElementDecl annotations that use the underscore names to set their "name" properties. Which might look like this:

    @XmlElementDecl(namespace = "http://foo.bar", name = "planet_name", scope = TypeName.class)
    public JAXBElement<FieldType> createTypeNamePlanetName(FieldType value) {
        return new JAXBElement<FieldType>(_TypeNamePlanetName_QNAME, FieldType.class, TypeName.class, value);
    }

Still kind of ok until I am trying to map my classes to the generated jaxb classes. For the cases where there is more than one property of the same type and one of them was generated from an underscore name in the schema I get a "Ambiguous mapping methods found for mapping property" compile error.

That seems to be because the XmlElementDeclSelector tries to exactly match the camel case name with the underscore name in the annotation. Failing that is falls back to only matching the scope, which result in too many candidates.

What I changed was add a third match on a method suffix. It seemed to me the generated code in ObjectFactory always followed the pattern of "TypeNamePropertyName" in the method names, so using the property name and match it as a suffix seemed like it might work.

@agudian

agudian commented Dec 21, 2015

Copy link
Copy Markdown
Member

(Message from the pull-request-builder): Admins, please verify this patch for it to build in the pull-request-builder.

@sjaakd

sjaakd commented Dec 22, 2015

Copy link
Copy Markdown
Contributor

Xjc also has an arg to decide how to handle dashes/underscores during code generation I believe. Would that be of any use?

@gunnarmorling

gunnarmorling commented Dec 22, 2015 via email

Copy link
Copy Markdown
Member

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

failed to mention, I tried setting underscoreBinding="asCharInWord" but for some reason that only made it convert "planet_name" to "Planet_Name" which still does not match what was set in the annotation

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

ok, the suffix idea was kind of stupid. It falls down as soon as are properties like "planetName" and "currentPlanetName" where one is a suffix of the other. then the code in my branch produces ambiguous matches. so nothing gained :)

A different idea I am exploring right now is to inspect the targetType and find the field annotated with XmlElementRef. These annotations also contain the name exactly how it would be spelled over in the XmlElementDecl annotation.

@sjaakd

sjaakd commented Dec 23, 2015

Copy link
Copy Markdown
Contributor

@sjaakd, maybe the JAXB method matching strategy should be adapted to take
the "_" pattern in name() into account as well?

Yep.. That would make sense.. Would that solve the problem above? E.g. construct a regex that matches both _ and -.. or something along that line..

@gunnarmorling

Copy link
Copy Markdown
Member

Would that solve the problem above?

Yes, I think it would. So from a camel-cased property name such as "planetName" we'd also find an element named "planet_name" in XML. Though we'd have to think about avoiding ambiguities if the elements "planet_name" and "planetName" are there.

A different idea I am exploring right now is to inspect the targetType and find the field annotated with XmlElementRef. These annotations also contain the name exactly how it would be spelled over in the XmlElementDecl annotation.

That sounds interesting. How would that look like? Thanks for working on this btw., @grandmasterpixel!

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

So my idea was something like this:
Since I get code from xjc that looks like this

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ShippingAddressType", propOrder = {
    "street",
    "houseNumber",
    "city",
    "country",
    "planetName"
})
public class ShippingAddressType {
//...
    @XmlElementRef(name = "planet_name", namespace = "http://www.mapstruct.org/itest/jaxb/xsd/test2", type = JAXBElement.class)
    protected JAXBElement<String> planetName;
//...
}

and this

@XmlRegistry
public class ObjectFactory {
//...
    @XmlElementDecl(namespace = "http://www.mapstruct.org/itest/jaxb/xsd/test2", name = "houseNumber", scope = ShippingAddressType.class)
    public JAXBElement<String> createShippingAddressTypeHouseNumber(String value) {
        return new JAXBElement<String>(_ShippingAddressTypeHouseNumber_QNAME, String.class, ShippingAddressType.class, value);
    }

    @XmlElementDecl(namespace = "http://www.mapstruct.org/itest/jaxb/xsd/test2", name = "planet_name", scope = ShippingAddressType.class)
    public JAXBElement<String> createShippingAddressTypePlanetName(String value) {
        return new JAXBElement<String>(_ShippingAddressTypePlanetName_QNAME, String.class, ShippingAddressType.class, value);
    }

}

I can see what factory method to choose from the information on the annotations.

So when XmlElementDeclSelector gets called to find a factory method for "planetName" it would need to

  • inspect the ShippingAddressType class and find the field for the property
  • look up the name in the XmlElementRef annotation
  • then use that to find the method annotated with XmlElementDecl having the right name and scope

the last point was already solved by you so is was trying my luck on the other parts.
I got caught up in a misunderstanding about the meaning of the sourceType and targetType parameters of the getMatchingMethods method. I mistook them for the source and target of the mapping method, but I think they are actually the types of the source and target properties. (in which case I think they should have been called sourcePropertyType and targetPropertyType ;))
anyway: a useable reference to the ShippingAddressType should be present the mappingMethod parameter so I try using that in my next attempt :)

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

what I last pushed still needs some code and branch cleanup but it is able to find the right factory for "planet_name" that I added to the jaxb integration test earlier.
I am using sourceMappingMethod.getResultType() over sourceMappingMethod.getReturnType() because it seemed to be able to have the actual type be overridden. Didn't look to hard though since I just wanted this idea out of my head for now and deal with the specifics later ;). I assumed it has something to do with cases where we want to map to interfaces or abstract classes (google auto values for example) but looking at the docs it seems not to be exactly that.

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

My first XmlElementRef lookup loop did not traverse up the inheritance chain. Now it does and a new version of the jaxb integration test tells me that that is the right thing to do :)
This should now fix the issue I had. Have not compiled our code with this yet though

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

I am back at work and my colleagues are already using a mapstruct version built from my branch so at least our problem is solved.
Also looking at the docs for XmlElementRef and XmlElementDecl it looks like I am clearly taking the right approach here.
But this is still missing at least one thing:
The XmlElementRefs (plural) annotation as demonstrated in an example in the XmlElementDecl javadoc. That seems not easily solvable to me at the moment. I have not thought about it much though.

Since our main problem is solved I will only be working on this on my own time now. Probably mostly in the evening (Central European Time) or weekends. That is unless we run into XmlElementRefs at work :)

@gunnarmorling

gunnarmorling commented Jan 4, 2016 via email

Copy link
Copy Markdown
Member

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

Today I have been playing around a bit.
With a schema like this:

    <complexType name="pea">
        <choice maxOccurs="unbounded">
            <element name="foo" type="xmlelementrefs:FooType"/>
            <element name="bar" type="xmlelementrefs:BarType"/>
        </choice>
    </complexType>
    <complexType name="FooType">
        <sequence>
            <element name="theFoo" type="string"/>
            <element name="otherFoo" type="string"/>
        </sequence>
    </complexType>
    <complexType name="BarType">
        <sequence>
            <element name="theBar" type="string"/>
            <element name="otherBar" type="string"/>
        </sequence>
    </complexType>

    <element name="pea" type="xmlelementrefs:pea"/>

I get a Pea class with a property like this

    @XmlElementRefs({
        @XmlElementRef(name = "bar", namespace = "http://www.mapstruct.org/itest/jaxb/xsd/xmlelementrefs", type = JAXBElement.class),
        @XmlElementRef(name = "foo", namespace = "http://www.mapstruct.org/itest/jaxb/xsd/xmlelementrefs", type = JAXBElement.class)
    })
    protected List<JAXBElement<?>> fooOrBar;

Which means this xml creates a heterogeneous List of a FooType and a BarType

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pea xmlns="http://www.mapstruct.org/itest/jaxb/xsd/xmlelementrefs">
    <foo>
        <theFoo>0</theFoo>
        <otherFoo>0</otherFoo>
    </foo>
    <bar>
        <theBar>0</theBar>
        <otherBar>0</otherBar>
    </bar>
</pea>

So to create a mapping method for that mapstruct would need to generate some kind "if instanceof else if" construct, I think. Does mapstruct already do something like that in the nonjaxb case?

@sjaakd

sjaakd commented Jan 10, 2016

Copy link
Copy Markdown
Contributor

Hi @grandmasterpixel ,

I was just reviewing your code 😄

So to create a mapping method for that mapstruct would need to generate some kind "if instanceof else if" construct, I think. Does mapstruct already do something like that in the nonjaxb case?

Did you look at the @TargetType annotation? That was intended AFAIK to add a target type to the selection. Perhaps that's usable?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reckon getResultType() is more safe.. (you do that a bit later as well)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

uh, thanks, using getExecutable().getReturnType() would have actually been a bug :)

@sjaakd

sjaakd commented Jan 11, 2016

Copy link
Copy Markdown
Contributor

@grandmasterpixel . First of all, thanks for your contribution.

I ran through your code. Main thing is that I find the selector hard to understand.

What I do understand is that you (somehow) try to match up the XmlElementRef and XmlElementDecl in the following way:
You obtain the XmlElementRef via the following steps:

  1. Find the target property in the target bean (or iterable /map) of the mapping method we try to implement.
  2. Find the annotation XmlElementRef
  3. See if you find a name match in the XmlElementDecl object factory method.

I think you're on the right track here.

Main issues:

  1. I think that this XmlElementRef (annotation of the target property) is not altogether different from the targetPropertyName. So perhaps it should be part of the SelectionCriteria. Its 'meta' information to make the selection if you catch my idea.
  2. Use Prisms. Its a more safe way to obtain an annotation.
  3. Use some more comments 😄.

Next: I like the integration test a lot. However, I would like to see some (fixed) unit test as well. See for instance test package: org.mapstruct.ap.test.selection.jaxb.test1.

Last but not least, I think you should cover additional problems in a separate PR. In this way we can speed up your solution a bit 👍

@gunnarmorling

Copy link
Copy Markdown
Member

Hey @grandmasterpixel, I am a bit confused by the changes in XmlElementDeclSelector, esp. this handling around super-types.

Wouldn't it be sufficient to alter the name check so it's based on a "normalized" value of XmlElementDecl#name() (by camel-casing and removing the underscore)?

E.g. we look for a method matching property name "planetName", and we have two candidate methods:

* `XmlElementDecl@name("universe_name")` -> convert name to "universeName", compare to "planetName" -> no match
* `XmlElementDecl@name("planet_name")` -> convert name to "planetName", compare to "planetName" -> match

Now if there was another method XmlElementDecl@name("planetName"), we'd still have an ambiguity between the last two, but I think that's alright. Not much we can do about it, but it's an edge case and users can work around that by providing qualified wrapper methods if needed.

Update: JAXB itself doesn't handle presence of "planet_name" and "planetName" very well:

Two declarations cause a collision in the ObjectFactory class.

So we should be on the safe side if doing it as described above. I don't think the route via the target type and @XmlElementRef is needed actually.

WDYT?

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

If it just had been the case that I just needed to camelcase (planet_name->planetName) XmlElementDecl.name to get a valid match I would have probably gone with that.
But there is also the case of the underscoreBinding="asCharInWord" setting that can be used to customize the binding (http://docs.oracle.com/javaee/5/tutorial/doc/bnbbf.html) which would generate "planet_Name".
Which means without knowledge of how the user configured xjc I would have needed to do at least "planet_name->{planetName, planet_Name} compare both to current property". I did not know if there might be further configuration options so I figured using the annotations was the most reliable source of information of which ObjectFactory method to choose.

regarding jaxb collisions:
We had those too, for simple cases cxf has an "autoNameResolution" switch that we use.
Our collision was in the class names though, but I would still assume it does the following:
If an xml type had both planet_name and planetName elements, a class with properties planetName and planetName2 would be generated.
update:
have been trying to use autoNameResolution for this case, but it seems it does not work for collisions in property names

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

just pushed something that I hope fixes all of the issues sjaakd mentioned

@gunnarmorling

Copy link
Copy Markdown
Member

@grandmasterpixel, cool, looks good to merge for me. Neat stuff with the @XmlElementRef path!

Could you only change the e-mail of the commits to the one associated with your GitHub account and squash everything into a single commit; That way they will be properly linked to your user. Thanks! Your name (for copyright.txt) is Vincent Alexander Beelte, right?

@sjaakd

sjaakd commented Jan 18, 2016

Copy link
Copy Markdown
Contributor

@grandmasterpixel. Looks good at first glance. I'll have one more thorough look tomorrow.

One thing I spotted though is the absence of unit test (only integration test). I do think its quite straightforward to add a unit test as well (there are already some for jaxb selection). In that way, we spot problems immediately and don't have to wait for the outcome of the integration test.

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

Forgot the unittest. Will be present in the squashed commit.
And yes, my name is Vincent Alexander Beelte

@gunnarmorling

Copy link
Copy Markdown
Member

Ah, could you also create an issue for it and refer it's number from the commit message ("#123 Bla bla"). Thx!

@grandmasterpixel

Copy link
Copy Markdown
Contributor Author

added unittest, rebased from origin/master fixed compilation, also I opened and referenced ticket #726
next I will be opening a ticket to request the checkstyle and licence checking be done in an earlier maven phase :)

@agudian

agudian commented Jan 19, 2016

Copy link
Copy Markdown
Member

Writing this to trigger the Jenkins pull-request-builder:
ok to test.

@gunnarmorling
gunnarmorling merged commit f84938f into mapstruct:master Jan 19, 2016
@gunnarmorling

Copy link
Copy Markdown
Member

Merged; @grandmasterpixel, many thanks for implementing this and following up on all the review remarks. Much appreciated!

@agudian

agudian commented Jan 19, 2016

Copy link
Copy Markdown
Member

or not, as gunnar was faster merging it... 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants