Giter VIP home page Giter VIP logo

krasa-jaxb-tools's Introduction

Maven Central

NOTE: I no longer use and maintain this plugin. Consider using this fork: https://github.com/fillumina/krasa-jaxb-tools

Contains:

  • plugin for replacing primitives -XReplacePrimitives (e.g. int -> Integer)
  • plugin for generation of Bean Validation Annotations (JSR-303) -XJsr303Annotations

Release:

<dependency>
    <groupId>com.github.krasa</groupId>
    <artifactId>krasa-jaxb-tools</artifactId>
    <version>1.8</version>
</dependency>

Very Old Snapshot:

<dependency>
    <groupId>com.github.krasa</groupId>
    <artifactId>krasa-jaxb-tools</artifactId>
    <version>1.7-SNAPSHOT</version>
</dependency>

<repository>
    <id>snapshots-repo</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    <releases>
        <enabled>false</enabled>
    </releases>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>

XJsr303Annotations

Generates:

  • @Valid annotation for all complex types, can be further restricted to generate only for types from defined schema: -XJsr303Annotations:targetNamespace=http://www.foo.com/bar
  • @NotNull annotation for objects that has a MinOccur value >= 1 or for attributes with required use
  • @Size for lists that have minOccurs > 1
  • @Size if there is a maxLength or minLength or length restriction
  • @DecimalMax for maxInclusive restriction
  • @DecimalMin for minInclusive restriction
  • @DecimalMax for maxExclusive restriction, enable new parameter (inclusive=false) with: -XJsr303Annotations:JSR_349=true
  • @DecimalMin for minExclusive restriction, enable new parameter (inclusive=false) with: -XJsr303Annotations:JSR_349=true
  • @Digits if there is a totalDigits or fractionDigits restriction.
  • @Pattern if there is a Pattern restriction

@NotNull's default validation message is not always helpful, so it can be customized with -XJsr303Annotations:notNullAnnotationsCustomMessages=OPTION where OPTION is one of the following:

  • false (default: no custom message -- not useful)
  • true (message is present but equivalent to the default: "{javax.validation.constraints.NotNull.message}" -- not useful)
  • FieldName (field name is prefixed to the default message: "field {javax....message}")
  • ClassName (class and field name are prefixed to the default message: "Class.field {javax....message}")
  • other-non-empty-text (arbitrary message, with substitutable, case-sensitive parameters {ClassName} and {FieldName}: "Class {ClassName} field {FieldName} non-null")

Bean validation policy can be customized with -XJsr303Annotations:generateServiceValidationAnnotations=OPTION where OPTION is one of the following:

  • InOut (default: validate requests and responses)
  • In (validate only requests)
  • Out (validate only responses)

Using this option requires to specify krasa as front end generator (See example below)


XReplacePrimitives

  • replaces primitive types by Objects
  • WARNING: must be defined before XhashCode or Xequals

Example project with tests:

https://github.com/krasa/krasa-jaxb-tools-example


Usage:

<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>${cxf-codegen-plugin.version}</version>
    <executions>
        <execution>
            <id>wsdl2java</id>
            <phase>generate-sources</phase>
            <configuration>
                <wsdlOptions>
                    <wsdlOption>
                        <wsdl>src/main/resources/wsdl/...</wsdl>
                        <extraargs>
                            ...
                            <extraarg>-xjc-XJsr303Annotations</extraarg>
							<!--optional-->
                            <extraarg>-xjc-XJsr303Annotations:targetNamespace=http://www.foo.com/bar</extraarg>
                         	<!--optional, this is default values-->
                            <extraarg>-xjc-XJsr303Annotations:generateNotNullAnnotations=true</extraarg>
                         	<!--optional, default is false, possible values are true, FieldName, ClassName, or an actual message -->
                            <extraarg>-xjc-XJsr303Annotations:notNullAnnotationsCustomMessages=false</extraarg>
                            <extraarg>-xjc-XJsr303Annotations:JSR_349=false</extraarg>
                            <extraarg>-xjc-XJsr303Annotations:verbose=false</extraarg>
                            <!--optional, only needed for generateServiceValidationAnnotations, which possible values are InOut (default), In, Out -->
                            <extraarg>-fe</extraarg>
                            <extraarg>krasa</extraarg>
                            <extraarg>-xjc-XJsr303Annotations:generateServiceValidationAnnotations=In</extraarg>
                        </extraargs>
                    </wsdlOption>
                </wsdlOptions>
            </configuration>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>com.github.krasa</groupId>
            <artifactId>krasa-jaxb-tools</artifactId>
            <version>${krasa-jaxb-tools.version}</version>
        </dependency>
        ...
    </dependencies>
</plugin>
<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <forceRegenerate>true</forceRegenerate>
                <schemas>
                    <schema>
                        <fileset>
                            <directory>${basedir}/src/main/resources/wsdl</directory>
                            <includes>
                                <include>*.*</include>
                            </includes>
                            <excludes>
                                <exclude>*.xs</exclude>
                            </excludes>
                        </fileset>
                    </schema>
                </schemas>
                <extension>true</extension>
                <args>
                    <arg>-XJsr303Annotations</arg>
                </args>
                <plugins>
                    <plugin>
                        <groupId>com.github.krasa</groupId>
                        <artifactId>krasa-jaxb-tools</artifactId>
                        <version>${krasa-jaxb-tools.version}</version>
                    </plugin>
                </plugins>
            </configuration>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-xjc-plugin</artifactId>
    <version>2.6.0</version>
    <configuration>
        <sourceRoot>${basedir}/src/generated/</sourceRoot>
        <xsdOptions>
            <xsdOption>
                <extension>true</extension>
                <xsd>src/main/resources/a.xsd</xsd>
                <packagename>foo</packagename>
                <extensionArgs>
                    <extensionArg>-XJsr303Annotations</extensionArg>
                    <extensionArg>-XJsr303Annotations:targetNamespace=http://www.foo.com/bar</extensionArg>
                </extensionArgs>
            </xsdOption>
        </xsdOptions>
        <extensions>
            <extension>com.github.krasa:krasa-jaxb-tools:${krasa-jaxb-tools.version}</extension>
        </extensions>
    </configuration>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>xsdtojava</goal>
            </goals>
        </execution>
    </executions>
</plugin>

krasa-jaxb-tools's People

Contributors

davidkarlsen avatar dennisl avatar jarst avatar krasa avatar ninckblokje avatar patelm5 avatar rosko01 avatar slavb18 avatar st-ddt avatar stefans avatar tyutyutyu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

krasa-jaxb-tools's Issues

Inner Objects not getting generated with @Valid

Hi,

In the below mentioned xsd, for the complex type zzDTO, name and place are mandatory. Since zzDTO itself is optional inside yyDTO, the tags of name and place inside zzDTO are not getting annotated with @Valid tag. It is getting annotated properly with @NotNull.

Can you help me out with this ?

<xs:complexType name="XXDTO">
xs:sequence
<xs:element type="yyDTO" name="resource" minOccurs="0"/>
/xs:sequence
/xs:complexType

<xs:complexType name="yyDTO">
xs:sequence
<xs:element type="ZZDTO" name="domainElement" minOccurs="0" maxOccurs="unbounded"/>
/xs:sequence
/xs:complexType

<xs:complexType name="ZZDTO">
xs:sequence
<xs:element type="xs:string" name="name" minOccurs="1"/>
<xs:element type="xs:string" name="place" minOccurs="1"/>
/xs:sequence
/xs:complexType

Thanks
Balaji

Choice annotations

created from #8

<xs:complexType name="DrinkType">
  <xs:sequence>
    <xs:choice>
      <xs:element ref="Tea"/>
      <xs:element ref="Coffee"/>
    </xs:choice>
  </xs:sequence>
</xs:complexType>

Should generate:

@Choice({"tea", "coffee"})
public class DrinkType {
  Tea tea;
  Coffee coffee;
}

support of java 5

hi,

i would like to use the krasa-jaxb-tools plugin to generate JSR 303 annotations for my project. unfortunately i am forced to use java 5. is it possible that you could provide a special (with maven classifier) version of your plugin?
would be great, as your plugin works like a charm for me and perfectly fits my needs -except the java version issue.

TIA,
~christoph

Further support for krasa-jaxb-tools

Hi there,

Thank you for the great plugin, I've used it in CXF projects and its very helpful if one has to use WADL (I did the BeanValidation support for Swagger-Springfox and Swagger-Codegen for Java).

I read you won't be able to further support this project - are you interested in providing it under an Apache license to further support it and hopefully eventually get this into Apache CXF?

Best regards,
Johannes

XReplacePrimitives not converting doubles and floats

I am observing the following behavior:

Without XReplacePrimitives (the default Jaxb behavior):
An optional int becomes Integer, a mandatory one becomes int
An optional double becomes Double, a mandatory one becomes double

With XReplacePrimitives:
An optional int becomes Integer, a mandatory one becomes Integer as well
An optional double becomes Double, a mandatory one becomes double, as opposed to Double that one would expect

Is this expected?

generated @NotNull

A piece of generated Java code looks like this:
@xmlelement(required = true)
@NotNull
@digits(integer = 5, fraction = 2)
protected BigDecimal mask02Mgbeitrag;

Is it possible to suppress the @NotNull generation? It's because JSF complains that the 'mask02Mgbeitrag' is null. But as it is used for a form-based-query, it may be null.

Parent element inherits validation annotation / lets validation fail

Hi krasa!

I have implemented a parser for european direct debit transactions using SEPA standard pain008 with the following schema (version pain.008.002.02):
http://obantoo.cvs.sourceforge.net/viewvc/obantoo/obantoo/xsd/pain.008.002.02.xsd?revision=1.1

The source code generated by xjc has a problem in class "DirectDebitTransactionInformationSDD". The property "protected ActiveOrHistoricCurrencyAndAmountSEPA instdAmt;" is annotated with "@digits(integer = 9, fraction = 2)", which is not correct. Validating using bean validation fails. Removing this annotation (which is used in class ActiveOrHistoricCurrencyAndAmountSEPA as well) solves the problem.

My command line is:
java -classpath $CLASSPATH com.sun.tools.xjc.XJCFacade -p xbc.server.format.pain.direct_debit -XJsr303Annotations -XJsr303Annotations:targetNamespace=urn:iso:std:iso:20022:tech:xsd:pain.008.002.02 -XJsr303Annotations:generateNotNullAnnotations=true -XJsr303Annotations:JSR_349=false -XJsr303Annotations:verbose=false -no-header -d ${XHOME}/source/java ${TARGET_DIR}/pain.008.002.02.xsd

XJC libs used:
jaxb-api-2.1.jar
jaxb-impl-2.1.13.jar
jaxb-xjc-2.1.13.jar
krasa-jaxb-tools-0.7.1.jar

But this is the only problem I have yet, thanks for this great plugin!!

Cheers,
Sebastian

Plugin throws RTE on XReplacePrimitives for serialVersionUID

Using an xjc binding

<jxb:globalBindings>
   <jxb:serializable uid="1"/>  
</jxb:globalBindings>

(i.e. with a uid attribute defined) generates the code

private final static long serialVersionUID = 1L;

-XReplacePrimitives then tries to replace that field and the (non existent) getter and setter and this results in an RTE.

The following patch fixes that:

diff --git a/src/main/java/com/sun/tools/xjc/addon/krasa/PrimitiveFixerPlugin.java b/src/main/java/com/sun/tools/xjc/addon/krasa/PrimitiveFixerPlugin.java
index aea005c..bff1911 100644
--- a/src/main/java/com/sun/tools/xjc/addon/krasa/PrimitiveFixerPlugin.java
+++ b/src/main/java/com/sun/tools/xjc/addon/krasa/PrimitiveFixerPlugin.java
@@ -43,6 +43,15 @@
             for (Map.Entry<String, JFieldVar> stringJFieldVarEntry : fields.entrySet()) {
                 JFieldVar fieldVar = stringJFieldVarEntry.getValue();
                 JType type = fieldVar.type();
+                
+                /*
+                 * Exclude "serialVersionUID" from processing XReplacePrimitives as this will 
+                 * have no getter or setter defined.
+                 */
+                if ("serialVersionUID".equals(fieldVar.name())) {
+                   continue;
+                }
+                    
                 if (type.isPrimitive()) {
                     Class o = hashMap.get(type.name());
                     if (o != null) {

how to add serializable statement

Normally I use the bindings.xml file (<xjc:serializable uid="1"/>) to configure that xjc will add serialization statements to the generated Java classes. How can I configure this behavior?

@Size for ArrayList/Collections/Maps

The DTO is generated and a collection is annotated with @XmlElementWrapper.
Here it is expected that the element is a collection.
I would like this extension to add @Size according to the minOccurs and maxOccurs.
I know that XSD does not understand collection and I know that you bind particular annotation to particular element type in schema. Would you be able to recognize Java Collection and add the annotation @Size?

minExclusive=0, fractionDigits=2 wrong annotation

Hi,
for schema

<xs:complexType name="Invoice">
    <xs:sequence>
        <xs:element name="amount">
            <xs:simpleType>
                <xs:restriction base="xs:decimal">
                    <xs:minExclusive value="0"/>
                    <xs:fractionDigits value="2"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:element>
    </xs:sequence>
</xs:complexType>

plugin generates

@NotNull
@DecimalMin("1")
protected BigDecimal amount;

Thanks,
Fedor.

Multiple patterns in xsd:restriction

Hi,

Currently with this type definition

<xsd:simpleType name="patternList">
    <xsd:restriction base="xsd:string">
        <xsd:pattern value="[0-9]" />           
    </xsd:restriction>
</xsd:simpleType>

the library generates

@Pattern(regexp = "[0-9]")
protected String patternList;

but with a definition like

<xsd:simpleType name="patternList">
    <xsd:restriction base="xsd:string">
        <xsd:pattern value="[0-9]" />           
        <xsd:pattern value="[A-B]" />           
    </xsd:restriction>
</xsd:simpleType>

the library fails, only generates one element instead of

@Pattern.List({
    @Pattern(regexp = "[0-9]"),
    @Pattern(regexp = "[A-B]")
})
protected String patternList;

Probably with a piece of code similar to the following, the issue could be fixed (I have no experience with CodeModel API)

List<XSFacet> patternList = simpleType.getFacets("pattern");
if (patternList.size()>1) {  // More than one pattern
    JAnnotationUse patternListAnnotation = field.annotate(Pattern.List.class);
    JAnnotationArrayMember listValue = patternListAnnotation.paramArray("value");

    String value;
    for (XSFacet xsFacet :patternList) {
        if ("String".equals(field.type().name())) {
            value = xsFacet.getValue().value;
            // cxf-codegen fix
            if (!"\\c+".equals(value)) {
                listValue.annotate(Pattern.class).param("regexp", replaceXmlProprietals(value));
            }
        }
    }
} else { // Only one pattern, current code

    ...

}

Best regards.

Krasa - JAXB : Wrong @Digit validation attribute with totalDigits & fractionDigits (XSD)

The converted JAXB target Bean using Krasa, is producing wrong @Digit validation attributes.

The Simple Type is :

<simpleType name="max11DecVal">
    <restriction base="decimal">
        <totalDigits value="11" />
        <fractionDigits value="10" />
    </restriction>
</simpleType>

The Genrated JAVA Bean property with validation is:

@xmlelement(required = true)
@generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-26T05:40:39+05:30", comments = "JAXB RI v2.2.11")
@NotNull
@digits(integer = 1, fraction = 10)
protected BigDecimal someProp;

The problem is :

ACTUAL Generation : @digits(integer = 1, fraction = 10) (the integer attribute is always coming the difference i.e 11-10 =1, which is not right)
It SHOULD BE : @digits(integer = 11, fraction = 10) (integer should be the totalDigits which is 11 as stated in XSD)

I am using below options in my pom.xml to genrate JAVA classes from XSD :

                  <extraargs>
                        <extraarg>-fe</extraarg>
                        <extraarg>jaxws21</extraarg>
                        <extraarg>-xjc-Xts</extraarg>
                        <extraarg>-xjc-Xfluent-api</extraarg>
                        <extraarg>-xjc-mark-generated</extraarg>
                        <extraarg>-verbose</extraarg>
                        <extraarg>-xjc-Xvalue-constructor</extraarg>
                        <extraarg>-xjc-Xannotate</extraarg>
                        <extraarg>-xjc-Xequals</extraarg>
                        <extraarg>-xjc-XhashCode</extraarg>
                        <extraarg>-xjc-Xcopyable</extraarg>
                        <extraarg>-xjc-Xmergeable</extraarg>
                        <extraarg>-xjc-XJsr303Annotations</extraarg>

                    </extraargs>

Please help to resolve the issue, or advice if I am missing something in the above extra arguments.

Tagged releases

Please can you add tags for each release?
It would make cheeking things a lot easier, and provide a feed to watch for new releases.

minInclusive on a type xs:gYearMonth

Hi,

I have a schema with the following type:

<xs:restriction base="xs:gYearMonth">
  <xs:minInclusive value="1911-01"/>
  <xs:pattern value="\d{4}-\d{2}"/>
</xs:restriction>

this generates an annotation @DecimalMin("1911-01") which will throw a NumberFormatException because 1911-01 cannot be converted to a BigDecimal value although "1911-01" is a legal minInclusive value for xs:gYearMonth (see http://books.xmlschemata.org/relaxng/ch19-77135.html).

What would be the solution?

  • have a custom annotation for this case?
  • not adding the @DecimalMin annotation when the value is not a BigDecimal?

Thanks,

Xavier

-XReplacePrimitives breakes -XhashCode and -Xequals

If the Arguments
-XhashCode or
-Xequals

and
-XReplacePrimitives

are used together, the code doesn't work anymore if any primitives are replaced. The generated hashcode and equals methods use still the primitive and assign the Object to the primitive, e.g.

long theDivisionId;
theDivisionId = this.getDivisionId();

if the method this.getDivisionId() returns null (because it is a Long Object not initialized) the code throws a NullPointerException.

Maven Error using Plugin

Checked out your 'krasa-jaxb-tools' project into a fresh Eclipse/Maven project on my workspace so I can use it in my Maven project. Followed your instructions and added the dependency and the third example which generates Java-classes from XSD's. Unfortunately I get the following error when doing a 'mvn compile' or 'mvn generate-sources'

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Java EE 6 webapp project
[INFO] task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [cxf-xjc:xsdtojava {execution: generate-sources}]
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Could not download extension artifact

Embedded error: Requested download does not exist.
Unable to download the artifact from any repository
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Wed Mar 13 11:36:24 CET 2013
[INFO] Final Memory: 11M/59M
[INFO] ------------------------------------------------------------------------

Any suggestions how to solve this error?

Superclass only on special XSD elements

I want to influence JAXB to only generate an '... extends ' for special XSD elements. Reading the documentation of JAXB it explains, that there is only the possibility that ALL generated classes are derived from a superclass ().

As I only want this on a special complex types (having the same name as the XSD-file) I wonder if adding another parameter () to krasa-jaxb-tools would makes sense?

Endless loop in Util.isNumber

The check for is numeric type leads to an endless loop, because class is never updated.
Setting the super class should be added like this:

  Class <?> aClass = Class.forName (field.type ().fullName ());
  while (aClass.getSuperclass () != Object.class)
  {
    if (aClass.getSuperclass () == Number.class)
      return true;
   // ADD THE NEXT LINE:
    aClass = aClass.getSuperclass ();
  }

Bug in @Digits annotations

It seems that xml schema and jsr303 have a different style of expressing the allowed digits. In xml schema, you provide totaldigits and fractionDigits, in jsr303 it is integer and fraction. The plugin assumes that totalDigits equals integer, but correctly it should be integer = totalDigits - fractionDigits.

Pattern generated for xs:ID and xs:IDREF invalid?

Hi,

First let me thank you for writing an excellent JAXB plugin and putting it out there! Have been looking for this for a long time and I'm very glad I found it!!!

It works like a charm. However, I have a question regarding the patterns generated for the xs:ID and xs:IDREF based types. The generated code is:

@Pattern(regexp = "[\\i-[:]][\\c-[:]]*")

This pattern does not seem to be accepted by the java.util.regex.Pattern class. When trying to 'compile' this pattern in a simple test it throws a java.util.regex.PatternSyntaxException with the message:

Illegal/unsupported escape sequence near index 2
[\i-[:]][\c-[:]]*
  ^

Are these expressions not evaluation using java.util.regex? Or am I missing the point?
I haven't actually tested the validations with Bean validation. Just browsed through the generated code and noticed this...

Best regards,

Tjeerd

Pattern Validation for enums. At the moment Krasa supports only String type for Patterns

At the moment Krasa only supports pattern for Strings.
We have a business scenario where we have Enum which consists of 10 values and There are many complex types which refer to enum but then we need it to be restricted to use only 2 enum values or 3 instead of all of them.

Here is a business case for this ::
ActionEnum:

 <xsd:simpleType name="ActionValues">
        <xsd:restriction base="xsd:string">
            <xsd:enumeration value="Flights"/>
            <xsd:enumeration value="Delta"/>
            <xsd:enumeration value="FareValue"/>
 </xsd:restriction>
    </xsd:simpleType>

complex type:

<xsd:complexType name="FlightsDeltaAction">
        <xsd:sequence>
            <xsd:element name="name">
                <xsd:simpleType>
                    <xsd:restriction base="ActionValues">
                        <xsd:pattern value="Flights"/>
                        <xsd:pattern value ="Delta"/>
                    </xsd:restriction>
                </xsd:simpleType>

I can see from the sourcecode that there is below code:
else if (simpleType.getFacet("pattern") != null) {
String pattern = simpleType.getFacet("pattern").getValue().value;
if ("String".equals(field.type().name())
Can we have this extended to have restrictions for Enums as well?

Thanks,
Rohan

Multiple Patterns with own base-restriction-simpletype is ignored

The additional pattern in a simpletype-base restriction is ignored in the wsdl2java generation.
Example:

<xsd:simpleType name="patternList">
		<xsd:restriction base="a:patternListBase">
			<xsd:pattern value="[0-9]" />
			<xsd:pattern value="[A-B]" />
		</xsd:restriction>
	</xsd:simpleType>

	<xsd:simpleType name="patternListBase">
		<xsd:restriction base="xsd:string">
			<xsd:pattern value="[Y-Z]" />
		</xsd:restriction>
	</xsd:simpleType>

The annotation in the java-class should look like this:

@Pattern.List({
        @Pattern(regexp = "[Y-Z]"),
        @Pattern(regexp = "([0-9])|([A-B])")
    })

but looks like this

@Pattern(regexp = "([0-9])|([A-B])")

I already created pull request #60 with the fix :)

missing @Valid

When you have an object composition, we have a mistake :
See the example below :

class ClassA {
@NotNull
ClassB b;
}

class ClassB {
@NotNull
String name;
}

if the name attribute of the ClassB is null, when I validate an object of ClassA, the validation says OK. It's because the @Valid annotation is missing on b member of ClassA.

You should generate a @Valid annotation on the b member.

class ClassA {
@NotNull
@Valid
ClassB b;
}

I have forked your project and had "field.annotate(Valid.class);" line 154 in the JaxbValidationsPlugins source file.
I installed the artifactId in local and the recursive validation is nowadays done.

Regards
Stéphane

Attributes don't seem to be annotated unless they have a minOccurs > 0

I have come across what I believe to be a bug, where when I have the following XSD

<xs:element minOccurs="0" maxOccurs="1" name="StateOrTerritoryC" nillable="true">
	<xs:simpleType>
		<xs:restriction base="xs:string">
			<xs:enumeration value="AAT" />
			<xs:enumeration value="ACT" />
			<xs:enumeration value="NSW" />
			<xs:enumeration value="NT" />
			<xs:enumeration value="QLD" />
			<xs:enumeration value="SA" />
			<xs:enumeration value="TAS" />
			<xs:enumeration value="VIC" />
			<xs:enumeration value="WA" />
		</xs:restriction>
	</xs:simpleType>
</xs:element>

I will end up with the following

@XmlElementRef(name = "StateOrTerritoryC", namespace = "http://xyz", type = JAXBElement.class)
    protected JAXBElement<String> stateOrTerritoryC;

The moment I change the minOccurs from 0 to 1

<xs:element minOccurs="1" maxOccurs="1" name="StateOrTerritoryC" nillable="true">
	<xs:simpleType>
		<xs:restriction base="xs:string">
			<xs:enumeration value="AAT" />
			<xs:enumeration value="ACT" />
			<xs:enumeration value="NSW" />
			<xs:enumeration value="NT" />
			<xs:enumeration value="QLD" />
			<xs:enumeration value="SA" />
			<xs:enumeration value="TAS" />
			<xs:enumeration value="VIC" />
			<xs:enumeration value="WA" />
		</xs:restriction>
	</xs:simpleType>
</xs:element>

I end up with the following

@XmlElement(name = "StateOrTerritoryC", required = true, nillable = true)
@Pattern(regexp = "(AAT)|(ACT)|(NSW)|(NT)|(QLD)|(SA)|(TAS)|(VIC)|(WA)")
protected String stateOrTerritoryC;

Has anybody noticed this ?

XSD <choice> adds @NotNull to all options

<choice>
    <element name="foo" type="Foo" />
    <element name="bar" type="Bar" />
    <element name="baz" type="Baz" />
</choice>

gives

@NotNull
protected XmlFoo foo;
@NotNull
protected XmlBar bar;
@NotNull
protected XmlBaz baz;

requiring all options to be filled which is clearly wrong.

Annotate getters instead of fields

It would be great to have the option of generating the validation annotations on getters instead of fields. That way, static analysis tools will pick up the annotations and warn about improper use.

Size constraint not applied for restriction of xsd:hexBinary base

Hi,
I have the following schema:

<xsd:complexType name="ProductType">
        <xsd:attribute name="prodId" type="ProductIdType">
        </xsd:attribute>
 </xsd:complexType>
<xsd:simpleType name="ProductIdType">
      <xsd:restriction base="xsd:hexBinary">
          <xsd:maxLength value="18" />
      </xsd:restriction>
</xsd:simpleType>

When I generate the code I get an array of byte in my ProductType class:
protected byte[] prodId;
But no Size annotation.
Are restrictions on hexBinary xsd datatypes not supported?

Thanks for your help!

Enumeration pattern is not escaped

Hi,

When krasa-jaxb-tools generate the @Package annotation, then the pattern is not escaped. The pattern is taken form the value attribute of the enumeration element. This element is a literal string (if I am correct). So placing a parentheses will result in a regular expression instead of a literal pattern.

Example:

<xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="test 123"/> <xs:enumeration value="test (123)"/> </xs:restriction> </xs:simpleType>

This will result in the following annotation:
@Pattern(regexp = "(test 123)|(test (123))")

test (123) is now a regular expression, because the parentheses are not escaped.

Would you be willing to consider a pull request for this?

Is the plugin executable from cmd line without need of maven?

Hi,

I've tried your maven plugin to convert xsd to POJO with 303 validation annotation and its exactly what I was looking for. But I would like to be able to run the maven plugin from the cmd line without need of maven :D. I know that it sounds weird, but for my use I cant use maven rn. Is there a way to somehow run the plugin like jar?

Thx for the help
Thomasator

Plugin crashes with NPE at fields with final static (fixed value)

I have intially reported an issue with the jaxb2-fixed-value plugin to supported fixed values on attributes: fbdo/jaxb2-fixed-value#1. The author adised to use <jxb:globalBindings fixedAttributeAsConstantProperty="true" /> as described in his IT. Unfortunately, that binding change makes this plugin crash:

[INFO] --- maven-jaxb2-plugin:0.10.0:generate (generate-model) @ helper-ws-model ---
[INFO] Sources are not up-to-date, XJC will be executed.
java.lang.NullPointerException
at com.sun.tools.xjc.addon.krasa.Utils.getField(Utils.java:62)
at com.sun.tools.xjc.addon.krasa.JaxbValidationsPlugins.hasAnnotation(JaxbValidationsPlugins.java:466)
at com.sun.tools.xjc.addon.krasa.JaxbValidationsPlugins.processType(JaxbValidationsPlugins.java:252)
at com.sun.tools.xjc.addon.krasa.JaxbValidationsPlugins.processAttribute(JaxbValidationsPlugins.java:455)
at com.sun.tools.xjc.addon.krasa.JaxbValidationsPlugins.run(JaxbValidationsPlugins.java:154)
at com.sun.tools.xjc.model.Model.generateCode(Model.java:294)
at org.jvnet.mjiip.v_2_2.XJC22Mojo.generateCode(XJC22Mojo.java:66)
at org.jvnet.mjiip.v_2_2.XJC22Mojo.doExecute(XJC22Mojo.java:41)
at org.jvnet.mjiip.v_2_2.XJC22Mojo.doExecute(XJC22Mojo.java:28)
at org.jvnet.jaxb2.maven2.RawXJC2Mojo.doExecute(RawXJC2Mojo.java:326)
at org.jvnet.jaxb2.maven2.RawXJC2Mojo.execute(RawXJC2Mojo.java:168)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:132)
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:116)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:120)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:347)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:154)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:213)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:157)
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:606)
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)
[INFO]

That probably needs some special attention.

Tested with 1.3.

annotation javax.validation.constraints.Digits is missing fraction

Hello,

I tested your plugin and I have a problem with BigInteger field.

For example for the field : "protected BigDecimal enveloppe;", the plugin generates a annotation : Digits(integer = 22).

The compiler fails because : "annotation javax.validation.constraints.Digits is missing fraction".

Thanks for your dev.

Best regards
Stéphane

Exception thrown if XSD union is used

For the next situation:

<xsd:schema
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        targetNamespace="c" xmlns:c="c"
        elementFormDefault="qualified">

    <xsd:simpleType name="DateOrDateTimeType">
        <xsd:union memberTypes="xsd:date xsd:dateTime"/>
    </xsd:simpleType>

    <xsd:complexType name="TimeInstantType">
        <xsd:simpleContent>
            <xsd:extension base="c:DateOrDateTimeType">
            </xsd:extension>
        </xsd:simpleContent>
    </xsd:complexType>
</xsd:schema>

the plugin throws the exception:
Attribute value added to class TimeInstantType
java.lang.ClassCastException: com.sun.xml.xsom.impl.UnionSimpleTypeImpl cannot be cast to com.sun.xml.xsom.impl.RestrictionSimpleTypeImpl
at com.sun.tools.xjc.addon.krasa.JaxbValidationsPlugins.processAttribute(JaxbValidationsPlugins.java:416)

When this happens the processing of the rest of the schema(s) does not continue.

In some cases @Size annotation is not applied properly.

In some cases @SiZe annotation is not applied properly. For the schema below following code is generated:

public class ParentElement {
    @XmlElement(name = "NumberWithCode")
    @Valid
    @Size(min = 1, max = 5)
    protected NumberWithCode numberWithCode;
...
}

public class NumberWithCode {
    @XmlValue
    protected String value;
    @XmlAttribute(name = "code")
    protected String code;
...
}

@SiZe annotation should be applied on value property.

  <xsd:simpleType name="Number">
    <xsd:restriction base="xsd:string">
      <xsd:minLength value="1" />
      <xsd:maxLength value="5" />
    </xsd:restriction>
  </xsd:simpleType>

  <xsd:complexType name="NumberWithCode">
    <xsd:simpleContent>
      <xsd:extension base="sec:Number">
        <xsd:attribute name="code" type="xsd:string" use="optional" />
      </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>

  <xsd:complexType name="ParentElement">
    <xsd:sequence>
      <xsd:element maxOccurs="1" minOccurs="0" name="NumberWithCode" type="sec:NumberWithCode" />
    </xsd:sequence>
  </xsd:complexType>

Here is sample project to reproduce the issue:
schema.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
    attributeFormDefault="unqualified"
    elementFormDefault="qualified"
    targetNamespace="http://test.com/common/v01"
    version="1.0.0"
    xmlns:sec="http://test.com/common/v01"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <xsd:complexType name="NumberWithCode">
    <xsd:simpleContent>
      <xsd:extension base="sec:Number">
        <xsd:attribute name="code" type="xsd:string" use="optional" />
      </xsd:extension>
    </xsd:simpleContent>
  </xsd:complexType>

  <xsd:simpleType name="Number">
    <xsd:restriction base="xsd:string">
      <xsd:minLength value="1" />
      <xsd:maxLength value="5" />
    </xsd:restriction>
  </xsd:simpleType>

  <xsd:element name="ParentElement" type="sec:ParentElement" />

  <xsd:complexType name="ParentElement">
    <xsd:sequence>
      <xsd:element maxOccurs="1" minOccurs="0" name="NumberWithCode" type="sec:NumberWithCode" />
    </xsd:sequence>
  </xsd:complexType>

  <xsd:element name="Fault" type="sec:Fault" />

  <xsd:complexType name="Fault">
    <xsd:sequence>
      <xsd:element name="faultcode" type="xsd:QName" />
    </xsd:sequence>
  </xsd:complexType>

</xsd:schema>

test.wsdl

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions
    name="Test"
    targetNamespace="http://test.com/common/v01"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:sec="http://test.com/common/v01">

  <wsdl:types>
    <xsd:schema targetNamespace="http://test.com/common/v01">
      <xsd:include schemaLocation="schema.xsd" />
    </xsd:schema>
  </wsdl:types>

  <wsdl:message name="GetRQ">
    <wsdl:part element="sec:ParentElement" name="body" />
  </wsdl:message>

  <wsdl:message name="GetRS">
    <wsdl:part element="sec:ParentElement" name="body" />
  </wsdl:message>

  <wsdl:message name="GetFault">
    <wsdl:part element="sec:Fault" name="body" />
  </wsdl:message>

  <wsdl:portType name="TestPortType">
    <wsdl:operation name="Get">
      <wsdl:input message="sec:GetRQ" />
      <wsdl:output message="sec:GetRS" />
      <wsdl:fault message="sec:GetFault" name="GetFault" />
    </wsdl:operation>
  </wsdl:portType>

  <wsdl:binding name="TestBinding" type="sec:TestPortType">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="Get">
      <soap:operation soapAction="Get" />
      <wsdl:input>
        <soap:header message="sec:GetRQ" part="header" use="literal" />
        <soap:body parts="body" use="literal" />
      </wsdl:input>
      <wsdl:output>
        <soap:header message="sec:GetRS" part="header" use="literal" />
        <soap:body parts="body" use="literal" />
      </wsdl:output>
      <wsdl:fault name="GetFault">
        <soap:fault name="GetFault" use="literal" />
      </wsdl:fault>
    </wsdl:operation>
  </wsdl:binding>

  <wsdl:service name="TestService">
    <wsdl:port binding="sec:TestBinding" name="TestPort">
      <soap:address location="http://test.com/common/v01" />
    </wsdl:port>
  </wsdl:service>

</wsdl:definitions>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 2012 Sabre Holdings -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sample</groupId>
  <artifactId>test</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.0.0.GA</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-codegen-plugin</artifactId>
        <version>2.6.0.fuse-71-047</version>
        <executions>
          <execution>
            <goals>
              <goal>wsdl2java</goal>
            </goals>
            <configuration>
              <wsdlRoot>.</wsdlRoot>
              <includes>
                <include>*.wsdl</include>
              </includes>
              <defaultOptions>
                <extraargs>
                  <extraarg>-xjc-XJsr303Annotations</extraarg>
                  <extraarg>-xjc-XJsr303Annotations:targetNamespace=http://</extraarg>
                </extraargs>
              </defaultOptions>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>com.github.krasa</groupId>
            <artifactId>krasa-jaxb-tools</artifactId>
            <version>0.4</version>
          </dependency>
        </dependencies>
      </plugin>
    </plugins>
  </build>
</project>

Wrong integral digits in Digit-Annotation in combination of totalDigits and fractionDigits in XSD

According to the documentation the totalDigits contains the fractionDigits: "xs:totalDigits defines the maximum number of digits of decimal and derived datatypes (both after and before the decimal point, not counting the decimal point itself)."
https://www.oreilly.com/library/view/xml-schema/0596002521/re52.html
At the moment totalDigits value in the xsd will be copied one-to-one into the integer attribute of Digit annotation without checking the fractionDigits of xsd.
That means when following is set into the xsd:

<xs:element name="exampleElement">
	<xs:simpleType>
		<xs:restriction base="xs:decimal">
			<xs:totalDigits value="10"/>
			<xs:fractionDigits value="2"/>
		</xs:restriction>
	</xs:simpleType>
</xs:element>

the JAXB class gets then the following annotation:

@Digits(integer = 10, fraction = 2)

But in these case following annotation would be correct:

@Digits(integer = 8, fraction = 2)
Because the integer attribute are only the integral digits and doesn't include the fraction digits.

add a "verbose" flag

It would be nice if there was a way to disable all the System.out logs with some sort of verbose flag like -XJsr303Annotations:verbose=false or, alternatively, log everything through a proper logger (instead of System.out) so that I can control what should be logged or not.

java.lang.ClassCastException: com.sun.xml.xsom.impl.parser.DelayedRef$Element cannot be cast to com.sun.xml.xsom.impl.ElementDecl

Here's the stack trace:

java.lang.ClassCastException: com.sun.xml.xsom.impl.parser.DelayedRef$Element cannot be cast to com.sun.xml.xsom.impl.ElementDecl
at com.sun.tools.xjc.addon.krasa.JaxbValidationsPlugins.processElement(JaxbValidationsPlugins.java:138)
at com.sun.tools.xjc.addon.krasa.JaxbValidationsPlugins.run(JaxbValidationsPlugins.java:94)
at com.sun.tools.xjc.model.Model.generateCode(Model.java:294)
at com.sun.tools.xjc.Driver.run(Driver.java:356)
at com.sun.tools.xjc.Driver.run(Driver.java:199)
at com.sun.tools.xjc.Driver._main(Driver.java:122)
at com.sun.tools.xjc.Driver.access$000(Driver.java:79)
at com.sun.tools.xjc.Driver$1.run(Driver.java:102)

xs:enumeration is not translated correctly to annotations

Give the following piece of an xsd :

        <xsd:enumeration value="12" />
        <xsd:enumeration value="13" />
        <xsd:enumeration value="14" />
        <xsd:enumeration value="15" />
        <xsd:enumeration value="19" />
        <xsd:enumeration value="26" />
        <xsd:enumeration value="35" />
        <xsd:enumeration value="37" />
        <xsd:enumeration value="38" />
        <xsd:enumeration value="39" />
        <xsd:enumeration value="40" />
        <xsd:enumeration value="90" />
        <xsd:enumeration value="91" />
        <xsd:enumeration value="92" />
        <xsd:enumeration value="93" />

the translated annotations are :

@Pattern.List({
@pattern(regexp = "12"),
@pattern(regexp = "13"),
@pattern(regexp = "14"),
@pattern(regexp = "15"),
@pattern(regexp = "19"),
@pattern(regexp = "26"),
@pattern(regexp = "35"),
@pattern(regexp = "37"),
@pattern(regexp = "38"),
@pattern(regexp = "39"),
@pattern(regexp = "40"),
@pattern(regexp = "90"),
@pattern(regexp = "91"),
@pattern(regexp = "92"),
@pattern(regexp = "93")
})

Which of course is wrong because the given value must satisfy all the patterns in the list at the same time.

Release to central Maven repo + tag in GIT

Can we get a release with the latest fixes and updates tagged in GIT and released to the central Maven repo?

Here is the documentation for getting something to the public repository:

http://maven.apache.org/guides/mini/guide-central-repository-upload.html

From the documentation:

The easiest way to upload another project is to use the Sonatype OSS Repository, which is an approved repository provided by Sonatype for any OSS Project that want to get their artifacts into Central Repository.

The service is proposed in two variants:

Maven repository hosting service: You can deploy snapshots, stage releases, and promote your releases so they will be published to Central Repository

Manual upload of artifacts: The process is mostly automated with turnaround time averaging 1 business day.

1.7 branch release

Hi,

thanks for great plugin,
when are you planning to release 1.7 version to maven central?

Regards, krzysiekbr

Ability to customise all messages

Nice project, it's working well for me.

It would be useful to be able to customise the messages configured. I see that you can configure messages for @NotNull annotations, but a more general solution would be nice. In my case, the schema has a lot of @Pattern annotations, which result in messages like must match \"[\dA-Z]+\", which I can't really display to a user. I'd prefer to say "must be alphanumeric capitals" or something like that (which means something to a user)

I would need to be able to provide custom messages for each place where a regex pattern is used, because each instance might be different.

I'm not sure how exactly this would best be configured, but maybe configuring the metadata in the XSD itself using <annotation/><appinfo/> elements would be best, similar to the solution here:

http://confluence.highsource.org/display/J2B/Inheritance+plugin

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.